@eskais/app-sdk 0.1.0 → 0.2.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 (90) hide show
  1. package/README.md +17 -11
  2. package/dist/action/action.d.ts +69 -10
  3. package/dist/action/action.js +147 -29
  4. package/dist/action/bulk.d.ts +24 -0
  5. package/dist/action/bulk.js +24 -0
  6. package/dist/core/constants.d.ts +57 -0
  7. package/dist/core/constants.js +31 -0
  8. package/dist/core/contracts.d.ts +7 -0
  9. package/dist/core/data-labels.d.ts +14 -0
  10. package/dist/core/data-labels.js +40 -0
  11. package/dist/core/errors.d.ts +11 -5
  12. package/dist/core/errors.js +52 -9
  13. package/dist/dialogs/dialogs.d.ts +75 -0
  14. package/dist/dialogs/dialogs.js +66 -0
  15. package/dist/errors/adapters.d.ts +21 -0
  16. package/dist/errors/adapters.js +81 -0
  17. package/dist/errors/define-errors.d.ts +88 -0
  18. package/dist/errors/define-errors.js +168 -0
  19. package/dist/errors/idempotency.d.ts +2 -0
  20. package/dist/errors/idempotency.js +13 -0
  21. package/dist/i18n/adapters.d.ts +53 -0
  22. package/dist/i18n/adapters.js +56 -0
  23. package/dist/i18n/format.d.ts +10 -0
  24. package/dist/i18n/format.js +273 -0
  25. package/dist/i18n/labels.d.ts +10 -0
  26. package/dist/i18n/labels.js +227 -0
  27. package/dist/i18n/locale.d.ts +73 -0
  28. package/dist/i18n/locale.js +74 -0
  29. package/dist/i18n/messages.d.ts +93 -0
  30. package/dist/i18n/messages.js +16 -0
  31. package/dist/import/import.d.ts +4 -2
  32. package/dist/import/import.js +7 -4
  33. package/dist/index.d.ts +18 -3
  34. package/dist/index.js +17 -2
  35. package/dist/navigation/nav.d.ts +14 -5
  36. package/dist/navigation/nav.js +37 -14
  37. package/dist/next/server/index.d.ts +2 -1
  38. package/dist/next/server/index.js +2 -1
  39. package/dist/next/server/page.d.ts +8 -2
  40. package/dist/next/server/page.js +14 -7
  41. package/dist/next/server/session.d.ts +13 -0
  42. package/dist/next/server/session.js +13 -0
  43. package/dist/permissions/permissions.d.ts +134 -0
  44. package/dist/permissions/permissions.js +121 -0
  45. package/dist/react/data-layer.d.ts +42 -5
  46. package/dist/react/data-layer.js +49 -4
  47. package/dist/react/hooks/use-action-dialog.d.ts +25 -0
  48. package/dist/react/hooks/use-action-dialog.js +31 -0
  49. package/dist/react/hooks/use-action.d.ts +30 -5
  50. package/dist/react/hooks/use-action.js +85 -27
  51. package/dist/react/hooks/use-bulk-action.d.ts +20 -0
  52. package/dist/react/hooks/use-bulk-action.js +24 -0
  53. package/dist/react/hooks/use-dialogs.d.ts +14 -0
  54. package/dist/react/hooks/use-dialogs.js +20 -0
  55. package/dist/react/hooks/use-nav.js +3 -2
  56. package/dist/react/hooks/use-new-rows.d.ts +22 -0
  57. package/dist/react/hooks/use-new-rows.js +24 -0
  58. package/dist/react/hooks/use-permissions.d.ts +13 -0
  59. package/dist/react/hooks/use-permissions.js +19 -0
  60. package/dist/react/hooks/use-reauthenticate.d.ts +6 -0
  61. package/dist/react/hooks/use-reauthenticate.js +11 -0
  62. package/dist/react/hooks/use-resource.d.ts +28 -5
  63. package/dist/react/hooks/use-resource.js +63 -26
  64. package/dist/react/index.d.ts +11 -4
  65. package/dist/react/index.js +11 -4
  66. package/dist/react/keys.d.ts +9 -0
  67. package/dist/react/keys.js +4 -0
  68. package/dist/react/new-rows.d.ts +22 -0
  69. package/dist/react/new-rows.js +72 -0
  70. package/dist/refresh/new-rows.d.ts +13 -0
  71. package/dist/refresh/new-rows.js +18 -0
  72. package/dist/resource/resource-relations.d.ts +6 -3
  73. package/dist/resource/resource-relations.js +26 -13
  74. package/dist/resource/resource-schema.d.ts +1 -1
  75. package/dist/resource/resource-schema.js +1 -1
  76. package/dist/resource/resource-texts.d.ts +18 -0
  77. package/dist/resource/resource-texts.js +13 -0
  78. package/dist/resource/resource-types.d.ts +169 -30
  79. package/dist/resource/resource-words.d.ts +25 -0
  80. package/dist/resource/resource-words.js +221 -0
  81. package/dist/resource/resource.d.ts +6 -2
  82. package/dist/resource/resource.js +99 -173
  83. package/dist/services/read-only-service.d.ts +18 -0
  84. package/dist/services/read-only-service.js +25 -0
  85. package/dist/services/rest-service.d.ts +4 -1
  86. package/dist/services/rest-service.js +2 -0
  87. package/dist/view/view-types.d.ts +4 -2
  88. package/locales/en.json +193 -0
  89. package/locales/es.json +193 -0
  90. package/package.json +5 -2
@@ -24,6 +24,10 @@ export const dataLabelsEn = {
24
24
  notFound: (one) => `This ${one.toLocaleLowerCase()} doesn't exist`,
25
25
  forbidden: (one) => `You can't see this ${one.toLocaleLowerCase()}`,
26
26
  notAllowed: "You don't have permission",
27
+ forbiddenPage: "You don't have access to this page",
28
+ newRows: (value, locale) => `Show ${count(value, locale)} new ${value === 1 ? "row" : "rows"}`,
29
+ confirm: "Confirm",
30
+ ok: "OK",
27
31
  range: ({ from, to, total, estimate }, locale) => {
28
32
  const shown = `Showing ${count(from, locale)}–${count(to, locale)}`;
29
33
  if (total === undefined)
@@ -156,6 +160,22 @@ export const dataLabelsEn = {
156
160
  addRow: "Add row",
157
161
  removeRow: (row) => `Remove row ${String(row)}`,
158
162
  invalidDuration: "Enter a duration, like 1:30",
163
+ errors: {
164
+ network: "Couldn't reach the server. Check your connection and try again.",
165
+ timeout: "The server took too long to answer. Try again.",
166
+ unauthorized: "Sign in to continue.",
167
+ "session-expired": "Your session has expired. Sign in again.",
168
+ forbidden: "You don't have permission to do this.",
169
+ "not-found": "It doesn't exist anymore.",
170
+ conflict: "Someone changed this in the meantime. Review it and try again.",
171
+ validation: "Check the highlighted fields.",
172
+ "rate-limited": "Too many requests. Wait a moment and try again.",
173
+ server: "The server ran into a problem. Try again later.",
174
+ unknown: "Something went wrong.",
175
+ aborted: "Cancelled.",
176
+ },
177
+ bulkResult: (succeeded, failed, locale) => `${count(succeeded, locale)} done, ${count(failed, locale)} failed`,
178
+ retryFailed: (value, locale) => `Retry failed (${count(value, locale)})`,
159
179
  };
160
180
  const several = (value, one, other) => (value === 1 ? one : other);
161
181
  function issueTextEs({ code, params }) {
@@ -210,6 +230,10 @@ export const dataLabelsEs = {
210
230
  notFound: (one) => `Este ${one.toLocaleLowerCase()} no existe`,
211
231
  forbidden: (one) => `No tienes permiso para ver este ${one.toLocaleLowerCase()}`,
212
232
  notAllowed: "No tienes permiso",
233
+ forbiddenPage: "No tienes acceso a esta página",
234
+ newRows: (value, locale) => `Mostrar ${count(value, locale)} ${value === 1 ? "fila nueva" : "filas nuevas"}`,
235
+ confirm: "Confirmar",
236
+ ok: "Aceptar",
213
237
  range: ({ from, to, total, estimate }, locale) => {
214
238
  const shown = `Mostrando ${count(from, locale)}–${count(to, locale)}`;
215
239
  if (total === undefined)
@@ -342,4 +366,20 @@ export const dataLabelsEs = {
342
366
  addRow: "Añadir fila",
343
367
  removeRow: (row) => `Quitar la fila ${String(row)}`,
344
368
  invalidDuration: "Escribe una duración, como 1:30",
369
+ errors: {
370
+ network: "No se ha podido conectar con el servidor. Comprueba la conexión y vuelve a intentarlo.",
371
+ timeout: "El servidor ha tardado demasiado en responder. Vuelve a intentarlo.",
372
+ unauthorized: "Inicia sesión para continuar.",
373
+ "session-expired": "Tu sesión ha caducado. Vuelve a iniciar sesión.",
374
+ forbidden: "No tienes permiso para hacer esto.",
375
+ "not-found": "Ya no existe.",
376
+ conflict: "Alguien lo ha cambiado mientras tanto. Revísalo y vuelve a intentarlo.",
377
+ validation: "Revisa los campos marcados.",
378
+ "rate-limited": "Demasiadas peticiones. Espera un momento y vuelve a intentarlo.",
379
+ server: "El servidor ha tenido un problema. Vuelve a intentarlo más tarde.",
380
+ unknown: "Algo ha fallado.",
381
+ aborted: "Cancelado.",
382
+ },
383
+ bulkResult: (succeeded, failed, locale) => `${count(succeeded, locale)} correctos, ${count(failed, locale)} con error`,
384
+ retryFailed: (value, locale) => `Reintentar los fallidos (${count(value, locale)})`,
345
385
  };
@@ -1,4 +1,4 @@
1
- import { ServiceErrorKind } from "./constants.js";
1
+ import { ErrorReason, ServiceErrorKind } from "./constants.js";
2
2
  export type ServiceFieldError = {
3
3
  path: string;
4
4
  message: string;
@@ -12,6 +12,10 @@ export type ServiceError = {
12
12
  current?: unknown;
13
13
  status?: number;
14
14
  cause?: unknown;
15
+ /** Why it failed, when the transport says more than `kind`: `session-expired`, `rate-limited`, `timeout`. */
16
+ reason?: ErrorReason;
17
+ /** The backend's own stable code (`card_declined`), which `defineErrors({ codes })` words and classifies. */
18
+ code?: string;
15
19
  };
16
20
  export declare function isServiceError(value: unknown): value is ServiceError;
17
21
  /**
@@ -29,6 +33,9 @@ export declare class ServiceFailure extends Error {
29
33
  }
30
34
  export declare function serviceError(kind: ServiceErrorKind, message: string, extra?: Partial<Omit<ServiceError, "kind" | "message">>): ServiceError;
31
35
  export declare function kindOfStatus(status: number): ServiceErrorKind;
36
+ export declare function isErrorReason(value: unknown): value is ErrorReason;
37
+ /** Its `reason`, or the one its status and kind tell: a 401 is `unauthorized`, a 429 `rate-limited`. */
38
+ export declare function reasonOf(error: ServiceError): ErrorReason;
32
39
  /**
33
40
  * Field errors from the shapes servers send: Spring's `errors`/`fieldErrors` (`field`, `defaultMessage`) and
34
41
  * constraint violations (`propertyPath`), RFC 9457
@@ -38,9 +45,8 @@ export declare function fieldErrorsOf(body: unknown): ServiceFieldError[] | unde
38
45
  export declare function httpServiceError(status: number, body: unknown, statusText?: string): ServiceError;
39
46
  export declare function problemDetailError(response: Response): Promise<ServiceFailure>;
40
47
  /**
41
- * Normalizes anything a service threw: a `ServiceFailure` or `ServiceError` comes back as it is, an abort is
42
- * `aborted`, fetch's `TypeError` is `network`, an object with an HTTP `status` maps by status (`400`/`422`
43
- * validation, `401`/`403` forbidden, `404` not found, `409`/`412` conflict, the rest server), and anything else is a
44
- * `server` error with its message.
48
+ * Normalizes anything a service threw: a `ServiceFailure` or `ServiceError` as it is, an abort `aborted`, a timeout
49
+ * and fetch's `TypeError` `network`, an HTTP `status` by status (`kindOfStatus`), anything else `server` with the
50
+ * `unknown` reason.
45
51
  */
46
52
  export declare function toServiceError(error: unknown): ServiceError;
@@ -1,4 +1,4 @@
1
- import { ServiceErrorKind } from "./constants.js";
1
+ import { ErrorReason, ServiceErrorKind } from "./constants.js";
2
2
  import { isBoolean, isNumber, isRecord, isString, isText } from "./guards.js";
3
3
  const kinds = new Set(Object.values(ServiceErrorKind));
4
4
  export function isServiceError(value) {
@@ -52,6 +52,35 @@ export function kindOfStatus(status) {
52
52
  function text(value) {
53
53
  return isText(value) ? value : undefined;
54
54
  }
55
+ const reasons = new Set(Object.values(ErrorReason));
56
+ export function isErrorReason(value) {
57
+ return isString(value) && reasons.has(value);
58
+ }
59
+ function reasonOfStatus(status) {
60
+ if (status === 401)
61
+ return ErrorReason.unauthorized;
62
+ if (status === 408 || status === 504)
63
+ return ErrorReason.timeout;
64
+ if (status === 429)
65
+ return ErrorReason.rateLimited;
66
+ return undefined;
67
+ }
68
+ const reasonOfKind = {
69
+ [ServiceErrorKind.validation]: ErrorReason.validation,
70
+ [ServiceErrorKind.conflict]: ErrorReason.conflict,
71
+ [ServiceErrorKind.forbidden]: ErrorReason.forbidden,
72
+ [ServiceErrorKind.notFound]: ErrorReason.notFound,
73
+ [ServiceErrorKind.network]: ErrorReason.network,
74
+ [ServiceErrorKind.server]: ErrorReason.server,
75
+ [ServiceErrorKind.aborted]: ErrorReason.aborted,
76
+ };
77
+ /** Its `reason`, or the one its status and kind tell: a 401 is `unauthorized`, a 429 `rate-limited`. */
78
+ export function reasonOf(error) {
79
+ if (error.reason !== undefined)
80
+ return error.reason;
81
+ const byStatus = error.status === undefined ? undefined : reasonOfStatus(error.status);
82
+ return byStatus ?? reasonOfKind[error.kind];
83
+ }
55
84
  function fieldEntry(entry) {
56
85
  if (!isRecord(entry))
57
86
  return undefined;
@@ -111,8 +140,13 @@ export function httpServiceError(status, body, statusText) {
111
140
  const kind = kindOfStatus(status);
112
141
  const fields = fieldErrorsOf(body);
113
142
  const message = messageOfBody(body) ?? text(statusText) ?? `Request failed with status ${String(status)}`;
143
+ const said = isRecord(body) ? body.reason : undefined;
144
+ const reason = isErrorReason(said) ? said : reasonOfStatus(status);
145
+ const code = isRecord(body) ? (text(body.code) ?? (isErrorReason(said) ? undefined : text(said))) : undefined;
114
146
  return serviceError(kind, message, {
115
147
  status,
148
+ ...(reason === undefined ? {} : { reason }),
149
+ ...(code === undefined ? {} : { code }),
116
150
  ...(fields ? { fields } : {}),
117
151
  ...(kind === ServiceErrorKind.conflict && isRecord(body) && "current" in body ? { current: body.current } : {}),
118
152
  cause: body,
@@ -130,20 +164,26 @@ export async function problemDetailError(response) {
130
164
  return new ServiceFailure(httpServiceError(response.status, body, response.statusText));
131
165
  }
132
166
  function isAbort(error) {
133
- return ((error instanceof DOMException && (error.name === "AbortError" || error.name === "TimeoutError")) ||
134
- (isRecord(error) && error.name === "AbortError"));
167
+ return ((error instanceof DOMException && error.name === "AbortError") || (isRecord(error) && error.name === "AbortError"));
168
+ }
169
+ function isTimeout(error) {
170
+ return (error instanceof DOMException || isRecord(error)) && error.name === "TimeoutError";
135
171
  }
136
172
  /**
137
- * Normalizes anything a service threw: a `ServiceFailure` or `ServiceError` comes back as it is, an abort is
138
- * `aborted`, fetch's `TypeError` is `network`, an object with an HTTP `status` maps by status (`400`/`422`
139
- * validation, `401`/`403` forbidden, `404` not found, `409`/`412` conflict, the rest server), and anything else is a
140
- * `server` error with its message.
173
+ * Normalizes anything a service threw: a `ServiceFailure` or `ServiceError` as it is, an abort `aborted`, a timeout
174
+ * and fetch's `TypeError` `network`, an HTTP `status` by status (`kindOfStatus`), anything else `server` with the
175
+ * `unknown` reason.
141
176
  */
142
177
  export function toServiceError(error) {
143
178
  if (error instanceof ServiceFailure)
144
179
  return error.error;
145
180
  if (isServiceError(error))
146
181
  return error;
182
+ if (isTimeout(error))
183
+ return serviceError(ServiceErrorKind.network, "The request timed out.", {
184
+ reason: ErrorReason.timeout,
185
+ cause: error,
186
+ });
147
187
  if (isAbort(error))
148
188
  return serviceError(ServiceErrorKind.aborted, "The request was cancelled.", { cause: error });
149
189
  if (error instanceof TypeError)
@@ -158,9 +198,12 @@ export function toServiceError(error) {
158
198
  }
159
199
  const fields = fieldErrorsOf(record);
160
200
  return serviceError(fields ? ServiceErrorKind.validation : ServiceErrorKind.server, message, {
161
- ...(fields ? { fields } : {}),
201
+ ...(fields ? { fields } : { reason: ErrorReason.unknown }),
162
202
  cause: error,
163
203
  });
164
204
  }
165
- return serviceError(ServiceErrorKind.server, text(error) ?? "Something went wrong.", { cause: error });
205
+ return serviceError(ServiceErrorKind.server, text(error) ?? "Something went wrong.", {
206
+ reason: ErrorReason.unknown,
207
+ cause: error,
208
+ });
166
209
  }
@@ -0,0 +1,75 @@
1
+ import type { Text } from "../i18n/locale.js";
2
+ export declare const DialogKind: {
3
+ readonly confirm: "confirm";
4
+ readonly alert: "alert";
5
+ readonly prompt: "prompt";
6
+ };
7
+ export type DialogKind = (typeof DialogKind)[keyof typeof DialogKind];
8
+ /** A dialog's words. Each may be a message (`msg("orders.approveTitle")`), worded in the `DataLayer`'s locale. */
9
+ export type DialogTexts = {
10
+ title: Text;
11
+ description?: Text;
12
+ /** The button that answers yes; the catalog's `confirm` (or `ok` for an alert) by default. */
13
+ confirmLabel?: Text;
14
+ };
15
+ export type ConfirmRequest = DialogTexts & {
16
+ /** Red, and the confirm button carries `data-agent-confirm`, so an agent shows a person before pressing it. */
17
+ destructive?: boolean;
18
+ /** The sentence an agent shows before confirming a destructive one: its description, or its title, by default. */
19
+ agentConfirm?: Text;
20
+ cancelLabel?: Text;
21
+ };
22
+ export type AlertRequest = DialogTexts;
23
+ export type PromptRequest = DialogTexts & {
24
+ /** The field's name; the title by default. */
25
+ label?: Text;
26
+ defaultValue?: string;
27
+ placeholder?: Text;
28
+ /** Confirming needs some text. Default false. */
29
+ required?: boolean;
30
+ cancelLabel?: Text;
31
+ };
32
+ export type DialogEntry = {
33
+ id: number;
34
+ kind: typeof DialogKind.confirm;
35
+ request: ConfirmRequest;
36
+ } | {
37
+ id: number;
38
+ kind: typeof DialogKind.alert;
39
+ request: AlertRequest;
40
+ } | {
41
+ id: number;
42
+ kind: typeof DialogKind.prompt;
43
+ request: PromptRequest;
44
+ };
45
+ /** What a dialog resolves with: `confirm` true or false, `prompt` the text or `null`, `alert` nothing. */
46
+ export type DialogAnswer = boolean | string | null | undefined;
47
+ export type DialogsSnapshot = {
48
+ /** The dialog on screen: one at a time, the others wait their turn in order. */
49
+ current: DialogEntry | undefined;
50
+ /** How many wait behind it. */
51
+ waiting: number;
52
+ /** The host that draws them: the first one attached. */
53
+ host: object | undefined;
54
+ };
55
+ export type Dialogs = {
56
+ confirm(request: ConfirmRequest): Promise<boolean>;
57
+ alert(request: AlertRequest): Promise<void>;
58
+ prompt(request: PromptRequest): Promise<string | null>;
59
+ };
60
+ export type DialogQueue = Dialogs & {
61
+ getSnapshot(): DialogsSnapshot;
62
+ subscribe(listener: () => void): () => void;
63
+ /** Answers a dialog and shows the next. A dialog answered twice keeps its first answer. */
64
+ settle(id: number, answer: DialogAnswer): void;
65
+ /** A component that draws the dialogs, by a token of its own; only the first one attached does. Returns detach. */
66
+ attach(host: object): () => void;
67
+ /** Answers every dialog as dismissed: `false`, `null` or nothing. */
68
+ clear(): void;
69
+ };
70
+ /**
71
+ * The queue behind `useDialogs`: `confirm`, `alert` and `prompt` return promises, and a host (`NavDialogs` in the
72
+ * blocks) draws the first one waiting. A request made while one is open waits for it; a dialog opened above another
73
+ * modal stacks over it.
74
+ */
75
+ export declare function createDialogQueue(): DialogQueue;
@@ -0,0 +1,66 @@
1
+ import { isString } from "../core/guards.js";
2
+ export const DialogKind = { confirm: "confirm", alert: "alert", prompt: "prompt" };
3
+ const dismissed = { [DialogKind.confirm]: false, [DialogKind.alert]: undefined, [DialogKind.prompt]: null };
4
+ /**
5
+ * The queue behind `useDialogs`: `confirm`, `alert` and `prompt` return promises, and a host (`NavDialogs` in the
6
+ * blocks) draws the first one waiting. A request made while one is open waits for it; a dialog opened above another
7
+ * modal stacks over it.
8
+ */
9
+ export function createDialogQueue() {
10
+ const waiting = [];
11
+ const hosts = [];
12
+ const listeners = new Set();
13
+ let nextId = 1;
14
+ let snapshot = { current: undefined, waiting: 0, host: undefined };
15
+ const publish = () => {
16
+ snapshot = { current: waiting[0]?.entry, waiting: Math.max(0, waiting.length - 1), host: hosts[0] };
17
+ for (const listener of listeners)
18
+ listener();
19
+ };
20
+ function open(entry) {
21
+ if (hosts.length === 0)
22
+ return Promise.reject(new Error("useDialogs needs a dialog host under the <DataLayer>: render <NavDialogs /> from the blocks."));
23
+ return new Promise((resolve) => {
24
+ waiting.push({ entry, resolve });
25
+ publish();
26
+ });
27
+ }
28
+ const id = () => nextId++;
29
+ return {
30
+ confirm: (request) => open({ id: id(), kind: DialogKind.confirm, request }).then((answer) => answer === true),
31
+ alert: (request) => open({ id: id(), kind: DialogKind.alert, request }).then(() => undefined),
32
+ prompt: (request) => open({ id: id(), kind: DialogKind.prompt, request }).then((answer) => (isString(answer) ? answer : null)),
33
+ getSnapshot: () => snapshot,
34
+ subscribe(listener) {
35
+ listeners.add(listener);
36
+ return () => {
37
+ listeners.delete(listener);
38
+ };
39
+ },
40
+ settle(target, answer) {
41
+ const index = waiting.findIndex((item) => item.entry.id === target);
42
+ if (index === -1)
43
+ return;
44
+ const [item] = waiting.splice(index, 1);
45
+ item?.resolve(answer);
46
+ publish();
47
+ },
48
+ attach(host) {
49
+ hosts.push(host);
50
+ publish();
51
+ return () => {
52
+ const index = hosts.indexOf(host);
53
+ if (index === -1)
54
+ return;
55
+ hosts.splice(index, 1);
56
+ publish();
57
+ };
58
+ },
59
+ clear() {
60
+ const all = waiting.splice(0);
61
+ for (const item of all)
62
+ item.resolve(dismissed[item.entry.kind]);
63
+ publish();
64
+ },
65
+ };
66
+ }
@@ -0,0 +1,21 @@
1
+ import { ErrorReason } from "../core/constants.js";
2
+ import { type ServiceError } from "../core/errors.js";
3
+ /**
4
+ * Turns what a transport threw into a `ServiceError`, or `undefined` when it isn't its shape, so the next adapter (and
5
+ * then `toServiceError`) reads it.
6
+ */
7
+ export type ErrorAdapter = (raw: unknown) => ServiceError | undefined;
8
+ /** A `ServiceError` for a reason, with the kind the rest of the App SDK reads: `appError(ErrorReason.sessionExpired)`. */
9
+ export declare function appError(reason: ErrorReason, message?: string, extra?: Partial<Omit<ServiceError, "kind" | "message" | "reason">>): ServiceError;
10
+ /**
11
+ * A fetch `Response` thrown as it is (`if (!response.ok) throw response`): its status classifies it. The body isn't
12
+ * read, since it may be read already; throw `await problemDetailError(response)` for its message and field errors.
13
+ */
14
+ export declare const responseErrors: ErrorAdapter;
15
+ /**
16
+ * Firebase's errors: a callable function's `HttpsError` (`functions/unauthenticated`), Auth's
17
+ * (`auth/requires-recent-login` is `session-expired`, `auth/network-request-failed` is `network`) and Firestore's.
18
+ * A callable's `details.reason` wins when it's an `ErrorReason`, and is kept as the `code` otherwise
19
+ * (`details: { reason: "card_declined" }`); `details` may carry field errors.
20
+ */
21
+ export declare const firebaseErrors: ErrorAdapter;
@@ -0,0 +1,81 @@
1
+ import { ErrorReason, ServiceErrorKind } from "../core/constants.js";
2
+ import { fieldErrorsOf, httpServiceError, isErrorReason, serviceError } from "../core/errors.js";
3
+ import { isNumber, isRecord, isString, isText } from "../core/guards.js";
4
+ const kindOfReason = {
5
+ [ErrorReason.network]: ServiceErrorKind.network,
6
+ [ErrorReason.timeout]: ServiceErrorKind.network,
7
+ [ErrorReason.unauthorized]: ServiceErrorKind.forbidden,
8
+ [ErrorReason.sessionExpired]: ServiceErrorKind.forbidden,
9
+ [ErrorReason.forbidden]: ServiceErrorKind.forbidden,
10
+ [ErrorReason.notFound]: ServiceErrorKind.notFound,
11
+ [ErrorReason.conflict]: ServiceErrorKind.conflict,
12
+ [ErrorReason.validation]: ServiceErrorKind.validation,
13
+ [ErrorReason.rateLimited]: ServiceErrorKind.server,
14
+ [ErrorReason.server]: ServiceErrorKind.server,
15
+ [ErrorReason.unknown]: ServiceErrorKind.server,
16
+ [ErrorReason.aborted]: ServiceErrorKind.aborted,
17
+ };
18
+ const retriedReasons = new Set([
19
+ ErrorReason.network,
20
+ ErrorReason.timeout,
21
+ ErrorReason.rateLimited,
22
+ ErrorReason.server,
23
+ ]);
24
+ /** A `ServiceError` for a reason, with the kind the rest of the App SDK reads: `appError(ErrorReason.sessionExpired)`. */
25
+ export function appError(reason, message = reason, extra = {}) {
26
+ return serviceError(kindOfReason[reason], message, { retryable: retriedReasons.has(reason), reason, ...extra });
27
+ }
28
+ /**
29
+ * A fetch `Response` thrown as it is (`if (!response.ok) throw response`): its status classifies it. The body isn't
30
+ * read, since it may be read already; throw `await problemDetailError(response)` for its message and field errors.
31
+ */
32
+ export const responseErrors = (raw) => raw instanceof Response ? httpServiceError(raw.status, undefined, raw.statusText) : undefined;
33
+ // Spec: Firebase's FunctionsErrorCode (gRPC canonical codes) and the Auth codes that mean "sign in again".
34
+ const firebaseReasons = {
35
+ cancelled: ErrorReason.aborted,
36
+ unknown: ErrorReason.unknown,
37
+ "invalid-argument": ErrorReason.validation,
38
+ "out-of-range": ErrorReason.validation,
39
+ "failed-precondition": ErrorReason.conflict,
40
+ "deadline-exceeded": ErrorReason.timeout,
41
+ "not-found": ErrorReason.notFound,
42
+ "already-exists": ErrorReason.conflict,
43
+ aborted: ErrorReason.conflict,
44
+ "permission-denied": ErrorReason.forbidden,
45
+ "resource-exhausted": ErrorReason.rateLimited,
46
+ unimplemented: ErrorReason.server,
47
+ internal: ErrorReason.server,
48
+ unavailable: ErrorReason.network,
49
+ "data-loss": ErrorReason.server,
50
+ unauthenticated: ErrorReason.unauthorized,
51
+ "network-request-failed": ErrorReason.network,
52
+ "too-many-requests": ErrorReason.rateLimited,
53
+ "requires-recent-login": ErrorReason.sessionExpired,
54
+ "user-token-expired": ErrorReason.sessionExpired,
55
+ "id-token-expired": ErrorReason.sessionExpired,
56
+ "user-disabled": ErrorReason.forbidden,
57
+ };
58
+ const firebasePrefix = /^(?:functions|auth|firestore|storage)\//u;
59
+ /**
60
+ * Firebase's errors: a callable function's `HttpsError` (`functions/unauthenticated`), Auth's
61
+ * (`auth/requires-recent-login` is `session-expired`, `auth/network-request-failed` is `network`) and Firestore's.
62
+ * A callable's `details.reason` wins when it's an `ErrorReason`, and is kept as the `code` otherwise
63
+ * (`details: { reason: "card_declined" }`); `details` may carry field errors.
64
+ */
65
+ export const firebaseErrors = (raw) => {
66
+ if (!isRecord(raw) || !isString(raw.code) || !firebasePrefix.test(raw.code) || raw.name === "ServiceFailure")
67
+ return undefined;
68
+ const bare = raw.code.replace(firebasePrefix, "");
69
+ const details = raw.details;
70
+ const said = isRecord(details) ? details.reason : undefined;
71
+ const reason = isErrorReason(said) ? said : (firebaseReasons[bare] ?? ErrorReason.unknown);
72
+ const fields = fieldErrorsOf(details);
73
+ const code = isText(said) && !isErrorReason(said) ? said : undefined;
74
+ const status = isRecord(details) && isNumber(details.status) ? details.status : undefined;
75
+ return appError(reason, isText(raw.message) ? raw.message : bare, {
76
+ cause: raw,
77
+ ...(fields ? { fields } : {}),
78
+ ...(code === undefined ? {} : { code }),
79
+ ...(status === undefined ? {} : { status }),
80
+ });
81
+ };
@@ -0,0 +1,88 @@
1
+ import { ErrorReason, Feedback, Idempotency, Operation } from "../core/constants.js";
2
+ import type { CallContext } from "../core/contracts.js";
3
+ import { type ServiceError } from "../core/errors.js";
4
+ import { type Locale, type Text } from "../i18n/locale.js";
5
+ import type { Session } from "../session/session.js";
6
+ import type { ErrorAdapter } from "./adapters.js";
7
+ /** A `ServiceError` whose `reason` is known. */
8
+ export type AppError = ServiceError & {
9
+ reason: ErrorReason;
10
+ };
11
+ /** What the app says about one reason: its message, where it shows, and whether a call retries on it. */
12
+ export type ReasonPolicy = {
13
+ message?: Text;
14
+ feedback?: Feedback;
15
+ retry?: boolean;
16
+ };
17
+ /** What the app says about one of its backend's codes; `reason` classifies it (`card_declined` is `validation`). */
18
+ export type CodePolicy = {
19
+ reason?: ErrorReason;
20
+ message?: Text;
21
+ feedback?: Feedback;
22
+ };
23
+ /**
24
+ * Signs the person in again, from the error that asked for it: a re-login or MFA dialog. Resolves `true` once they
25
+ * did, so the call that failed runs again; `false` (or a rejection) when they didn't.
26
+ */
27
+ export type Reauthenticate = (error: AppError) => Promise<boolean> | boolean;
28
+ export type RetryOptions = {
29
+ /** Retries after the first try; 2 by default. */
30
+ attempts?: number;
31
+ /** The wait before retry `attempt` (0 first), in ms; exponential from 300 ms with jitter, at most 5 s, by default. */
32
+ delay?: (attempt: number, error: AppError) => number;
33
+ };
34
+ export type ErrorsOptions = {
35
+ /** Read a transport's own errors before `toServiceError`: `[firebaseErrors]`, or your own. */
36
+ adapters?: readonly ErrorAdapter[];
37
+ reasons?: Partial<Readonly<Record<ErrorReason, ReasonPolicy>>>;
38
+ codes?: Readonly<Record<string, CodePolicy>>;
39
+ /** Where a write's outcome shows when its action doesn't say: success as a toast and errors by reason by default. */
40
+ mutations?: {
41
+ success?: Feedback;
42
+ error?: Feedback;
43
+ };
44
+ retry?: RetryOptions;
45
+ reauthenticate?: Reauthenticate;
46
+ };
47
+ export type CallOptions = {
48
+ operation: Operation;
49
+ signal?: AbortSignal | undefined;
50
+ session?: Session | undefined;
51
+ /** A write retries only when it's `idempotent`, or with `key`, sending one key for every try. */
52
+ idempotency?: Idempotency | undefined;
53
+ /** The submit's key, when it outlives this call (a dialog's next submit, a bulk retry of failed rows). */
54
+ idempotencyKey?: string | undefined;
55
+ };
56
+ export type FeedbackOptions = {
57
+ operation?: Operation;
58
+ feedback?: Feedback | undefined;
59
+ };
60
+ export type Errors = {
61
+ /** Classifies anything a call threw: adapters first, then `toServiceError`, then `codes`. */
62
+ classify(raw: unknown): AppError;
63
+ /**
64
+ * The sentence a person reads: the code's message, the reason's, or `errors.<reason>` in the locale (or in
65
+ * `fallback`, the `DataLayer`'s `labels.errors`). Never the transport's raw message.
66
+ */
67
+ text(error: AppError, locale?: Locale, fallback?: Readonly<Record<ErrorReason, string>>): string;
68
+ /** Where an error shows: the action's `feedback.error`, then the code's, the reason's and `mutations.error`. */
69
+ feedback(error: AppError, options?: FeedbackOptions): Feedback;
70
+ /** Where a write's success shows: the action's `feedback.success`, then `mutations.success`. */
71
+ successFeedback(feedback?: Feedback): Feedback;
72
+ /** Whether `error` asks to sign in again: `unauthorized` and `session-expired`, never a network error. */
73
+ needsReauth(error: AppError): boolean;
74
+ /** Registers the handler a dialog provides, over `reauthenticate`; returns its removal. */
75
+ onReauthenticate(handler: Reauthenticate): () => void;
76
+ /**
77
+ * Runs `call`: a query retries with backoff on a retryable reason, a write only when it's idempotent or keyed; an
78
+ * `unauthorized` or `session-expired` error waits for one shared re-authentication and runs again once. Every wait
79
+ * stops when `signal` aborts. Rejects with a `ServiceFailure` whose error has its `reason`.
80
+ */
81
+ run<R>(call: (context: CallContext) => Promise<R>, options: CallOptions): Promise<R>;
82
+ };
83
+ /**
84
+ * The app's error policy: how transport errors classify into reasons, how each reason is worded and shown, when calls
85
+ * retry and how an expired session signs in again. Give it to `DataLayer` (`errors`) and every resource call and
86
+ * action goes through it.
87
+ */
88
+ export declare function defineErrors(options?: ErrorsOptions): Errors;