@sfxcode/nuxt-ui-mongocamp 1.5.6 → 1.5.8

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 (72) hide show
  1. package/dist/module.d.mts +26 -0
  2. package/dist/module.json +1 -1
  3. package/dist/module.mjs +5 -0
  4. package/dist/runtime/components/MongocampAccount.vue +12 -14
  5. package/dist/runtime/components/MongocampAggregationBuilder.vue +27 -43
  6. package/dist/runtime/components/MongocampAggregationChart.vue +7 -5
  7. package/dist/runtime/components/MongocampAggregationStagePreview.vue +1 -1
  8. package/dist/runtime/components/MongocampBucketFiles.vue +25 -34
  9. package/dist/runtime/components/MongocampBulkDelete.d.vue.ts +2 -2
  10. package/dist/runtime/components/MongocampBulkDelete.vue +8 -9
  11. package/dist/runtime/components/MongocampBulkDelete.vue.d.ts +2 -2
  12. package/dist/runtime/components/MongocampBulkEdit.vue +5 -4
  13. package/dist/runtime/components/MongocampChart.vue +1 -1
  14. package/dist/runtime/components/MongocampCollectionCharts.vue +6 -5
  15. package/dist/runtime/components/MongocampCollectionCopy.d.vue.ts +2 -2
  16. package/dist/runtime/components/MongocampCollectionCopy.vue +6 -6
  17. package/dist/runtime/components/MongocampCollectionCopy.vue.d.ts +2 -2
  18. package/dist/runtime/components/MongocampCollectionData.vue +37 -62
  19. package/dist/runtime/components/MongocampCollectionInfos.vue +18 -23
  20. package/dist/runtime/components/MongocampCollectionRename.d.vue.ts +2 -2
  21. package/dist/runtime/components/MongocampCollectionRename.vue +5 -4
  22. package/dist/runtime/components/MongocampCollectionRename.vue.d.ts +2 -2
  23. package/dist/runtime/components/MongocampCollections.vue +24 -33
  24. package/dist/runtime/components/MongocampCommandPalette.d.vue.ts +2 -2
  25. package/dist/runtime/components/MongocampCommandPalette.vue +3 -1
  26. package/dist/runtime/components/MongocampCommandPalette.vue.d.ts +2 -2
  27. package/dist/runtime/components/MongocampConfirmByName.vue +5 -4
  28. package/dist/runtime/components/MongocampDashboard.vue +5 -3
  29. package/dist/runtime/components/MongocampDatabases.vue +14 -8
  30. package/dist/runtime/components/MongocampDocumentCompare.vue +6 -4
  31. package/dist/runtime/components/MongocampDocumentView.vue +6 -8
  32. package/dist/runtime/components/MongocampEmptyState.vue +4 -1
  33. package/dist/runtime/components/MongocampErrorAlert.vue +8 -7
  34. package/dist/runtime/components/MongocampExportAll.vue +7 -7
  35. package/dist/runtime/components/MongocampFilePreview.vue +7 -6
  36. package/dist/runtime/components/MongocampFilterBuilder.vue +12 -16
  37. package/dist/runtime/components/MongocampGrantList.vue +6 -2
  38. package/dist/runtime/components/MongocampImport.vue +29 -28
  39. package/dist/runtime/components/MongocampIndexes.vue +15 -17
  40. package/dist/runtime/components/MongocampJobs.vue +20 -20
  41. package/dist/runtime/components/MongocampLogin.vue +2 -1
  42. package/dist/runtime/components/MongocampPermissionMatrix.vue +14 -11
  43. package/dist/runtime/components/MongocampQueryBar.vue +18 -32
  44. package/dist/runtime/components/MongocampRoleGrants.vue +21 -17
  45. package/dist/runtime/components/MongocampRoles.vue +28 -32
  46. package/dist/runtime/components/MongocampServerInfo.vue +17 -12
  47. package/dist/runtime/components/MongocampServerOverview.vue +16 -12
  48. package/dist/runtime/components/MongocampServerStatus.vue +2 -1
  49. package/dist/runtime/components/MongocampSettings.vue +15 -11
  50. package/dist/runtime/components/MongocampUserAccess.vue +11 -6
  51. package/dist/runtime/components/MongocampUsers.vue +32 -35
  52. package/dist/runtime/components/MongocampVersion.vue +6 -4
  53. package/dist/runtime/composables/useMongocampAdmin.d.ts +4 -4
  54. package/dist/runtime/composables/useMongocampClientApi.d.ts +13 -1
  55. package/dist/runtime/composables/useMongocampConnection.d.ts +25 -0
  56. package/dist/runtime/composables/useMongocampConnection.js +33 -0
  57. package/dist/runtime/composables/useMongocampRoles.d.ts +5 -5
  58. package/dist/runtime/composables/useMongocampUi.d.ts +8 -0
  59. package/dist/runtime/composables/useMongocampUi.js +7 -0
  60. package/dist/runtime/plugin.d.ts +5 -1
  61. package/dist/runtime/plugin.js +62 -2
  62. package/dist/runtime/publicUtils.d.ts +1 -0
  63. package/dist/runtime/publicUtils.js +1 -0
  64. package/dist/runtime/utils/compactSession.d.ts +13 -0
  65. package/dist/runtime/utils/compactSession.js +12 -0
  66. package/dist/runtime/utils/connection.d.ts +23 -0
  67. package/dist/runtime/utils/connection.js +31 -0
  68. package/dist/runtime/utils/sessionGuard.d.ts +1 -0
  69. package/dist/runtime/utils/sessionGuard.js +8 -0
  70. package/dist/runtime/utils/uiTheme.d.ts +65 -0
  71. package/dist/runtime/utils/uiTheme.js +47 -0
  72. package/package.json +13 -13
@@ -6,12 +6,14 @@ import { runBulkDelete } from "../utils/bulkDelete";
6
6
  import { createSelectColumn } from "../utils/createSelectColumn";
7
7
  import { createListPagination } from "../utils/listPagination";
8
8
  import { useMongocampAdminGate } from "../composables/useMongocampAdminGate";
9
+ import { useMongocampUi } from "../composables/useMongocampUi";
9
10
  defineProps({
10
11
  hideHeading: { type: Boolean, required: false },
11
12
  hideRefresh: { type: Boolean, required: false }
12
13
  });
13
14
  const emit = defineEmits(["changed"]);
14
15
  const { t } = useI18n();
16
+ const ui = useMongocampUi();
15
17
  const { listUsers, addUser, deleteUser, updateUserRoles, updateUserPassword, listRoles, regenerateUserApiKey } = useMongocampAdmin();
16
18
  const toast = useToast();
17
19
  const users = ref([]);
@@ -256,8 +258,7 @@ function withTooltip(text, node) {
256
258
  function sortHeader(column, label) {
257
259
  const isSorted = column.getIsSorted();
258
260
  return h(UButton, {
259
- color: "neutral",
260
- variant: "ghost",
261
+ ...ui.value.sortHeader,
261
262
  label,
262
263
  icon: isSorted === "asc" ? "i-lucide-arrow-up-narrow-wide" : isSorted === "desc" ? "i-lucide-arrow-down-wide-narrow" : "i-lucide-arrow-up-down",
263
264
  class: "-mx-2.5",
@@ -267,9 +268,8 @@ function sortHeader(column, label) {
267
268
  function deleteButton(userId) {
268
269
  const button = (disabled) => h(UButton, {
269
270
  "icon": "i-lucide-trash-2",
271
+ ...ui.value.iconButton,
270
272
  "color": "error",
271
- "variant": "ghost",
272
- "size": "sm",
273
273
  "aria-label": t("nuxtUiMongocamp.users.deleteUserTooltip"),
274
274
  disabled,
275
275
  "onClick": () => confirmDelete(userId)
@@ -295,7 +295,7 @@ const columns = computed(() => [
295
295
  cell: ({ row }) => h(UBadge, {
296
296
  label: row.original.isAdmin ? t("nuxtUiMongocamp.users.roleAdmin") : t("nuxtUiMongocamp.users.roleUser"),
297
297
  color: row.original.isAdmin ? "primary" : "neutral",
298
- variant: "subtle"
298
+ variant: ui.value.badge.variant
299
299
  })
300
300
  },
301
301
  {
@@ -308,35 +308,30 @@ const columns = computed(() => [
308
308
  return h(
309
309
  "div",
310
310
  { class: "flex flex-wrap gap-1" },
311
- roles.map((role) => h(UBadge, { label: role, color: "primary", variant: "subtle" }))
311
+ roles.map((role) => h(UBadge, { label: role, color: "primary", variant: ui.value.badge.variant }))
312
312
  );
313
313
  }
314
314
  },
315
315
  {
316
316
  id: "actions",
317
317
  header: "",
318
- cell: ({ row }) => h("div", { class: "flex gap-1 justify-end" }, [
318
+ cell: ({ row }) => h("div", { "class": "flex gap-1 justify-end", "data-mongocamp-part": "row-actions" }, [
319
319
  withTooltip(t("nuxtUiMongocamp.users.detailsTooltip"), h(UButton, {
320
320
  "icon": "i-lucide-info",
321
- "color": "neutral",
322
- "variant": "ghost",
323
- "size": "sm",
321
+ ...ui.value.iconButton,
324
322
  "aria-label": t("nuxtUiMongocamp.users.detailsTooltip"),
325
323
  "onClick": () => openDetail(row.original)
326
324
  })),
327
325
  withTooltip(t("nuxtUiMongocamp.users.editUserTooltip"), h(UButton, {
328
326
  "icon": "i-lucide-pencil",
329
- "color": "neutral",
330
- "variant": "ghost",
331
- "size": "sm",
327
+ ...ui.value.iconButton,
332
328
  "aria-label": t("nuxtUiMongocamp.users.editUserTooltip"),
333
329
  "onClick": () => openEdit(row.original)
334
330
  })),
335
331
  isSelf(row.original.user) ? null : withTooltip(t("nuxtUiMongocamp.users.regenerateKeyTooltip"), h(UButton, {
336
332
  "icon": "i-lucide-key-round",
333
+ ...ui.value.iconButton,
337
334
  "color": "warning",
338
- "variant": "ghost",
339
- "size": "sm",
340
335
  "aria-label": t("nuxtUiMongocamp.users.regenerateKeyTooltip"),
341
336
  "onClick": () => confirmRegenerateKey(row.original.user)
342
337
  })),
@@ -354,27 +349,32 @@ defineExpose({ refresh: fetchUsers });
354
349
  <template>
355
350
  <MongocampEmptyState
356
351
  v-if="blocked"
352
+ class="mongocamp-users"
357
353
  icon="i-lucide-shield-alert"
358
354
  :title="message"
359
355
  data-test="admin-only"
360
356
  />
361
357
  <div
362
358
  v-else
363
- class="flex flex-col gap-4"
359
+ class="mongocamp-users flex flex-col gap-4"
364
360
  >
365
361
  <div class="flex items-center justify-between gap-4">
366
362
  <h2
367
363
  v-if="!hideHeading"
364
+ data-mongocamp-part="heading"
368
365
  class="text-xl font-semibold"
369
366
  >
370
367
  {{ t("nuxtUiMongocamp.users.heading") }}
371
368
  </h2>
372
- <div class="flex flex-1 items-center gap-2">
369
+ <div
370
+ data-mongocamp-part="toolbar"
371
+ class="flex flex-1 items-center gap-2"
372
+ >
373
373
  <UInput
374
374
  v-model="filterText"
375
375
  icon="i-lucide-search"
376
376
  :placeholder="t('nuxtUiMongocamp.users.searchPlaceholder')"
377
- size="sm"
377
+ :size="ui.controlSize"
378
378
  class="flex-1 max-w-xs"
379
379
  @input="onFilterInput"
380
380
  />
@@ -384,8 +384,7 @@ defineExpose({ refresh: fetchUsers });
384
384
  >
385
385
  <UButton
386
386
  icon="i-lucide-refresh-cw"
387
- color="neutral"
388
- variant="ghost"
387
+ v-bind="ui.toolbarButton"
389
388
  :loading="loading"
390
389
  :aria-label="t('nuxtUiMongocamp.common.refresh')"
391
390
  @click="fetchUsers"
@@ -418,6 +417,7 @@ defineExpose({ refresh: fetchUsers });
418
417
  v-model:sorting="sorting"
419
418
  v-model:row-selection="rowSelection"
420
419
  v-model:pagination="pagination"
420
+ data-mongocamp-part="table"
421
421
  :pagination-options="paginationOptions"
422
422
  :get-row-id="(row) => row.user"
423
423
  :row-selection-options="{ enableRowSelection: canSelectUser }"
@@ -488,7 +488,7 @@ defineExpose({ refresh: fetchUsers });
488
488
  <UModal
489
489
  v-model:open="isDeleteModalOpen"
490
490
  :title="t('nuxtUiMongocamp.users.deleteUserTitle')"
491
- :ui="{ footer: 'justify-end' }"
491
+ :ui="{ footer: ui.modal.footer }"
492
492
  >
493
493
  <template #body>
494
494
  <p>{{ t("nuxtUiMongocamp.users.confirmDelete", { userId: userToDelete }) }}</p>
@@ -496,7 +496,7 @@ defineExpose({ refresh: fetchUsers });
496
496
  v-if="deleteError"
497
497
  class="mt-3"
498
498
  color="error"
499
- variant="subtle"
499
+ :variant="ui.alert.variant"
500
500
  icon="i-lucide-circle-alert"
501
501
  :description="deleteError"
502
502
  />
@@ -504,14 +504,13 @@ defineExpose({ refresh: fetchUsers });
504
504
  <template #footer>
505
505
  <UButton
506
506
  :label="t('nuxtUiMongocamp.common.cancel')"
507
- color="neutral"
508
- variant="ghost"
507
+ v-bind="ui.dialogCancel"
509
508
  :disabled="deleting"
510
509
  @click="isDeleteModalOpen = false"
511
510
  />
512
511
  <UButton
513
512
  :label="t('nuxtUiMongocamp.common.delete')"
514
- color="error"
513
+ v-bind="ui.dangerAction"
515
514
  :loading="deleting"
516
515
  @click="handleDeleteUser"
517
516
  />
@@ -522,7 +521,7 @@ defineExpose({ refresh: fetchUsers });
522
521
  v-model:open="isKeyModalOpen"
523
522
  :title="t('nuxtUiMongocamp.users.regenerateKeyTitle', { userId: keyUser })"
524
523
  :dismissible="!keyBusy"
525
- :ui="{ footer: 'justify-end' }"
524
+ :ui="{ footer: ui.modal.footer }"
526
525
  >
527
526
  <template #body>
528
527
  <div
@@ -542,8 +541,7 @@ defineExpose({ refresh: fetchUsers });
542
541
  <UButton
543
542
  icon="i-lucide-copy"
544
543
  :label="t('nuxtUiMongocamp.common.copy')"
545
- color="neutral"
546
- variant="subtle"
544
+ v-bind="ui.secondaryAction"
547
545
  @click="copyNewApiKey"
548
546
  />
549
547
  </div>
@@ -554,7 +552,7 @@ defineExpose({ refresh: fetchUsers });
554
552
  v-if="keyError"
555
553
  class="mt-3"
556
554
  color="error"
557
- variant="subtle"
555
+ :variant="ui.alert.variant"
558
556
  icon="i-lucide-circle-alert"
559
557
  :description="keyError"
560
558
  />
@@ -570,14 +568,13 @@ defineExpose({ refresh: fetchUsers });
570
568
  <template v-else>
571
569
  <UButton
572
570
  :label="t('nuxtUiMongocamp.common.cancel')"
573
- color="neutral"
574
- variant="ghost"
571
+ v-bind="ui.dialogCancel"
575
572
  :disabled="keyBusy"
576
573
  @click="isKeyModalOpen = false"
577
574
  />
578
575
  <UButton
579
576
  :label="t('nuxtUiMongocamp.account.regenerate')"
580
- color="error"
577
+ v-bind="ui.dangerAction"
581
578
  icon="i-lucide-key-round"
582
579
  :loading="keyBusy"
583
580
  @click="handleRegenerateKey"
@@ -589,7 +586,7 @@ defineExpose({ refresh: fetchUsers });
589
586
  <USlideover
590
587
  v-model:open="isDetailOpen"
591
588
  :title="t('nuxtUiMongocamp.users.detailsTitle', { userId: detail?.user ?? '' })"
592
- :ui="{ content: 'sm:max-w-xl' }"
589
+ :ui="{ content: ui.modal.md }"
593
590
  >
594
591
  <template #body>
595
592
  <div
@@ -600,7 +597,7 @@ defineExpose({ refresh: fetchUsers });
600
597
  <UBadge
601
598
  :label="detail.isAdmin ? t('nuxtUiMongocamp.users.roleAdmin') : t('nuxtUiMongocamp.users.roleUser')"
602
599
  :color="detail.isAdmin ? 'primary' : 'neutral'"
603
- variant="subtle"
600
+ :variant="ui.badge.variant"
604
601
  />
605
602
  </div>
606
603
  <section class="flex flex-col gap-2">
@@ -616,7 +613,7 @@ defineExpose({ refresh: fetchUsers });
616
613
  :key="role"
617
614
  :label="role"
618
615
  color="primary"
619
- variant="subtle"
616
+ :variant="ui.badge.variant"
620
617
  />
621
618
  </div>
622
619
  <p
@@ -2,10 +2,12 @@
2
2
  import { computed, ref, watch } from "vue";
3
3
  import { useI18n, useMongocampProxyMode, useMongocampStorage, useMongocampSystem } from "#imports";
4
4
  import { useNuxtApp } from "#app";
5
+ import { useMongocampUi } from "../composables/useMongocampUi";
5
6
  const props = defineProps({
6
7
  hideDatabase: { type: Boolean, required: false, default: false }
7
8
  });
8
9
  const { t } = useI18n();
10
+ const ui = useMongocampUi();
9
11
  const { $mongocampVersion } = useNuxtApp();
10
12
  const { getServerInfo } = useMongocampSystem();
11
13
  const state = useMongocampStorage();
@@ -27,11 +29,11 @@ watch(canAsk, async (ask) => {
27
29
  </script>
28
30
 
29
31
  <template>
30
- <span class="inline-flex items-center gap-1.5">
32
+ <span class="mongocamp-version inline-flex items-center gap-1.5">
31
33
  <UBadge
32
34
  v-if="version"
33
35
  color="primary"
34
- variant="subtle"
36
+ :variant="ui.badge.variant"
35
37
  icon="i-lucide-database"
36
38
  >
37
39
  {{ version.name }} v{{ version.version }}
@@ -39,7 +41,7 @@ watch(canAsk, async (ask) => {
39
41
  <UBadge
40
42
  v-else
41
43
  color="neutral"
42
- variant="subtle"
44
+ :variant="ui.badge.variant"
43
45
  icon="i-lucide-database-zap"
44
46
  >
45
47
  {{ t("nuxtUiMongocamp.version.unavailable") }}
@@ -47,7 +49,7 @@ watch(canAsk, async (ask) => {
47
49
  <UBadge
48
50
  v-if="mongoDbVersion"
49
51
  color="neutral"
50
- variant="subtle"
52
+ :variant="ui.badge.variant"
51
53
  icon="i-simple-icons-mongodb"
52
54
  data-testid="mongodb-version"
53
55
  >
@@ -2,15 +2,15 @@ import type { Grant, JsonSchema, JsonValueBoolean, Role, SchemaAnalysis, UserPro
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>;
5
- deleteUser: (userId: string) => Promise<any>;
5
+ deleteUser: (userId: string) => Promise<JsonValueBoolean>;
6
6
  updateUserRoles: (userId: string, roles: string[]) => Promise<UserProfile>;
7
- updateUserPassword: (userId: string, password: string) => Promise<any>;
7
+ updateUserPassword: (userId: string, password: string) => Promise<JsonValueBoolean>;
8
8
  listRoles: (filter?: string) => Promise<Role[]>;
9
9
  addRole: (name: string, isAdmin?: boolean, collectionGrants?: Grant[]) => Promise<Role>;
10
10
  updateRole: (roleName: string, isAdmin: boolean, collectionGrants?: Grant[]) => Promise<Role>;
11
- deleteRole: (roleName: string) => Promise<any>;
11
+ deleteRole: (roleName: string) => Promise<JsonValueBoolean>;
12
12
  listCollections: () => Promise<string[]>;
13
- clearCollection: (collectionName: string) => Promise<any>;
13
+ clearCollection: (collectionName: string) => Promise<JsonValueBoolean>;
14
14
  deleteCollection: (collectionName: string) => Promise<JsonValueBoolean>;
15
15
  getJsonSchema: (collectionName: string) => Promise<JsonSchema>;
16
16
  getSchemaAnalysis: (collectionName: string, documents: number, depth?: number) => Promise<SchemaAnalysis>;
@@ -1 +1,13 @@
1
- export declare function useMongocampClientApi(): any;
1
+ export declare function useMongocampClientApi(): {
2
+ adminApi: import("@sfxcode/nuxt-mongocamp-server").AdminApi;
3
+ applicationApi: import("@sfxcode/nuxt-mongocamp-server").ApplicationApi;
4
+ authApi: import("@sfxcode/nuxt-mongocamp-server").AuthApi;
5
+ bucketApi: import("@sfxcode/nuxt-mongocamp-server").BucketApi;
6
+ collectionApi: import("@sfxcode/nuxt-mongocamp-server").CollectionApi;
7
+ databaseApi: import("@sfxcode/nuxt-mongocamp-server").DatabaseApi;
8
+ documentApi: import("@sfxcode/nuxt-mongocamp-server").DocumentApi;
9
+ fileApi: import("@sfxcode/nuxt-mongocamp-server").FileApi;
10
+ indexApi: import("@sfxcode/nuxt-mongocamp-server").IndexApi;
11
+ systemApi: import("@sfxcode/nuxt-mongocamp-server").SystemApi;
12
+ jobApi: import("@sfxcode/nuxt-mongocamp-server").JobsApi;
13
+ };
@@ -0,0 +1,25 @@
1
+ import type { ComputedRef, Ref } from 'vue';
2
+ import type { ConnectionState } from '../utils/connection.js';
3
+ export interface MongocampConnection {
4
+ /** `online`, `offline` (no network at all) or `unreachable` (network, but the server does not answer). */
5
+ state: Ref<ConnectionState>;
6
+ /** Shorthand for `state === 'online'`. */
7
+ isOnline: ComputedRef<boolean>;
8
+ /** When the server last answered a check or a reported request. */
9
+ lastAnswer: Ref<string | null>;
10
+ /** Asks the server now (`GET /version`, with a short timeout) and returns the new state. */
11
+ check: () => Promise<ConnectionState>;
12
+ /**
13
+ * Feeds the outcome of an app's own request into the state, so a failing request switches to `unreachable` at once
14
+ * instead of waiting for the next check: pass nothing after a success, or the caught error after a failure. An error
15
+ * with an HTTP status (401, 404, 500, ...) still proves the server answered. Returns whether it was a network failure.
16
+ */
17
+ report: (error?: unknown) => boolean;
18
+ }
19
+ /**
20
+ * Whether the MongoCamp server can be reached right now. One shared state per app. With the module option `offline`,
21
+ * the plugin keeps it current (browser online/offline events, a retry with backoff while unreachable, a check when the
22
+ * tab becomes visible) and the session guard keeps the session while it is not `online`. Without that option the state
23
+ * still works but only changes through `check()` and `report()`.
24
+ */
25
+ export declare function useMongocampConnection(): MongocampConnection;
@@ -0,0 +1,33 @@
1
+ import { computed } from "vue";
2
+ import { useState } from "#app";
3
+ import { useMongocampClientApi } from "#imports";
4
+ import { CONNECTION_CHECK_TIMEOUT_MS, initialConnectionState, isNetworkFailure, nextConnectionState } from "../utils/connection.js";
5
+ export function useMongocampConnection() {
6
+ const state = useState("mongocamp.connection.state", () => initialConnectionState(typeof navigator === "undefined" ? void 0 : navigator.onLine));
7
+ const lastAnswer = useState("mongocamp.connection.lastAnswer", () => null);
8
+ const { systemApi } = useMongocampClientApi();
9
+ function apply(event) {
10
+ state.value = nextConnectionState(state.value, event);
11
+ if (event === "server-answered") lastAnswer.value = (/* @__PURE__ */ new Date()).toISOString();
12
+ }
13
+ function report(error) {
14
+ const failed = error !== void 0 && isNetworkFailure(error);
15
+ apply(failed ? "network-failure" : "server-answered");
16
+ return failed;
17
+ }
18
+ async function check() {
19
+ if (typeof navigator !== "undefined" && navigator.onLine === false) {
20
+ apply("browser-offline");
21
+ return state.value;
22
+ }
23
+ apply("browser-online");
24
+ try {
25
+ await systemApi.version({ signal: AbortSignal.timeout(CONNECTION_CHECK_TIMEOUT_MS) });
26
+ report();
27
+ } catch (error) {
28
+ report(error);
29
+ }
30
+ return state.value;
31
+ }
32
+ return { state, isOnline: computed(() => state.value === "online"), lastAnswer, check, report };
33
+ }
@@ -1,10 +1,10 @@
1
1
  export declare function useMongocampRoles(): {
2
- isLoggedIn: any;
3
- isAdmin: import("vue").ComputedRef<any>;
4
- isManager: import("vue").ComputedRef<any>;
2
+ isLoggedIn: import("vue").ComputedRef<boolean>;
3
+ isAdmin: import("vue").ComputedRef<boolean>;
4
+ isManager: import("vue").ComputedRef<boolean>;
5
5
  isProxyMode: boolean;
6
- canSeeAdmin: import("vue").ComputedRef<any>;
7
- canSeeManagement: import("vue").ComputedRef<any>;
6
+ canSeeAdmin: import("vue").ComputedRef<boolean>;
7
+ canSeeManagement: import("vue").ComputedRef<boolean>;
8
8
  notAllowedPath: string;
9
9
  logoutRedirectPath: string;
10
10
  logoutPath: string;
@@ -0,0 +1,8 @@
1
+ import type { ComputedRef } from 'vue';
2
+ import type { MongocampUiTheme } from '../utils/uiTheme.js';
3
+ /**
4
+ * The module's look from `app.config.ts` (key `ui` under `nuxtUiMongocamp`), merged over the defaults and checked. Reactive:
5
+ * `updateAppConfig()` restyles the components without a reload. Components spread a role onto Nuxt UI
6
+ * components (`v-bind="ui.iconButton"`, `h(UButton, { ...ui.value.iconButton, color: 'error' })`).
7
+ */
8
+ export declare function useMongocampUi(): ComputedRef<MongocampUiTheme>;
@@ -0,0 +1,7 @@
1
+ import { computed } from "vue";
2
+ import { useAppConfig } from "#app";
3
+ import { resolveUi } from "../utils/uiTheme.js";
4
+ export function useMongocampUi() {
5
+ const appConfig = useAppConfig();
6
+ return computed(() => resolveUi(appConfig.nuxtUiMongocamp?.ui));
7
+ }
@@ -1,2 +1,6 @@
1
- declare const _default: any;
1
+ declare const _default: import("nuxt/app").Plugin<{
2
+ mongocampVersion: import("vue").Ref<import("@sfxcode/nuxt-mongocamp-server").Version | null | undefined, import("@sfxcode/nuxt-mongocamp-server").Version | null | undefined>;
3
+ }> & import("nuxt/app").ObjectPlugin<{
4
+ mongocampVersion: import("vue").Ref<import("@sfxcode/nuxt-mongocamp-server").Version | null | undefined, import("@sfxcode/nuxt-mongocamp-server").Version | null | undefined>;
5
+ }>;
2
6
  export default _default;
@@ -1,17 +1,41 @@
1
+ import { watch } from "vue";
1
2
  import { defineNuxtPlugin, addRouteMiddleware, navigateTo, useAsyncData, useRuntimeConfig } from "#app";
2
3
  import { useMongocampAuth, useMongocampClientApi, useMongocampStorage } from "#imports";
3
4
  import { useMongocampRoles } from "./composables/useMongocampRoles.js";
4
5
  import { useMongocampSession } from "./composables/useMongocampSession.js";
6
+ import { useMongocampConnection } from "./composables/useMongocampConnection.js";
7
+ import { CONNECTION_CHECK_TIMEOUT_MS, CONNECTION_RETRY_MAX_MS, CONNECTION_RETRY_MS } from "./utils/connection.js";
8
+ import { nextDelay } from "./utils/autoRefresh.js";
5
9
  import { createVerifyCache, runSessionGuard } from "./utils/sessionGuard.js";
10
+ import { compactProfile } from "./utils/compactSession.js";
6
11
  export default defineNuxtPlugin(async (_nuxtApp) => {
7
12
  const { systemApi } = useMongocampClientApi();
8
13
  const config = useRuntimeConfig();
9
14
  const useGlobalAuthMiddleware = config.public.nuxtUiMongocampOptions.useGlobalAuthMiddleware ?? false;
10
15
  const useServerProxy = config.public.nuxtUiMongocampOptions.useServerProxy ?? false;
11
16
  const sessionGuard = config.public.nuxtUiMongocampOptions.sessionGuard ?? false;
17
+ const offline = config.public.nuxtUiMongocampOptions.offline ?? false;
12
18
  const sessionGuardVerify = (config.public.nuxtUiMongocampOptions.sessionGuardVerify ?? false) && import.meta.client;
13
19
  const verifyCache = createVerifyCache(3e4);
14
- const { data: version } = await useAsyncData("version", () => systemApi.version());
20
+ const { data: version } = offline && import.meta.client ? await useAsyncData("version", async () => {
21
+ const connection = useMongocampConnection();
22
+ try {
23
+ const result = await systemApi.version({ signal: AbortSignal.timeout(CONNECTION_CHECK_TIMEOUT_MS) });
24
+ connection.report();
25
+ return result;
26
+ } catch (error) {
27
+ connection.report(error);
28
+ return null;
29
+ }
30
+ }, { lazy: true, server: false }) : await useAsyncData("version", () => systemApi.version());
31
+ if (offline && import.meta.client) watchConnection();
32
+ if (config.public.nuxtUiMongocampOptions.compactSession && import.meta.client) {
33
+ const storage = useMongocampStorage();
34
+ watch(() => storage.value?.profile, (profile) => {
35
+ const compact = compactProfile(profile);
36
+ if (compact) storage.value.profile = compact;
37
+ }, { immediate: true, flush: "sync" });
38
+ }
15
39
  if (sessionGuard && !useServerProxy) {
16
40
  addRouteMiddleware("session-guard", async (to) => {
17
41
  const { checkExpiry, invalidateSession, verify } = useMongocampSession();
@@ -23,7 +47,9 @@ export default defineNuxtPlugin(async (_nuxtApp) => {
23
47
  invalidate: invalidateSession,
24
48
  verify: sessionGuardVerify ? () => verifyCache(String(useMongocampStorage().value?.token ?? ""), verify) : void 0,
25
49
  // a fresh call: it must read the session as it is after the invalidation
26
- isAllowed: (path) => useMongocampRoles().isAllowedPathForRoute(path)
50
+ isAllowed: (path) => useMongocampRoles().isAllowedPathForRoute(path),
51
+ // only asked when a session is about to be cleared, so it costs a request only for an expired token
52
+ serverReachable: offline ? async () => await useMongocampConnection().check() === "online" : void 0
27
53
  });
28
54
  if (outcome === "redirect") return navigateTo(loginPath);
29
55
  }, { global: true });
@@ -47,3 +73,37 @@ export default defineNuxtPlugin(async (_nuxtApp) => {
47
73
  }
48
74
  };
49
75
  });
76
+ function watchConnection() {
77
+ const connection = useMongocampConnection();
78
+ let timer;
79
+ let failures = 0;
80
+ function schedule() {
81
+ if (timer !== void 0) clearTimeout(timer);
82
+ timer = void 0;
83
+ if (connection.state.value !== "unreachable") {
84
+ failures = 0;
85
+ return;
86
+ }
87
+ timer = setTimeout(async () => {
88
+ timer = void 0;
89
+ failures++;
90
+ await connection.check();
91
+ schedule();
92
+ }, nextDelay(CONNECTION_RETRY_MS, failures, { maxMs: CONNECTION_RETRY_MAX_MS }));
93
+ }
94
+ async function checkNow() {
95
+ await connection.check();
96
+ schedule();
97
+ }
98
+ window.addEventListener("online", () => {
99
+ void checkNow();
100
+ });
101
+ window.addEventListener("offline", () => {
102
+ void connection.check();
103
+ schedule();
104
+ });
105
+ document.addEventListener("visibilitychange", () => {
106
+ if (!document.hidden && !connection.isOnline.value) void checkNow();
107
+ });
108
+ watch(connection.state, () => schedule());
109
+ }
@@ -2,3 +2,4 @@ export { formatBytes } from './utils/formatBytes.js';
2
2
  export { connectionUsage, formatCount, formatUptime } from './utils/serverInfo.js';
3
3
  export { groupCollectionNames } from './utils/collectionNames.js';
4
4
  export { bucketNameOf, isBucketMemberCollection, isProtectedCollection } from './utils/collectionProtection.js';
5
+ export { isNetworkFailure } from './utils/connection.js';
@@ -2,3 +2,4 @@ export { formatBytes } from "./utils/formatBytes.js";
2
2
  export { connectionUsage, formatCount, formatUptime } from "./utils/serverInfo.js";
3
3
  export { groupCollectionNames } from "./utils/collectionNames.js";
4
4
  export { bucketNameOf, isBucketMemberCollection, isProtectedCollection } from "./utils/collectionProtection.js";
5
+ export { isNetworkFailure } from "./utils/connection.js";
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Module option `compactSession`: what of the user profile goes into the session cookie. `@sfxcode/nuxt-mongocamp-server`
3
+ * stores the whole `userProfile` of a login or token refresh — grants and the API key included — so a user with many
4
+ * grants pushes the cookie past the browser's ~4 KB limit and the login silently fails. The module itself never reads
5
+ * grants from the session (`useMongocampPermissions` asks the server), so the cookie only needs who the user is.
6
+ */
7
+ export interface CompactProfile {
8
+ user: string;
9
+ isAdmin: boolean;
10
+ roles?: string[];
11
+ }
12
+ /** The compact profile, or `undefined` when the stored one is already compact (or missing) and nothing needs writing. */
13
+ export declare function compactProfile(profile: unknown): CompactProfile | undefined;
@@ -0,0 +1,12 @@
1
+ const KEPT = /* @__PURE__ */ new Set(["user", "isAdmin", "roles"]);
2
+ export function compactProfile(profile) {
3
+ if (!profile || typeof profile !== "object") return void 0;
4
+ const p = profile;
5
+ if (Object.keys(p).every((key) => KEPT.has(key))) return void 0;
6
+ const roles = Array.isArray(p.roles) ? p.roles.filter((r) => typeof r === "string") : void 0;
7
+ return {
8
+ user: typeof p.user === "string" ? p.user : "",
9
+ isAdmin: p.isAdmin === true,
10
+ ...roles ? { roles } : {}
11
+ };
12
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * - `online`: the MongoCamp server answered recently.
3
+ * - `offline`: the browser itself reports no network.
4
+ * - `unreachable`: the browser has a network, but the server does not answer (e.g. a WLAN without internet, or the
5
+ * server is down). Also the state right after the browser reports a network again, until a check succeeds.
6
+ */
7
+ export type ConnectionState = 'online' | 'offline' | 'unreachable';
8
+ export type ConnectionEvent = 'browser-online' | 'browser-offline' | 'server-answered' | 'network-failure';
9
+ /** First wait between checks while the server cannot be reached; it doubles per failed check up to the ceiling. */
10
+ export declare const CONNECTION_RETRY_MS = 5000;
11
+ export declare const CONNECTION_RETRY_MAX_MS = 60000;
12
+ /** A check that takes longer than this counts as failed (a WLAN without internet can stall a request for minutes). */
13
+ export declare const CONNECTION_CHECK_TIMEOUT_MS = 5000;
14
+ export declare function nextConnectionState(current: ConnectionState, event: ConnectionEvent): ConnectionState;
15
+ /** The state to start with, from the browser's own flag (`navigator.onLine`); `undefined` (server side) counts as online. */
16
+ export declare function initialConnectionState(browserOnline: boolean | undefined): ConnectionState;
17
+ /**
18
+ * True when a request failed without any answer from the server: a network error, a timeout or an abort. An error that
19
+ * carries an HTTP status (401, 404, 500, ...) is an answer and therefore never a network failure — the server was there.
20
+ * Covers the generated MongoCamp client (`FetchError` with a `cause`, `ResponseError` with a `response`), ofetch/`$fetch`
21
+ * (`FetchError` with `statusCode` only when the server answered), plain `fetch` (`TypeError`) and `AbortSignal.timeout`.
22
+ */
23
+ export declare function isNetworkFailure(error: unknown): boolean;
@@ -0,0 +1,31 @@
1
+ export const CONNECTION_RETRY_MS = 5e3;
2
+ export const CONNECTION_RETRY_MAX_MS = 6e4;
3
+ export const CONNECTION_CHECK_TIMEOUT_MS = 5e3;
4
+ export function nextConnectionState(current, event) {
5
+ switch (event) {
6
+ case "browser-offline":
7
+ return "offline";
8
+ case "browser-online":
9
+ return current === "online" ? "online" : "unreachable";
10
+ case "server-answered":
11
+ return "online";
12
+ case "network-failure":
13
+ return current === "offline" ? "offline" : "unreachable";
14
+ }
15
+ }
16
+ export function initialConnectionState(browserOnline) {
17
+ return browserOnline === false ? "offline" : "online";
18
+ }
19
+ function statusOf(error) {
20
+ const response = error.response;
21
+ const responseStatus = typeof response === "object" && response !== null ? response.status : void 0;
22
+ return error.status ?? error.statusCode ?? responseStatus;
23
+ }
24
+ export function isNetworkFailure(error) {
25
+ if (typeof error !== "object" || error === null) return false;
26
+ const e = error;
27
+ if (statusOf(e) !== void 0) return false;
28
+ if (e.name === "AbortError" || e.name === "TimeoutError" || e.name === "FetchError") return true;
29
+ if (error instanceof TypeError) return true;
30
+ return e.cause !== void 0 && e.cause !== error && isNetworkFailure(e.cause);
31
+ }
@@ -7,6 +7,7 @@ interface SessionGuardDeps {
7
7
  invalidate: () => Promise<void>;
8
8
  verify?: () => Promise<VerifyResult>;
9
9
  isAllowed: (path: string) => boolean;
10
+ serverReachable?: () => Promise<boolean>;
10
11
  }
11
12
  export declare function runSessionGuard(deps: SessionGuardDeps): Promise<'continue' | 'redirect'>;
12
13
  export declare function createVerifyCache(ttlMs: number, now?: () => number): (key: string, run: () => Promise<VerifyResult>) => Promise<VerifyResult>;
@@ -1,6 +1,7 @@
1
1
  export async function runSessionGuard(deps) {
2
2
  const expiry = deps.checkExpiry();
3
3
  if (expiry !== "expired" && !(expiry === "valid" && deps.verify && await isRejectedByServer(deps.verify))) return "continue";
4
+ if (deps.serverReachable && !await isReachable(deps.serverReachable)) return "continue";
4
5
  try {
5
6
  await deps.invalidate();
6
7
  } catch {
@@ -9,6 +10,13 @@ export async function runSessionGuard(deps) {
9
10
  if (deps.path === deps.loginPath) return "continue";
10
11
  return deps.isAllowed(deps.path) ? "continue" : "redirect";
11
12
  }
13
+ async function isReachable(serverReachable) {
14
+ try {
15
+ return await serverReachable();
16
+ } catch {
17
+ return false;
18
+ }
19
+ }
12
20
  async function isRejectedByServer(verify) {
13
21
  try {
14
22
  return await verify() === "invalid";