@jskit-ai/http-web 0.2.34 → 0.2.36

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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,10 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - A list's, a record's or a form's load notice offers Retry only when trying again can help: after a network failure (no status), a timeout (408), a rate limit (429) or a server error (5xx). Before, it offered Retry on every failed load, also when the server had refused it (401, 403, 404, 422 and the other 4xx), where Retry only failed again; such a notice now has no action. One helper decides it for `useView()`, `useList()` and `useAddEdit()` (whose notice still offers nothing while `readEnabled` is false, and whose `canRetryLoad` and `refresh()` are unchanged).
6
+ - `CrudListScreen`, `CrudViewScreen` and `CrudAddEditScreen` show their own Retry button under the same rule, so a refused load shows no Retry anywhere on the screen, and the three say the same thing about a refusal: the server's own message when the error carries one, otherwise a neutral text for its kind ("Sign in again to see this." for a 401, "You don't have access to this." for a 403, "This wasn't found." for a 404, "This couldn't be loaded." for another 4xx). Before, the button showed after every failed load, also next to a notice that offered none; the list screen said "Check the connection and try again." after a refusal too, and the record and form screens said "Unable to load resource." when the server sent no message. A failure trying again can help keeps its text: the list screen's `loadErrorBody` (by default "Check the connection and try again."), now shown only then, and the record and form screens' `loadError`. A runtime without `errorStatus`, such as one a page builds itself, keeps its Retry button and text as before; the list screen shows the `loadError` of a refusal from a runtime without `loadRefusalMessage`.
7
+ - `useList()`, and so `useCrudList()`, and `useAddEdit()` expose the failed load's HTTP status as `errorStatus`, 0 when it has none (a network failure), as `useView()` already did, so a screen can tell a refusal from a network failure. The three runtimes also expose `loadRefusalMessage`, the text above for a refused load and empty when trying again can help, which the CRUD screens show. `loadError` and the load notice's text are unchanged.
8
+ - `useUiFeedback()` has `warning(message)`, for an action that did its work with a catch the person should act on, such as an invitation created but not emailed: the shell shows it as a warning, where `success()` showed it as a success. It goes to the new `warningChannel` option's channel, by default the one the shell's policy picks. `success()` and `error()` are unchanged.
5
9
  - A `useCommand()` DELETE sends its parsed input as the request body when the command declares an `input` schema or a `buildRawPayload`, so a DELETE that needs a reason or a confirmation reaches the server with it. Before, the client parsed the input and then dropped it for every DELETE, and a route that required a body answered 500. A DELETE that declares neither still sends no body, and `buildCommandPayload` still decides the body when given.
6
10
  - The CRUD list screen, form lookups and list-filter lookups no longer pass `search: { mode: "query" }`: a list's search runs on the server only, so they leave the mode out, as the guide says to. They search on the server as before.
7
11
  - **Breaking.** `useList`'s search runs on the server only: `search: { mode: "local" }`, which filtered the page the list had loaded in the browser and so missed every row past it, throws naming the server search, and so does `search.fields`, which only that mode read: the resource's `searchSchema.q` names the fields a search reads. Upgrading: drop the mode and give the resource `searchSchema.q`, which the list's search sends as `q`.
package/locales/en.json CHANGED
@@ -101,6 +101,12 @@
101
101
  "loadFailed": "Unable to load list.",
102
102
  "search": "Search"
103
103
  },
104
+ "loadRefused": {
105
+ "forbidden": "You don't have access to this.",
106
+ "notFound": "This wasn't found.",
107
+ "other": "This couldn't be loaded.",
108
+ "unauthorized": "Sign in again to see this."
109
+ },
104
110
  "resource": {
105
111
  "label": "Resource",
106
112
  "loadFailed": "Unable to load resource.",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/http-web",
3
- "version": "0.2.34",
3
+ "version": "0.2.36",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "jskit test"
@@ -52,15 +52,15 @@
52
52
  "peerDependencies": {
53
53
  "@jskit-ai/http-runtime": "0.2.21",
54
54
  "@jskit-ai/kernel": "0.2.21",
55
- "@jskit-ai/realtime": "0.2.32",
56
- "@jskit-ai/shell-web": "0.2.29",
55
+ "@jskit-ai/realtime": "0.2.33",
56
+ "@jskit-ai/shell-web": "0.2.30",
57
57
  "@tanstack/vue-query": "^5.90.5",
58
58
  "vue": "^3.5.13",
59
59
  "vue-router": "^5.0.4",
60
60
  "vuetify": "^4.3.0"
61
61
  },
62
62
  "devDependencies": {
63
- "@jskit-ai/material-web": "0.1.5"
63
+ "@jskit-ai/material-web": "0.1.6"
64
64
  },
65
65
  "description": "Neutral Vue request, command, resource, and CRUD UI runtime for JSKIT web applications.",
66
66
  "jskit": {
@@ -4,6 +4,7 @@ import ShellPageAction from "@jskit-ai/shell-web/client/components/ShellPageActi
4
4
  import ShellPageActions from "@jskit-ai/shell-web/client/components/ShellPageActions";
5
5
  import { useShellPageClose } from "@jskit-ai/shell-web/client/composables/useShellPageClose";
6
6
  import { useShellNavigation } from "@jskit-ai/shell-web/client/navigation/useShellNavigation";
7
+ import { isRetryableLoadStatus } from "../composables/support/resourceLoadStateHelpers.js";
7
8
  import { useJskitText } from "../i18n.js";
8
9
 
9
10
  // A new or edit page as Material 3 lays out a full-screen form: the top app bar's leading close (X) cancels, Save is
@@ -40,6 +41,12 @@ const props = defineProps({
40
41
  const { t, text } = useJskitText();
41
42
  const formRuntime = computed(() => props.screen.formRuntime);
42
43
  const addEdit = computed(() => props.screen.addEdit);
44
+ // Trying again can help, as the load notice offers Retry: a refused load (403, 404, ...) has no Retry.
45
+ const loadFailureIsRetryable = computed(() => isRetryableLoadStatus(unref(addEdit.value.errorStatus)));
46
+ // A refused read says why: the server's message or a neutral text for its kind (the runtime's loadRefusalMessage).
47
+ const loadErrorText = computed(() =>
48
+ String(unref(addEdit.value.loadRefusalMessage) || unref(addEdit.value.loadError) || "").trim()
49
+ );
43
50
  const formState = computed(() => props.screen.formState);
44
51
  const mode = computed(() => String(unref(props.screen.mode) || "new").trim() || "new");
45
52
  const saveLabel = computed(() =>
@@ -99,9 +106,9 @@ useShellPageClose({ label: () => t("jskit.http.actions.cancel"), close: cancel }
99
106
 
100
107
  <div v-if="addEdit.loadError" class="crud-add-edit-form__state">
101
108
  <v-icon icon="$cloudOff" size="48" />
102
- <p class="text-body-large">{{ addEdit.loadError }}</p>
109
+ <p class="text-body-large">{{ loadErrorText }}</p>
103
110
  <v-btn
104
- v-if="addEdit.canRetryLoad"
111
+ v-if="addEdit.canRetryLoad && loadFailureIsRetryable"
105
112
  color="secondary-container"
106
113
  prepend-icon="$refresh"
107
114
  :disabled="addEdit.isFetching"
@@ -7,6 +7,7 @@ import ShellPrimaryAction from "@jskit-ai/shell-web/client/components/ShellPrima
7
7
  import CrudListBulkActionSurface from "./CrudListBulkActionSurface.vue";
8
8
  import CrudListFilterSurface from "./CrudListFilterSurface.vue";
9
9
  import CrudListRecordActionMenu from "./CrudListRecordActionMenu.vue";
10
+ import { isRetryableLoadStatus } from "../composables/support/resourceLoadStateHelpers.js";
10
11
  import { useJskitText } from "../i18n.js";
11
12
 
12
13
  // Unset copy comes from the catalog; passed copy may be a message key.
@@ -43,6 +44,15 @@ const resolvedEmptyBody = computed(() =>
43
44
  const route = useRoute();
44
45
  const router = useRouter();
45
46
  const records = computed(() => props.screen.records);
47
+ // Retry only where trying again can help, as the load notice offers it: a refused load (403, 404, ...) has none.
48
+ const canRetryLoad = computed(() => isRetryableLoadStatus(unref(records.value.errorStatus)));
49
+ // The connection advice only where trying again can help; a refused load says why instead: the server's message or
50
+ // a neutral text for its kind (the runtime's loadRefusalMessage), else the runtime's load error.
51
+ const loadErrorText = computed(() =>
52
+ canRetryLoad.value
53
+ ? resolvedLoadErrorBody.value
54
+ : String(unref(records.value.loadRefusalMessage) || unref(records.value.loadError) || "").trim()
55
+ );
46
56
  const bulkActions = computed(() => props.screen.bulkActions);
47
57
  const rowActions = computed(() => props.screen.rowActions);
48
58
  const listFilters = computed(() => props.screen.listFilters);
@@ -162,8 +172,9 @@ function setSelectableRowsSelected(selected = true) {
162
172
  <template v-else>
163
173
  <div v-if="records.loadError" class="crud-list-state">
164
174
  <v-icon icon="$cloudOff" size="48" class="crud-list-state__icon" />
165
- <p class="text-body-large">{{ resolvedLoadErrorBody }}</p>
175
+ <p class="text-body-large">{{ loadErrorText }}</p>
166
176
  <v-btn
177
+ v-if="canRetryLoad"
167
178
  color="secondary-container"
168
179
  prepend-icon="$refresh"
169
180
  :disabled="records.isFetching"
@@ -3,6 +3,7 @@ import { computed, unref, watch } from "vue";
3
3
  import ShellPageAction from "@jskit-ai/shell-web/client/components/ShellPageAction";
4
4
  import ShellPageActions from "@jskit-ai/shell-web/client/components/ShellPageActions";
5
5
  import { useShellNavigation } from "@jskit-ai/shell-web/client/navigation/useShellNavigation";
6
+ import { isRetryableLoadStatus } from "../composables/support/resourceLoadStateHelpers.js";
6
7
  import { useJskitText } from "../i18n.js";
7
8
 
8
9
  // A record page as Material 3 lays it out: Edit and the page's own actions in the top app bar, a header naming the
@@ -30,6 +31,12 @@ const recordTitle = computed(() => String(unref(props.screen.recordTitle) || "")
30
31
  const isNotFound = computed(() => Boolean(unref(view.value.isNotFound)));
31
32
  // Gone (not found) or no longer the reader's to see (403).
32
33
  const isUnavailable = computed(() => isNotFound.value || Number(unref(view.value.errorStatus)) === 403);
34
+ // Retry only where trying again can help, as the load notice offers it: a refused load (401, 403, ...) has none.
35
+ const canRetryLoad = computed(() => isRetryableLoadStatus(unref(view.value.errorStatus)));
36
+ // A refused read says why: the server's message or a neutral text for its kind (the runtime's loadRefusalMessage).
37
+ const loadErrorText = computed(() =>
38
+ String(unref(view.value.loadRefusalMessage) || unref(view.value.loadError) || "").trim()
39
+ );
33
40
 
34
41
  // A record that is unavailable when Up returns here sends the reader on to this page's parent instead.
35
42
  const { pageUnavailable } = useShellNavigation();
@@ -54,8 +61,9 @@ watch(isUnavailable, (unavailable) => {
54
61
 
55
62
  <div v-if="view.loadError" class="crud-view-state">
56
63
  <v-icon icon="$cloudOff" size="48" />
57
- <p class="text-body-large">{{ view.loadError }}</p>
64
+ <p class="text-body-large">{{ loadErrorText }}</p>
58
65
  <v-btn
66
+ v-if="canRetryLoad"
59
67
  color="secondary-container"
60
68
  prepend-icon="$refresh"
61
69
  :disabled="view.isFetching"
@@ -8,12 +8,15 @@ import { createAddEditUiRuntime } from "../runtime/addEditUiRuntime.js";
8
8
  import { useUiFeedback } from "../runtime/useUiFeedback.js";
9
9
  import { useFieldErrorBag } from "../runtime/useFieldErrorBag.js";
10
10
  import {
11
+ createLoadRetryActionFactory,
11
12
  setupRouteChangeCleanup,
12
13
  setupOperationErrorReporting
13
14
  } from "../runtime/operationUiHelpers.js";
14
15
  import {
15
16
  resolveResourceMessages
16
17
  } from "../support/scopeHelpers.js";
18
+ import { resolveLoadErrorStatus } from "../support/resourceLoadStateHelpers.js";
19
+ import { toLoadRefusalMessage } from "../support/errorMessageHelpers.js";
17
20
  import { createRequestQueryRuntime } from "../support/requestQueryRuntimeSupport.js";
18
21
  import { resolveRouteParamNamesInOrder } from "../support/routeTemplateHelpers.js";
19
22
  import { useJskitText } from "../../i18n.js";
@@ -178,6 +181,10 @@ function useAddEdit({
178
181
  Boolean(isInitialLoading.value || isRefetching.value || !canSave.value || addEdit.saving.value)
179
182
  );
180
183
  const loadError = operationScope.loadError(endpointResource.loadError);
184
+ // The HTTP status of the failed load, or 0: the form's Retry and its notice offer Retry only when it can help.
185
+ const errorStatus = computed(() => resolveLoadErrorStatus(endpointResource.query.error.value));
186
+ // What the form says when the server refused its record read, or "" when trying again may help.
187
+ const loadRefusalMessage = computed(() => toLoadRefusalMessage(endpointResource.query.error.value));
181
188
  const isLoading = operationScope.isLoading(endpointResource.isLoading);
182
189
  const canRetryLoad = computed(() => readEnabled !== false);
183
190
 
@@ -193,21 +200,19 @@ function useAddEdit({
193
200
  source: `${placementSource}.load`,
194
201
  loadError,
195
202
  dedupeWindowMs: 0,
196
- loadActionFactory: () => canRetryLoad.value
197
- ? {
198
- label: t("jskit.http.actions.retry"),
199
- dismissOnRun: true,
200
- handler() {
201
- void refresh();
202
- }
203
- }
204
- : null
203
+ loadActionFactory: createLoadRetryActionFactory({
204
+ errorStatus,
205
+ retry: refresh,
206
+ enabled: canRetryLoad
207
+ })
205
208
  });
206
209
 
207
210
  return proxyRefs({
208
211
  canView,
209
212
  canSave,
210
213
  loadError,
214
+ errorStatus,
215
+ loadRefusalMessage,
211
216
  isInitialLoading,
212
217
  isFetching,
213
218
  isRefetching,
@@ -8,9 +8,14 @@ import {
8
8
  } from "../crud/crudLookupFieldLabelSupport.js";
9
9
  import { useListCore } from "../runtime/useListCore.js";
10
10
  import { useOperationScope } from "../internal/useOperationScope.js";
11
- import { setupOperationErrorReporting } from "../runtime/operationUiHelpers.js";
11
+ import {
12
+ createLoadRetryActionFactory,
13
+ setupOperationErrorReporting
14
+ } from "../runtime/operationUiHelpers.js";
12
15
  import { createListUiRuntime } from "../runtime/listUiRuntime.js";
13
16
  import { asPlainObject } from "../support/scopeHelpers.js";
17
+ import { resolveLoadErrorStatus } from "../support/resourceLoadStateHelpers.js";
18
+ import { toLoadRefusalMessage } from "../support/errorMessageHelpers.js";
14
19
  import {
15
20
  buildRequestQueryObject,
16
21
  createRequestQueryRuntime
@@ -431,6 +436,10 @@ function useList({
431
436
  const isFetching = operationScope.isLoading(list.isFetching);
432
437
  const isRefetching = computed(() => Boolean(isFetching.value && !isInitialLoading.value));
433
438
  const loadError = operationScope.loadError(list.loadError);
439
+ // The HTTP status of the failed load, or 0: a screen tells a refusal (403) from a network failure by it.
440
+ const errorStatus = computed(() => resolveLoadErrorStatus(list.query.error.value));
441
+ // What the screen says when the server refused the load, or "" when trying again may help.
442
+ const loadRefusalMessage = computed(() => toLoadRefusalMessage(list.query.error.value));
434
443
  const isLoading = operationScope.isLoading(list.isLoading);
435
444
  const listUiRuntime = createListUiRuntime({
436
445
  items: listItems,
@@ -447,12 +456,9 @@ function useList({
447
456
  source: `${placementSource}.load`,
448
457
  loadError,
449
458
  dedupeWindowMs: 0,
450
- loadActionFactory: () => ({
451
- label: t("jskit.http.actions.retry"),
452
- dismissOnRun: true,
453
- handler() {
454
- void list.reload();
455
- }
459
+ loadActionFactory: createLoadRetryActionFactory({
460
+ errorStatus,
461
+ retry: list.reload
456
462
  })
457
463
  });
458
464
 
@@ -465,6 +471,8 @@ function useList({
465
471
  isLoadingMore: list.isLoadingMore,
466
472
  hasMore: list.hasMore,
467
473
  loadError,
474
+ errorStatus,
475
+ loadRefusalMessage,
468
476
  pages: list.pages,
469
477
  items: listItems,
470
478
  reload: list.reload,
@@ -8,7 +8,10 @@ import {
8
8
  import { useViewCore } from "../runtime/useViewCore.js";
9
9
  import { useEndpointResource } from "../runtime/useEndpointResource.js";
10
10
  import { useOperationScope } from "../internal/useOperationScope.js";
11
- import { setupOperationErrorReporting } from "../runtime/operationUiHelpers.js";
11
+ import {
12
+ createLoadRetryActionFactory,
13
+ setupOperationErrorReporting
14
+ } from "../runtime/operationUiHelpers.js";
12
15
  import { createViewUiRuntime } from "../runtime/viewUiRuntime.js";
13
16
  import { createRequestQueryRuntime } from "../support/requestQueryRuntimeSupport.js";
14
17
  import { resolveRouteParamNamesInOrder } from "../support/routeTemplateHelpers.js";
@@ -137,12 +140,9 @@ function useView({
137
140
  loadError,
138
141
  notFoundError: view.notFoundError,
139
142
  dedupeWindowMs: 0,
140
- loadActionFactory: () => ({
141
- label: t("jskit.http.actions.retry"),
142
- dismissOnRun: true,
143
- handler() {
144
- void view.refresh();
145
- }
143
+ loadActionFactory: createLoadRetryActionFactory({
144
+ errorStatus: view.errorStatus,
145
+ retry: view.refresh
146
146
  })
147
147
  });
148
148
 
@@ -160,6 +160,7 @@ function useView({
160
160
  isNotFound: view.isNotFound,
161
161
  notFoundError: view.notFoundError,
162
162
  loadError,
163
+ loadRefusalMessage: view.loadRefusalMessage,
163
164
  refresh: view.refresh,
164
165
  resource: endpointResource,
165
166
  resolveFieldDisplay: resolveLookupFieldDisplayValue,
@@ -1,5 +1,9 @@
1
- import { watch } from "vue";
1
+ import { toValue, watch } from "vue";
2
2
  import { useShellWebErrorRuntime } from "@jskit-ai/shell-web/client/error";
3
+ import { isRetryableLoadStatus } from "../support/resourceLoadStateHelpers.js";
4
+ import { useJskitText } from "../../i18n.js";
5
+
6
+ const { t } = useJskitText();
3
7
 
4
8
  function normalizeMessage(value) {
5
9
  return String(value || "").trim();
@@ -9,6 +13,31 @@ function noRetryAction() {
9
13
  return null;
10
14
  }
11
15
 
16
+ /**
17
+ * A load notice's Retry, offered only while trying again may succeed (`isRetryableLoadStatus`): a load the server
18
+ * refused, such as a 403 or a 404, is refused again, so its notice offers no Retry.
19
+ * @param {object} options
20
+ * @param {import("vue").MaybeRefOrGetter<number>} options.errorStatus The failed load's HTTP status, or 0.
21
+ * @param {() => unknown} options.retry Loads again.
22
+ * @param {import("vue").MaybeRefOrGetter<boolean>} [options.enabled] False offers no Retry whatever the status.
23
+ * @returns {() => Record<string, any> | null}
24
+ */
25
+ function createLoadRetryActionFactory({ errorStatus, retry, enabled = true }) {
26
+ return () => {
27
+ if (!toValue(enabled) || !isRetryableLoadStatus(toValue(errorStatus))) {
28
+ return null;
29
+ }
30
+
31
+ return {
32
+ label: t("jskit.http.actions.retry"),
33
+ dismissOnRun: true,
34
+ handler() {
35
+ void retry();
36
+ }
37
+ };
38
+ };
39
+ }
40
+
12
41
  /** @param {import("../../types.js").OperationErrorReporting} [options] */
13
42
  function setupOperationErrorReporting({
14
43
  enabled = true,
@@ -123,5 +152,6 @@ function setupRouteChangeCleanup({ enabled = true, route, feedback, onClear }) {
123
152
  );
124
153
  }
125
154
 
155
+ export { createLoadRetryActionFactory };
126
156
  export { setupRouteChangeCleanup };
127
157
  export { setupOperationErrorReporting };
@@ -7,6 +7,7 @@ function useUiFeedback({
7
7
  initialType = "success",
8
8
  source = "http-web.ui-feedback",
9
9
  successChannel = "",
10
+ warningChannel = "",
10
11
  errorChannel = "",
11
12
  dedupeWindowMs = 2000
12
13
  } = {}) {
@@ -44,8 +45,9 @@ function useUiFeedback({
44
45
  message.value = "";
45
46
  }
46
47
 
47
- function success(nextMessage = "") {
48
- messageType.value = "success";
48
+ // An action that did its work: a success, or a warning when it did it with a catch the person should act on.
49
+ function reportDone(severity, channel, nextMessage) {
50
+ messageType.value = severity;
49
51
  const normalizedMessage = String(nextMessage || "").trim();
50
52
  message.value = normalizedMessage;
51
53
  dismissLastErrorPresentation();
@@ -57,13 +59,21 @@ function useUiFeedback({
57
59
  source: normalizedSource,
58
60
  message: normalizedMessage,
59
61
  intent: "action-feedback",
60
- severity: "success",
61
- channel: successChannel,
62
- dedupeKey: `${normalizedSource}:success:${normalizedMessage}`,
62
+ severity,
63
+ channel,
64
+ dedupeKey: `${normalizedSource}:${severity}:${normalizedMessage}`,
63
65
  dedupeWindowMs
64
66
  });
65
67
  }
66
68
 
69
+ function success(nextMessage = "") {
70
+ reportDone("success", successChannel, nextMessage);
71
+ }
72
+
73
+ function warning(nextMessage = "") {
74
+ reportDone("warning", warningChannel, nextMessage);
75
+ }
76
+
67
77
  function error(errorValue, fallbackMessage = "") {
68
78
  messageType.value = "error";
69
79
  message.value = toUiErrorMessage(errorValue, fallbackMessage);
@@ -92,6 +102,7 @@ function useUiFeedback({
92
102
  messageType,
93
103
  clear,
94
104
  success,
105
+ warning,
95
106
  error
96
107
  };
97
108
  }
@@ -1,5 +1,7 @@
1
1
  import { computed } from "vue";
2
2
  import { watchResourceModelState } from "./modelStateHelpers.js";
3
+ import { resolveLoadErrorStatus } from "../support/resourceLoadStateHelpers.js";
4
+ import { toLoadRefusalMessage } from "../support/errorMessageHelpers.js";
3
5
  import { useJskitText } from "../../i18n.js";
4
6
 
5
7
  const { t } = useJskitText();
@@ -39,8 +41,10 @@ function useViewCore({
39
41
  const error = computed(() => resource.query.error.value || null);
40
42
 
41
43
  // The HTTP status of the failed load, or 0.
42
- const errorStatus = computed(() => Number(error.value?.status || 0));
44
+ const errorStatus = computed(() => resolveLoadErrorStatus(error.value));
43
45
  const isNotFound = computed(() => statusList.includes(errorStatus.value));
46
+ // What the screen says when the server refused the read, or "" when trying again may help.
47
+ const loadRefusalMessage = computed(() => toLoadRefusalMessage(error.value));
44
48
 
45
49
  const notFoundError = computed(() => {
46
50
  if (!isNotFound.value) {
@@ -78,6 +82,7 @@ function useViewCore({
78
82
  isNotFound,
79
83
  notFoundError,
80
84
  loadError,
85
+ loadRefusalMessage,
81
86
  canView: resolvedCanView,
82
87
  refresh
83
88
  };
@@ -1,4 +1,5 @@
1
1
  import { isGenericHttpErrorMessage, resolveFieldErrors } from "@jskit-ai/http-runtime/client";
2
+ import { isRetryableLoadStatus, resolveLoadErrorStatus } from "./resourceLoadStateHelpers.js";
2
3
  import { useJskitText } from "../../i18n.js";
3
4
 
4
5
  const { t, text, serverMessage, fieldErrorMessages } = useJskitText();
@@ -27,6 +28,24 @@ function toQueryErrorMessage(error, fallbackMessage = "", defaultMessage = "") {
27
28
  return error ? toUiErrorMessage(error, fallbackMessage, defaultMessage) : "";
28
29
  }
29
30
 
31
+ const LOAD_REFUSED_MESSAGE_KEYS = Object.freeze({
32
+ 401: "jskit.http.loadRefused.unauthorized",
33
+ 403: "jskit.http.loadRefused.forbidden",
34
+ 404: "jskit.http.loadRefused.notFound"
35
+ });
36
+
37
+ // What a screen says about a load the server refused (a status trying again cannot help, see
38
+ // isRetryableLoadStatus): the server's own message when the error carries one, as a load error shows it,
39
+ // otherwise a neutral text for the kind of refusal. Empty when there is no error or trying again may help.
40
+ function toLoadRefusalMessage(error) {
41
+ const status = resolveLoadErrorStatus(error);
42
+ if (!error || isRetryableLoadStatus(status)) {
43
+ return "";
44
+ }
45
+
46
+ return toUiErrorMessage(error, LOAD_REFUSED_MESSAGE_KEYS[status] || "jskit.http.loadRefused.other");
47
+ }
48
+
30
49
  // Field errors in the user's language, field by field under the same rule.
31
50
  function toUiFieldErrors(error) {
32
51
  return fieldErrorMessages({
@@ -36,6 +55,7 @@ function toUiFieldErrors(error) {
36
55
  }
37
56
 
38
57
  export {
58
+ toLoadRefusalMessage,
39
59
  toQueryErrorMessage,
40
60
  toUiErrorMessage,
41
61
  toUiFieldErrors
@@ -1,6 +1,20 @@
1
1
  import { unref } from "vue";
2
2
  import { hasValue, isRecord, normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
3
3
 
4
+ // The HTTP status of a failed load, or 0 when it has none: the network failed, or the error came before any request.
5
+ function resolveLoadErrorStatus(error) {
6
+ const status = Number(error?.status || 0);
7
+ return Number.isInteger(status) && status > 0 ? status : 0;
8
+ }
9
+
10
+ // Whether trying a failed load again may succeed: the network failed (no status), the request timed out (408), was
11
+ // rate limited (429) or met a server error (5xx). The server answers any other refusal (401, 403, 404, 422, ...) the
12
+ // same way again.
13
+ function isRetryableLoadStatus(status) {
14
+ const value = Number(status) || 0;
15
+ return value === 0 || value === 408 || value === 429 || (value >= 500 && value <= 599);
16
+ }
17
+
4
18
  function hasResolvedQueryData({ query = null, data = null } = {}) {
5
19
  const querySucceeded = Boolean(unref(query?.isSuccess));
6
20
  const hasDataPayload = unref(data) != null;
@@ -114,6 +128,8 @@ function mergeRequestRecoveryQueryMeta(queryOptions = null, requestRecovery = nu
114
128
  export {
115
129
  buildRequestRecoveryMeta,
116
130
  hasResolvedQueryData,
131
+ isRetryableLoadStatus,
117
132
  mergeQueryMeta,
118
- mergeRequestRecoveryQueryMeta
133
+ mergeRequestRecoveryQueryMeta,
134
+ resolveLoadErrorStatus
119
135
  };
@@ -113,6 +113,7 @@
113
113
  * @property {string} [initialType]
114
114
  * @property {string} [source]
115
115
  * @property {string} [successChannel]
116
+ * @property {string} [warningChannel]
116
117
  * @property {string} [errorChannel]
117
118
  * @property {number} [dedupeWindowMs]
118
119
  */
@@ -0,0 +1,205 @@
1
+ import assert from "node:assert/strict";
2
+ import { readFileSync } from "node:fs";
3
+ import { registerHooks } from "node:module";
4
+ import test from "node:test";
5
+ import { compileScript, parse } from "@vue/compiler-sfc";
6
+ import { createSSRApp, defineComponent, h } from "vue";
7
+ import { renderToString } from "vue/server-renderer";
8
+ import { createMemoryHistory, createRouter } from "vue-router";
9
+
10
+ // The three CRUD screens, compiled from source. Their other components render nothing, and the shell's navigation
11
+ // stands in as a plain object, so only each screen's own load-error state renders.
12
+ const componentUrls = Object.freeze({
13
+ list: new URL("../src/client/components/CrudListScreen.vue", import.meta.url).href,
14
+ view: new URL("../src/client/components/CrudViewScreen.vue", import.meta.url).href,
15
+ addEdit: new URL("../src/client/components/CrudAddEditScreen.vue", import.meta.url).href
16
+ });
17
+ const screenUrls = new Set(Object.values(componentUrls));
18
+ const SHELL_STUBS = Object.freeze({
19
+ "@jskit-ai/shell-web/client/navigation/useShellNavigation": [
20
+ "export function useShellNavigation() {",
21
+ " return { canGoUp: { value: false }, upTarget: { value: '' }, finish() {}, pageUnavailable() {} };",
22
+ "}"
23
+ ].join("\n"),
24
+ "@jskit-ai/shell-web/client/composables/useShellPageClose": "export function useShellPageClose() {}"
25
+ });
26
+ const hooks = registerHooks({
27
+ resolve(specifier, context, nextResolve) {
28
+ if (Object.hasOwn(SHELL_STUBS, specifier) && screenUrls.has(context.parentURL)) {
29
+ return { url: `data:text/javascript,${encodeURIComponent(SHELL_STUBS[specifier])}`, shortCircuit: true };
30
+ }
31
+ return nextResolve(specifier, context);
32
+ },
33
+ load(url, context, nextLoad) {
34
+ if (!url.endsWith(".vue")) return nextLoad(url, context);
35
+ if (!screenUrls.has(url)) {
36
+ return { format: "module", shortCircuit: true, source: "export default { render: () => null };" };
37
+ }
38
+ const { descriptor } = parse(readFileSync(new URL(url), "utf8"));
39
+ return {
40
+ format: "module",
41
+ shortCircuit: true,
42
+ source: compileScript(descriptor, {
43
+ id: `crud-screen-load-retry-${[...screenUrls].indexOf(url)}`,
44
+ inlineTemplate: true
45
+ }).content
46
+ };
47
+ }
48
+ });
49
+ let screens;
50
+ try {
51
+ screens = {
52
+ list: (await import(componentUrls.list)).default,
53
+ view: (await import(componentUrls.view)).default,
54
+ addEdit: (await import(componentUrls.addEdit)).default
55
+ };
56
+ } finally {
57
+ hooks.deregister();
58
+ }
59
+
60
+ const VUETIFY_STUBS = Object.freeze([
61
+ "VCard", "VCheckboxBtn", "VCol", "VDivider", "VFab", "VForm", "VIcon", "VList", "VListItem", "VRow",
62
+ "VSkeletonLoader", "VTable", "VTextField", "VTooltip"
63
+ ]);
64
+
65
+ const HTML_ENTITIES = Object.freeze({ "&amp;": "&", "&lt;": "<", "&gt;": ">", "&quot;": "\"", "&#39;": "'" });
66
+
67
+ // The screen's load-error state, given its runtime: the text it shows and whether it shows its Retry button.
68
+ async function renderLoadError(screen, Component) {
69
+ const app = createSSRApp({ render: () => h(Component, { screen }) });
70
+ const router = createRouter({
71
+ history: createMemoryHistory(),
72
+ routes: [{ path: "/books/:recordId?", component: { render: () => null } }]
73
+ });
74
+ await router.push("/books/7");
75
+ app.use(router);
76
+ app.component("VBtn", defineComponent({ setup: (_props, { slots }) => () => h("button", slots.default?.()) }));
77
+ for (const name of VUETIFY_STUBS) {
78
+ app.component(name, defineComponent({ setup: (_props, { slots }) => () => h("div", slots.default?.()) }));
79
+ }
80
+ const html = await renderToString(app);
81
+ const text = html.match(/<p class="text-body-large">([^<]*)<\/p>/u)?.[1];
82
+ assert.notEqual(text, undefined, "The load-error state renders.");
83
+ return {
84
+ text: text.replace(/&(?:amp|lt|gt|quot|#39);/gu, (entity) => HTML_ENTITIES[entity]),
85
+ retry: /<button[^>]*>[^<]*\bRetry\b/u.test(html)
86
+ };
87
+ }
88
+
89
+ async function showsRetry(screen, Component) {
90
+ const { text, retry } = await renderLoadError(screen, Component);
91
+ assert.match(text, /Unable to load books\.|Check the connection/u, "The load-error state renders.");
92
+ return retry;
93
+ }
94
+
95
+ // A status of `undefined` is a runtime that has no `errorStatus` (one a page builds), which keeps its Retry.
96
+ const LOAD_FAILURES = Object.freeze([
97
+ { status: 0, retry: true },
98
+ { status: 503, retry: true },
99
+ { status: undefined, retry: true },
100
+ { status: 401, retry: false },
101
+ { status: 403, retry: false },
102
+ { status: 422, retry: false }
103
+ ]);
104
+
105
+ const SCREENS = Object.freeze({
106
+ list: (errorStatus, { loadRefusalMessage } = {}) => ({
107
+ records: {
108
+ loadError: "Unable to load books.",
109
+ ...(errorStatus === undefined ? {} : { errorStatus }),
110
+ ...(loadRefusalMessage === undefined ? {} : { loadRefusalMessage }),
111
+ isFetching: false,
112
+ showListSkeleton: false,
113
+ searchEnabled: false,
114
+ reload() {}
115
+ },
116
+ listPrimaryAction: "",
117
+ bulkActions: { hasActions: false },
118
+ rowActions: { hasActions: false, hasVisibleActionsFor: () => false },
119
+ displayRows: [],
120
+ selectableRows: [],
121
+ resolveRecordTitle: (record) => record.title
122
+ }),
123
+ view: (errorStatus, { loadRefusalMessage } = {}) => ({
124
+ view: {
125
+ loadError: "Unable to load books.",
126
+ ...(errorStatus === undefined ? {} : { errorStatus }),
127
+ ...(loadRefusalMessage === undefined ? {} : { loadRefusalMessage }),
128
+ isNotFound: false,
129
+ isLoading: false,
130
+ isFetching: false,
131
+ refresh() {}
132
+ },
133
+ editLocation: null,
134
+ recordTitle: ""
135
+ }),
136
+ addEdit: (errorStatus, { canRetryLoad = true, loadRefusalMessage } = {}) => ({
137
+ mode: "edit",
138
+ saveLabel: "Save book",
139
+ cancelTo: "",
140
+ formRuntime: { showFormSkeleton: false },
141
+ addEdit: {
142
+ loadError: "Unable to load books.",
143
+ ...(errorStatus === undefined ? {} : { errorStatus }),
144
+ ...(loadRefusalMessage === undefined ? {} : { loadRefusalMessage }),
145
+ canRetryLoad,
146
+ isFetching: false,
147
+ isSaving: false,
148
+ isSubmitDisabled: false,
149
+ refresh() {},
150
+ submit() {}
151
+ },
152
+ formState: {},
153
+ resolveFieldErrors: () => [],
154
+ resolveCancelTo: () => ""
155
+ })
156
+ });
157
+
158
+ const SCREEN_NAMES = Object.freeze({ list: "CrudListScreen", view: "CrudViewScreen", addEdit: "CrudAddEditScreen" });
159
+
160
+ for (const [key, buildScreen] of Object.entries(SCREENS)) {
161
+ for (const { status, retry } of LOAD_FAILURES) {
162
+ const label = status === undefined ? "a runtime without errorStatus" : `a ${status} load failure`;
163
+ test(`${SCREEN_NAMES[key]} ${retry ? "shows" : "hides"} its Retry button after ${label}`, async () => {
164
+ assert.equal(await showsRetry(buildScreen(status), screens[key]), retry);
165
+ });
166
+ }
167
+ }
168
+
169
+ test("CrudAddEditScreen still shows no Retry while its form reads no record", async () => {
170
+ assert.equal(await showsRetry(SCREENS.addEdit(503, { canRetryLoad: false }), screens.addEdit), false);
171
+ });
172
+
173
+ // What each screen says after a failed load. `refusal` is the runtime's `loadRefusalMessage` for it: empty where trying
174
+ // again may help, else the server's message or the neutral text for the refusal's kind.
175
+ const LOAD_ERROR_TEXTS = Object.freeze([
176
+ { label: "a network failure", status: 0, refusal: "" },
177
+ { label: "a 503", status: 503, refusal: "" },
178
+ { label: "a 401 without a message", status: 401, refusal: "Sign in again to see this." },
179
+ { label: "a 403 without a message", status: 403, refusal: "You don't have access to this." },
180
+ { label: "a 404 without a message", status: 404, refusal: "This wasn't found." },
181
+ { label: "a 422 without a message", status: 422, refusal: "This couldn't be loaded." },
182
+ { label: "a 403 with the server's message", status: 403, refusal: "Only editors can read books." }
183
+ ]);
184
+ // The text each screen showed before for a load trying again may fix: the list's connection advice, or the runtime's
185
+ // load error.
186
+ const RETRYABLE_TEXTS = Object.freeze({
187
+ list: "Check the connection and try again.",
188
+ view: "Unable to load books.",
189
+ addEdit: "Unable to load books."
190
+ });
191
+
192
+ for (const [key, buildScreen] of Object.entries(SCREENS)) {
193
+ for (const { label, status, refusal } of LOAD_ERROR_TEXTS) {
194
+ const expected = refusal || RETRYABLE_TEXTS[key];
195
+ test(`${SCREEN_NAMES[key]} says "${expected}" after ${label}`, async () => {
196
+ const { text } = await renderLoadError(buildScreen(status, { loadRefusalMessage: refusal }), screens[key]);
197
+ assert.equal(text, expected);
198
+ });
199
+ }
200
+ }
201
+
202
+ test("CrudListScreen gives a refusal from a runtime without loadRefusalMessage its load error, not the connection advice", async () => {
203
+ const { text } = await renderLoadError(SCREENS.list(403), screens.list);
204
+ assert.equal(text, "Unable to load books.");
205
+ });
@@ -0,0 +1,249 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { QueryClient, VueQueryPlugin } from "@tanstack/vue-query";
4
+ import { createRenderer, h, reactive } from "vue";
5
+ import { createMemoryHistory, createRouter } from "vue-router";
6
+ import { SHELL_WEB_ERROR_RUNTIME_KEY } from "@jskit-ai/shell-web/client/error";
7
+ import { useAddEdit } from "../src/client/composables/records/useAddEdit.js";
8
+ import { useCrudList } from "../src/client/composables/records/useCrudList.js";
9
+ import { useList } from "../src/client/composables/records/useList.js";
10
+ import { useView } from "../src/client/composables/records/useView.js";
11
+
12
+ // A failed load's notice offers Retry only while trying again may succeed. `status` undefined is an error that
13
+ // carries none, as a network failure or an error thrown before any request.
14
+ const LOAD_FAILURES = Object.freeze([
15
+ { status: undefined, retry: true },
16
+ { status: 408, retry: true },
17
+ { status: 429, retry: true },
18
+ { status: 500, retry: true },
19
+ { status: 503, retry: true },
20
+ { status: 401, retry: false },
21
+ { status: 403, retry: false },
22
+ { status: 404, retry: false },
23
+ { status: 422, retry: false }
24
+ ]);
25
+
26
+ const node = (type, text = "") => ({ type, text, props: {}, children: [], parent: null });
27
+ const renderer = createRenderer({
28
+ createElement: node,
29
+ createText: (text) => node("text", text),
30
+ createComment: () => node("comment"),
31
+ setText: (item, text) => { item.text = text; },
32
+ setElementText: (item, text) => { item.text = text; item.children = []; },
33
+ patchProp: (item, key, _previous, value) => { item.props[key] = value; },
34
+ parentNode: (item) => item.parent,
35
+ nextSibling: (item) => item.parent?.children[item.parent.children.indexOf(item) + 1] ?? null,
36
+ insert(item, parent, anchor) {
37
+ if (item.parent) item.parent.children.splice(item.parent.children.indexOf(item), 1);
38
+ item.parent = parent;
39
+ const index = anchor ? parent.children.indexOf(anchor) : -1;
40
+ if (index < 0) parent.children.push(item); else parent.children.splice(index, 0, item);
41
+ },
42
+ remove(item) {
43
+ if (item.parent) item.parent.children.splice(item.parent.children.indexOf(item), 1);
44
+ }
45
+ });
46
+
47
+ function describeStatus(status) {
48
+ return status === undefined ? "no status" : String(status);
49
+ }
50
+
51
+ async function waitFor(check, message) {
52
+ for (let attempt = 0; attempt < 200; attempt += 1) {
53
+ if (check()) {
54
+ return;
55
+ }
56
+ await new Promise((resolve) => setTimeout(resolve, 1));
57
+ }
58
+ assert.fail(message);
59
+ }
60
+
61
+ // Mounts one runtime whose every read fails with `status` (and `message`, by default one of the server's own), and
62
+ // records what it reports to the shell.
63
+ async function mountFailingLoad(t, status, useRuntime, { message = `Contacts refused the read (${describeStatus(status)}).` } = {}) {
64
+ const requests = [];
65
+ const client = {
66
+ async request(path) {
67
+ requests.push(path);
68
+ const error = new Error(message);
69
+ if (status !== undefined) {
70
+ error.status = status;
71
+ }
72
+ throw error;
73
+ }
74
+ };
75
+ const reports = [];
76
+ const router = createRouter({
77
+ history: createMemoryHistory(),
78
+ routes: [{ path: "/contacts/:recordId?", component: { render: () => h("div") } }]
79
+ });
80
+ await router.push("/contacts/7");
81
+ await router.isReady();
82
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
83
+ let runtime = null;
84
+ const app = renderer.createApp({
85
+ setup() {
86
+ runtime = useRuntime(client);
87
+ return () => h("div");
88
+ }
89
+ });
90
+ app.use(router);
91
+ app.use(VueQueryPlugin, { queryClient });
92
+ app.provide(SHELL_WEB_ERROR_RUNTIME_KEY, {
93
+ report(event) {
94
+ reports.push(event);
95
+ return { presentationId: `presentation-${reports.length}` };
96
+ },
97
+ dismiss() {}
98
+ });
99
+ app.mount(node("root"));
100
+ t.after(() => {
101
+ app.unmount();
102
+ queryClient.clear();
103
+ });
104
+
105
+ await waitFor(
106
+ () => reports.some((event) => event.intent === "resource-load"),
107
+ `Expected a load notice for a ${describeStatus(status)} failure.`
108
+ );
109
+ return { runtime, reports, requests };
110
+ }
111
+
112
+ // The load notices' Retry, checked against what the failure should offer: the action, or null for a refusal.
113
+ function assertRetryOffer({ reports }, { status, retry }) {
114
+ const notices = reports.filter((event) => event.intent === "resource-load");
115
+ const actions = notices.map((event) => event.action).filter(Boolean);
116
+ if (!retry) {
117
+ assert.deepEqual(actions, [], `A ${describeStatus(status)} refusal offers no Retry.`);
118
+ return null;
119
+ }
120
+
121
+ assert.equal(actions.length, 1, `A ${describeStatus(status)} failure offers Retry.`);
122
+ assert.equal(actions[0].label, "Retry");
123
+ assert.equal(actions[0].dismissOnRun, true);
124
+ return actions[0];
125
+ }
126
+
127
+ // Runs the Retry, which loads again. The status is read before: the new attempt clears the failed one's error.
128
+ async function assertRetryLoadsAgain({ requests }, retryAction) {
129
+ if (!retryAction) {
130
+ return;
131
+ }
132
+
133
+ const requestsBefore = requests.length;
134
+ retryAction.handler();
135
+ await waitFor(() => requests.length > requestsBefore, "Retry loads again.");
136
+ }
137
+
138
+ function listOptions(client) {
139
+ return {
140
+ apiSuffix: "/contacts",
141
+ ownershipFilter: "public",
142
+ client,
143
+ queryKeyFactory: () => ["contacts"]
144
+ };
145
+ }
146
+
147
+ for (const failure of LOAD_FAILURES) {
148
+ const label = describeStatus(failure.status);
149
+
150
+ test(`useView: a ${label} load failure ${failure.retry ? "offers" : "does not offer"} Retry and exposes its status`, async (t) => {
151
+ const mounted = await mountFailingLoad(t, failure.status, (client) => useView({
152
+ apiSuffix: "/contacts/7",
153
+ ownershipFilter: "public",
154
+ client,
155
+ queryKeyFactory: () => ["contacts", "7"]
156
+ }));
157
+
158
+ const retryAction = assertRetryOffer(mounted, failure);
159
+ assert.equal(mounted.runtime.errorStatus, failure.status ?? 0);
160
+ await assertRetryLoadsAgain(mounted, retryAction);
161
+ });
162
+
163
+ test(`useList: a ${label} load failure ${failure.retry ? "offers" : "does not offer"} Retry and exposes its status`, async (t) => {
164
+ const mounted = await mountFailingLoad(t, failure.status, (client) => useList(listOptions(client)));
165
+
166
+ const retryAction = assertRetryOffer(mounted, failure);
167
+ assert.ok(mounted.runtime.loadError, "The message stays.");
168
+ assert.equal(mounted.runtime.errorStatus, failure.status ?? 0);
169
+ await assertRetryLoadsAgain(mounted, retryAction);
170
+ });
171
+ }
172
+
173
+ test("useCrudList offers no Retry after a refused load, and exposes its status", async (t) => {
174
+ const mounted = await mountFailingLoad(t, 403, (client) => useCrudList(listOptions(client)));
175
+
176
+ assertRetryOffer(mounted, { status: 403, retry: false });
177
+ assert.ok(mounted.runtime.loadError);
178
+ assert.equal(mounted.runtime.errorStatus, 403);
179
+ });
180
+
181
+ test("useCrudList offers Retry after a network failure, whose status is 0", async (t) => {
182
+ const mounted = await mountFailingLoad(t, undefined, (client) => useCrudList(listOptions(client)));
183
+
184
+ const retryAction = assertRetryOffer(mounted, { status: undefined, retry: true });
185
+ assert.equal(mounted.runtime.errorStatus, 0);
186
+ await assertRetryLoadsAgain(mounted, retryAction);
187
+ });
188
+
189
+ for (const failure of [{ status: 503, retry: true }, { status: 403, retry: false }]) {
190
+ test(`useAddEdit: a ${failure.status} load failure ${failure.retry ? "offers" : "does not offer"} Retry`, async (t) => {
191
+ const mounted = await mountFailingLoad(t, failure.status, (client) => useAddEdit({
192
+ apiSuffix: "/contacts/7",
193
+ ownershipFilter: "public",
194
+ client,
195
+ queryKeyFactory: () => ["contacts", "7", "edit"],
196
+ model: reactive({ name: "" })
197
+ }));
198
+
199
+ assert.equal(mounted.runtime.canRetryLoad, true, "The form's own Retry button is unchanged.");
200
+ await assertRetryLoadsAgain(mounted, assertRetryOffer(mounted, failure));
201
+ });
202
+ }
203
+
204
+ // What a screen says about a refused load (`loadRefusalMessage`): the server's message when the error carries one,
205
+ // else a neutral text for the refusal's kind; empty where trying again may help. A message of `null` is the one the
206
+ // HTTP client builds when the server sent none ("Request failed with status 403.").
207
+ const LOAD_REFUSALS = Object.freeze([
208
+ { label: "a network failure", status: undefined, message: "Network request failed.", refusal: "" },
209
+ { label: "a 503", status: 503, message: null, refusal: "" },
210
+ { label: "a 401 without a message", status: 401, message: null, refusal: "Sign in again to see this." },
211
+ { label: "a 403 without a message", status: 403, message: null, refusal: "You don't have access to this." },
212
+ { label: "a 404 without a message", status: 404, message: null, refusal: "This wasn't found." },
213
+ { label: "a 422 without a message", status: 422, message: null, refusal: "This couldn't be loaded." },
214
+ {
215
+ label: "a 403 with the server's message",
216
+ status: 403,
217
+ message: "Only editors can read contacts.",
218
+ refusal: "Only editors can read contacts."
219
+ }
220
+ ]);
221
+
222
+ const REFUSAL_RUNTIMES = Object.freeze({
223
+ useList: (client) => useList(listOptions(client)),
224
+ useView: (client) => useView({
225
+ apiSuffix: "/contacts/7",
226
+ ownershipFilter: "public",
227
+ client,
228
+ queryKeyFactory: () => ["contacts", "7"]
229
+ }),
230
+ useAddEdit: (client) => useAddEdit({
231
+ apiSuffix: "/contacts/7",
232
+ ownershipFilter: "public",
233
+ client,
234
+ queryKeyFactory: () => ["contacts", "7", "edit"],
235
+ model: reactive({ name: "" })
236
+ })
237
+ });
238
+
239
+ for (const [name, useRuntime] of Object.entries(REFUSAL_RUNTIMES)) {
240
+ for (const { label, status, message, refusal } of LOAD_REFUSALS) {
241
+ test(`${name}: loadRefusalMessage after ${label} is ${refusal ? `"${refusal}"` : "empty"}`, async (t) => {
242
+ const mounted = await mountFailingLoad(t, status, useRuntime, {
243
+ message: message ?? `Request failed with status ${status}.`
244
+ });
245
+
246
+ assert.equal(mounted.runtime.loadRefusalMessage, refusal);
247
+ });
248
+ }
249
+ }
@@ -0,0 +1,64 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { createApp } from "vue";
4
+ import { SHELL_WEB_ERROR_RUNTIME_KEY } from "@jskit-ai/shell-web/client/error";
5
+ import { useUiFeedback } from "../src/client/composables/runtime/useUiFeedback.js";
6
+
7
+ const CAVEAT = "Invite created, but email delivery failed. Copy the invite link to share it.";
8
+
9
+ // One feedback runtime and what it reports to, and dismisses from, the shell.
10
+ function feedbackWithShell(options) {
11
+ const reports = [];
12
+ const dismissed = [];
13
+ const app = createApp({ render: () => null });
14
+ app.provide(SHELL_WEB_ERROR_RUNTIME_KEY, {
15
+ report(event) {
16
+ reports.push(event);
17
+ return { presentationId: `presentation-${reports.length}`, decision: { presenterId: "snackbar" } };
18
+ },
19
+ dismiss(presentationId) {
20
+ dismissed.push(presentationId);
21
+ }
22
+ });
23
+ const feedback = app.runWithContext(() => useUiFeedback(options));
24
+ return { feedback, reports, dismissed };
25
+ }
26
+
27
+ test("warning() shows an action that did its work with a catch as a warning", () => {
28
+ const { feedback, reports } = feedbackWithShell({ source: "members.invite" });
29
+
30
+ feedback.warning(CAVEAT);
31
+
32
+ assert.equal(feedback.messageType.value, "warning");
33
+ assert.equal(feedback.message.value, CAVEAT);
34
+ assert.deepEqual(reports, [{
35
+ source: "members.invite",
36
+ message: CAVEAT,
37
+ intent: "action-feedback",
38
+ severity: "warning",
39
+ channel: "",
40
+ dedupeKey: `members.invite:warning:${CAVEAT}`,
41
+ dedupeWindowMs: 2000
42
+ }]);
43
+ });
44
+
45
+ test("warning() goes to the warning channel and puts away an earlier attempt's error", () => {
46
+ const { feedback, reports, dismissed } = feedbackWithShell({ warningChannel: "banner", successChannel: "snackbar" });
47
+
48
+ feedback.error(new Error("Unable to create invite."));
49
+ feedback.warning(CAVEAT);
50
+
51
+ assert.deepEqual(dismissed, ["presentation-1"]);
52
+ assert.equal(reports[1].channel, "banner");
53
+ });
54
+
55
+ test("success() still reports a success on its own channel", () => {
56
+ const { feedback, reports } = feedbackWithShell({ warningChannel: "banner", successChannel: "snackbar" });
57
+
58
+ feedback.success("Invite sent.");
59
+
60
+ assert.equal(feedback.messageType.value, "success");
61
+ assert.equal(reports[0].severity, "success");
62
+ assert.equal(reports[0].channel, "snackbar");
63
+ assert.equal(reports[0].dedupeKey, "http-web.ui-feedback:success:Invite sent.");
64
+ });