@sfxcode/nuxt-mongocamp-server 2.4.0 → 2.5.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 (28) hide show
  1. package/dist/module.d.mts +10 -4
  2. package/dist/module.json +1 -1
  3. package/dist/module.mjs +36 -20
  4. package/dist/runtime/composables/mongocampApi.d.ts +4 -0
  5. package/dist/runtime/composables/mongocampApi.js +10 -2
  6. package/dist/runtime/composables/mongocampAuth.js +29 -25
  7. package/dist/runtime/composables/mongocampCollection.d.ts +2 -1
  8. package/dist/runtime/composables/mongocampCollection.js +36 -13
  9. package/dist/runtime/composables/mongocampLive.js +25 -3
  10. package/dist/runtime/composables/mongocampSearch.js +12 -3
  11. package/dist/runtime/plugins/bson-payload.d.ts +8 -0
  12. package/dist/runtime/plugins/bson-payload.js +6 -0
  13. package/dist/runtime/server/composables/mongocampApi.d.ts +5 -1
  14. package/dist/runtime/server/composables/mongocampApi.js +1 -9
  15. package/dist/runtime/server/composables/mongocampServerApi.d.ts +4 -0
  16. package/dist/runtime/server/composables/mongocampServerApi.js +5 -0
  17. package/dist/runtime/server/mongocamp/core.d.ts +1 -1
  18. package/dist/runtime/server/mongocamp/core.js +1 -1
  19. package/dist/runtime/server/mongocamp/embedded-api.d.ts +18 -0
  20. package/dist/runtime/server/mongocamp/embedded-api.js +10 -0
  21. package/dist/runtime/utils/appState.d.ts +21 -0
  22. package/dist/runtime/utils/appState.js +11 -0
  23. package/dist/runtime/utils/bsonPayload.d.ts +8 -0
  24. package/dist/runtime/utils/bsonPayload.js +10 -0
  25. package/dist/runtime/utils/buildFieldFilterExpression.d.ts +4 -0
  26. package/dist/runtime/utils/buildFieldFilterExpression.js +5 -3
  27. package/dist/runtime/utils/sse.js +7 -1
  28. package/package.json +15 -7
package/dist/module.d.mts CHANGED
@@ -39,12 +39,17 @@ interface ResolvedServerOptions {
39
39
  }
40
40
 
41
41
  interface ModuleOptions {
42
- /** The url of the MongoCamp API; with `server.enabled` it defaults to the prefix of the embedded server. */
43
- url: string;
42
+ /** The url of the MongoCamp API; with `server.enabled` it defaults to the prefix of the embedded server (2.5.0: optional then). */
43
+ url?: string;
44
+ /** An api key for the server code (`useMongocampApi(event)`); private, never sent to the browser. Better set by env. */
44
45
  apiKey?: string;
46
+ /** Rows per page of the client composables (default 500, at least 10). */
45
47
  paginationSize?: number;
48
+ /** Refreshes the token of the session while the user is active (default false). */
46
49
  refreshToken?: boolean;
47
- tokenRefreshInterval: number;
50
+ /** Milliseconds between two token refreshes (default 5000, at least 5000). */
51
+ tokenRefreshInterval?: number;
52
+ /** Seconds the session cookie lives (default 30 days). */
48
53
  sessionMaxAge?: number;
49
54
  /** The MongoCamp server embedded in the Nitro of this application. */
50
55
  server?: ServerOptions;
@@ -61,7 +66,8 @@ declare module '@nuxt/schema' {
61
66
  }
62
67
  interface RuntimeConfig {
63
68
  mongocampApiKey: string;
64
- mongocampServer: ResolvedServerOptions & {
69
+ /** Only when the embedded server is enabled (2.5.0). */
70
+ mongocampServer?: ResolvedServerOptions & {
65
71
  version: {
66
72
  name: string;
67
73
  version: string;
package/dist/module.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sfxcode/nuxt-mongocamp-server",
3
- "version": "2.4.0",
3
+ "version": "2.5.0",
4
4
  "configKey": "mongocamp",
5
5
  "compatibility": {
6
6
  "nuxt": ">=4.7.0"
package/dist/module.mjs CHANGED
@@ -1,11 +1,10 @@
1
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
+ import { defineNuxtModule, useLogger, createResolver, addImportsDir, addPlugin, addImports, addServerImports, addServerHandler, addServerPlugin, addTypeTemplate, addServerTemplate, updateTemplates, resolveFiles } from '@nuxt/kit';
3
3
  import { defu } from 'defu';
4
- import { consola } from 'consola';
5
4
  export * from '../dist/runtime/api/index.js';
6
5
 
7
6
  const name = "@sfxcode/nuxt-mongocamp-server";
8
- const version = "2.4.0";
7
+ const version = "2.5.0";
9
8
 
10
9
  const DefaultServerPrefix = "/api/mongocamp-server";
11
10
  const DefaultCollectionsDir = "mongocamp";
@@ -107,7 +106,15 @@ const module$1 = defineNuxtModule({
107
106
  nuxt: ">=4.7.0"
108
107
  }
109
108
  },
109
+ defaults: {
110
+ paginationSize: 500,
111
+ refreshToken: false,
112
+ tokenRefreshInterval: 5e3,
113
+ sessionMaxAge: 60 * 60 * 24 * 30
114
+ // 30 days
115
+ },
110
116
  setup(options, nuxt) {
117
+ const logger = useLogger("mongocamp");
111
118
  if (nuxt.options._nitroMajor !== 3) {
112
119
  throw new Error('[mongocamp] the module needs Nitro 3: add "nitro" to the dependencies of the application (Nuxt then builds with @nuxt/nitro-v3-server)');
113
120
  }
@@ -119,24 +126,21 @@ const module$1 = defineNuxtModule({
119
126
  if (!options.url || options.url.length === 0)
120
127
  throw new Error('[mongocamp] Missing required "url" module option (or enable the embedded server with "server.enabled").');
121
128
  });
122
- if (options.paginationSize !== void 0 && options.paginationSize < 10)
123
- consola.warn(`[mongocamp] paginationSize of ${options.paginationSize} is below the minimum of 10, falling back to 500`);
124
- if (!options.paginationSize || options.paginationSize < 10)
129
+ if (!options.paginationSize || options.paginationSize < 10) {
130
+ logger.warn(`paginationSize of ${options.paginationSize} is below the minimum of 10, falling back to 500`);
125
131
  options.paginationSize = 500;
126
- if (options.tokenRefreshInterval !== void 0 && options.tokenRefreshInterval < 5e3)
127
- consola.warn(`[mongocamp] tokenRefreshInterval of ${options.tokenRefreshInterval} is below the minimum of 5000, falling back to 5000`);
128
- if (!options.tokenRefreshInterval || options.tokenRefreshInterval < 5e3)
132
+ }
133
+ if (!options.tokenRefreshInterval || options.tokenRefreshInterval < 5e3) {
134
+ logger.warn(`tokenRefreshInterval of ${options.tokenRefreshInterval} is below the minimum of 5000, falling back to 5000`);
129
135
  options.tokenRefreshInterval = 5e3;
130
- if (options.refreshToken === void 0) {
131
- consola.warn('[mongocamp] "refreshToken" module option is not set, falling back to false (no auto token refresh)');
132
- options.refreshToken = false;
133
136
  }
134
- if (!options.sessionMaxAge || options.sessionMaxAge <= 0)
137
+ if (!options.sessionMaxAge || options.sessionMaxAge <= 0) {
135
138
  options.sessionMaxAge = 60 * 60 * 24 * 30;
139
+ }
136
140
  nuxt.options.runtimeConfig.public.mongocamp = defu(
137
141
  nuxt.options.runtimeConfig.public.mongocamp,
138
142
  {
139
- url: options.url,
143
+ url: options.url ?? "",
140
144
  paginationSize: options.paginationSize,
141
145
  refreshToken: options.refreshToken,
142
146
  tokenRefreshInterval: options.tokenRefreshInterval,
@@ -147,13 +151,21 @@ const module$1 = defineNuxtModule({
147
151
  const { resolve: resolve$1 } = createResolver(import.meta.url);
148
152
  const runtimeDir = resolve$1("./runtime");
149
153
  addImportsDir(resolve$1(runtimeDir, "composables"));
154
+ addPlugin(resolve$1(runtimeDir, "plugins/bson-payload"));
150
155
  addImports(["fromExtendedJson", "toExtendedJson", "documentId"].map((name2) => ({ name: name2, from: resolve$1(runtimeDir, "utils/extendedJson") })));
151
- addServerImportsDir(resolve$1(runtimeDir, "server/composables"));
152
- nuxt.options.runtimeConfig.mongocampServer = defu(nuxt.options.runtimeConfig.mongocampServer, { ...server, version: { name: "mongocamp-nitro-server", version } });
156
+ addServerImports([
157
+ { name: "useMongocampServerApi", from: resolve$1(runtimeDir, "server/composables/mongocampServerApi") },
158
+ { name: "useMongocampApi", from: resolve$1(runtimeDir, server.enabled ? "server/mongocamp/embedded-api" : "server/composables/mongocampApi") }
159
+ ]);
153
160
  if (server.enabled) {
161
+ nuxt.options.runtimeConfig.mongocampServer = defu(nuxt.options.runtimeConfig.mongocampServer, { ...server, version: { name: "mongocamp-nitro-server", version } });
154
162
  addServerHandler({ route: `${server.prefix}/**`, handler: resolve$1(runtimeDir, "server/mongocamp/handler") });
155
163
  addServerPlugin(resolve$1(runtimeDir, "server/mongocamp/plugin"));
156
- addServerImports([{ name: "useMongocampCore", from: resolve$1(runtimeDir, "server/mongocamp/core") }]);
164
+ addServerImports([
165
+ { name: "useMongocampCore", from: resolve$1(runtimeDir, "server/mongocamp/core") },
166
+ // the documents of a collection with the rules of the API, in-process (2.4.0)
167
+ { name: "useMongocampServerCollection", from: resolve$1(runtimeDir, "server/composables/mongocampServerCollection") }
168
+ ]);
157
169
  addTypeTemplate({
158
170
  filename: "types/mongocamp-hooks.d.ts",
159
171
  getContents: () => [
@@ -164,7 +176,7 @@ const module$1 = defineNuxtModule({
164
176
  "export {}"
165
177
  ].join("\n")
166
178
  }, { nitro: true, nuxt: true });
167
- consola.info(`[mongocamp] embedded server at ${server.prefix}`);
179
+ logger.info(`embedded server at ${server.prefix}`);
168
180
  }
169
181
  if (server.enabled || options.server?.collectionsDir !== void 0) {
170
182
  const dirs = collectionDirs(nuxt.options._layers, server.collectionsDir);
@@ -180,12 +192,16 @@ const module$1 = defineNuxtModule({
180
192
  }, { nitro: true, nuxt: true });
181
193
  nuxt.hook("builder:watch", async (event, path) => {
182
194
  const candidates = isAbsolute(path) ? [path] : [resolve(nuxt.options.srcDir, path), resolve(nuxt.options.rootDir, path)];
183
- if ((event === "add" || event === "unlink") && candidates.some((candidate) => dirs.some((dir) => candidate.startsWith(`${dir}/`)))) {
195
+ const inDir = (candidate) => dirs.some((dir) => {
196
+ const rest = relative(dir, candidate);
197
+ return rest !== "" && !rest.startsWith("..") && !isAbsolute(rest);
198
+ });
199
+ if ((event === "add" || event === "unlink") && candidates.some(inDir)) {
184
200
  await updateTemplates({ filter: (template) => template.filename === "types/mongocamp-collections.d.ts" });
185
201
  }
186
202
  });
187
203
  }
188
- consola.success("mongocamp-nuxt available");
204
+ logger.debug("mongocamp-nuxt available");
189
205
  }
190
206
  });
191
207
 
@@ -1,3 +1,7 @@
1
+ /**
2
+ * The generated clients for the browser and server side rendering, with the token of the session. Created once per Nuxt app and url
3
+ * (2.5.0; before, on every call): the token is read per request, so the clients stay valid after a login or a refresh.
4
+ */
1
5
  export declare function useMongocampApi(): {
2
6
  adminApi: import("../api/index.js").AdminApi;
3
7
  applicationApi: import("../api/index.js").ApplicationApi;
@@ -1,15 +1,21 @@
1
1
  import { useRequestFetch } from "#app";
2
2
  import { Configuration } from "../api/index.js";
3
+ import { mongocampAppState } from "../utils/appState.js";
3
4
  import { createMongocampApis } from "../utils/createMongocampApis.js";
4
5
  import { useMongocampUrl } from "./mongocampUrl.js";
5
6
  import { useMongocampStorage } from "./mongocampStorage.js";
6
7
  export function useMongocampApi() {
7
8
  const url = useMongocampUrl();
9
+ const { apis } = mongocampAppState();
10
+ const known = apis.get(url);
11
+ if (known !== void 0) {
12
+ return known;
13
+ }
8
14
  const state = useMongocampStorage();
9
15
  let fetchApi;
10
16
  if (import.meta.server && url?.startsWith("/")) {
11
17
  const requestFetch = useRequestFetch();
12
- fetchApi = ((input, init) => requestFetch.native(input, init));
18
+ fetchApi = (input, init) => requestFetch.native(input, init);
13
19
  }
14
20
  const configuration = new Configuration({
15
21
  basePath: url,
@@ -28,5 +34,7 @@ export function useMongocampApi() {
28
34
  }
29
35
  }]
30
36
  });
31
- return createMongocampApis(configuration);
37
+ const created = createMongocampApis(configuration);
38
+ apis.set(url, created);
39
+ return created;
32
40
  }
@@ -1,24 +1,35 @@
1
- import { computed, watch } from "vue";
1
+ import { computed, effectScope, watch } from "vue";
2
2
  import { consola } from "consola";
3
+ import { mongocampAppState } from "../utils/appState.js";
3
4
  import { toMongocampError } from "../utils/toMongocampError.js";
4
5
  import { useMongocampApi } from "./mongocampApi.js";
5
6
  import { useMongocampStorage } from "./mongocampStorage.js";
6
- import { useRuntimeConfig, useState } from "#app";
7
+ import { useRuntimeConfig } from "#app";
7
8
  export function useMongocampAuth() {
8
9
  const config = useRuntimeConfig();
9
10
  const refreshToken = config.public.mongocamp?.refreshToken;
10
11
  const tokenRefreshInterval = config.public.mongocamp?.tokenRefreshInterval;
11
12
  const state = useMongocampStorage();
12
13
  const { authApi } = useMongocampApi();
13
- const updateTokenInterval = useState("mongocamp.tokenRefreshInterval", () => void 0);
14
+ const { auth } = mongocampAppState();
15
+ function updateUserState(result) {
16
+ state.value.token = result.authToken;
17
+ state.value.profile = result.userProfile;
18
+ }
19
+ const logout = () => {
20
+ if (state.value.token)
21
+ authApi.logout().catch((e) => consola.error(e));
22
+ state.value.token = "";
23
+ state.value.profile = { user: "", isAdmin: false };
24
+ };
14
25
  function startTokenRefresh() {
15
- if (import.meta.client && refreshToken && !updateTokenInterval.value)
16
- updateTokenInterval.value = window.setInterval(updateToken, tokenRefreshInterval);
26
+ if (import.meta.client && refreshToken && auth.timer === void 0)
27
+ auth.timer = setInterval(updateToken, tokenRefreshInterval);
17
28
  }
18
29
  function stopTokenRefresh() {
19
- if (import.meta.client && updateTokenInterval.value) {
20
- window.clearInterval(updateTokenInterval.value);
21
- updateTokenInterval.value = void 0;
30
+ if (auth.timer !== void 0) {
31
+ clearInterval(auth.timer);
32
+ auth.timer = void 0;
22
33
  }
23
34
  }
24
35
  async function isAuthenticated() {
@@ -35,10 +46,6 @@ export function useMongocampAuth() {
35
46
  logout();
36
47
  }
37
48
  }
38
- function updateUserState(result) {
39
- state.value.token = result.authToken;
40
- state.value.profile = result.userProfile;
41
- }
42
49
  const login = async (loginId, loginPassword) => {
43
50
  logout();
44
51
  const login2 = { userId: loginId, password: loginPassword };
@@ -46,20 +53,17 @@ export function useMongocampAuth() {
46
53
  updateUserState(result);
47
54
  return result.userProfile;
48
55
  };
49
- const logout = () => {
50
- if (state.value.token)
51
- authApi.logout().catch((e) => consola.error(e));
52
- state.value.token = "";
53
- state.value.profile = { user: "", isAdmin: false };
54
- };
55
56
  const isLoggedIn = computed(() => (state.value.token?.length ?? 0) > 0);
56
- if (import.meta.client) {
57
- watch(isLoggedIn, (loggedIn) => {
58
- if (loggedIn)
59
- startTokenRefresh();
60
- else
61
- stopTokenRefresh();
62
- }, { immediate: true });
57
+ if (import.meta.client && auth.scope === void 0) {
58
+ auth.scope = effectScope(true);
59
+ auth.scope.run(() => {
60
+ watch(isLoggedIn, (loggedIn) => {
61
+ if (loggedIn)
62
+ startTokenRefresh();
63
+ else
64
+ stopTokenRefresh();
65
+ }, { immediate: true });
66
+ });
63
67
  }
64
68
  const userRoles = computed(() => state.value.profile.roles ?? []);
65
69
  const userGrants = computed(() => state.value.profile.grants ?? []);
@@ -72,10 +72,11 @@ export interface AuditEntry<T> {
72
72
  after?: T;
73
73
  }
74
74
  /** The id of a document: the text of the path, an `ObjectId` or a document with `_id`. */
75
+ /** (2.5.0: `_id` optional, as in the type of a declared schema; a document without one is refused when it is used.) */
75
76
  export type DocumentIdentity = string | number | {
76
77
  toHexString: () => string;
77
78
  } | {
78
- _id: unknown;
79
+ _id?: unknown;
79
80
  };
80
81
  export interface TypedCollection<T, I = T, Refs = Record<string, string>> {
81
82
  readonly name: string;
@@ -1,5 +1,6 @@
1
1
  import { ref } from "vue";
2
2
  import { ResponseError } from "../api/index.js";
3
+ import { mongocampAppState } from "../utils/appState.js";
3
4
  import { documentId, fromExtendedJson, toExtendedJson } from "../utils/extendedJson.js";
4
5
  import { toMongocampError } from "../utils/toMongocampError.js";
5
6
  import { useMongocampApi } from "./mongocampApi.js";
@@ -21,7 +22,6 @@ async function requestError(error) {
21
22
  ...current !== void 0 ? { current: fromExtendedJson(current) } : {}
22
23
  });
23
24
  }
24
- const declarations = /* @__PURE__ */ new Map();
25
25
  function getPath(document, path) {
26
26
  let current = document;
27
27
  for (const segment of path.split(".")) {
@@ -65,6 +65,14 @@ function setPathOf(document, path, value) {
65
65
  function idOfReference(value) {
66
66
  return isDocument(value) ? value._id : value;
67
67
  }
68
+ function idOf(target) {
69
+ const plain = target !== null && typeof target === "object" && Object.getPrototypeOf(target) === Object.prototype;
70
+ const id = plain ? target._id : target;
71
+ if (id === void 0 || id === null) {
72
+ throw Object.assign(new Error("the document has no _id"), { status: 400, isConflict: false });
73
+ }
74
+ return documentId(target);
75
+ }
68
76
  function isDocument(target) {
69
77
  return target !== null && typeof target === "object" && "_id" in target && typeof target.toHexString !== "function";
70
78
  }
@@ -79,6 +87,7 @@ export function useMongocampCollection(name) {
79
87
  const session = useMongocampStorage();
80
88
  const defaultRows = () => config.public.mongocamp?.paginationSize;
81
89
  const declarationKey = `${useMongocampUrl()}|${name}`;
90
+ const { declarations } = mongocampAppState();
82
91
  const declaration = declarations.get(declarationKey) ?? ref(void 0);
83
92
  declarations.set(declarationKey, declaration);
84
93
  let loading;
@@ -86,9 +95,15 @@ export function useMongocampCollection(name) {
86
95
  if (declaration.value !== void 0) {
87
96
  return Promise.resolve(declaration.value);
88
97
  }
89
- loading ??= Promise.resolve().then(() => collectionApi.getCollectionDeclaration({ collectionName: name })).catch(() => null).then((loaded) => {
98
+ loading ??= Promise.resolve().then(() => collectionApi.getCollectionDeclaration({ collectionName: name })).then((loaded) => {
90
99
  declaration.value = loaded;
91
100
  return loaded;
101
+ }, (error) => {
102
+ if (error instanceof ResponseError && error.response.status === 404) {
103
+ declaration.value = null;
104
+ }
105
+ loading = void 0;
106
+ return null;
92
107
  });
93
108
  return loading;
94
109
  };
@@ -170,7 +185,7 @@ export function useMongocampCollection(name) {
170
185
  findById: async (id, options = {}) => {
171
186
  const expand = options.expand !== void 0 && options.expand.length > 0 ? { expand: [...options.expand] } : {};
172
187
  try {
173
- return markExpanded(fromExtendedJson(await documentApi.getDocument({ collectionName: name, documentId: documentId(id), ...expand })), options.expand);
188
+ return markExpanded(fromExtendedJson(await documentApi.getDocument({ collectionName: name, documentId: idOf(id), ...expand })), options.expand);
174
189
  } catch (error) {
175
190
  if (error instanceof ResponseError && error.response.status === 404) {
176
191
  return null;
@@ -182,16 +197,16 @@ export function useMongocampCollection(name) {
182
197
  insertMany: (documents) => call(async () => documentApi.insertMany({ collectionName: name, requestBody: await Promise.all(documents.map(async (document) => toExtendedJson(await writable(document)))) })),
183
198
  replace: (target, document, options) => withRetry(target, options, (current) => call(async () => (requireComplete(document), documentApi.update({
184
199
  collectionName: name,
185
- documentId: documentId(current),
200
+ documentId: idOf(current),
186
201
  requestBody: toExtendedJson({ ...await writable(document), ...await versionOf(current) })
187
202
  })))),
188
203
  update: (target, changes, options) => withRetry(target, options, (current) => call(async () => documentApi.updateDocumentPartial({
189
204
  collectionName: name,
190
- documentId: documentId(current),
205
+ documentId: idOf(current),
191
206
  requestBody: toExtendedJson({ ...await writable(changes), ...await versionOf(current) })
192
207
  }))),
193
- remove: (id) => call(() => documentApi._delete({ collectionName: name, documentId: documentId(id) })),
194
- restore: (id) => call(() => documentApi.restoreDocument({ collectionName: name, documentId: documentId(id) })),
208
+ remove: (id) => call(() => documentApi._delete({ collectionName: name, documentId: idOf(id) })),
209
+ restore: (id) => call(() => documentApi.restoreDocument({ collectionName: name, documentId: idOf(id) })),
195
210
  isMine: (document) => {
196
211
  if (declaration.value === void 0) {
197
212
  void loadDeclaration();
@@ -201,10 +216,11 @@ export function useMongocampCollection(name) {
201
216
  return field !== void 0 && document !== null && document !== void 0 && session.value.profile.user !== "" && getPath(document, field) === session.value.profile.user;
202
217
  },
203
218
  history: (id, options = {}) => call(async () => {
204
- const records = await documentApi.getDocumentHistory({ collectionName: name, documentId: documentId(id), page: options.page ?? 1, rowsPerPage: options.rowsPerPage ?? defaultRows() });
219
+ const records = await documentApi.getDocumentHistory({ collectionName: name, documentId: idOf(id), page: options.page ?? 1, rowsPerPage: options.rowsPerPage ?? defaultRows() });
205
220
  return records.map((record) => fromExtendedJson(record));
206
221
  }),
207
222
  paginated: (options = {}) => {
223
+ let latest = 0;
208
224
  const state = {
209
225
  documents: ref([]),
210
226
  page: ref(1),
@@ -214,17 +230,24 @@ export function useMongocampCollection(name) {
214
230
  pending: ref(false),
215
231
  error: ref(null),
216
232
  load: async () => {
233
+ const request = ++latest;
217
234
  state.pending.value = true;
218
235
  state.error.value = null;
219
236
  try {
220
237
  const result = await findPage({ ...options, page: state.page.value, rowsPerPage: state.rowsPerPage.value });
221
- state.documents.value = result.documents;
222
- state.countRows.value = result.countRows;
223
- state.countPages.value = result.countPages;
238
+ if (request === latest) {
239
+ state.documents.value = result.documents;
240
+ state.countRows.value = result.countRows;
241
+ state.countPages.value = result.countPages;
242
+ }
224
243
  } catch (error) {
225
- state.error.value = error;
244
+ if (request === latest) {
245
+ state.error.value = error;
246
+ }
226
247
  } finally {
227
- state.pending.value = false;
248
+ if (request === latest) {
249
+ state.pending.value = false;
250
+ }
228
251
  }
229
252
  },
230
253
  goToPage: (target) => {
@@ -4,6 +4,7 @@ import { createSseParser } from "../utils/sse.js";
4
4
  import { markExpanded, useMongocampCollection } from "./mongocampCollection.js";
5
5
  import { useMongocampStorage } from "./mongocampStorage.js";
6
6
  import { useMongocampUrl } from "./mongocampUrl.js";
7
+ import { useRuntimeConfig } from "#app";
7
8
  const MaxBackoff = 3e4;
8
9
  const RefetchDebounce = 200;
9
10
  let pollingExplained = false;
@@ -11,6 +12,7 @@ export function useMongocampLive(name, options = {}) {
11
12
  const collection = useMongocampCollection(name);
12
13
  const url = useMongocampUrl();
13
14
  const session = useMongocampStorage();
15
+ const rows = options.rowsPerPage ?? useRuntimeConfig().public.mongocamp?.paginationSize;
14
16
  const mode = options.mode ?? (options.sort !== void 0 || options.page !== void 0 ? "refetch" : "patch");
15
17
  const documents = ref([]);
16
18
  const status = ref("idle");
@@ -30,14 +32,17 @@ export function useMongocampLive(name, options = {}) {
30
32
  error.value = caught;
31
33
  }
32
34
  };
35
+ const refetch = () => {
36
+ clearTimeout(debounce);
37
+ debounce = setTimeout(() => void reload(), RefetchDebounce);
38
+ };
33
39
  const apply = (event, data) => {
34
40
  if (event === "reset") {
35
41
  void reload();
36
42
  return;
37
43
  }
38
44
  if (mode === "refetch") {
39
- clearTimeout(debounce);
40
- debounce = setTimeout(() => void reload(), RefetchDebounce);
45
+ refetch();
41
46
  return;
42
47
  }
43
48
  const id = documentId(fromExtendedJson({ _id: data.id }));
@@ -47,6 +52,10 @@ export function useMongocampLive(name, options = {}) {
47
52
  } else if (event === "upsert" && data.document !== void 0) {
48
53
  const document = markExpanded(fromExtendedJson(data.document), options.expand);
49
54
  const index = documents.value.findIndex((entry) => documentId(entry) === id);
55
+ if (index < 0 && typeof rows === "number" && rows > 0 && documents.value.length >= rows) {
56
+ refetch();
57
+ return;
58
+ }
50
59
  documents.value = index < 0 ? [...documents.value, document] : documents.value.map((entry, position) => position === index ? document : entry);
51
60
  }
52
61
  };
@@ -98,7 +107,14 @@ export function useMongocampLive(name, options = {}) {
98
107
  if (message.id !== void 0) {
99
108
  lastEventId = message.id;
100
109
  }
101
- apply(message.event, message.data === "" ? {} : JSON.parse(message.data));
110
+ let data;
111
+ try {
112
+ data = message.data === "" ? {} : JSON.parse(message.data);
113
+ } catch {
114
+ error.value = new Error(`live updates: the data of the event ${message.event} is no JSON`);
115
+ return;
116
+ }
117
+ apply(message.event, data);
102
118
  });
103
119
  const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
104
120
  for (; ; ) {
@@ -131,6 +147,12 @@ export function useMongocampLive(name, options = {}) {
131
147
  }
132
148
  stopped = false;
133
149
  await reload();
150
+ const failedStatus = error.value?.status;
151
+ if (failedStatus === 401 || failedStatus === 403) {
152
+ status.value = "error";
153
+ stopped = true;
154
+ return;
155
+ }
134
156
  void connect();
135
157
  };
136
158
  const stop = () => {
@@ -31,15 +31,24 @@ export function usePaginatedFind(collectionName, options = {}) {
31
31
  const documents = ref([]);
32
32
  const pending = ref(false);
33
33
  const error = ref(null);
34
+ let latest = 0;
34
35
  async function load() {
36
+ const request = ++latest;
35
37
  pending.value = true;
36
38
  error.value = null;
37
39
  try {
38
- documents.value = await find(collectionName, options.filter, page.value, options.sort, options.projection, rowsPerPage.value, options.filterCaseInsensitive);
40
+ const loaded = await find(collectionName, options.filter, page.value, options.sort, options.projection, rowsPerPage.value, options.filterCaseInsensitive);
41
+ if (request === latest) {
42
+ documents.value = loaded;
43
+ }
39
44
  } catch (e) {
40
- error.value = e;
45
+ if (request === latest) {
46
+ error.value = e;
47
+ }
41
48
  } finally {
42
- pending.value = false;
49
+ if (request === latest) {
50
+ pending.value = false;
51
+ }
43
52
  }
44
53
  }
45
54
  function goToPage(target) {
@@ -0,0 +1,8 @@
1
+ /**
2
+ * The BSON values of decoded documents in the payload of server side rendering (2.5.0): `useAsyncData(() => orders.find())` puts
3
+ * `ObjectId`s, `Decimal128`s, ... into the payload, which devalue cannot write (before: a 500 of the page as soon as a document was found).
4
+ * They travel as canonical Extended JSON and are values again in the browser. A payload plugin, so the reviver exists before the payload
5
+ * is read.
6
+ */
7
+ declare const _default: import("nuxt/app").Plugin<Record<string, unknown>> & import("nuxt/app").ObjectPlugin<Record<string, unknown>>;
8
+ export default _default;
@@ -0,0 +1,6 @@
1
+ import { reduceBson, reviveBson } from "../utils/bsonPayload.js";
2
+ import { definePayloadPlugin, definePayloadReducer, definePayloadReviver } from "#app";
3
+ export default definePayloadPlugin(() => {
4
+ definePayloadReducer("MongocampBson", reduceBson);
5
+ definePayloadReviver("MongocampBson", reviveBson);
6
+ });
@@ -1,5 +1,9 @@
1
1
  import type { H3Event } from 'h3';
2
- /** The generated client for the server code; `event` is kept for the signature of the earlier versions. */
2
+ /**
3
+ * The generated client for the server code, against the external server at the module option `url`; `event` is kept for the signature of
4
+ * the earlier versions. With the embedded server the module registers `server/mongocamp/embedded-api.ts` under this name instead (2.5.0),
5
+ * so an application with an external server does not bundle the core and the MongoDB driver.
6
+ */
3
7
  export declare function useMongocampApi(_event: H3Event, token?: string): {
4
8
  adminApi: import("../../api/index.js").AdminApi;
5
9
  applicationApi: import("../../api/index.js").ApplicationApi;
@@ -1,14 +1,6 @@
1
1
  import { useRuntimeConfig } from "nitro/runtime-config";
2
- import { useMongocampCore } from "../mongocamp/core.js";
3
2
  import { useMongocampServerApi } from "./mongocampServerApi.js";
4
- const EmbeddedBase = "http://mongocamp.embedded";
5
3
  export function useMongocampApi(_event, token) {
6
4
  const config = useRuntimeConfig();
7
- const apiKey = config.mongocampApiKey;
8
- const embedded = config.mongocampServer;
9
- if (embedded?.enabled) {
10
- const fetchApi = async (input, init) => (await useMongocampCore(embedded)).fetch(new Request(input, init));
11
- return useMongocampServerApi(EmbeddedBase, apiKey, token, fetchApi);
12
- }
13
- return useMongocampServerApi(config.public.mongocamp?.url, apiKey, token);
5
+ return useMongocampServerApi(config.public.mongocamp?.url, config.mongocampApiKey, token);
14
6
  }
@@ -1,4 +1,8 @@
1
1
  import type { FetchAPI } from '../../api/index.js';
2
+ /**
3
+ * The generated client for server code. With an api key the calls run with the rights of the key's user, also when a token is given (the
4
+ * key wins, as since 1.x); in development a warning says so once (2.5.0).
5
+ */
2
6
  export declare function useMongocampServerApi(url: string, key?: string, token?: string, fetchApi?: FetchAPI): {
3
7
  adminApi: import("../../api/index.js").AdminApi;
4
8
  applicationApi: import("../../api/index.js").ApplicationApi;
@@ -1,6 +1,11 @@
1
1
  import { Configuration } from "../../api/index.js";
2
2
  import { createMongocampApis } from "../../utils/createMongocampApis.js";
3
+ let precedenceExplained = false;
3
4
  export function useMongocampServerApi(url, key, token, fetchApi) {
5
+ if (import.meta.dev && key && token && !precedenceExplained) {
6
+ precedenceExplained = true;
7
+ console.warn("[mongocamp] useMongocampApi: the api key of the module options wins over the token of the user; the calls run with the rights of the key's user");
8
+ }
4
9
  const credentials = key && key.length > 0 ? { apiKey: key } : token && token.length > 0 ? { accessToken: token } : {};
5
10
  return createMongocampApis(new Configuration({ basePath: url, ...credentials, ...fetchApi ? { fetchApi } : {} }));
6
11
  }
@@ -17,7 +17,7 @@ export interface EmbeddedServerConfig {
17
17
  * The MongoCamp server of this Nitro instance, created with the first request. The env variables of the Scala server (`CONNECTION_*`,
18
18
  * `AUTH_*`, ...) are read by the core and win over `config`.
19
19
  */
20
- export declare function useMongocampCore(settings?: EmbeddedServerConfig): Promise<MongocampServer>;
20
+ export declare function useMongocampCore(settings?: EmbeddedServerConfig | undefined): Promise<MongocampServer>;
21
21
  /** Closes the server (database, scheduler, timers) when Nitro stops. */
22
22
  export declare function closeMongocampCore(): Promise<void>;
23
23
  /** A request for the core: the path without the prefix, the body as a stream. */
@@ -3,7 +3,7 @@ import { useNitroApp } from "nitro/app";
3
3
  import { useRuntimeConfig } from "nitro/runtime-config";
4
4
  let server;
5
5
  export function useMongocampCore(settings = useRuntimeConfig().mongocampServer) {
6
- if (!settings.enabled) {
6
+ if (!settings?.enabled) {
7
7
  return Promise.reject(new Error('[mongocamp] the embedded server is not enabled (module option "server.enabled")'));
8
8
  }
9
9
  server ??= createMongocampServer({
@@ -0,0 +1,18 @@
1
+ import type { H3Event } from 'h3';
2
+ /**
3
+ * `useMongocampApi(event, token?)` of an application with the embedded server: the generated client, answered in-process by the core (no
4
+ * network hop to the own Nitro). Registered by the module instead of `server/composables/mongocampApi.ts` when `server.enabled`.
5
+ */
6
+ export declare function useMongocampApi(_event: H3Event, token?: string): {
7
+ adminApi: import("../../api/index.js").AdminApi;
8
+ applicationApi: import("../../api/index.js").ApplicationApi;
9
+ authApi: import("../../api/index.js").AuthApi;
10
+ bucketApi: import("../../api/index.js").BucketApi;
11
+ collectionApi: import("../../api/index.js").CollectionApi;
12
+ databaseApi: import("../../api/index.js").DatabaseApi;
13
+ documentApi: import("../../api/index.js").DocumentApi;
14
+ fileApi: import("../../api/index.js").FileApi;
15
+ indexApi: import("../../api/index.js").IndexApi;
16
+ systemApi: import("../../api/index.js").SystemApi;
17
+ jobApi: import("../../api/index.js").JobsApi;
18
+ };
@@ -0,0 +1,10 @@
1
+ import { useRuntimeConfig } from "nitro/runtime-config";
2
+ import { useMongocampServerApi } from "../composables/mongocampServerApi.js";
3
+ import { useMongocampCore } from "./core.js";
4
+ const EmbeddedBase = "http://mongocamp.embedded";
5
+ export function useMongocampApi(_event, token) {
6
+ const config = useRuntimeConfig();
7
+ const embedded = config.mongocampServer;
8
+ const fetchApi = async (input, init) => (await useMongocampCore(embedded)).fetch(new Request(input, init));
9
+ return useMongocampServerApi(EmbeddedBase, config.mongocampApiKey, token, fetchApi);
10
+ }
@@ -0,0 +1,21 @@
1
+ import type { EffectScope, Ref } from 'vue';
2
+ import type { CollectionDeclaration } from '../api/index.js';
3
+ import type { createMongocampApis } from './createMongocampApis.js';
4
+ /**
5
+ * The state of the module that must not outlive one Nuxt app (2.5.0): on the server a Nuxt app is one request, so nothing of a user (the
6
+ * declarations their grants could read, the clients with their token, timers) is shared with the request of another user; in the browser
7
+ * there is one app. Kept in a `WeakMap` by app: it ends with the request, nothing is serialized into the payload (unlike `useState`).
8
+ */
9
+ export interface MongocampAppState {
10
+ /** The declarations of the collections by `url|name`; `null`: not declared (404). A failed lookup is not kept. */
11
+ declarations: Map<string, Ref<CollectionDeclaration | null | undefined>>;
12
+ /** The generated clients by url (the token is read per request). */
13
+ apis: Map<string, ReturnType<typeof createMongocampApis>>;
14
+ /** The token refresh of the session: one timer and one watcher per app, however many components use `useMongocampAuth()`. */
15
+ auth: {
16
+ timer?: ReturnType<typeof setInterval>;
17
+ scope?: EffectScope;
18
+ };
19
+ }
20
+ /** The state of the current Nuxt app. */
21
+ export declare function mongocampAppState(): MongocampAppState;
@@ -0,0 +1,11 @@
1
+ import { useNuxtApp } from "#app";
2
+ const states = /* @__PURE__ */ new WeakMap();
3
+ export function mongocampAppState() {
4
+ const app = useNuxtApp();
5
+ let state = states.get(app);
6
+ if (state === void 0) {
7
+ state = { declarations: /* @__PURE__ */ new Map(), apis: /* @__PURE__ */ new Map(), auth: {} };
8
+ states.set(app, state);
9
+ }
10
+ return state;
11
+ }
@@ -0,0 +1,8 @@
1
+ /** A value of the BSON library (`ObjectId`, `Decimal128`, `Long`, `Binary`, ...): every one has `_bsontype`. */
2
+ export declare function isBsonValue(value: unknown): value is {
3
+ _bsontype: string;
4
+ };
5
+ /** The payload form of a BSON value (canonical Extended JSON), `false` for any other value (the reducer does not apply). */
6
+ export declare function reduceBson(value: unknown): unknown;
7
+ /** The BSON value of its payload form. */
8
+ export declare function reviveBson(value: unknown): unknown;
@@ -0,0 +1,10 @@
1
+ import { EJSON } from "bson";
2
+ export function isBsonValue(value) {
3
+ return value !== null && typeof value === "object" && "_bsontype" in value;
4
+ }
5
+ export function reduceBson(value) {
6
+ return isBsonValue(value) && EJSON.serialize({ value }, { relaxed: false }).value;
7
+ }
8
+ export function reviveBson(value) {
9
+ return EJSON.deserialize({ value }, { relaxed: false }).value;
10
+ }
@@ -1,2 +1,6 @@
1
1
  export type FilterFieldValue = string | number | boolean | Date;
2
+ /**
3
+ * A Lucene filter `field: value` for one field (`findByField`). Texts and dates are a quoted phrase in which `\\` and `"` are escaped; the
4
+ * field name is escaped as a whole (2.5.0: before, a `\\` in the value or a `:` / space in the field could change the query).
5
+ */
2
6
  export declare function buildFieldFilterExpression(field: string, value: FilterFieldValue): string;
@@ -1,7 +1,9 @@
1
+ const fieldSpecial = /[+\-&|!(){}[\]^"~*?:\\/\s]/g;
1
2
  export function buildFieldFilterExpression(field, value) {
3
+ const escapedField = field.replace(fieldSpecial, (match) => `\\${match}`);
2
4
  if (typeof value === "number" || typeof value === "boolean")
3
- return `${field}: ${value}`;
5
+ return `${escapedField}: ${value}`;
4
6
  const stringValue = value instanceof Date ? value.toISOString() : value;
5
- const escapedValue = stringValue.replace(/"/g, '\\"');
6
- return `${field}: "${escapedValue}"`;
7
+ const escapedValue = stringValue.replace(/[\\"]/g, (match) => `\\${match}`);
8
+ return `${escapedField}: "${escapedValue}"`;
7
9
  }
@@ -1,7 +1,13 @@
1
1
  export function createSseParser(onEvent) {
2
2
  let buffer = "";
3
+ let carriedReturn = false;
3
4
  return (chunk) => {
4
- buffer += chunk.replace(/\r\n?/g, "\n");
5
+ let text = (carriedReturn ? "\r" : "") + chunk;
6
+ carriedReturn = text.endsWith("\r");
7
+ if (carriedReturn) {
8
+ text = text.slice(0, -1);
9
+ }
10
+ buffer += text.replace(/\r\n?/g, "\n");
5
11
  let end = buffer.indexOf("\n\n");
6
12
  while (end >= 0) {
7
13
  const block = buffer.slice(0, end);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sfxcode/nuxt-mongocamp-server",
3
- "version": "2.4.0",
3
+ "version": "2.5.0",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -24,13 +24,15 @@
24
24
  "files": [
25
25
  "dist"
26
26
  ],
27
+ "engines": {
28
+ "node": ">=22.22.0"
29
+ },
27
30
  "build": {
28
31
  "failOnWarn": false
29
32
  },
30
33
  "dependencies": {
31
34
  "@nuxt/kit": "^4.7.0",
32
- "@sfxcode/mongocamp-server-core": "2.4.0",
33
- "@vueuse/nuxt": "^15.1.0",
35
+ "@sfxcode/mongocamp-server-core": "2.5.0",
34
36
  "bson": "^7.3.4",
35
37
  "consola": "^3.4.2",
36
38
  "defu": "^6.1.7"
@@ -44,6 +46,7 @@
44
46
  "@openapitools/openapi-generator-cli": "^2.44.0",
45
47
  "@types/node": "^26.6.11",
46
48
  "@unocss/nuxt": "^66.13.0",
49
+ "@vitest/coverage-v8": "5.1.2",
47
50
  "changelogen": "^0.6.2",
48
51
  "eslint": "^10.16.0",
49
52
  "evlog": "2.37.1",
@@ -54,6 +57,7 @@
54
57
  "srvx": "1.0.8",
55
58
  "typescript": "6.0.3",
56
59
  "vitest": "^5.1.2",
60
+ "vue-tsc": "^3.3.14",
57
61
  "zod": "^4.6.7"
58
62
  },
59
63
  "peerDependencies": {
@@ -63,7 +67,7 @@
63
67
  "scripts": {
64
68
  "dev": "nuxi dev playground",
65
69
  "dev:build": "nuxi build playground",
66
- "dev:prepare": "nuxt-module-build build --stub && nuxt-module-build prepare && nuxi prepare playground",
70
+ "dev:prepare": "nuxt-module-build build --stub && nuxt-module-build prepare && nuxi prepare playground && nuxi prepare docs/tutorial/app",
67
71
  "release": "npm run lint && npm run test && npm run prepack && changelogen --minor --release --no-commit --no-tag && node scripts/sync-versions.mjs --commit && pnpm -r --include-workspace-root --filter @sfxcode/mongocamp-server-core --filter @sfxcode/nuxt-mongocamp-server publish --access public && git push --follow-tags",
68
72
  "release:next": "npm run lint && npm run test && npm run prepack && changelogen --prerelease=alpha --release --no-commit --no-tag && node scripts/sync-versions.mjs --commit && pnpm -r --include-workspace-root --filter @sfxcode/mongocamp-server-core --filter @sfxcode/nuxt-mongocamp-server publish --access public --tag next && git push --follow-tags",
69
73
  "lint": "eslint .",
@@ -73,12 +77,16 @@
73
77
  "test:coverage": "vitest run --coverage",
74
78
  "test:update": "vitest run --update",
75
79
  "test:update:watch": "vitest run --update --watch",
76
- "api-codegen": "openapi-generator-cli generate -i ./openapi/docs.yaml -g typescript-fetch -o src/runtime/api --additional-properties=typescriptThreePlus=true,supportsES6=true",
80
+ "api-codegen": "openapi-generator-cli generate -i ./openapi/docs.yaml -g typescript-fetch -o src/runtime/api --additional-properties=typescriptThreePlus=true,supportsES6=true && node scripts/api-codegen-post.mjs",
77
81
  "test:contract": "vitest run --config vitest.contract.config.ts",
78
- "typecheck:server": "pnpm --filter @sfxcode/mongocamp-server-core typecheck",
79
82
  "sync-versions": "node scripts/sync-versions.mjs",
80
83
  "docs:dev": "pnpm --filter mongocamp-docs dev",
81
84
  "docs:build": "pnpm --filter mongocamp-docs build",
82
- "docs:preview": "pnpm --filter mongocamp-docs preview"
85
+ "docs:preview": "pnpm --filter mongocamp-docs preview",
86
+ "codegen": "pnpm api-codegen && pnpm --filter @sfxcode/mongocamp-server-core api-types && pnpm --filter @sfxcode/mongocamp-server-core operations",
87
+ "codegen:check": "pnpm codegen && git diff --exit-code -- src/runtime/api packages/server-core/src/generated",
88
+ "typecheck": "vue-tsc --noEmit && vue-tsc -b playground --noEmit && vue-tsc -b docs/tutorial/app --noEmit && pnpm -r typecheck",
89
+ "test:contract:coverage": "vitest run --config vitest.contract.config.ts --coverage",
90
+ "test:e2e": "vitest run --project e2e"
83
91
  }
84
92
  }