@sfxcode/nuxt-ui-mongocamp 1.3.5 → 1.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 (224) hide show
  1. package/README.md +1 -1
  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.d.vue.ts +1 -0
  6. package/dist/runtime/components/MongocampAggregationBuilder.vue +331 -5
  7. package/dist/runtime/components/MongocampAggregationBuilder.vue.d.ts +1 -0
  8. package/dist/runtime/components/MongocampAggregationChart.d.vue.ts +6 -0
  9. package/dist/runtime/components/MongocampAggregationChart.vue +93 -0
  10. package/dist/runtime/components/MongocampAggregationChart.vue.d.ts +6 -0
  11. package/dist/runtime/components/MongocampAggregationStagePreview.d.vue.ts +10 -0
  12. package/dist/runtime/components/MongocampAggregationStagePreview.vue +149 -0
  13. package/dist/runtime/components/MongocampAggregationStagePreview.vue.d.ts +10 -0
  14. package/dist/runtime/components/MongocampBucketFiles.vue +230 -48
  15. package/dist/runtime/components/MongocampBulkDelete.d.vue.ts +9 -0
  16. package/dist/runtime/components/MongocampBulkDelete.vue +94 -25
  17. package/dist/runtime/components/MongocampBulkDelete.vue.d.ts +9 -0
  18. package/dist/runtime/components/MongocampBulkEdit.d.vue.ts +5 -0
  19. package/dist/runtime/components/MongocampBulkEdit.vue +41 -3
  20. package/dist/runtime/components/MongocampBulkEdit.vue.d.ts +5 -0
  21. package/dist/runtime/components/MongocampChart.d.vue.ts +29 -0
  22. package/dist/runtime/components/MongocampChart.vue +129 -0
  23. package/dist/runtime/components/MongocampChart.vue.d.ts +29 -0
  24. package/dist/runtime/components/MongocampCollectionCharts.d.vue.ts +17 -0
  25. package/dist/runtime/components/MongocampCollectionCharts.vue +200 -0
  26. package/dist/runtime/components/MongocampCollectionCharts.vue.d.ts +17 -0
  27. package/dist/runtime/components/MongocampCollectionCopy.d.vue.ts +23 -0
  28. package/dist/runtime/components/MongocampCollectionCopy.vue +206 -0
  29. package/dist/runtime/components/MongocampCollectionCopy.vue.d.ts +23 -0
  30. package/dist/runtime/components/MongocampCollectionData.d.vue.ts +6 -0
  31. package/dist/runtime/components/MongocampCollectionData.vue +423 -138
  32. package/dist/runtime/components/MongocampCollectionData.vue.d.ts +6 -0
  33. package/dist/runtime/components/MongocampCollectionInfos.vue +106 -238
  34. package/dist/runtime/components/MongocampCollectionRename.d.vue.ts +22 -0
  35. package/dist/runtime/components/MongocampCollectionRename.vue +116 -0
  36. package/dist/runtime/components/MongocampCollectionRename.vue.d.ts +22 -0
  37. package/dist/runtime/components/MongocampCollections.vue +93 -12
  38. package/dist/runtime/components/MongocampCommandPalette.d.vue.ts +40 -0
  39. package/dist/runtime/components/MongocampCommandPalette.vue +135 -0
  40. package/dist/runtime/components/MongocampCommandPalette.vue.d.ts +40 -0
  41. package/dist/runtime/components/MongocampConfirmByName.vue +2 -2
  42. package/dist/runtime/components/MongocampDashboard.d.vue.ts +3 -1
  43. package/dist/runtime/components/MongocampDashboard.vue +39 -5
  44. package/dist/runtime/components/MongocampDashboard.vue.d.ts +3 -1
  45. package/dist/runtime/components/MongocampDatabases.vue +35 -2
  46. package/dist/runtime/components/MongocampDocumentCompare.d.vue.ts +20 -0
  47. package/dist/runtime/components/MongocampDocumentCompare.vue +146 -0
  48. package/dist/runtime/components/MongocampDocumentCompare.vue.d.ts +20 -0
  49. package/dist/runtime/components/MongocampDocumentView.d.vue.ts +22 -0
  50. package/dist/runtime/components/MongocampDocumentView.vue +202 -0
  51. package/dist/runtime/components/MongocampDocumentView.vue.d.ts +22 -0
  52. package/dist/runtime/components/MongocampErrorAlert.vue +12 -4
  53. package/dist/runtime/components/MongocampExportAll.d.vue.ts +18 -0
  54. package/dist/runtime/components/MongocampExportAll.vue +191 -0
  55. package/dist/runtime/components/MongocampExportAll.vue.d.ts +18 -0
  56. package/dist/runtime/components/MongocampFilePreview.d.vue.ts +16 -0
  57. package/dist/runtime/components/MongocampFilePreview.vue +162 -0
  58. package/dist/runtime/components/MongocampFilePreview.vue.d.ts +16 -0
  59. package/dist/runtime/components/MongocampFilterBuilder.vue +11 -0
  60. package/dist/runtime/components/MongocampImport.vue +171 -13
  61. package/dist/runtime/components/MongocampIndexes.d.vue.ts +18 -0
  62. package/dist/runtime/components/MongocampIndexes.vue +496 -0
  63. package/dist/runtime/components/MongocampIndexes.vue.d.ts +18 -0
  64. package/dist/runtime/components/MongocampJobs.d.vue.ts +6 -1
  65. package/dist/runtime/components/MongocampJobs.vue +36 -5
  66. package/dist/runtime/components/MongocampJobs.vue.d.ts +6 -1
  67. package/dist/runtime/components/MongocampPermissionMatrix.d.vue.ts +12 -0
  68. package/dist/runtime/components/MongocampPermissionMatrix.vue +301 -0
  69. package/dist/runtime/components/MongocampPermissionMatrix.vue.d.ts +12 -0
  70. package/dist/runtime/components/MongocampQueryBar.d.vue.ts +26 -0
  71. package/dist/runtime/components/MongocampQueryBar.vue +398 -0
  72. package/dist/runtime/components/MongocampQueryBar.vue.d.ts +26 -0
  73. package/dist/runtime/components/MongocampRoleGrants.vue +18 -5
  74. package/dist/runtime/components/MongocampRoles.vue +16 -5
  75. package/dist/runtime/components/MongocampServerOverview.d.vue.ts +20 -0
  76. package/dist/runtime/components/MongocampServerOverview.vue +420 -0
  77. package/dist/runtime/components/MongocampServerOverview.vue.d.ts +20 -0
  78. package/dist/runtime/components/MongocampSettings.d.vue.ts +28 -1
  79. package/dist/runtime/components/MongocampSettings.vue +83 -10
  80. package/dist/runtime/components/MongocampSettings.vue.d.ts +28 -1
  81. package/dist/runtime/components/MongocampUsers.vue +19 -6
  82. package/dist/runtime/composables/useMongocampAdmin.d.ts +2 -1
  83. package/dist/runtime/composables/useMongocampAdmin.js +6 -1
  84. package/dist/runtime/composables/useMongocampAdminGate.d.ts +12 -0
  85. package/dist/runtime/composables/useMongocampAdminGate.js +12 -0
  86. package/dist/runtime/composables/useMongocampAggregation.d.ts +23 -1
  87. package/dist/runtime/composables/useMongocampAggregation.js +41 -26
  88. package/dist/runtime/composables/useMongocampAutoRefresh.d.ts +26 -0
  89. package/dist/runtime/composables/useMongocampAutoRefresh.js +78 -0
  90. package/dist/runtime/composables/useMongocampBucket.d.ts +13 -1
  91. package/dist/runtime/composables/useMongocampBucket.js +34 -0
  92. package/dist/runtime/composables/useMongocampBulkByFilter.d.ts +15 -0
  93. package/dist/runtime/composables/useMongocampBulkByFilter.js +32 -0
  94. package/dist/runtime/composables/useMongocampClientApi.js +2 -1
  95. package/dist/runtime/composables/useMongocampCollectionCopy.d.ts +45 -0
  96. package/dist/runtime/composables/useMongocampCollectionCopy.js +48 -0
  97. package/dist/runtime/composables/useMongocampCollectionStats.d.ts +10 -0
  98. package/dist/runtime/composables/useMongocampCollectionStats.js +17 -0
  99. package/dist/runtime/composables/useMongocampError.d.ts +2 -1
  100. package/dist/runtime/composables/useMongocampError.js +16 -1
  101. package/dist/runtime/composables/useMongocampExportAll.d.ts +53 -0
  102. package/dist/runtime/composables/useMongocampExportAll.js +57 -0
  103. package/dist/runtime/composables/useMongocampExtendedJson.d.ts +7 -2
  104. package/dist/runtime/composables/useMongocampExtendedJson.js +44 -11
  105. package/dist/runtime/composables/useMongocampFetchAll.d.ts +25 -0
  106. package/dist/runtime/composables/useMongocampFetchAll.js +27 -0
  107. package/dist/runtime/composables/useMongocampFieldTypes.d.ts +24 -0
  108. package/dist/runtime/composables/useMongocampFieldTypes.js +44 -0
  109. package/dist/runtime/composables/useMongocampImport.d.ts +4 -0
  110. package/dist/runtime/composables/useMongocampImport.js +5 -2
  111. package/dist/runtime/composables/useMongocampIndex.d.ts +6 -1
  112. package/dist/runtime/composables/useMongocampIndex.js +7 -1
  113. package/dist/runtime/composables/useMongocampPermissions.d.ts +17 -0
  114. package/dist/runtime/composables/useMongocampPermissions.js +43 -0
  115. package/dist/runtime/composables/useMongocampPersistedState.d.ts +15 -0
  116. package/dist/runtime/composables/useMongocampPersistedState.js +21 -0
  117. package/dist/runtime/composables/useMongocampProxyApi.js +2 -1
  118. package/dist/runtime/composables/useMongocampQuery.d.ts +50 -2
  119. package/dist/runtime/composables/useMongocampQuery.js +72 -1
  120. package/dist/runtime/composables/useMongocampSavedPipelines.d.ts +25 -0
  121. package/dist/runtime/composables/useMongocampSavedPipelines.js +23 -0
  122. package/dist/runtime/composables/useMongocampSavedQueries.d.ts +37 -0
  123. package/dist/runtime/composables/useMongocampSavedQueries.js +50 -0
  124. package/dist/runtime/composables/useMongocampServerOverview.d.ts +35 -0
  125. package/dist/runtime/composables/useMongocampServerOverview.js +51 -0
  126. package/dist/runtime/composables/useMongocampSession.d.ts +2 -0
  127. package/dist/runtime/composables/useMongocampSession.js +16 -2
  128. package/dist/runtime/composables/useMongocampSystem.d.ts +7 -2
  129. package/dist/runtime/composables/useMongocampSystem.js +6 -2
  130. package/dist/runtime/locales/de.json +509 -25
  131. package/dist/runtime/locales/en.json +509 -25
  132. package/dist/runtime/plugin.js +6 -3
  133. package/dist/runtime/utils/aggregationErrors.d.ts +4 -0
  134. package/dist/runtime/utils/aggregationErrors.js +7 -0
  135. package/dist/runtime/utils/aggregationPipeline.d.ts +5 -4
  136. package/dist/runtime/utils/aggregationPipeline.js +23 -9
  137. package/dist/runtime/utils/aggregationPreview.d.ts +13 -0
  138. package/dist/runtime/utils/aggregationPreview.js +10 -0
  139. package/dist/runtime/utils/aggregationResult.d.ts +5 -0
  140. package/dist/runtime/utils/aggregationResult.js +4 -0
  141. package/dist/runtime/utils/aggregationTemplates.d.ts +34 -0
  142. package/dist/runtime/utils/aggregationTemplates.js +47 -0
  143. package/dist/runtime/utils/analyzeSamples.d.ts +1 -0
  144. package/dist/runtime/utils/analyzeSamples.js +1 -1
  145. package/dist/runtime/utils/autoRefresh.d.ts +14 -0
  146. package/dist/runtime/utils/autoRefresh.js +15 -0
  147. package/dist/runtime/utils/batchInsert.d.ts +6 -0
  148. package/dist/runtime/utils/batchInsert.js +31 -3
  149. package/dist/runtime/utils/bigIntJson.d.ts +15 -0
  150. package/dist/runtime/utils/bigIntJson.js +55 -0
  151. package/dist/runtime/utils/bsonTypes.d.ts +10 -0
  152. package/dist/runtime/utils/bsonTypes.js +42 -0
  153. package/dist/runtime/utils/bulkDelete.d.ts +9 -1
  154. package/dist/runtime/utils/bulkDelete.js +15 -3
  155. package/dist/runtime/utils/bulkEdit.d.ts +6 -0
  156. package/dist/runtime/utils/bulkEdit.js +7 -0
  157. package/dist/runtime/utils/chartData.d.ts +11 -0
  158. package/dist/runtime/utils/chartData.js +9 -0
  159. package/dist/runtime/utils/collectionChart.d.ts +36 -0
  160. package/dist/runtime/utils/collectionChart.js +73 -0
  161. package/dist/runtime/utils/collectionCopy.d.ts +24 -0
  162. package/dist/runtime/utils/collectionCopy.js +37 -0
  163. package/dist/runtime/utils/collectionStats.d.ts +31 -0
  164. package/dist/runtime/utils/collectionStats.js +42 -0
  165. package/dist/runtime/utils/commandPalette.d.ts +48 -0
  166. package/dist/runtime/utils/commandPalette.js +39 -0
  167. package/dist/runtime/utils/configRows.d.ts +7 -0
  168. package/dist/runtime/utils/configRows.js +4 -0
  169. package/dist/runtime/utils/documentCompare.d.ts +31 -0
  170. package/dist/runtime/utils/documentCompare.js +71 -0
  171. package/dist/runtime/utils/documentDiff.d.ts +19 -0
  172. package/dist/runtime/utils/documentDiff.js +71 -0
  173. package/dist/runtime/utils/documentPaths.d.ts +41 -0
  174. package/dist/runtime/utils/documentPaths.js +139 -0
  175. package/dist/runtime/utils/documentTree.d.ts +40 -0
  176. package/dist/runtime/utils/documentTree.js +102 -0
  177. package/dist/runtime/utils/exportDocuments.d.ts +33 -0
  178. package/dist/runtime/utils/exportDocuments.js +53 -0
  179. package/dist/runtime/utils/exportRows.d.ts +2 -0
  180. package/dist/runtime/utils/exportRows.js +6 -3
  181. package/dist/runtime/utils/fieldDetails.d.ts +51 -0
  182. package/dist/runtime/utils/fieldDetails.js +113 -0
  183. package/dist/runtime/utils/filePreview.d.ts +27 -0
  184. package/dist/runtime/utils/filePreview.js +50 -0
  185. package/dist/runtime/utils/filterBuilder.d.ts +6 -1
  186. package/dist/runtime/utils/filterBuilder.js +6 -5
  187. package/dist/runtime/utils/formatBytes.d.ts +2 -0
  188. package/dist/runtime/utils/formatBytes.js +11 -0
  189. package/dist/runtime/utils/grantMatching.d.ts +8 -0
  190. package/dist/runtime/utils/grantMatching.js +15 -0
  191. package/dist/runtime/utils/importRows.js +12 -2
  192. package/dist/runtime/utils/indexForm.d.ts +83 -0
  193. package/dist/runtime/utils/indexForm.js +74 -0
  194. package/dist/runtime/utils/luceneExpression.d.ts +15 -0
  195. package/dist/runtime/utils/luceneExpression.js +74 -0
  196. package/dist/runtime/utils/pagedFetch.d.ts +46 -0
  197. package/dist/runtime/utils/pagedFetch.js +58 -0
  198. package/dist/runtime/utils/paginationHeaders.d.ts +4 -0
  199. package/dist/runtime/utils/paginationHeaders.js +4 -0
  200. package/dist/runtime/utils/permissionDenied.d.ts +10 -0
  201. package/dist/runtime/utils/permissionDenied.js +23 -0
  202. package/dist/runtime/utils/permissionMatrix.d.ts +55 -0
  203. package/dist/runtime/utils/permissionMatrix.js +85 -0
  204. package/dist/runtime/utils/persistedState.d.ts +25 -0
  205. package/dist/runtime/utils/persistedState.js +47 -0
  206. package/dist/runtime/utils/queryState.d.ts +45 -0
  207. package/dist/runtime/utils/queryState.js +75 -0
  208. package/dist/runtime/utils/requestLimits.d.ts +2 -0
  209. package/dist/runtime/utils/requestLimits.js +4 -0
  210. package/dist/runtime/utils/resultChart.d.ts +32 -0
  211. package/dist/runtime/utils/resultChart.js +59 -0
  212. package/dist/runtime/utils/savedPipelines.d.ts +22 -0
  213. package/dist/runtime/utils/savedPipelines.js +46 -0
  214. package/dist/runtime/utils/savedQueries.d.ts +60 -0
  215. package/dist/runtime/utils/savedQueries.js +143 -0
  216. package/dist/runtime/utils/schemaAnalysis.d.ts +16 -0
  217. package/dist/runtime/utils/schemaAnalysis.js +57 -0
  218. package/dist/runtime/utils/serverError.d.ts +19 -0
  219. package/dist/runtime/utils/serverError.js +19 -0
  220. package/dist/runtime/utils/serverOverview.d.ts +47 -0
  221. package/dist/runtime/utils/serverOverview.js +40 -0
  222. package/dist/runtime/utils/sessionGuard.d.ts +3 -0
  223. package/dist/runtime/utils/sessionGuard.js +18 -1
  224. package/package.json +15 -14
@@ -4,6 +4,7 @@ import { useI18n, useMongocampError, useMongocampStorage, useToast } from "#impo
4
4
  import useMongocampAdmin from "../composables/useMongocampAdmin";
5
5
  import { runBulkDelete } from "../utils/bulkDelete";
6
6
  import { createSelectColumn } from "../utils/createSelectColumn";
7
+ import { useMongocampAdminGate } from "../composables/useMongocampAdminGate";
7
8
  const { t } = useI18n();
8
9
  const { listUsers, addUser, deleteUser, updateUserRoles, updateUserPassword, listRoles, regenerateUserApiKey } = useMongocampAdmin();
9
10
  const toast = useToast();
@@ -79,7 +80,7 @@ const editUserSchema = reactive([
79
80
  }
80
81
  ]);
81
82
  const loadError = ref(null);
82
- const { describeError } = useMongocampError();
83
+ const { describeError, describeServerError } = useMongocampError();
83
84
  const storage = useMongocampStorage();
84
85
  const rowSelection = ref({});
85
86
  const selectedUserIds = computed(() => Object.keys(rowSelection.value).filter((id) => rowSelection.value[id]));
@@ -107,6 +108,7 @@ async function handleBulkDelete() {
107
108
  bulkDeleting.value = false;
108
109
  }
109
110
  }
111
+ const { blocked, message } = useMongocampAdminGate();
110
112
  async function fetchUsers() {
111
113
  loading.value = true;
112
114
  loadError.value = null;
@@ -179,7 +181,7 @@ async function handleDeleteUser() {
179
181
  isDeleteModalOpen.value = false;
180
182
  await fetchUsers();
181
183
  } catch (e) {
182
- deleteError.value = describeError(e, "nuxtUiMongocamp.users.errorDelete").message;
184
+ deleteError.value = (await describeServerError(e, "nuxtUiMongocamp.users.errorDelete")).message;
183
185
  } finally {
184
186
  deleting.value = false;
185
187
  }
@@ -204,7 +206,7 @@ async function handleRegenerateKey() {
204
206
  newApiKey.value = await regenerateUserApiKey(keyUser.value);
205
207
  await fetchUsers();
206
208
  } catch (e) {
207
- keyError.value = describeError(e).message;
209
+ keyError.value = (await describeServerError(e)).message;
208
210
  } finally {
209
211
  keyBusy.value = false;
210
212
  }
@@ -327,12 +329,23 @@ const columns = computed(() => [
327
329
  ])
328
330
  }
329
331
  ]);
330
- fetchUsers();
331
- fetchRoles();
332
+ if (!blocked.value) {
333
+ fetchUsers();
334
+ fetchRoles();
335
+ }
332
336
  </script>
333
337
 
334
338
  <template>
335
- <div class="flex flex-col gap-4">
339
+ <MongocampEmptyState
340
+ v-if="blocked"
341
+ icon="i-lucide-shield-alert"
342
+ :title="message"
343
+ data-test="admin-only"
344
+ />
345
+ <div
346
+ v-else
347
+ class="flex flex-col gap-4"
348
+ >
336
349
  <div class="flex items-center justify-between gap-4">
337
350
  <h2 class="text-xl font-semibold">
338
351
  {{ t("nuxtUiMongocamp.users.heading") }}
@@ -1,4 +1,4 @@
1
- import type { Grant, JsonSchema, JsonValueBoolean, Role, UserProfile } from '@sfxcode/nuxt-mongocamp-server';
1
+ import type { Grant, JsonSchema, JsonValueBoolean, Role, SchemaAnalysis, UserProfile } from '@sfxcode/nuxt-mongocamp-server';
2
2
  declare const _default: () => {
3
3
  listUsers: (filter?: string) => Promise<UserProfile[]>;
4
4
  addUser: (userId: string, password: string, apiKey?: string, roles?: string[]) => Promise<UserProfile>;
@@ -13,6 +13,7 @@ declare const _default: () => {
13
13
  clearCollection: (collectionName: string) => Promise<JsonValueBoolean>;
14
14
  deleteCollection: (collectionName: string) => Promise<JsonValueBoolean>;
15
15
  getJsonSchema: (collectionName: string) => Promise<JsonSchema>;
16
+ getSchemaAnalysis: (collectionName: string, documents: number, depth?: number) => Promise<SchemaAnalysis>;
16
17
  getUser: (userId: string) => Promise<UserProfile>;
17
18
  getRole: (roleName: string) => Promise<Role>;
18
19
  regenerateUserApiKey: (userId: string) => Promise<string>;
@@ -1,4 +1,5 @@
1
1
  import { useMongocampClientApi } from "#imports";
2
+ import { analysisSampleSize, analysisTimeoutMs } from "../utils/schemaAnalysis.js";
2
3
  const REQUEST_TIMEOUT_MS = 15e3;
3
4
  function withTimeout() {
4
5
  return { signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) };
@@ -57,6 +58,10 @@ export default () => {
57
58
  async function getJsonSchema(collectionName) {
58
59
  return collectionApi.getJsonSchema({ collectionName }, withTimeout());
59
60
  }
61
+ async function getSchemaAnalysis(collectionName, documents, depth = 3) {
62
+ const sampleSize = analysisSampleSize(documents);
63
+ return collectionApi.getSchemaAnalysis({ collectionName, sampleSize, deepth: depth }, { signal: AbortSignal.timeout(analysisTimeoutMs(sampleSize)) });
64
+ }
60
65
  async function getUser(userId) {
61
66
  return adminApi.getUser({ userId }, withTimeout());
62
67
  }
@@ -67,5 +72,5 @@ export default () => {
67
72
  const result = await adminApi.gnerateNewApiKeyForUser({ userId }, withTimeout());
68
73
  return result.value;
69
74
  }
70
- return { listUsers, addUser, deleteUser, updateUserRoles, updateUserPassword, listRoles, addRole, updateRole, deleteRole, listCollections, clearCollection, deleteCollection, getJsonSchema, getUser, getRole, regenerateUserApiKey };
75
+ return { listUsers, addUser, deleteUser, updateUserRoles, updateUserPassword, listRoles, addRole, updateRole, deleteRole, listCollections, clearCollection, deleteCollection, getJsonSchema, getSchemaAnalysis, getUser, getRole, regenerateUserApiKey };
71
76
  };
@@ -0,0 +1,12 @@
1
+ /**
2
+ * For components that only make sense for an administrator (they call admin endpoints on mount): `blocked` is true when the
3
+ * signed-in user is known **not** to be an administrator, so the component can show `message` ("administrators only")
4
+ * **without sending a request** that the server must refuse. It is a UI hint, not a guard — the server stays the authority.
5
+ *
6
+ * Fail-open: server proxy mode (the api key's power decides), no profile yet, or a profile without an `isAdmin` flag are never
7
+ * blocked.
8
+ */
9
+ export declare function useMongocampAdminGate(): {
10
+ blocked: import("vue").ComputedRef<boolean>;
11
+ message: import("vue").ComputedRef<string>;
12
+ };
@@ -0,0 +1,12 @@
1
+ import { useRuntimeConfig } from "#app";
2
+ import { useI18n, useMongocampStorage } from "#imports";
3
+ import { computed } from "vue";
4
+ export function useMongocampAdminGate() {
5
+ const config = useRuntimeConfig();
6
+ const state = useMongocampStorage();
7
+ const { t } = useI18n();
8
+ const isProxyMode = config.public.nuxtUiMongocampOptions?.useServerProxy ?? false;
9
+ const blocked = computed(() => !isProxyMode && state.value?.profile?.isAdmin === false);
10
+ const message = computed(() => t("nuxtUiMongocamp.common.adminOnly"));
11
+ return { blocked, message };
12
+ }
@@ -1,8 +1,25 @@
1
+ import type { FieldInfo } from '@sfxcode/nuxt-mongocamp-server';
1
2
  import type { RequestStage } from '../utils/aggregationPipeline.js';
2
3
  export interface AggregationPaging {
3
4
  page?: number;
4
5
  rowsPerPage?: number;
5
6
  }
7
+ export interface AggregationOptions {
8
+ /**
9
+ * Lets the pipeline use `$collStats` / `$indexStats` (storage and index-usage numbers) — and nothing else from the
10
+ * deny-list. Their results carry the database server's address, so `host` and `ns` are removed from every row.
11
+ * For the module's own stats calls; the aggregation builder never sets it.
12
+ */
13
+ allowStatsStages?: boolean;
14
+ /**
15
+ * A Lucene filter (the syntax of the document list) applied by the server as the first `$match` (server 1.7.0), so an
16
+ * aggregation can follow what a table shows. It travels in the URL: one over ~1 800 encoded characters is refused up front
17
+ * with a `FilterTooLongError` instead of becoming an opaque network failure.
18
+ */
19
+ filter?: string;
20
+ /** Aborting rejects the call (an `AbortError`); the 30 s timeout still applies. */
21
+ signal?: AbortSignal;
22
+ }
6
23
  export interface AggregationResult {
7
24
  rows: Record<string, unknown>[];
8
25
  total: number;
@@ -21,8 +38,13 @@ export interface DescribedAggregationError {
21
38
  message: string;
22
39
  }
23
40
  export declare function useMongocampAggregation(): {
24
- runAggregation: (collectionName: string, pipeline: RequestStage[], paging?: AggregationPaging) => Promise<AggregationResult>;
41
+ runAggregation: (collectionName: string, pipeline: RequestStage[], paging?: AggregationPaging, options?: AggregationOptions) => Promise<AggregationResult>;
25
42
  listDistinct: (collectionName: string, field: string, limit?: number) => Promise<DistinctResult>;
43
+ listFieldNames: (collectionName: string) => Promise<string[]>;
44
+ listFieldDetails: (collectionName: string, options?: {
45
+ sampleSize?: number;
46
+ depth?: number;
47
+ }) => Promise<FieldInfo[]>;
26
48
  sampleDocuments: (collectionName: string, size?: number) => Promise<AggregationResult>;
27
49
  describeAggregationError: (error: unknown) => Promise<DescribedAggregationError>;
28
50
  };
@@ -1,7 +1,14 @@
1
1
  import { useMongocampClientApi, useI18n } from "#imports";
2
2
  import { useMongocampError } from "./useMongocampError.js";
3
- import { findForbidden } from "../utils/aggregationPipeline.js";
4
- import { ForbiddenPipelineError, parseServerError } from "../utils/aggregationErrors.js";
3
+ import { findForbidden, STATS_OPERATORS } from "../utils/aggregationPipeline.js";
4
+ import { FilterTooLongError, ForbiddenPipelineError } from "../utils/aggregationErrors.js";
5
+ import { fieldPathsOf } from "../utils/fieldDetails.js";
6
+ import { isFilterTooLong, MAX_ENCODED_FILTER_LENGTH } from "../utils/requestLimits.js";
7
+ import { stripServerFields } from "../utils/aggregationResult.js";
8
+ import { readJsonKeepingLongs } from "../utils/bigIntJson.js";
9
+ import { headerNumber } from "../utils/paginationHeaders.js";
10
+ import { unwrapExtendedJson } from "./useMongocampExtendedJson.js";
11
+ import { notAllowedOperator, OPERATOR_NOT_ALLOWED_CODE, readServerError } from "../utils/serverError.js";
5
12
  const AGGREGATE_TIMEOUT_MS = 3e4;
6
13
  const REQUEST_TIMEOUT_MS = 15e3;
7
14
  const DEFAULT_SAMPLE_SIZE = 500;
@@ -10,30 +17,33 @@ const DEFAULT_DISTINCT_LIMIT = 100;
10
17
  function withTimeout(ms) {
11
18
  return { signal: AbortSignal.timeout(ms) };
12
19
  }
20
+ function requestInit(ms, signal) {
21
+ const timeout = AbortSignal.timeout(ms);
22
+ return { signal: signal && typeof AbortSignal.any === "function" ? AbortSignal.any([signal, timeout]) : timeout };
23
+ }
13
24
  function isPlainObject(value) {
14
25
  return typeof value === "object" && value !== null && !Array.isArray(value);
15
26
  }
16
- function headerNumber(headers, name) {
17
- const parsed = Number.parseInt(headers?.get(name) ?? "", 10);
18
- return Number.isNaN(parsed) ? void 0 : parsed;
19
- }
20
27
  export function useMongocampAggregation() {
21
28
  const { collectionApi } = useMongocampClientApi();
22
29
  const { describeError } = useMongocampError();
23
30
  const { t } = useI18n();
24
- async function runAggregation(collectionName, pipeline, paging = {}) {
25
- const findings = findForbidden(pipeline);
31
+ async function runAggregation(collectionName, pipeline, paging = {}, options = {}) {
32
+ const findings = findForbidden(pipeline, options.allowStatsStages ? STATS_OPERATORS : []);
26
33
  if (findings.length > 0) throw new ForbiddenPipelineError(findings);
34
+ if (isFilterTooLong(options.filter)) throw new FilterTooLongError(MAX_ENCODED_FILTER_LENGTH);
27
35
  const page = paging.page ?? 1;
28
36
  const response = await collectionApi.aggregateRaw({
29
37
  collectionName,
30
38
  // the generated type says string values; the server takes any JSON. allowDiskUse is required.
31
39
  mongoAggregateRequest: { pipeline, allowDiskUse: false },
32
40
  rowsPerPage: paging.rowsPerPage,
33
- page
34
- }, withTimeout(AGGREGATE_TIMEOUT_MS));
35
- const value = await response.value();
36
- const rows = Array.isArray(value) ? value.filter(isPlainObject) : [];
41
+ page,
42
+ filter: options.filter?.trim() ? options.filter : void 0
43
+ }, requestInit(AGGREGATE_TIMEOUT_MS, options.signal));
44
+ const value = await readJsonKeepingLongs(response);
45
+ const unwrapped = Array.isArray(value) ? value.filter(isPlainObject).map((row) => unwrapExtendedJson(row)) : [];
46
+ const rows = options.allowStatsStages ? stripServerFields(unwrapped) : unwrapped;
37
47
  const headers = response.raw?.headers;
38
48
  return {
39
49
  rows,
@@ -42,9 +52,15 @@ export function useMongocampAggregation() {
42
52
  page: headerNumber(headers, "x-pagination-current-page") ?? page
43
53
  };
44
54
  }
55
+ async function listFieldDetails(collectionName, options = {}) {
56
+ return collectionApi.getFieldDetails({ collectionName, sampleSize: options.sampleSize, depth: options.depth }, withTimeout(REQUEST_TIMEOUT_MS));
57
+ }
58
+ async function listFieldNames(collectionName) {
59
+ return fieldPathsOf(await listFieldDetails(collectionName));
60
+ }
45
61
  async function listDistinct(collectionName, field, limit = DEFAULT_DISTINCT_LIMIT) {
46
62
  const response = await collectionApi.distinctRaw({ collectionName, field, rowsPerPage: limit, page: 1 }, withTimeout(REQUEST_TIMEOUT_MS));
47
- const value = await response.value();
63
+ const value = unwrapExtendedJson(await readJsonKeepingLongs(response));
48
64
  const values = (Array.isArray(value) ? value : []).filter((v) => typeof v === "string" || typeof v === "number" || typeof v === "boolean");
49
65
  const total = headerNumber(response.raw?.headers, "x-pagination-count-rows") ?? values.length;
50
66
  return { values, total, truncated: total > values.length };
@@ -54,25 +70,24 @@ export function useMongocampAggregation() {
54
70
  return runAggregation(collectionName, [{ stage: "$sample", value: { size: clamped } }], { page: 1, rowsPerPage: clamped });
55
71
  }
56
72
  async function describeAggregationError(error) {
73
+ if (error instanceof FilterTooLongError) return { kind: "other", message: t("nuxtUiMongocamp.aggregation.errors.filterTooLong", { max: error.max }) };
57
74
  if (error instanceof ForbiddenPipelineError) {
58
75
  return { kind: "forbidden", message: t("nuxtUiMongocamp.aggregation.errors.forbidden", { operator: error.findings[0]?.operator ?? "" }) };
59
76
  }
60
- const response = error?.response;
61
- const status = response?.status;
77
+ const server = await readServerError(error);
78
+ if (server.code === OPERATOR_NOT_ALLOWED_CODE) {
79
+ const operator = notAllowedOperator(server.message);
80
+ return { kind: "forbidden", message: operator ? t("nuxtUiMongocamp.aggregation.errors.forbidden", { operator }) : t("nuxtUiMongocamp.errors.notAllowed") };
81
+ }
82
+ const status = server.status;
62
83
  if (status === 405) return { kind: "retryable", message: t("nuxtUiMongocamp.aggregation.errors.retryable") };
63
84
  if (status === 503) return { kind: "retryable", message: t("nuxtUiMongocamp.aggregation.errors.unavailable") };
64
- if (response && status !== void 0 && status >= 400 && status !== 401 && status !== 403) {
65
- try {
66
- const body = await response.clone().json();
67
- if (typeof body?.msg === "string" && body.msg) {
68
- const info = parseServerError(body.msg);
69
- if (info.message) return { kind: info.kind, message: info.message };
70
- }
71
- } catch {
72
- }
85
+ if (status !== void 0 && status >= 400 && status !== 401 && status !== 403 && server.message) {
86
+ return { kind: server.kind ?? "other", message: server.message };
73
87
  }
74
88
  const described = describeError(error);
75
- return { kind: described.kind === "forbidden" ? "forbidden-access" : described.kind, message: described.message };
89
+ const kind = described.kind === "forbidden" ? "forbidden-access" : described.kind === "notAllowed" || described.kind === "invalid" ? "other" : described.kind;
90
+ return { kind, message: described.message };
76
91
  }
77
- return { runAggregation, listDistinct, sampleDocuments, describeAggregationError };
92
+ return { runAggregation, listDistinct, listFieldNames, listFieldDetails, sampleDocuments, describeAggregationError };
78
93
  }
@@ -0,0 +1,26 @@
1
+ import type { MaybeRefOrGetter, Ref } from 'vue';
2
+ import type { BackoffOptions } from '../utils/autoRefresh.js';
3
+ export interface AutoRefreshOptions {
4
+ /** Time between the end of one load and the start of the next (at least 1000; a ref or getter is read at every schedule). */
5
+ intervalMs: MaybeRefOrGetter<number>;
6
+ /** Wait while the tab is hidden and load again as soon as it is shown (default true). */
7
+ pauseWhenHidden?: boolean;
8
+ /** Slow down after failures (`false` = always the plain interval). Default: ×2 up to 5 minutes. */
9
+ backoff?: BackoffOptions | false;
10
+ }
11
+ export interface AutoRefresh {
12
+ start: () => void;
13
+ stop: () => void;
14
+ /** Loads now (unless a load is running) and restarts the wait; works while stopped too, without starting the timer. */
15
+ refreshNow: () => Promise<void>;
16
+ running: Ref<boolean>;
17
+ lastRefreshed: Ref<Date | null>;
18
+ /** The error of the latest load, cleared by the next success. */
19
+ lastError: Ref<unknown>;
20
+ }
21
+ /**
22
+ * Calls `load` repeatedly while running. Loads never overlap (the next wait starts after the previous load ended), a
23
+ * failing load backs the delay off and is reported in `lastError` instead of being thrown, a hidden tab pauses it, and it
24
+ * stops with the component/effect scope that created it. It never runs on the server.
25
+ */
26
+ export declare function useMongocampAutoRefresh(load: () => Promise<unknown> | unknown, options: AutoRefreshOptions): AutoRefresh;
@@ -0,0 +1,78 @@
1
+ import { getCurrentScope, onScopeDispose, ref, toValue } from "vue";
2
+ import { nextDelay } from "../utils/autoRefresh.js";
3
+ export function useMongocampAutoRefresh(load, options) {
4
+ const running = ref(false);
5
+ const lastRefreshed = ref(null);
6
+ const lastError = ref(null);
7
+ const pauseWhenHidden = options.pauseWhenHidden ?? true;
8
+ const isBrowser = typeof document !== "undefined";
9
+ let timer;
10
+ let inFlight;
11
+ let failures = 0;
12
+ let generation = 0;
13
+ let listening = false;
14
+ const hidden = () => pauseWhenHidden && isBrowser && document.hidden;
15
+ const delay = () => nextDelay(toValue(options.intervalMs), failures, options.backoff);
16
+ function clearTimer() {
17
+ if (timer !== void 0) clearTimeout(timer);
18
+ timer = void 0;
19
+ }
20
+ function schedule() {
21
+ clearTimer();
22
+ if (!running.value || hidden()) return;
23
+ timer = setTimeout(() => void run(), delay());
24
+ }
25
+ function run() {
26
+ if (inFlight) return inFlight;
27
+ clearTimer();
28
+ const mine = generation;
29
+ inFlight = (async () => {
30
+ try {
31
+ await load();
32
+ failures = 0;
33
+ lastError.value = null;
34
+ lastRefreshed.value = /* @__PURE__ */ new Date();
35
+ } catch (e) {
36
+ failures++;
37
+ lastError.value = e;
38
+ } finally {
39
+ inFlight = void 0;
40
+ if (mine === generation) schedule();
41
+ }
42
+ })();
43
+ return inFlight;
44
+ }
45
+ function onVisibility() {
46
+ if (!running.value) return;
47
+ if (document.hidden) {
48
+ if (pauseWhenHidden) clearTimer();
49
+ return;
50
+ }
51
+ if (pauseWhenHidden && !inFlight) void run();
52
+ }
53
+ function start() {
54
+ if (!isBrowser || running.value) return;
55
+ running.value = true;
56
+ failures = 0;
57
+ if (!listening) {
58
+ document.addEventListener("visibilitychange", onVisibility);
59
+ listening = true;
60
+ }
61
+ schedule();
62
+ }
63
+ function stop() {
64
+ generation++;
65
+ running.value = false;
66
+ clearTimer();
67
+ if (listening && isBrowser) {
68
+ document.removeEventListener("visibilitychange", onVisibility);
69
+ listening = false;
70
+ }
71
+ }
72
+ async function refreshNow() {
73
+ if (!isBrowser) return;
74
+ await run();
75
+ }
76
+ if (getCurrentScope()) onScopeDispose(stop);
77
+ return { start, stop, refreshNow, running, lastRefreshed, lastError };
78
+ }
@@ -12,7 +12,7 @@ export interface ListFilesResult {
12
12
  }
13
13
  export interface UpdateFileInformationOptions {
14
14
  filename?: string;
15
- metadata?: Record<string, string>;
15
+ metadata?: Record<string, unknown>;
16
16
  }
17
17
  export declare function useMongocampBucket(): {
18
18
  isBucketCollection: (collectionName: string) => boolean;
@@ -22,6 +22,18 @@ export declare function useMongocampBucket(): {
22
22
  uploading: import("vue").Ref<boolean, boolean>;
23
23
  downloadFile: (collectionName: string, fileId: string) => Promise<void>;
24
24
  uploadFile: (collectionName: string, file: File) => Promise<boolean>;
25
+ uploadFiles: (bucketName: string, files: File[], options?: {
26
+ signal?: AbortSignal;
27
+ onProgress?: (done: number, total: number, current?: string) => void;
28
+ }) => Promise<{
29
+ uploaded: string[];
30
+ failed: {
31
+ name: string;
32
+ message: string;
33
+ }[];
34
+ aborted: boolean;
35
+ }>;
36
+ fetchFileBlob: (bucketName: string, fileId: string) => Promise<Blob>;
25
37
  bucketActionInFlight: import("vue").Ref<Set<string> & Omit<Set<string>, keyof Set<any>>, Set<string> | (Set<string> & Omit<Set<string>, keyof Set<any>>)>;
26
38
  fileActionInFlight: import("vue").Ref<Set<string> & Omit<Set<string>, keyof Set<any>>, Set<string> | (Set<string> & Omit<Set<string>, keyof Set<any>>)>;
27
39
  listFiles: (bucketName: string, options?: ListFilesOptions) => Promise<ListFilesResult>;
@@ -1,6 +1,7 @@
1
1
  import { ref } from "vue";
2
2
  import { useI18n, useMongocampClientApi, useToast } from "#imports";
3
3
  import { BUCKET_COLLECTION_SUFFIX } from "../utils/collectionProtection.js";
4
+ import { isFilterTooLong, MAX_ENCODED_FILTER_LENGTH } from "../utils/requestLimits.js";
4
5
  function unwrapId(value) {
5
6
  if (typeof value === "string") return value;
6
7
  if (typeof value === "object" && value !== null && "$oid" in value) {
@@ -62,7 +63,38 @@ export function useMongocampBucket() {
62
63
  uploading.value = false;
63
64
  }
64
65
  }
66
+ async function fetchFileBlob(bucketName, fileId) {
67
+ return fileApi.getFile({ bucketName, fileId });
68
+ }
69
+ async function uploadFiles(bucketName, files, options = {}) {
70
+ const uploaded = [];
71
+ const failed = [];
72
+ let aborted = false;
73
+ uploading.value = true;
74
+ try {
75
+ for (const [index, file] of files.entries()) {
76
+ if (options.signal?.aborted) {
77
+ aborted = true;
78
+ break;
79
+ }
80
+ options.onProgress?.(index, files.length, file.name);
81
+ try {
82
+ await fileApi.insertFile({ bucketName, file, fileName: file.name, metaData: "{}" });
83
+ uploaded.push(file.name);
84
+ } catch (e) {
85
+ failed.push({ name: file.name, message: e instanceof Error ? e.message : t("nuxtUiMongocamp.bucket.uploadFailedFallback") });
86
+ }
87
+ }
88
+ options.onProgress?.(uploaded.length + failed.length, files.length);
89
+ } finally {
90
+ uploading.value = false;
91
+ }
92
+ return { uploaded, failed, aborted };
93
+ }
65
94
  async function listFiles(bucketName, options = {}) {
95
+ if (isFilterTooLong(options.filter)) {
96
+ throw new Error(t("nuxtUiMongocamp.bucket.filterTooLong", { max: MAX_ENCODED_FILTER_LENGTH }));
97
+ }
66
98
  const res = await fileApi.listFilesRaw({
67
99
  bucketName,
68
100
  filter: options.filter,
@@ -145,6 +177,8 @@ export function useMongocampBucket() {
145
177
  uploading,
146
178
  downloadFile,
147
179
  uploadFile,
180
+ uploadFiles,
181
+ fetchFileBlob,
148
182
  bucketActionInFlight,
149
183
  fileActionInFlight,
150
184
  listFiles,
@@ -0,0 +1,15 @@
1
+ export interface BulkUpdateByFilterResult {
2
+ matched: number;
3
+ modified: number;
4
+ }
5
+ /**
6
+ * Count, delete and update by the **Lucene filter** of the list — one request each (server 1.7.0): no ids are collected,
7
+ * so there is no cap, no id snapshot and nothing to chunk. An empty filter would touch the whole collection, which the
8
+ * server only does with `matchAll=true`; it is sent exactly when the filter is empty, so the caller's own confirmation
9
+ * (the typed collection name) is what guards that case. A filter the server cannot parse is answered 400 (nothing changes).
10
+ */
11
+ export declare function useMongocampBulkByFilter(): {
12
+ countDocuments: (collectionName: string, filter?: string, signal?: AbortSignal) => Promise<number>;
13
+ deleteByFilter: (collectionName: string, filter?: string, signal?: AbortSignal) => Promise<number>;
14
+ updateByFilter: (collectionName: string, filter: string | undefined, document: Record<string, unknown>, signal?: AbortSignal) => Promise<BulkUpdateByFilterResult>;
15
+ };
@@ -0,0 +1,32 @@
1
+ import { useMongocampClientApi } from "#imports";
2
+ export function useMongocampBulkByFilter() {
3
+ const { documentApi } = useMongocampClientApi();
4
+ const clean = (filter) => filter && filter.trim() !== "" ? filter : void 0;
5
+ async function countDocuments(collectionName, filter, signal) {
6
+ const response = await documentApi.countDocuments({ collectionName, filter: clean(filter) }, signal ? { signal } : void 0);
7
+ return response.count;
8
+ }
9
+ async function deleteByFilter(collectionName, filter, signal) {
10
+ const lucene = clean(filter);
11
+ const response = await documentApi.deleteMany(
12
+ { collectionName, requestBody: {}, filter: lucene, matchAll: lucene === void 0 ? true : void 0 },
13
+ signal ? { signal } : void 0
14
+ );
15
+ return response.deletedCount;
16
+ }
17
+ async function updateByFilter(collectionName, filter, document, signal) {
18
+ const lucene = clean(filter);
19
+ const response = await documentApi.updateMany(
20
+ {
21
+ collectionName,
22
+ // the generated type says string values only; the server takes any JSON value
23
+ updateRequest: { filter: {}, document },
24
+ filter: lucene,
25
+ matchAll: lucene === void 0 ? true : void 0
26
+ },
27
+ signal ? { signal } : void 0
28
+ );
29
+ return { matched: response.matchedCount, modified: response.modifiedCount };
30
+ }
31
+ return { countDocuments, deleteByFilter, updateByFilter };
32
+ }
@@ -1,8 +1,9 @@
1
1
  import { useRuntimeConfig } from "#app";
2
2
  import { useMongocampApi } from "#imports";
3
+ import { installPermissionDeniedMiddleware } from "../utils/permissionDenied.js";
3
4
  import { useMongocampProxyApi } from "./useMongocampProxyApi.js";
4
5
  export function useMongocampClientApi() {
5
6
  const config = useRuntimeConfig();
6
7
  const useServerProxy = config.public.nuxtUiMongocampOptions?.useServerProxy ?? false;
7
- return useServerProxy ? useMongocampProxyApi() : useMongocampApi();
8
+ return useServerProxy ? useMongocampProxyApi() : installPermissionDeniedMiddleware(useMongocampApi());
8
9
  }
@@ -0,0 +1,45 @@
1
+ export interface CopyOptions {
2
+ source: string;
3
+ target: string;
4
+ /** Lucene filter: copy only the documents that match. */
5
+ filter?: string;
6
+ /** Create the same indexes on the new collection (the server reproduces them from the real index specifications). */
7
+ withIndexes?: boolean;
8
+ signal?: AbortSignal;
9
+ }
10
+ export type CopyRefusal = 'target-exists';
11
+ export interface CopyResult {
12
+ /** Why nothing was copied; absent when the copy ran. */
13
+ refused?: CopyRefusal;
14
+ /** The new collection's name. */
15
+ target: string;
16
+ /** How many documents the new collection holds. */
17
+ count: number;
18
+ /** How many indexes (besides `_id_`) were created on it. */
19
+ indexes: number;
20
+ }
21
+ export interface BackupOptions extends Omit<CopyOptions, 'target'> {
22
+ /** The time put into the name (default: now). */
23
+ now?: Date;
24
+ /** Called with the chosen name before the request, so a UI can show it. */
25
+ onTarget?: (target: string) => void;
26
+ }
27
+ export interface RenameResult {
28
+ refused?: CopyRefusal;
29
+ /** The collection's new name. */
30
+ target: string;
31
+ }
32
+ /**
33
+ * Copy and rename a collection **inside the database** (server 1.8.1): one request, no cap, no browser memory — the server
34
+ * copies with its own checks and, with `withIndexes`, recreates the indexes from the real index specifications (compound
35
+ * order, partial filter, text weights, collation …). Grants, the schema and GridFS files are not copied; the copy is a
36
+ * snapshot taken by the server. A name the server refuses (a target that exists: 409, a reserved one: 400) is thrown, except
37
+ * "target exists", which is returned as `refused` so a dialog can offer another name.
38
+ */
39
+ export declare function useMongocampCollectionCopy(): {
40
+ copyCollection: (options: CopyOptions) => Promise<CopyResult>;
41
+ backupCollection: (options: BackupOptions) => Promise<CopyResult>;
42
+ renameCollection: (source: string, target: string, signal?: AbortSignal) => Promise<RenameResult>;
43
+ listCollectionNames: () => Promise<string[]>;
44
+ countDocuments: (collectionName: string, filter?: string, signal?: AbortSignal) => Promise<number>;
45
+ };
@@ -0,0 +1,48 @@
1
+ import { useMongocampClientApi } from "#imports";
2
+ import { backupName, canCopyCollection, CollectionNotCopyableError } from "../utils/collectionCopy.js";
3
+ import { useMongocampBulkByFilter } from "./useMongocampBulkByFilter.js";
4
+ function isTargetExists(error) {
5
+ return error?.response?.status === 409;
6
+ }
7
+ export function useMongocampCollectionCopy() {
8
+ const { collectionApi } = useMongocampClientApi();
9
+ const { countDocuments } = useMongocampBulkByFilter();
10
+ async function listCollectionNames() {
11
+ return await collectionApi.listCollections();
12
+ }
13
+ async function copyCollection(options) {
14
+ const { source, target, filter, withIndexes, signal } = options;
15
+ try {
16
+ const response = await collectionApi.copyCollection({
17
+ collectionName: source,
18
+ copyRequest: { target, filter: filter?.trim() ? filter : void 0, withIndexes: withIndexes ?? false }
19
+ }, signal ? { signal } : void 0);
20
+ return { target: response.name, count: response.count, indexes: response.indexes };
21
+ } catch (error) {
22
+ if (isTargetExists(error)) return { refused: "target-exists", target, count: 0, indexes: 0 };
23
+ throw error;
24
+ }
25
+ }
26
+ async function backupCollection(options) {
27
+ if (!canCopyCollection(options.source)) throw new CollectionNotCopyableError(options.source);
28
+ const { now, onTarget, ...copy } = options;
29
+ let result;
30
+ for (let attempt = 0; attempt < 3; attempt++) {
31
+ const target = backupName(options.source, await listCollectionNames(), now);
32
+ onTarget?.(target);
33
+ result = await copyCollection({ ...copy, target });
34
+ if (result.refused !== "target-exists") break;
35
+ }
36
+ return result;
37
+ }
38
+ async function renameCollection(source, target, signal) {
39
+ try {
40
+ const response = await collectionApi.renameCollection({ collectionName: source, renameRequest: { target } }, signal ? { signal } : void 0);
41
+ return { target: response.name };
42
+ } catch (error) {
43
+ if (isTargetExists(error)) return { refused: "target-exists", target };
44
+ throw error;
45
+ }
46
+ }
47
+ return { copyCollection, backupCollection, renameCollection, listCollectionNames, countDocuments };
48
+ }
@@ -0,0 +1,10 @@
1
+ import type { CollectionStorage, IndexUsage } from '../utils/collectionStats.js';
2
+ export type { CollectionStorage, IndexUsage } from '../utils/collectionStats.js';
3
+ /**
4
+ * Typed storage and index-usage numbers of one collection. Both come from the server with a 15 s limit; neither shows
5
+ * the database's host, namespace or an index spec.
6
+ */
7
+ export declare function useMongocampCollectionStats(): {
8
+ getStorage: (collection: string) => Promise<CollectionStorage>;
9
+ getIndexUsage: (collection: string) => Promise<IndexUsage[]>;
10
+ };