@sfxcode/nuxt-mongocamp-server 2.3.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 (62) hide show
  1. package/README.md +24 -2
  2. package/dist/module.d.mts +10 -4
  3. package/dist/module.json +1 -1
  4. package/dist/module.mjs +41 -21
  5. package/dist/runtime/api/.openapi-generator/FILES +4 -0
  6. package/dist/runtime/api/apis/CollectionApi.d.ts +6 -6
  7. package/dist/runtime/api/apis/CollectionApi.js +4 -4
  8. package/dist/runtime/api/apis/DocumentApi.d.ts +42 -14
  9. package/dist/runtime/api/apis/DocumentApi.js +27 -6
  10. package/dist/runtime/api/docs/CollectionApi.md +6 -6
  11. package/dist/runtime/api/docs/CollectionDeclaration.md +4 -0
  12. package/dist/runtime/api/docs/CollectionDeclarationIndexesInner.md +38 -0
  13. package/dist/runtime/api/docs/CollectionDeclarationRefsInner.md +38 -0
  14. package/dist/runtime/api/docs/DocumentApi.md +47 -26
  15. package/dist/runtime/api/docs/ExportRequest.md +2 -0
  16. package/dist/runtime/api/docs/MongoFindRequest.md +2 -0
  17. package/dist/runtime/api/docs/SearchRequest.md +2 -0
  18. package/dist/runtime/api/models/CollectionDeclaration.d.ts +10 -0
  19. package/dist/runtime/api/models/CollectionDeclaration.js +14 -0
  20. package/dist/runtime/api/models/CollectionDeclarationIndexesInner.d.ts +40 -0
  21. package/dist/runtime/api/models/CollectionDeclarationIndexesInner.js +32 -0
  22. package/dist/runtime/api/models/CollectionDeclarationRefsInner.d.ts +38 -0
  23. package/dist/runtime/api/models/CollectionDeclarationRefsInner.js +31 -0
  24. package/dist/runtime/api/models/ErrorDescription.d.ts +1 -1
  25. package/dist/runtime/api/models/ExportRequest.d.ts +4 -0
  26. package/dist/runtime/api/models/ExportRequest.js +4 -2
  27. package/dist/runtime/api/models/MongoFindRequest.d.ts +4 -0
  28. package/dist/runtime/api/models/MongoFindRequest.js +4 -2
  29. package/dist/runtime/api/models/SearchRequest.d.ts +4 -0
  30. package/dist/runtime/api/models/SearchRequest.js +4 -2
  31. package/dist/runtime/api/models/index.d.ts +2 -0
  32. package/dist/runtime/api/models/index.js +2 -0
  33. package/dist/runtime/composables/mongocampApi.d.ts +4 -0
  34. package/dist/runtime/composables/mongocampApi.js +10 -2
  35. package/dist/runtime/composables/mongocampAuth.js +29 -25
  36. package/dist/runtime/composables/mongocampCollection.d.ts +50 -11
  37. package/dist/runtime/composables/mongocampCollection.js +85 -21
  38. package/dist/runtime/composables/mongocampLive.d.ts +5 -2
  39. package/dist/runtime/composables/mongocampLive.js +30 -5
  40. package/dist/runtime/composables/mongocampSearch.js +12 -3
  41. package/dist/runtime/plugins/bson-payload.d.ts +8 -0
  42. package/dist/runtime/plugins/bson-payload.js +6 -0
  43. package/dist/runtime/server/composables/mongocampApi.d.ts +5 -1
  44. package/dist/runtime/server/composables/mongocampApi.js +1 -9
  45. package/dist/runtime/server/composables/mongocampServerApi.d.ts +4 -0
  46. package/dist/runtime/server/composables/mongocampServerApi.js +5 -0
  47. package/dist/runtime/server/composables/mongocampServerCollection.d.ts +20 -0
  48. package/dist/runtime/server/composables/mongocampServerCollection.js +12 -0
  49. package/dist/runtime/server/mongocamp/core.d.ts +1 -1
  50. package/dist/runtime/server/mongocamp/core.js +1 -1
  51. package/dist/runtime/server/mongocamp/embedded-api.d.ts +18 -0
  52. package/dist/runtime/server/mongocamp/embedded-api.js +10 -0
  53. package/dist/runtime/types/collections.d.ts +10 -0
  54. package/dist/runtime/utils/appState.d.ts +21 -0
  55. package/dist/runtime/utils/appState.js +11 -0
  56. package/dist/runtime/utils/bsonPayload.d.ts +8 -0
  57. package/dist/runtime/utils/bsonPayload.js +10 -0
  58. package/dist/runtime/utils/buildFieldFilterExpression.d.ts +4 -0
  59. package/dist/runtime/utils/buildFieldFilterExpression.js +5 -3
  60. package/dist/runtime/utils/sse.d.ts +1 -1
  61. package/dist/runtime/utils/sse.js +7 -1
  62. package/package.json +15 -7
@@ -1,11 +1,19 @@
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";
6
7
  import { useMongocampStorage } from "./mongocampStorage.js";
7
8
  import { useMongocampUrl } from "./mongocampUrl.js";
8
9
  import { useRuntimeConfig } from "#app";
10
+ export const ExpandedFields = Symbol.for("mongocamp.expanded");
11
+ export function markExpanded(document, fields) {
12
+ if (fields !== void 0 && fields.length > 0) {
13
+ Object.defineProperty(document, ExpandedFields, { value: [...fields], enumerable: true, configurable: true, writable: true });
14
+ }
15
+ return document;
16
+ }
9
17
  const VersionConflict = 4092;
10
18
  async function requestError(error) {
11
19
  const { current, ...described } = await toMongocampError(error);
@@ -14,7 +22,6 @@ async function requestError(error) {
14
22
  ...current !== void 0 ? { current: fromExtendedJson(current) } : {}
15
23
  });
16
24
  }
17
- const declarations = /* @__PURE__ */ new Map();
18
25
  function getPath(document, path) {
19
26
  let current = document;
20
27
  for (const segment of path.split(".")) {
@@ -43,6 +50,29 @@ function withoutPaths(document, paths) {
43
50
  }
44
51
  return copy;
45
52
  }
53
+ function setPathOf(document, path, value) {
54
+ const segments = path.split(".");
55
+ let current = document;
56
+ for (const segment of segments.slice(0, -1)) {
57
+ const next = current[segment];
58
+ if (next === null || typeof next !== "object") {
59
+ return;
60
+ }
61
+ current = next;
62
+ }
63
+ current[segments.at(-1)] = value;
64
+ }
65
+ function idOfReference(value) {
66
+ return isDocument(value) ? value._id : value;
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
+ }
46
76
  function isDocument(target) {
47
77
  return target !== null && typeof target === "object" && "_id" in target && typeof target.toHexString !== "function";
48
78
  }
@@ -57,6 +87,7 @@ export function useMongocampCollection(name) {
57
87
  const session = useMongocampStorage();
58
88
  const defaultRows = () => config.public.mongocamp?.paginationSize;
59
89
  const declarationKey = `${useMongocampUrl()}|${name}`;
90
+ const { declarations } = mongocampAppState();
60
91
  const declaration = declarations.get(declarationKey) ?? ref(void 0);
61
92
  declarations.set(declarationKey, declaration);
62
93
  let loading;
@@ -64,15 +95,38 @@ export function useMongocampCollection(name) {
64
95
  if (declaration.value !== void 0) {
65
96
  return Promise.resolve(declaration.value);
66
97
  }
67
- loading ??= Promise.resolve().then(() => collectionApi.getCollectionDeclaration({ collectionName: name })).catch(() => null).then((loaded) => {
98
+ loading ??= Promise.resolve().then(() => collectionApi.getCollectionDeclaration({ collectionName: name })).then((loaded) => {
68
99
  declaration.value = loaded;
69
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;
70
107
  });
71
108
  return loading;
72
109
  };
73
110
  const writable = async (document) => {
74
111
  const loaded = await loadDeclaration();
75
- return loaded === null ? { ...document } : withoutPaths(document, [...loaded.systemFields, ...loaded.protectedFields]);
112
+ if (loaded === null) {
113
+ return { ...document };
114
+ }
115
+ const body = withoutPaths(document, [...loaded.systemFields, ...loaded.protectedFields]);
116
+ for (const reference of loaded.refs ?? []) {
117
+ const value = getPath(body, reference.field);
118
+ if (value !== null && typeof value === "object") {
119
+ setPathOf(body, reference.field, Array.isArray(value) ? value.map(idOfReference) : idOfReference(value));
120
+ }
121
+ }
122
+ return body;
123
+ };
124
+ const requireComplete = (document) => {
125
+ const fields = document?.[ExpandedFields];
126
+ const lossy = (fields ?? []).find((field) => getPath(document, field) === null || Array.isArray(getPath(document, field)));
127
+ if (lossy !== void 0) {
128
+ throw Object.assign(new Error(`replace: ${lossy} was read with expand, references you cannot read are not in it; use update with the changed fields`), { status: 400, isConflict: false });
129
+ }
76
130
  };
77
131
  const versionOf = async (target) => {
78
132
  const loaded = await loadDeclaration();
@@ -100,7 +154,7 @@ export function useMongocampCollection(name) {
100
154
  throw await requestError(error);
101
155
  }
102
156
  };
103
- const decode = (documents) => documents.map((document) => fromExtendedJson(document));
157
+ const decode = (documents, expand) => documents.map((document) => markExpanded(fromExtendedJson(document), expand));
104
158
  const listParameters = (options) => ({
105
159
  collectionName: name,
106
160
  filter: options.filter,
@@ -109,14 +163,15 @@ export function useMongocampCollection(name) {
109
163
  page: options.page ?? 1,
110
164
  rowsPerPage: options.rowsPerPage ?? defaultRows(),
111
165
  filterCaseInsensitive: options.filterCaseInsensitive,
112
- ...options.withDeleted ? { withDeleted: true } : {}
166
+ ...options.withDeleted ? { withDeleted: true } : {},
167
+ ...options.expand !== void 0 && options.expand.length > 0 ? { expand: [...options.expand] } : {}
113
168
  });
114
169
  const findPage = (options = {}) => call(async () => {
115
170
  const parameters = listParameters(options);
116
171
  const response = await documentApi.listDocumentsRaw(parameters);
117
172
  const headers = response.raw.headers;
118
173
  return {
119
- documents: decode(await response.value()),
174
+ documents: decode(await response.value(), options.expand),
120
175
  page: parameters.page,
121
176
  rowsPerPage: parameters.rowsPerPage,
122
177
  countRows: headerNumber(headers, "x-pagination-count-rows"),
@@ -125,11 +180,12 @@ export function useMongocampCollection(name) {
125
180
  });
126
181
  const collection = {
127
182
  name,
128
- find: (options) => call(async () => decode(await documentApi.listDocuments(listParameters(options ?? {})))),
183
+ find: (options) => call(async () => decode(await documentApi.listDocuments(listParameters(options ?? {})), options?.expand)),
129
184
  findPage,
130
- findById: async (id) => {
185
+ findById: async (id, options = {}) => {
186
+ const expand = options.expand !== void 0 && options.expand.length > 0 ? { expand: [...options.expand] } : {};
131
187
  try {
132
- return fromExtendedJson(await documentApi.getDocument({ collectionName: name, documentId: documentId(id) }));
188
+ return markExpanded(fromExtendedJson(await documentApi.getDocument({ collectionName: name, documentId: idOf(id), ...expand })), options.expand);
133
189
  } catch (error) {
134
190
  if (error instanceof ResponseError && error.response.status === 404) {
135
191
  return null;
@@ -139,18 +195,18 @@ export function useMongocampCollection(name) {
139
195
  },
140
196
  insert: (document) => call(async () => documentApi.insert({ collectionName: name, requestBody: toExtendedJson(await writable(document)) })),
141
197
  insertMany: (documents) => call(async () => documentApi.insertMany({ collectionName: name, requestBody: await Promise.all(documents.map(async (document) => toExtendedJson(await writable(document)))) })),
142
- replace: (target, document, options) => withRetry(target, options, (current) => call(async () => documentApi.update({
198
+ replace: (target, document, options) => withRetry(target, options, (current) => call(async () => (requireComplete(document), documentApi.update({
143
199
  collectionName: name,
144
- documentId: documentId(current),
200
+ documentId: idOf(current),
145
201
  requestBody: toExtendedJson({ ...await writable(document), ...await versionOf(current) })
146
- }))),
202
+ })))),
147
203
  update: (target, changes, options) => withRetry(target, options, (current) => call(async () => documentApi.updateDocumentPartial({
148
204
  collectionName: name,
149
- documentId: documentId(current),
205
+ documentId: idOf(current),
150
206
  requestBody: toExtendedJson({ ...await writable(changes), ...await versionOf(current) })
151
207
  }))),
152
- remove: (id) => call(() => documentApi._delete({ collectionName: name, documentId: documentId(id) })),
153
- 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) })),
154
210
  isMine: (document) => {
155
211
  if (declaration.value === void 0) {
156
212
  void loadDeclaration();
@@ -160,10 +216,11 @@ export function useMongocampCollection(name) {
160
216
  return field !== void 0 && document !== null && document !== void 0 && session.value.profile.user !== "" && getPath(document, field) === session.value.profile.user;
161
217
  },
162
218
  history: (id, options = {}) => call(async () => {
163
- 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() });
164
220
  return records.map((record) => fromExtendedJson(record));
165
221
  }),
166
222
  paginated: (options = {}) => {
223
+ let latest = 0;
167
224
  const state = {
168
225
  documents: ref([]),
169
226
  page: ref(1),
@@ -173,17 +230,24 @@ export function useMongocampCollection(name) {
173
230
  pending: ref(false),
174
231
  error: ref(null),
175
232
  load: async () => {
233
+ const request = ++latest;
176
234
  state.pending.value = true;
177
235
  state.error.value = null;
178
236
  try {
179
237
  const result = await findPage({ ...options, page: state.page.value, rowsPerPage: state.rowsPerPage.value });
180
- state.documents.value = result.documents;
181
- state.countRows.value = result.countRows;
182
- 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
+ }
183
243
  } catch (error) {
184
- state.error.value = error;
244
+ if (request === latest) {
245
+ state.error.value = error;
246
+ }
185
247
  } finally {
186
- state.pending.value = false;
248
+ if (request === latest) {
249
+ state.pending.value = false;
250
+ }
187
251
  }
188
252
  },
189
253
  goToPage: (target) => {
@@ -1,8 +1,8 @@
1
1
  import type { Ref } from 'vue';
2
- import type { MongocampCollectionName, MongocampDocument } from '../types/collections.js';
2
+ import type { MongocampCollectionName, MongocampDocument, MongocampExpandedDocument, MongocampRefName } from '../types/collections.js';
3
3
  import type { CollectionFindOptions, MongocampRequestError } from './mongocampCollection.js';
4
4
  /**
5
- * A live list in one line (2.4.0): `const { documents, status } = useMongocampLive('orders', { filter: 'status:open' })`. The documents
5
+ * A live list in one line (2.3.0): `const { documents, status } = useMongocampLive('orders', { filter: 'status:open' })`. The documents
6
6
  * are loaded with the typed composable and kept in sync with the live updates of the server (Server-Sent Events on change streams):
7
7
  *
8
8
  * - mode `patch` (default without `sort` and `page`): an update changes the document in the list, a new one is added, a removed one goes;
@@ -29,5 +29,8 @@ export interface LiveState<T> {
29
29
  stop: () => void;
30
30
  reload: () => Promise<void>;
31
31
  }
32
+ export declare function useMongocampLive<N extends MongocampCollectionName, K extends MongocampRefName<N>>(name: N, options: Omit<LiveOptions, 'expand'> & {
33
+ expand: readonly K[];
34
+ }): LiveState<MongocampExpandedDocument<N, K>>;
32
35
  export declare function useMongocampLive<N extends MongocampCollectionName>(name: N, options?: LiveOptions): LiveState<MongocampDocument<N>>;
33
36
  export declare function useMongocampLive<T extends object = Record<string, unknown>>(name: string, options?: LiveOptions): LiveState<T>;
@@ -1,9 +1,10 @@
1
1
  import { getCurrentInstance, getCurrentScope, onMounted, onScopeDispose, ref } from "vue";
2
2
  import { documentId, fromExtendedJson } from "../utils/extendedJson.js";
3
3
  import { createSseParser } from "../utils/sse.js";
4
- import { useMongocampCollection } from "./mongocampCollection.js";
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 }));
@@ -45,8 +50,12 @@ export function useMongocampLive(name, options = {}) {
45
50
  if (event === "remove") {
46
51
  documents.value = others;
47
52
  } else if (event === "upsert" && data.document !== void 0) {
48
- const document = fromExtendedJson(data.document);
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
  };
@@ -69,6 +78,9 @@ export function useMongocampLive(name, options = {}) {
69
78
  if (options.filter !== void 0 && options.filter !== "") {
70
79
  query.set("filter", options.filter);
71
80
  }
81
+ for (const field of options.expand ?? []) {
82
+ query.append("expand", field);
83
+ }
72
84
  if (options.filterCaseInsensitive) {
73
85
  query.set("filterCaseInsensitive", "true");
74
86
  }
@@ -95,7 +107,14 @@ export function useMongocampLive(name, options = {}) {
95
107
  if (message.id !== void 0) {
96
108
  lastEventId = message.id;
97
109
  }
98
- 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);
99
118
  });
100
119
  const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
101
120
  for (; ; ) {
@@ -128,6 +147,12 @@ export function useMongocampLive(name, options = {}) {
128
147
  }
129
148
  stopped = false;
130
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
+ }
131
156
  void connect();
132
157
  };
133
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
  }
@@ -0,0 +1,20 @@
1
+ import type { AuthorizedUser, ServerCollection } from '@sfxcode/mongocamp-server-core';
2
+ import type { H3Event } from 'h3';
3
+ import type { MongocampCollectionName, MongocampDocument, MongocampDocumentInput } from '../../types/collections.js';
4
+ /**
5
+ * The documents of a collection in a Nitro route (2.4.0), typed like `useMongocampCollection` in the browser and with the same rules as
6
+ * the API: grants, read scope (owner, soft delete, hooks), validation, behaviours (timestamps, version, audit) and events.
7
+ *
8
+ * export default defineEventHandler(async (event) => {
9
+ * const orders = useMongocampServerCollection('orders', { user: event }) // the caller of the request
10
+ * return orders.insert({ customer: 'Ada' })
11
+ * })
12
+ *
13
+ * `user`: the event (its credentials), a user id, an authorized user, or `'system'` (an administrator without grant checks and owner rules,
14
+ * for jobs and seeds). Needs the embedded server.
15
+ */
16
+ export interface ServerCollectionUserOptions {
17
+ user: H3Event | string | AuthorizedUser | 'system';
18
+ }
19
+ export declare function useMongocampServerCollection<N extends MongocampCollectionName>(name: N, options: ServerCollectionUserOptions): ServerCollection<MongocampDocument<N>, MongocampDocumentInput<N>>;
20
+ export declare function useMongocampServerCollection<T = Record<string, unknown>, I = T>(name: string, options: ServerCollectionUserOptions): ServerCollection<T, I>;
@@ -0,0 +1,12 @@
1
+ import { useMongocampCore } from "../mongocamp/core.js";
2
+ const methods = ["find", "findPage", "findById", "count", "insert", "insertMany", "replace", "update", "updateMany", "remove", "removeMany", "restore", "history"];
3
+ function isEvent(user) {
4
+ return user !== null && typeof user === "object" && "req" in user && user.req instanceof Request;
5
+ }
6
+ export function useMongocampServerCollection(name, options) {
7
+ const user = isEvent(options.user) ? options.user.req : options.user;
8
+ let collection;
9
+ const get = () => collection ??= useMongocampCore().then((core) => core.collection(name, { user }));
10
+ const lazy = Object.fromEntries(methods.map((method) => [method, (...args) => get().then((target) => target[method](...args))]));
11
+ return { name, ...lazy };
12
+ }
@@ -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
+ }
@@ -1,3 +1,4 @@
1
+ import type { ExpandedDocument } from '@sfxcode/mongocamp-server-core';
1
2
  /**
2
3
  * The documents of the declared collections by name (2.3.0). Empty here; the module adds the declarations of `server/mongocamp/*.ts`
3
4
  * (`.nuxt/types/mongocamp-collections.d.ts`), an application without the module's scan (external server) can add its own:
@@ -11,6 +12,9 @@ declare global {
11
12
  /** The documents as they are written (the input of the schema: fields with a default are optional); falls back to the stored type. */
12
13
  interface MongocampCollectionInputs {
13
14
  }
15
+ /** The references of the declared collections (2.4.0): `{ orders: { customerId: 'customers' } }`. */
16
+ interface MongocampCollectionRefs {
17
+ }
14
18
  }
15
19
  /** The names of the declared collections. */
16
20
  export type MongocampCollectionName = keyof MongocampCollections & string;
@@ -18,3 +22,9 @@ export type MongocampCollectionName = keyof MongocampCollections & string;
18
22
  export type MongocampDocument<N extends MongocampCollectionName> = MongocampCollections[N];
19
23
  /** The written document type of a declared collection. */
20
24
  export type MongocampDocumentInput<N extends MongocampCollectionName> = N extends keyof MongocampCollectionInputs ? MongocampCollectionInputs[N] : MongocampCollections[N];
25
+ /** The references of a declared collection: field → target collection name (`{}` without refs). */
26
+ export type MongocampRefs<N extends MongocampCollectionName> = N extends keyof MongocampCollectionRefs ? MongocampCollectionRefs[N] : Record<never, never>;
27
+ /** The fields of a declared collection that a read can expand. */
28
+ export type MongocampRefName<N extends MongocampCollectionName> = keyof MongocampRefs<N> & string;
29
+ /** A document of a declared collection with the references `K` expanded (target document or `null`, arrays of documents). */
30
+ export type MongocampExpandedDocument<N extends MongocampCollectionName, K extends MongocampRefName<N>> = ExpandedDocument<MongocampDocument<N>, MongocampRefs<N>, K, MongocampCollections>;
@@ -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,5 +1,5 @@
1
1
  /**
2
- * A parser of Server-Sent Events for a stream read with `fetch` (2.4.0, live updates): `EventSource` cannot send the bearer token of the
2
+ * A parser of Server-Sent Events for a stream read with `fetch` (2.3.0, live updates): `EventSource` cannot send the bearer token of the
3
3
  * session. Feed it the decoded text as it arrives; it calls `onEvent` for every complete event (comments are skipped).
4
4
  */
5
5
  export interface SseEvent {
@@ -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);