@sfxcode/nuxt-ui-mongocamp 1.3.4 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (212) hide show
  1. package/README.md +4 -0
  2. package/dist/module.d.mts +8 -0
  3. package/dist/module.json +1 -1
  4. package/dist/module.mjs +6 -0
  5. package/dist/runtime/components/MongocampAggregationBuilder.vue +302 -3
  6. package/dist/runtime/components/MongocampAggregationChart.d.vue.ts +6 -0
  7. package/dist/runtime/components/MongocampAggregationChart.vue +93 -0
  8. package/dist/runtime/components/MongocampAggregationChart.vue.d.ts +6 -0
  9. package/dist/runtime/components/MongocampAggregationStagePreview.d.vue.ts +9 -0
  10. package/dist/runtime/components/MongocampAggregationStagePreview.vue +148 -0
  11. package/dist/runtime/components/MongocampAggregationStagePreview.vue.d.ts +9 -0
  12. package/dist/runtime/components/MongocampBucketFiles.vue +169 -48
  13. package/dist/runtime/components/MongocampBulkDelete.d.vue.ts +19 -0
  14. package/dist/runtime/components/MongocampBulkDelete.vue +118 -23
  15. package/dist/runtime/components/MongocampBulkDelete.vue.d.ts +19 -0
  16. package/dist/runtime/components/MongocampBulkEdit.d.vue.ts +6 -0
  17. package/dist/runtime/components/MongocampBulkEdit.vue +23 -2
  18. package/dist/runtime/components/MongocampBulkEdit.vue.d.ts +6 -0
  19. package/dist/runtime/components/MongocampChart.d.vue.ts +29 -0
  20. package/dist/runtime/components/MongocampChart.vue +129 -0
  21. package/dist/runtime/components/MongocampChart.vue.d.ts +29 -0
  22. package/dist/runtime/components/MongocampCollectionCharts.d.vue.ts +15 -0
  23. package/dist/runtime/components/MongocampCollectionCharts.vue +199 -0
  24. package/dist/runtime/components/MongocampCollectionCharts.vue.d.ts +15 -0
  25. package/dist/runtime/components/MongocampCollectionCopy.d.vue.ts +23 -0
  26. package/dist/runtime/components/MongocampCollectionCopy.vue +445 -0
  27. package/dist/runtime/components/MongocampCollectionCopy.vue.d.ts +23 -0
  28. package/dist/runtime/components/MongocampCollectionData.d.vue.ts +4 -0
  29. package/dist/runtime/components/MongocampCollectionData.vue +343 -146
  30. package/dist/runtime/components/MongocampCollectionData.vue.d.ts +4 -0
  31. package/dist/runtime/components/MongocampCollectionInfos.vue +106 -238
  32. package/dist/runtime/components/MongocampCollections.vue +62 -0
  33. package/dist/runtime/components/MongocampCommandPalette.d.vue.ts +40 -0
  34. package/dist/runtime/components/MongocampCommandPalette.vue +135 -0
  35. package/dist/runtime/components/MongocampCommandPalette.vue.d.ts +40 -0
  36. package/dist/runtime/components/MongocampConfirmByName.vue +2 -2
  37. package/dist/runtime/components/MongocampDashboard.d.vue.ts +3 -1
  38. package/dist/runtime/components/MongocampDashboard.vue +21 -2
  39. package/dist/runtime/components/MongocampDashboard.vue.d.ts +3 -1
  40. package/dist/runtime/components/MongocampDatabases.vue +22 -0
  41. package/dist/runtime/components/MongocampDocumentCompare.d.vue.ts +20 -0
  42. package/dist/runtime/components/MongocampDocumentCompare.vue +146 -0
  43. package/dist/runtime/components/MongocampDocumentCompare.vue.d.ts +20 -0
  44. package/dist/runtime/components/MongocampDocumentView.d.vue.ts +22 -0
  45. package/dist/runtime/components/MongocampDocumentView.vue +202 -0
  46. package/dist/runtime/components/MongocampDocumentView.vue.d.ts +22 -0
  47. package/dist/runtime/components/MongocampErrorAlert.vue +12 -16
  48. package/dist/runtime/components/MongocampExportAll.d.vue.ts +18 -0
  49. package/dist/runtime/components/MongocampExportAll.vue +204 -0
  50. package/dist/runtime/components/MongocampExportAll.vue.d.ts +18 -0
  51. package/dist/runtime/components/MongocampFilePreview.d.vue.ts +16 -0
  52. package/dist/runtime/components/MongocampFilePreview.vue +162 -0
  53. package/dist/runtime/components/MongocampFilePreview.vue.d.ts +16 -0
  54. package/dist/runtime/components/MongocampFilterBuilder.vue +11 -0
  55. package/dist/runtime/components/MongocampImport.vue +2 -10
  56. package/dist/runtime/components/MongocampIndexes.d.vue.ts +18 -0
  57. package/dist/runtime/components/MongocampIndexes.vue +455 -0
  58. package/dist/runtime/components/MongocampIndexes.vue.d.ts +18 -0
  59. package/dist/runtime/components/MongocampJobs.d.vue.ts +6 -1
  60. package/dist/runtime/components/MongocampJobs.vue +24 -4
  61. package/dist/runtime/components/MongocampJobs.vue.d.ts +6 -1
  62. package/dist/runtime/components/MongocampPermissionMatrix.d.vue.ts +12 -0
  63. package/dist/runtime/components/MongocampPermissionMatrix.vue +301 -0
  64. package/dist/runtime/components/MongocampPermissionMatrix.vue.d.ts +12 -0
  65. package/dist/runtime/components/MongocampQueryBar.d.vue.ts +26 -0
  66. package/dist/runtime/components/MongocampQueryBar.vue +398 -0
  67. package/dist/runtime/components/MongocampQueryBar.vue.d.ts +26 -0
  68. package/dist/runtime/components/MongocampRoleGrants.vue +2 -2
  69. package/dist/runtime/components/MongocampRoles.vue +3 -3
  70. package/dist/runtime/components/MongocampServerOverview.d.vue.ts +20 -0
  71. package/dist/runtime/components/MongocampServerOverview.vue +443 -0
  72. package/dist/runtime/components/MongocampServerOverview.vue.d.ts +20 -0
  73. package/dist/runtime/components/MongocampSettings.d.vue.ts +25 -1
  74. package/dist/runtime/components/MongocampSettings.vue +70 -9
  75. package/dist/runtime/components/MongocampSettings.vue.d.ts +25 -1
  76. package/dist/runtime/components/MongocampUsers.vue +3 -3
  77. package/dist/runtime/composables/useMongocampAdmin.d.ts +2 -1
  78. package/dist/runtime/composables/useMongocampAdmin.js +7 -15
  79. package/dist/runtime/composables/useMongocampAggregation.d.ts +12 -1
  80. package/dist/runtime/composables/useMongocampAggregation.js +33 -25
  81. package/dist/runtime/composables/useMongocampAutoRefresh.d.ts +26 -0
  82. package/dist/runtime/composables/useMongocampAutoRefresh.js +78 -0
  83. package/dist/runtime/composables/useMongocampBucket.d.ts +13 -1
  84. package/dist/runtime/composables/useMongocampBucket.js +34 -0
  85. package/dist/runtime/composables/useMongocampClientApi.d.ts +1 -1
  86. package/dist/runtime/composables/useMongocampClientApi.js +2 -1
  87. package/dist/runtime/composables/useMongocampCollectionCopy.d.ts +85 -0
  88. package/dist/runtime/composables/useMongocampCollectionCopy.js +105 -0
  89. package/dist/runtime/composables/useMongocampCollectionStats.d.ts +10 -0
  90. package/dist/runtime/composables/useMongocampCollectionStats.js +17 -0
  91. package/dist/runtime/composables/useMongocampError.d.ts +2 -1
  92. package/dist/runtime/composables/useMongocampError.js +16 -1
  93. package/dist/runtime/composables/useMongocampExportAll.d.ts +47 -0
  94. package/dist/runtime/composables/useMongocampExportAll.js +27 -0
  95. package/dist/runtime/composables/useMongocampExtendedJson.d.ts +5 -1
  96. package/dist/runtime/composables/useMongocampExtendedJson.js +12 -6
  97. package/dist/runtime/composables/useMongocampFetchAll.d.ts +25 -0
  98. package/dist/runtime/composables/useMongocampFetchAll.js +27 -0
  99. package/dist/runtime/composables/useMongocampPermissions.d.ts +14 -0
  100. package/dist/runtime/composables/useMongocampPermissions.js +21 -0
  101. package/dist/runtime/composables/useMongocampPersistedState.d.ts +15 -0
  102. package/dist/runtime/composables/useMongocampPersistedState.js +21 -0
  103. package/dist/runtime/composables/useMongocampProxyApi.d.ts +1 -1
  104. package/dist/runtime/composables/useMongocampProxyApi.js +2 -1
  105. package/dist/runtime/composables/useMongocampQuery.d.ts +50 -2
  106. package/dist/runtime/composables/useMongocampQuery.js +72 -1
  107. package/dist/runtime/composables/useMongocampSavedPipelines.d.ts +25 -0
  108. package/dist/runtime/composables/useMongocampSavedPipelines.js +23 -0
  109. package/dist/runtime/composables/useMongocampSavedQueries.d.ts +37 -0
  110. package/dist/runtime/composables/useMongocampSavedQueries.js +50 -0
  111. package/dist/runtime/composables/useMongocampServerOverview.d.ts +42 -0
  112. package/dist/runtime/composables/useMongocampServerOverview.js +61 -0
  113. package/dist/runtime/composables/useMongocampSession.d.ts +3 -2
  114. package/dist/runtime/composables/useMongocampSession.js +14 -22
  115. package/dist/runtime/composables/useMongocampSystem.d.ts +7 -2
  116. package/dist/runtime/composables/useMongocampSystem.js +6 -2
  117. package/dist/runtime/locales/de.json +495 -10
  118. package/dist/runtime/locales/en.json +495 -10
  119. package/dist/runtime/plugin.js +8 -5
  120. package/dist/runtime/utils/aggregationPipeline.d.ts +5 -4
  121. package/dist/runtime/utils/aggregationPipeline.js +23 -9
  122. package/dist/runtime/utils/aggregationPreview.d.ts +13 -0
  123. package/dist/runtime/utils/aggregationPreview.js +10 -0
  124. package/dist/runtime/utils/aggregationResult.d.ts +5 -0
  125. package/dist/runtime/utils/aggregationResult.js +4 -0
  126. package/dist/runtime/utils/aggregationTemplates.d.ts +34 -0
  127. package/dist/runtime/utils/aggregationTemplates.js +47 -0
  128. package/dist/runtime/utils/analyzeSamples.d.ts +1 -0
  129. package/dist/runtime/utils/analyzeSamples.js +1 -1
  130. package/dist/runtime/utils/autoRefresh.d.ts +14 -0
  131. package/dist/runtime/utils/autoRefresh.js +15 -0
  132. package/dist/runtime/utils/bigIntJson.d.ts +15 -0
  133. package/dist/runtime/utils/bigIntJson.js +55 -0
  134. package/dist/runtime/utils/bulkDelete.d.ts +9 -1
  135. package/dist/runtime/utils/bulkDelete.js +15 -3
  136. package/dist/runtime/utils/bulkEdit.d.ts +6 -0
  137. package/dist/runtime/utils/bulkEdit.js +7 -0
  138. package/dist/runtime/utils/chartData.d.ts +11 -0
  139. package/dist/runtime/utils/chartData.js +9 -0
  140. package/dist/runtime/utils/collectionChart.d.ts +36 -0
  141. package/dist/runtime/utils/collectionChart.js +73 -0
  142. package/dist/runtime/utils/collectionCopy.d.ts +26 -0
  143. package/dist/runtime/utils/collectionCopy.js +38 -0
  144. package/dist/runtime/utils/collectionStats.d.ts +31 -0
  145. package/dist/runtime/utils/collectionStats.js +42 -0
  146. package/dist/runtime/utils/commandPalette.d.ts +48 -0
  147. package/dist/runtime/utils/commandPalette.js +39 -0
  148. package/dist/runtime/utils/createProxyMongocampApis.d.ts +2 -2
  149. package/dist/runtime/utils/createProxyMongocampApis.js +2 -2
  150. package/dist/runtime/utils/documentCompare.d.ts +31 -0
  151. package/dist/runtime/utils/documentCompare.js +70 -0
  152. package/dist/runtime/utils/documentDiff.d.ts +19 -0
  153. package/dist/runtime/utils/documentDiff.js +71 -0
  154. package/dist/runtime/utils/documentPaths.d.ts +44 -0
  155. package/dist/runtime/utils/documentPaths.js +144 -0
  156. package/dist/runtime/utils/documentTree.d.ts +40 -0
  157. package/dist/runtime/utils/documentTree.js +94 -0
  158. package/dist/runtime/utils/exportDocuments.d.ts +35 -0
  159. package/dist/runtime/utils/exportDocuments.js +54 -0
  160. package/dist/runtime/utils/exportRows.js +1 -1
  161. package/dist/runtime/utils/filePreview.d.ts +27 -0
  162. package/dist/runtime/utils/filePreview.js +50 -0
  163. package/dist/runtime/utils/filterBuilder.d.ts +6 -1
  164. package/dist/runtime/utils/filterBuilder.js +6 -5
  165. package/dist/runtime/utils/formatBytes.d.ts +2 -0
  166. package/dist/runtime/utils/formatBytes.js +11 -0
  167. package/dist/runtime/utils/grantMatching.d.ts +8 -0
  168. package/dist/runtime/utils/grantMatching.js +15 -0
  169. package/dist/runtime/utils/importRows.js +12 -2
  170. package/dist/runtime/utils/indexCopy.d.ts +26 -0
  171. package/dist/runtime/utils/indexCopy.js +22 -0
  172. package/dist/runtime/utils/indexForm.d.ts +69 -0
  173. package/dist/runtime/utils/indexForm.js +63 -0
  174. package/dist/runtime/utils/limitedMap.d.ts +17 -0
  175. package/dist/runtime/utils/limitedMap.js +19 -0
  176. package/dist/runtime/utils/luceneExpression.d.ts +15 -0
  177. package/dist/runtime/utils/luceneExpression.js +74 -0
  178. package/dist/runtime/utils/pagedFetch.d.ts +46 -0
  179. package/dist/runtime/utils/pagedFetch.js +58 -0
  180. package/dist/runtime/utils/paginationHeaders.d.ts +4 -0
  181. package/dist/runtime/utils/paginationHeaders.js +4 -0
  182. package/dist/runtime/utils/permissionDenied.d.ts +10 -0
  183. package/dist/runtime/utils/permissionDenied.js +23 -0
  184. package/dist/runtime/utils/permissionMatrix.d.ts +55 -0
  185. package/dist/runtime/utils/permissionMatrix.js +85 -0
  186. package/dist/runtime/utils/persistedState.d.ts +25 -0
  187. package/dist/runtime/utils/persistedState.js +47 -0
  188. package/dist/runtime/utils/queryState.d.ts +45 -0
  189. package/dist/runtime/utils/queryState.js +75 -0
  190. package/dist/runtime/utils/requestLimits.d.ts +2 -0
  191. package/dist/runtime/utils/requestLimits.js +4 -0
  192. package/dist/runtime/utils/resultChart.d.ts +32 -0
  193. package/dist/runtime/utils/resultChart.js +59 -0
  194. package/dist/runtime/utils/savedPipelines.d.ts +22 -0
  195. package/dist/runtime/utils/savedPipelines.js +46 -0
  196. package/dist/runtime/utils/savedQueries.d.ts +60 -0
  197. package/dist/runtime/utils/savedQueries.js +143 -0
  198. package/dist/runtime/utils/schemaAnalysis.d.ts +16 -0
  199. package/dist/runtime/utils/schemaAnalysis.js +57 -0
  200. package/dist/runtime/utils/serverError.d.ts +19 -0
  201. package/dist/runtime/utils/serverError.js +19 -0
  202. package/dist/runtime/utils/serverOverview.d.ts +47 -0
  203. package/dist/runtime/utils/serverOverview.js +40 -0
  204. package/dist/runtime/utils/sessionGuard.d.ts +3 -0
  205. package/dist/runtime/utils/sessionGuard.js +18 -1
  206. package/package.json +13 -12
  207. package/dist/runtime/utils/failureKind.d.ts +0 -3
  208. package/dist/runtime/utils/failureKind.js +0 -11
  209. package/dist/runtime/utils/serverProbe.d.ts +0 -10
  210. package/dist/runtime/utils/serverProbe.js +0 -25
  211. package/dist/runtime/utils/throttled.d.ts +0 -6
  212. package/dist/runtime/utils/throttled.js +0 -16
@@ -1,8 +1,9 @@
1
- export type MongocampErrorKind = 'network' | 'unauthorized' | 'forbidden' | 'other';
1
+ export type MongocampErrorKind = 'network' | 'unauthorized' | 'forbidden' | 'notAllowed' | 'invalid' | 'other';
2
2
  export interface DescribedError {
3
3
  kind: MongocampErrorKind;
4
4
  message: string;
5
5
  }
6
6
  export declare function useMongocampError(): {
7
7
  describeError: (error: unknown, fallbackKey?: string) => DescribedError;
8
+ describeServerError: (error: unknown, fallbackKey?: string) => Promise<DescribedError>;
8
9
  };
@@ -1,4 +1,5 @@
1
1
  import { useI18n } from "#imports";
2
+ import { notAllowedOperator, OPERATOR_NOT_ALLOWED_CODE, readServerError } from "../utils/serverError.js";
2
3
  export function useMongocampError() {
3
4
  const { t } = useI18n();
4
5
  function describeError(error, fallbackKey) {
@@ -16,5 +17,19 @@ export function useMongocampError() {
16
17
  const message = error instanceof Error && error.message ? error.message : t(fallbackKey ?? "nuxtUiMongocamp.errors.generic");
17
18
  return { kind: "other", message };
18
19
  }
19
- return { describeError };
20
+ async function describeServerError(error, fallbackKey) {
21
+ const base = describeError(error, fallbackKey);
22
+ if (base.kind === "network" || base.kind === "unauthorized") return base;
23
+ const server = await readServerError(error);
24
+ if (server.code === OPERATOR_NOT_ALLOWED_CODE) {
25
+ const operator = notAllowedOperator(server.message);
26
+ return { kind: "notAllowed", message: operator ? t("nuxtUiMongocamp.errors.notAllowedOperator", { operator }) : t("nuxtUiMongocamp.errors.notAllowed") };
27
+ }
28
+ if (base.kind === "forbidden") return base;
29
+ if (server.message && server.status !== void 0 && server.status >= 400) {
30
+ return { kind: server.status === 400 ? "invalid" : "other", message: server.message };
31
+ }
32
+ return base;
33
+ }
34
+ return { describeError, describeServerError };
20
35
  }
@@ -0,0 +1,47 @@
1
+ import type { ExportFormat } from '../utils/exportDocuments.js';
2
+ import type { FetchAllProgress } from '../utils/pagedFetch.js';
3
+ export interface ExportCollectionOptions {
4
+ collection: string;
5
+ format: ExportFormat;
6
+ /** Lucene filter: export only the documents that match (the current filter of a table). */
7
+ filter?: string;
8
+ sort?: string[];
9
+ /** Limit the fields; `columns` also orders a CSV. */
10
+ projection?: string[];
11
+ /** CSV columns in this order; default: the keys of all rows, `_id` first. */
12
+ columns?: string[];
13
+ /** Stop after this many documents (default 50 000) and report `truncated`. */
14
+ maxRows?: number;
15
+ pageSize?: number;
16
+ onProgress?: (progress: FetchAllProgress) => void;
17
+ /** Aborting rejects with an `AbortError`; nothing is downloaded. */
18
+ signal?: AbortSignal;
19
+ /** File name; default `<collection>-<yyyymmdd>-<hhmm>.<format>`. */
20
+ filename?: string;
21
+ /** Hand the file to the browser as a download (default `true`). `false` only returns the text. */
22
+ download?: boolean;
23
+ }
24
+ export interface ExportResult {
25
+ /** The file's text. */
26
+ content: string;
27
+ filename: string;
28
+ mimeType: string;
29
+ format: ExportFormat;
30
+ /** Documents written. */
31
+ rowCount: number;
32
+ /** The server's count when the last page was read. */
33
+ total?: number;
34
+ /** More documents exist than were exported: the cap was hit. **The file is incomplete** — tell the user. */
35
+ truncated: boolean;
36
+ /** Documents were added or removed while reading; the file may miss or repeat one. */
37
+ totalChanged: boolean;
38
+ }
39
+ /**
40
+ * Exports a whole collection, or every document matching a filter, as JSON, NDJSON or CSV — not just the rows on screen.
41
+ * It reads every page (`useMongocampFetchAll`: pages of 500, progress, abort) and writes the file in the browser. The rows
42
+ * are written as the table shows them, except that an integer beyond 2^53 keeps every digit (bare number in JSON, digits
43
+ * in CSV). Everything is held in memory: with the default cap of 50 000 documents that is tens of megabytes.
44
+ */
45
+ export declare function useMongocampExportAll(): {
46
+ exportCollection: (options: ExportCollectionOptions) => Promise<ExportResult>;
47
+ };
@@ -0,0 +1,27 @@
1
+ import { downloadTextFile } from "../utils/exportRows.js";
2
+ import { DEFAULT_EXPORT_MAX_ROWS, EXPORT_MIME_TYPES, exportFilename, formatDocuments, toExportRow } from "../utils/exportDocuments.js";
3
+ import { useMongocampFetchAll } from "./useMongocampFetchAll.js";
4
+ export function useMongocampExportAll() {
5
+ const { fetchAllDocuments } = useMongocampFetchAll();
6
+ async function exportCollection(options) {
7
+ const { collection, format, columns, download = true } = options;
8
+ const fetched = await fetchAllDocuments(collection, {
9
+ filter: options.filter,
10
+ sort: options.sort,
11
+ projection: options.projection,
12
+ pageSize: options.pageSize,
13
+ maxRows: options.maxRows ?? DEFAULT_EXPORT_MAX_ROWS,
14
+ onProgress: options.onProgress,
15
+ signal: options.signal,
16
+ // skip/limit paging can repeat a document when the collection changes during the read
17
+ keyOf: (row) => String(row._id)
18
+ });
19
+ const rows = fetched.rows.map(toExportRow);
20
+ const content = formatDocuments(rows, format, { columns });
21
+ const filename = options.filename ?? exportFilename(collection, format);
22
+ const mimeType = EXPORT_MIME_TYPES[format];
23
+ if (download) downloadTextFile(filename, content, mimeType);
24
+ return { content, filename, mimeType, format, rowCount: rows.length, total: fetched.total, truncated: fetched.truncated, totalChanged: fetched.totalChanged };
25
+ }
26
+ return { exportCollection };
27
+ }
@@ -1,2 +1,6 @@
1
- export declare function unwrapExtendedJson(value: unknown): unknown;
1
+ export interface UnwrapOptions {
2
+ /** Keep a `$numberLong` outside the safe-integer range as its exact digit string (default `true`). `false` gives the rounded number, e.g. for type inference. */
3
+ exactLongs?: boolean;
4
+ }
5
+ export declare function unwrapExtendedJson(value: unknown, options?: UnwrapOptions): unknown;
2
6
  export declare function wrapExtendedJson(formData: Record<string, unknown>, originalDoc?: Record<string, unknown>): Record<string, unknown>;
@@ -9,28 +9,34 @@ function unwrapDateTime(raw) {
9
9
  if (isPlainObject(inner) && typeof inner.$numberLong === "string") return new Date(Number(inner.$numberLong)).toISOString();
10
10
  return raw;
11
11
  }
12
- function unwrapNumber(raw) {
12
+ const INTEGER_TEXT = /^-?\d+$/;
13
+ function unwrapNumber(raw, exactLongs) {
13
14
  for (const key of NUMBER_WRAPPER_KEYS) {
14
15
  const wrapped = raw[key];
15
16
  if (typeof wrapped === "string" || typeof wrapped === "number") {
16
17
  const parsed = Number(wrapped);
17
- if (!Number.isNaN(parsed)) return parsed;
18
+ if (Number.isNaN(parsed)) continue;
19
+ if (key === "$numberLong" && exactLongs && typeof wrapped === "string" && INTEGER_TEXT.test(wrapped) && !Number.isSafeInteger(parsed)) return wrapped;
20
+ return parsed;
18
21
  }
19
22
  }
20
23
  return void 0;
21
24
  }
22
- export function unwrapExtendedJson(value) {
23
- if (Array.isArray(value)) return value.map(unwrapExtendedJson);
25
+ export function unwrapExtendedJson(value, options = {}) {
26
+ if (Array.isArray(value)) return value.map((item) => unwrapExtendedJson(item, options));
24
27
  if (!isPlainObject(value)) return value;
25
28
  if (typeof value.$oid === "string") return value.$oid;
26
29
  if ("$date" in value) return unwrapDateTime(value);
27
- const number = unwrapNumber(value);
30
+ const number = unwrapNumber(value, options.exactLongs ?? true);
28
31
  if (number !== void 0) return number;
29
32
  const result = {};
30
- for (const [key, v] of Object.entries(value)) result[key] = unwrapExtendedJson(v);
33
+ for (const [key, v] of Object.entries(value)) result[key] = unwrapExtendedJson(v, options);
31
34
  return result;
32
35
  }
33
36
  function rewrapValue(value, originalValue) {
37
+ if (typeof value === "string" && INTEGER_TEXT.test(value) && isPlainObject(originalValue) && typeof originalValue.$numberLong === "string") {
38
+ return { $numberLong: value };
39
+ }
34
40
  if (typeof value === "string" && isIsoDateTimeString(value)) {
35
41
  return { $date: value };
36
42
  }
@@ -0,0 +1,25 @@
1
+ import type { FetchAllOptions, FetchAllResult } from '../utils/pagedFetch.js';
2
+ export interface FetchAllDocumentsOptions<T> extends FetchAllOptions<T> {
3
+ /** Lucene filter, as for the document list. */
4
+ filter?: string;
5
+ /** Sort keys as the document list takes them (`['name', '-age']`). Without one the server's natural order is used. */
6
+ sort?: string[];
7
+ /** Fields to return; `['_id']` is the cheap way to collect ids. */
8
+ projection?: string[];
9
+ }
10
+ export interface FetchAllFilesOptions<T> extends FetchAllOptions<T> {
11
+ filter?: string;
12
+ sort?: string;
13
+ projection?: string;
14
+ }
15
+ /**
16
+ * Reads every document of a collection (or of a Lucene filter) page by page: `fetchAllPages` over the document list. The
17
+ * rows are what the list returns — read from the response text, so integers beyond 2^53 are `{ $numberLong }` wrappers
18
+ * (run them through `unwrapExtendedJson` for display) — and the total comes from the pagination header.
19
+ * Capped at 10 000 rows by default (`maxRows` raises it); see `utils/pagedFetch.ts` for stopping, progress, abort and
20
+ * the effect of documents changing during the read. Every page has its own 60 s timeout.
21
+ */
22
+ export declare function useMongocampFetchAll(): {
23
+ fetchAllDocuments: <T = Record<string, unknown>>(collectionName: string, options?: FetchAllDocumentsOptions<T>) => Promise<FetchAllResult<T>>;
24
+ fetchAllFiles: <T = Record<string, unknown>>(bucketName: string, options?: FetchAllFilesOptions<T>) => Promise<FetchAllResult<T>>;
25
+ };
@@ -0,0 +1,27 @@
1
+ import { useMongocampClientApi } from "#imports";
2
+ import { readJsonKeepingLongs } from "../utils/bigIntJson.js";
3
+ import { fetchAllPages } from "../utils/pagedFetch.js";
4
+ import { headerNumber } from "../utils/paginationHeaders.js";
5
+ const PAGE_TIMEOUT_MS = 6e4;
6
+ function requestInit(signal) {
7
+ const timeout = AbortSignal.timeout(PAGE_TIMEOUT_MS);
8
+ return { signal: signal && typeof AbortSignal.any === "function" ? AbortSignal.any([signal, timeout]) : timeout };
9
+ }
10
+ export function useMongocampFetchAll() {
11
+ const { documentApi, fileApi } = useMongocampClientApi();
12
+ async function fetchAllDocuments(collectionName, options = {}) {
13
+ const { filter, sort, projection, ...paging } = options;
14
+ return fetchAllPages(async (page, pageSize) => {
15
+ const response = await documentApi.listDocumentsRaw({ collectionName, filter, sort, projection, page, rowsPerPage: pageSize }, requestInit(options.signal));
16
+ return { rows: await readJsonKeepingLongs(response), total: headerNumber(response.raw?.headers, "x-pagination-count-rows") };
17
+ }, paging);
18
+ }
19
+ async function fetchAllFiles(bucketName, options = {}) {
20
+ const { filter, sort, projection, ...paging } = options;
21
+ return fetchAllPages(async (page, pageSize) => {
22
+ const response = await fileApi.listFilesRaw({ bucketName, filter, sort, projection, page, rowsPerPage: pageSize }, requestInit(options.signal));
23
+ return { rows: await readJsonKeepingLongs(response), total: headerNumber(response.raw?.headers, "x-pagination-count-rows") };
24
+ }, paging);
25
+ }
26
+ return { fetchAllDocuments, fetchAllFiles };
27
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * What the signed-in user may do with a collection, from the grants in the session profile — so a component can hide an
3
+ * action the server would refuse instead of letting the click fail. **UI-level only**: the server stays the authority.
4
+ *
5
+ * It fails open: an administrator, server proxy mode (the api key's power is the server's decision), a profile without a
6
+ * grant list, and GridFS bucket members all answer "yes". Grants are read from the profile each time, so the answers
7
+ * follow it when the token refresh brings a new one.
8
+ */
9
+ export declare function useMongocampPermissions(): {
10
+ canRead: (collectionName: string) => boolean;
11
+ canWrite: (collectionName: string) => boolean;
12
+ canAdminister: (collectionName: string) => boolean;
13
+ readableCollections: (collectionNames: string[]) => string[];
14
+ };
@@ -0,0 +1,21 @@
1
+ import { useRuntimeConfig } from "#app";
2
+ import { useMongocampStorage } from "#imports";
3
+ import { permissionFromGrants } from "../utils/grantMatching.js";
4
+ export function useMongocampPermissions() {
5
+ const config = useRuntimeConfig();
6
+ const state = useMongocampStorage();
7
+ const isProxyMode = config.public.nuxtUiMongocampOptions?.useServerProxy ?? false;
8
+ function allowed(collectionName, permission) {
9
+ if (isProxyMode) return true;
10
+ const profile = state.value?.profile;
11
+ if (!profile || profile.isAdmin) return true;
12
+ return permissionFromGrants(profile.grants, collectionName, permission) ?? true;
13
+ }
14
+ const canRead = (collectionName) => allowed(collectionName, "read");
15
+ const canWrite = (collectionName) => allowed(collectionName, "write");
16
+ const canAdminister = (collectionName) => allowed(collectionName, "administrate");
17
+ function readableCollections(collectionNames) {
18
+ return collectionNames.filter(canRead);
19
+ }
20
+ return { canRead, canWrite, canAdminister, readableCollections };
21
+ }
@@ -0,0 +1,15 @@
1
+ import type { MaybeRefOrGetter, Ref } from 'vue';
2
+ import type { PersistOptions, StorageLike } from '../utils/persistedState.js';
3
+ export interface PersistedStateOptions<T> extends PersistOptions<T> {
4
+ /** Defaults to `localStorage` in the browser; `null` turns it off; nothing is stored on the server or when it is unreachable. */
5
+ storage?: StorageLike | null;
6
+ }
7
+ /**
8
+ * A ref whose value is remembered in `localStorage` under `nuxt-ui-mongocamp:<key>` (a versioned `{ v, data }` envelope).
9
+ * `key` may be a getter: when it changes the stored value for the new key is loaded (or the defaults). Stored values are
10
+ * merged over the defaults, so a field added later gets its default. Anything unreadable falls back to the defaults.
11
+ */
12
+ export declare function useMongocampPersistedState<T extends Record<string, unknown>>(key: MaybeRefOrGetter<string>, defaults: T, options?: PersistedStateOptions<T>): {
13
+ state: Ref<T>;
14
+ reset: () => void;
15
+ };
@@ -0,0 +1,21 @@
1
+ import { ref, toValue, watch } from "vue";
2
+ import { browserStorage, clearPersisted, PERSISTED_STATE_PREFIX, readPersisted, writePersisted } from "../utils/persistedState.js";
3
+ export function useMongocampPersistedState(key, defaults, options = {}) {
4
+ const storage = options.storage === null ? void 0 : options.storage ?? (import.meta.client ? browserStorage() : void 0);
5
+ const fullKey = () => PERSISTED_STATE_PREFIX + toValue(key);
6
+ const load = () => ({ ...defaults, ...readPersisted(storage, fullKey(), options) });
7
+ const state = ref(load());
8
+ let loadedKey = fullKey();
9
+ watch(() => fullKey(), (next) => {
10
+ loadedKey = next;
11
+ state.value = load();
12
+ });
13
+ watch(state, (value) => {
14
+ writePersisted(storage, loadedKey, value, options.version, options.maxBytes);
15
+ }, { deep: true });
16
+ function reset() {
17
+ clearPersisted(storage, loadedKey);
18
+ state.value = { ...defaults };
19
+ }
20
+ return { state, reset };
21
+ }
@@ -8,6 +8,6 @@ export declare function useMongocampProxyApi(): {
8
8
  documentApi: import("@sfxcode/nuxt-mongocamp-server").DocumentApi;
9
9
  fileApi: import("@sfxcode/nuxt-mongocamp-server").FileApi;
10
10
  indexApi: import("@sfxcode/nuxt-mongocamp-server").IndexApi;
11
- informationApi: import("@sfxcode/nuxt-mongocamp-server").InformationApi;
11
+ systemApi: import("@sfxcode/nuxt-mongocamp-server").SystemApi;
12
12
  jobApi: import("@sfxcode/nuxt-mongocamp-server").JobsApi;
13
13
  };
@@ -1,9 +1,10 @@
1
1
  import { useRuntimeConfig } from "#app";
2
2
  import { Configuration } from "@sfxcode/nuxt-mongocamp-server/api";
3
3
  import { createProxyMongocampApis } from "../utils/createProxyMongocampApis.js";
4
+ import { permissionDeniedMiddleware } from "../utils/permissionDenied.js";
4
5
  export function useMongocampProxyApi() {
5
6
  const config = useRuntimeConfig();
6
7
  const serverProxyPath = config.public.nuxtUiMongocampOptions.serverProxyPath ?? "/api/_mongocamp";
7
- const configuration = new Configuration({ basePath: serverProxyPath });
8
+ const configuration = new Configuration({ basePath: serverProxyPath, middleware: [permissionDeniedMiddleware] });
8
9
  return createProxyMongocampApis(configuration);
9
10
  }
@@ -10,7 +10,7 @@ export interface MongocampQueryHelper {
10
10
  * Matches documents where the field has a value. Without `type` this ORs a text wildcard with a
11
11
  * full-range number and a full-range date clause, so it works for any of those types.
12
12
  *
13
- * MongoCamp (1.5 and still 1.6.1) does not understand `_exists_:field` (it matches nothing), and `field:*` only matches text,
13
+ * MongoCamp (still, as of 1.6.3) does not understand `_exists_:field` (it matches nothing), and `field:*` only matches text,
14
14
  * which is why this is not just a wildcard.
15
15
  */
16
16
  exists: (fieldName: string, type?: ExistsFieldType) => string;
@@ -36,7 +36,7 @@ export interface MongocampQueryHelper {
36
36
  /**
37
37
  * `field:[from TO to]` — inclusive range.
38
38
  *
39
- * Pass `null` (or `'*'`) for an open end. MongoCamp (1.5 and still 1.6.1) rejects `[x TO *]`, so the open end is replaced by
39
+ * Pass `null` (or `'*'`) for an open end. MongoCamp (still, as of 1.6.3) rejects `[x TO *]`, so the open end is replaced by
40
40
  * the far bound of the other bound's type: the 64-bit integer limits for numbers, year 0001 / 9999 for
41
41
  * dates. Both ends open means "has a value" and returns `exists(field)`. An open end next to a *text*
42
42
  * bound can't be expressed and still becomes `*`, which the server rejects.
@@ -102,5 +102,53 @@ export interface MongocampQueryHelper {
102
102
  * A single surviving part is returned unwrapped (no outer parens).
103
103
  */
104
104
  or: (...queryParts: (string | null | undefined)[]) => string;
105
+ /**
106
+ * `_id:"<hex>"` — the document with this id. The id must be a 24-character hex ObjectId (any case); anything else
107
+ * **throws** a `TypeError` instead of returning `''`, because "no filter" would match every document. (A wildcard on
108
+ * `_id` matches nothing on the server, so there is no `like` for ids.)
109
+ */
110
+ byId: (id: string) => string;
111
+ /**
112
+ * `_id:("a" OR "b")` — any of these documents. Every id must be a 24-character hex ObjectId or it throws, like `byId`.
113
+ * An empty array returns `''` (no clause), as `inClause` does.
114
+ */
115
+ byIds: (ids: string[]) => string;
116
+ /** `field:true` — a boolean field that is true. A document without the field does not match. */
117
+ isTrue: (fieldName: string) => string;
118
+ /** `field:false` — a boolean field that is false. A document without the field does not match. */
119
+ isFalse: (fieldName: string) => string;
120
+ /**
121
+ * `field:"x"` / `field:5` — the array contains this element (text quoted, numbers not). Any one array element
122
+ * matching is enough, so `arrayContains('tags', 'a')` finds `["a","b"]`.
123
+ */
124
+ arrayContains: (fieldName: string, value: QueryValue) => string;
125
+ /**
126
+ * The field is an array with at least one element (an empty array and a missing field do not match). Written like
127
+ * `exists` — a text wildcard ORed with a full number and a full date range — because `field:*` alone only finds
128
+ * arrays of *text* (verified: `nums:*` matched no array of numbers). Pass `type` when you know the element type for the
129
+ * shorter clause. Arrays of booleans and of objects are not covered (nothing matches them).
130
+ */
131
+ hasItems: (fieldName: string, type?: ExistsFieldType) => string;
132
+ /**
133
+ * The whole UTC day `YYYY-MM-DD`: `field:[YYYY-MM-DDT00:00:00Z TO YYYY-MM-DDT23:59:59.999Z]`. The server matches nothing
134
+ * for a bare one-day range, so the bounds are widened to the full day. Throws a `TypeError` for anything that is not a
135
+ * real calendar date.
136
+ */
137
+ onDay: (fieldName: string, day: string) => string;
138
+ /** `-field:[the whole UTC day]` — everything except that day (documents without the field included). */
139
+ notOnDay: (fieldName: string, day: string) => string;
140
+ /**
141
+ * The negation of any expression these helpers produced, written so the server evaluates it correctly.
142
+ * MongoCamp (still, as of 1.6.3) evaluates `-(A AND B)` as `-A AND -B`, so a negated `AND` group is rewritten with
143
+ * De Morgan's law as `((-A) OR (-B))` — each negated clause in its own parentheses, which the server needs — and a
144
+ * negated `OR` group as `((-A) AND (-B))`, recursively. A single clause becomes `-clause` (and `-clause` becomes
145
+ * `clause`). Returns `''` for an empty expression. Throws `UnsupportedExpressionError` for text it cannot read
146
+ * (`NOT …`, `AND`/`OR` mixed without parentheses) rather than guessing.
147
+ */
148
+ not: (queryPart: string | null | undefined) => string;
149
+ /** The negation of "all of these": `notAnd(a, b)` = `not(and(a, b))` = `((-a) OR (-b))`. Empty parts are ignored. */
150
+ notAnd: (...queryParts: (string | null | undefined)[]) => string;
151
+ /** The negation of "any of these": `notOr(a, b)` = `not(or(a, b))` = `((-a) AND (-b))`. Empty parts are ignored. */
152
+ notOr: (...queryParts: (string | null | undefined)[]) => string;
105
153
  }
106
154
  export declare function useMongocampQuery(): MongocampQueryHelper;
@@ -1,5 +1,7 @@
1
1
  import { escapeFieldName } from "../utils/escapeFieldName.js";
2
2
  import { isIsoDateTimeString } from "../utils/isoDate.js";
3
+ import { isObjectIdHex } from "../utils/objectId.js";
4
+ import { parseLuceneExpression } from "../utils/luceneExpression.js";
3
5
  import { useMongocampQueryBuilder } from "./useMongocampQueryBuilder.js";
4
6
  const NUMBER_BOUNDS = { from: "-9223372036854775808", to: "9223372036854775807" };
5
7
  const DATE_BOUNDS = { from: "0001-01-01T00:00:00Z", to: "9999-12-31T23:59:59.999Z" };
@@ -127,6 +129,64 @@ export function useMongocampQuery() {
127
129
  function or(...queryParts) {
128
130
  return logicalOperators("OR", queryParts);
129
131
  }
132
+ function requireObjectId(id, helper) {
133
+ if (!isObjectIdHex(id)) throw new TypeError(`${helper} needs a 24-character hex ObjectId, got ${typeof id === "string" ? `"${id}"` : String(id)}`);
134
+ return id;
135
+ }
136
+ function byId(id) {
137
+ return equals("_id", requireObjectId(id, "byId"));
138
+ }
139
+ function byIds(ids) {
140
+ return inClause("_id", ids.map((id) => requireObjectId(id, "byIds")));
141
+ }
142
+ function isTrue(fieldName) {
143
+ return fieldTerm(fieldName, "true");
144
+ }
145
+ function isFalse(fieldName) {
146
+ return fieldTerm(fieldName, "false");
147
+ }
148
+ function arrayContains(fieldName, value) {
149
+ if (value == null || value.toString().length === 0) return "";
150
+ return inClause(fieldName, [value]);
151
+ }
152
+ function hasItems(fieldName, type) {
153
+ return exists(fieldName, type);
154
+ }
155
+ function requireDay(day, helper) {
156
+ const parsed = DATE_ONLY_REGEX.test(day) ? /* @__PURE__ */ new Date(`${day}T00:00:00Z`) : null;
157
+ const valid = parsed !== null && !Number.isNaN(parsed.getTime()) && parsed.toISOString().startsWith(day);
158
+ if (!valid) throw new TypeError(`${helper} needs a calendar date like 2024-03-01, got "${day}"`);
159
+ return day;
160
+ }
161
+ function onDay(fieldName, day) {
162
+ const checked = requireDay(day, "onDay");
163
+ return inRange(fieldName, checked, checked);
164
+ }
165
+ function notOnDay(fieldName, day) {
166
+ return `-${onDay(fieldName, requireDay(day, "notOnDay"))}`;
167
+ }
168
+ function render(node) {
169
+ if (node.kind === "clause") return node.text;
170
+ if (node.kind === "not") return negate(node.node);
171
+ const parts = node.parts.map(render);
172
+ return node.kind === "and" ? and(...parts) : or(...parts);
173
+ }
174
+ function negate(node) {
175
+ if (node.kind === "clause") return node.text.startsWith("-") ? node.text.slice(1) : `-${node.text}`;
176
+ if (node.kind === "not") return render(node.node);
177
+ const negated = node.parts.map(negate);
178
+ return node.kind === "and" ? or(...negated) : and(...negated);
179
+ }
180
+ function not(queryPart) {
181
+ const node = parseLuceneExpression(queryPart ?? "");
182
+ return node === null ? "" : negate(node);
183
+ }
184
+ function notAnd(...queryParts) {
185
+ return not(and(...queryParts));
186
+ }
187
+ function notOr(...queryParts) {
188
+ return not(or(...queryParts));
189
+ }
130
190
  return {
131
191
  exists,
132
192
  notExists,
@@ -146,7 +206,18 @@ export function useMongocampQuery() {
146
206
  inClause,
147
207
  notInClause,
148
208
  containsAll,
209
+ byId,
210
+ byIds,
211
+ isTrue,
212
+ isFalse,
213
+ arrayContains,
214
+ hasItems,
215
+ onDay,
216
+ notOnDay,
149
217
  and,
150
- or
218
+ or,
219
+ not,
220
+ notAnd,
221
+ notOr
151
222
  };
152
223
  }
@@ -0,0 +1,25 @@
1
+ import type { ComputedRef, MaybeRefOrGetter } from 'vue';
2
+ import type { RequestStage } from '../utils/aggregationPipeline.js';
3
+ import type { SavePipelineFailure, SavedPipelineEntry } from '../utils/savedPipelines.js';
4
+ import type { PersistedStateOptions } from './useMongocampPersistedState.js';
5
+ type Store = {
6
+ pipelines: SavedPipelineEntry[];
7
+ };
8
+ export type SavedPipelinesSaveResult = {
9
+ ok: true;
10
+ } | {
11
+ ok: false;
12
+ reason: SavePipelineFailure | 'too-large';
13
+ };
14
+ /**
15
+ * Saved aggregation pipelines of one collection, kept in this browser only (`localStorage` through
16
+ * `useMongocampPersistedState`; nothing is sent to the server). Up to 50 per collection. Everything read back is checked like
17
+ * a pipeline typed into the JSON tab — a stored `$out`, `$function` or `$lookup` is dropped — so edited storage cannot smuggle
18
+ * a denied operator past the builder.
19
+ */
20
+ export declare function useMongocampSavedPipelines(collection: MaybeRefOrGetter<string>, options?: Pick<PersistedStateOptions<Store>, 'storage'>): {
21
+ saved: ComputedRef<SavedPipelineEntry[]>;
22
+ save: (name: string, pipeline: RequestStage[]) => SavedPipelinesSaveResult;
23
+ remove: (name: string) => void;
24
+ };
25
+ export {};
@@ -0,0 +1,23 @@
1
+ import { computed, toValue } from "vue";
2
+ import { MAX_PIPELINE_BYTES, MAX_SAVED, sanitizePipelineList, upsertPipeline } from "../utils/savedPipelines.js";
3
+ import { useMongocampPersistedState } from "./useMongocampPersistedState.js";
4
+ export function useMongocampSavedPipelines(collection, options = {}) {
5
+ const { state } = useMongocampPersistedState(
6
+ () => `savedPipelines:${toValue(collection)}`,
7
+ { pipelines: [] },
8
+ { ...options, maxBytes: MAX_PIPELINE_BYTES * MAX_SAVED }
9
+ );
10
+ const saved = computed(() => sanitizePipelineList(state.value.pipelines));
11
+ function save(name, pipeline) {
12
+ const result = upsertPipeline(saved.value, name, pipeline);
13
+ if (!result.ok) return result;
14
+ if (JSON.stringify({ pipelines: result.list }).length > MAX_PIPELINE_BYTES * MAX_SAVED) return { ok: false, reason: "too-large" };
15
+ state.value = { pipelines: result.list };
16
+ return { ok: true };
17
+ }
18
+ function remove(name) {
19
+ const lower = name.toLowerCase();
20
+ state.value = { pipelines: saved.value.filter((e) => e.name.toLowerCase() !== lower) };
21
+ }
22
+ return { saved, save, remove };
23
+ }
@@ -0,0 +1,37 @@
1
+ import type { ComputedRef, MaybeRefOrGetter } from 'vue';
2
+ import type { ImportFailure, SaveFailure, SavedQuery, SavedQueryEntry } from '../utils/savedQueries.js';
3
+ import type { PersistedStateOptions } from './useMongocampPersistedState.js';
4
+ type Store = {
5
+ saved: SavedQueryEntry[];
6
+ recent: SavedQuery[];
7
+ };
8
+ export type SavedQueriesSaveResult = {
9
+ ok: true;
10
+ } | {
11
+ ok: false;
12
+ reason: SaveFailure | 'too-large';
13
+ };
14
+ export type SavedQueriesImportResult = {
15
+ ok: true;
16
+ imported: number;
17
+ skipped: number;
18
+ } | {
19
+ ok: false;
20
+ reason: ImportFailure | 'too-large';
21
+ };
22
+ /**
23
+ * Saved queries and a short history for one collection, kept in this browser only (`localStorage`, through
24
+ * `useMongocampPersistedState`; nothing is sent to the server). A query is `{ filterGroup?, lucene?, sort?, projection? }`.
25
+ * Everything read back — from storage or an imported file — is validated and bounded: 50 saved, 20 recent.
26
+ */
27
+ export declare function useMongocampSavedQueries(collection: MaybeRefOrGetter<string>, options?: Pick<PersistedStateOptions<Store>, 'storage'>): {
28
+ saved: ComputedRef<SavedQueryEntry[]>;
29
+ recent: ComputedRef<SavedQuery[]>;
30
+ save: (name: string, query: SavedQuery) => SavedQueriesSaveResult;
31
+ remove: (name: string) => void;
32
+ record: (query: SavedQuery) => boolean;
33
+ clearRecent: () => void;
34
+ exportJson: () => string;
35
+ importJson: (text: string) => SavedQueriesImportResult;
36
+ };
37
+ export {};
@@ -0,0 +1,50 @@
1
+ import { computed, toValue } from "vue";
2
+ import { MAX_STORE_BYTES, parseSavedImport, pushRecent, sanitizeRecentList, sanitizeSavedList, serializeSaved, upsertSaved } from "../utils/savedQueries.js";
3
+ import { useMongocampPersistedState } from "./useMongocampPersistedState.js";
4
+ export function useMongocampSavedQueries(collection, options = {}) {
5
+ const { state } = useMongocampPersistedState(
6
+ () => `savedQueries:${toValue(collection)}`,
7
+ { saved: [], recent: [] },
8
+ { ...options, maxBytes: MAX_STORE_BYTES }
9
+ );
10
+ const saved = computed(() => sanitizeSavedList(state.value.saved));
11
+ const recent = computed(() => sanitizeRecentList(state.value.recent));
12
+ function fits(next) {
13
+ return JSON.stringify(next).length <= MAX_STORE_BYTES;
14
+ }
15
+ function save(name, query) {
16
+ const result = upsertSaved(saved.value, name, query);
17
+ if (!result.ok) return result;
18
+ const next = { saved: result.list, recent: recent.value };
19
+ if (!fits(next)) return { ok: false, reason: "too-large" };
20
+ state.value = next;
21
+ return { ok: true };
22
+ }
23
+ function remove(name) {
24
+ const lower = name.toLowerCase();
25
+ state.value = { saved: saved.value.filter((e) => e.name.toLowerCase() !== lower), recent: recent.value };
26
+ }
27
+ function record(query) {
28
+ const clean = sanitizeRecentList([query])[0];
29
+ if (!clean) return false;
30
+ const next = { saved: saved.value, recent: pushRecent(recent.value, clean) };
31
+ if (!fits(next)) return false;
32
+ state.value = next;
33
+ return true;
34
+ }
35
+ function clearRecent() {
36
+ state.value = { saved: saved.value, recent: [] };
37
+ }
38
+ function exportJson() {
39
+ return serializeSaved(saved.value);
40
+ }
41
+ function importJson(text) {
42
+ const result = parseSavedImport(text, saved.value);
43
+ if (!result.ok) return result;
44
+ const next = { saved: result.list, recent: recent.value };
45
+ if (!fits(next)) return { ok: false, reason: "too-large" };
46
+ state.value = next;
47
+ return { ok: true, imported: result.imported, skipped: result.skipped };
48
+ }
49
+ return { saved, recent, save, remove, record, clearRecent, exportJson, importJson };
50
+ }