@eskais/app-sdk 0.0.0-stage → 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.
- package/LICENSE +21 -0
- package/README.md +74 -2
- package/dist/action/action.d.ts +133 -0
- package/dist/action/action.js +224 -0
- package/dist/action/bulk.d.ts +24 -0
- package/dist/action/bulk.js +24 -0
- package/dist/cli/cli.d.ts +2 -0
- package/dist/cli/cli.js +51 -0
- package/dist/cli/routes.d.ts +17 -0
- package/dist/cli/routes.js +36 -0
- package/dist/core/assume.d.ts +1 -0
- package/dist/core/assume.js +8 -0
- package/dist/core/constants.d.ts +359 -0
- package/dist/core/constants.js +187 -0
- package/dist/core/contracts.d.ts +107 -0
- package/dist/core/contracts.js +3 -0
- package/dist/core/data-labels.d.ts +210 -0
- package/dist/core/data-labels.js +385 -0
- package/dist/core/errors.d.ts +52 -0
- package/dist/core/errors.js +209 -0
- package/dist/core/guards.d.ts +9 -0
- package/dist/core/guards.js +14 -0
- package/dist/core/refusal.d.ts +30 -0
- package/dist/core/refusal.js +53 -0
- package/dist/dialogs/dialogs.d.ts +75 -0
- package/dist/dialogs/dialogs.js +66 -0
- package/dist/draft/draft.d.ts +36 -0
- package/dist/draft/draft.js +87 -0
- package/dist/errors/adapters.d.ts +21 -0
- package/dist/errors/adapters.js +81 -0
- package/dist/errors/define-errors.d.ts +88 -0
- package/dist/errors/define-errors.js +168 -0
- package/dist/errors/idempotency.d.ts +2 -0
- package/dist/errors/idempotency.js +13 -0
- package/dist/export/csv.d.ts +25 -0
- package/dist/export/csv.js +59 -0
- package/dist/i18n/adapters.d.ts +53 -0
- package/dist/i18n/adapters.js +56 -0
- package/dist/i18n/format.d.ts +10 -0
- package/dist/i18n/format.js +273 -0
- package/dist/i18n/labels.d.ts +10 -0
- package/dist/i18n/labels.js +227 -0
- package/dist/i18n/locale.d.ts +73 -0
- package/dist/i18n/locale.js +74 -0
- package/dist/i18n/messages.d.ts +93 -0
- package/dist/i18n/messages.js +16 -0
- package/dist/import/csv-parse.d.ts +11 -0
- package/dist/import/csv-parse.js +70 -0
- package/dist/import/import.d.ts +104 -0
- package/dist/import/import.js +266 -0
- package/dist/index.d.ts +46 -0
- package/dist/index.js +45 -0
- package/dist/navigation/nav.d.ts +128 -0
- package/dist/navigation/nav.js +301 -0
- package/dist/navigation/router.d.ts +81 -0
- package/dist/navigation/router.js +249 -0
- package/dist/navigation/shortcuts.d.ts +37 -0
- package/dist/navigation/shortcuts.js +93 -0
- package/dist/next/index.d.ts +3 -0
- package/dist/next/index.js +3 -0
- package/dist/next/screen-hydration.d.ts +12 -0
- package/dist/next/screen-hydration.js +26 -0
- package/dist/next/screen.d.ts +25 -0
- package/dist/next/screen.js +44 -0
- package/dist/next/server/handler.d.ts +39 -0
- package/dist/next/server/handler.js +190 -0
- package/dist/next/server/index.d.ts +6 -0
- package/dist/next/server/index.js +6 -0
- package/dist/next/server/page.d.ts +63 -0
- package/dist/next/server/page.js +110 -0
- package/dist/next/server/prefetch.d.ts +29 -0
- package/dist/next/server/prefetch.js +97 -0
- package/dist/next/server/session.d.ts +25 -0
- package/dist/next/server/session.js +23 -0
- package/dist/next/use-next-router.d.ts +21 -0
- package/dist/next/use-next-router.js +104 -0
- package/dist/permissions/permissions.d.ts +134 -0
- package/dist/permissions/permissions.js +121 -0
- package/dist/react/data-layer.d.ts +68 -0
- package/dist/react/data-layer.js +76 -0
- package/dist/react/hooks/use-action-dialog.d.ts +25 -0
- package/dist/react/hooks/use-action-dialog.js +31 -0
- package/dist/react/hooks/use-action.d.ts +37 -0
- package/dist/react/hooks/use-action.js +125 -0
- package/dist/react/hooks/use-better-auth.d.ts +12 -0
- package/dist/react/hooks/use-better-auth.js +11 -0
- package/dist/react/hooks/use-bulk-action.d.ts +20 -0
- package/dist/react/hooks/use-bulk-action.js +24 -0
- package/dist/react/hooks/use-dialogs.d.ts +14 -0
- package/dist/react/hooks/use-dialogs.js +20 -0
- package/dist/react/hooks/use-draft.d.ts +5 -0
- package/dist/react/hooks/use-draft.js +17 -0
- package/dist/react/hooks/use-nav.d.ts +17 -0
- package/dist/react/hooks/use-nav.js +35 -0
- package/dist/react/hooks/use-new-rows.d.ts +22 -0
- package/dist/react/hooks/use-new-rows.js +24 -0
- package/dist/react/hooks/use-permissions.d.ts +13 -0
- package/dist/react/hooks/use-permissions.js +19 -0
- package/dist/react/hooks/use-reauthenticate.d.ts +6 -0
- package/dist/react/hooks/use-reauthenticate.js +11 -0
- package/dist/react/hooks/use-resource.d.ts +92 -0
- package/dist/react/hooks/use-resource.js +255 -0
- package/dist/react/hooks/use-view.d.ts +6 -0
- package/dist/react/hooks/use-view.js +24 -0
- package/dist/react/index.d.ts +15 -0
- package/dist/react/index.js +15 -0
- package/dist/react/keys.d.ts +60 -0
- package/dist/react/keys.js +71 -0
- package/dist/react/new-rows.d.ts +22 -0
- package/dist/react/new-rows.js +72 -0
- package/dist/refresh/new-rows.d.ts +13 -0
- package/dist/refresh/new-rows.js +18 -0
- package/dist/resource/form-schema.d.ts +11 -0
- package/dist/resource/form-schema.js +51 -0
- package/dist/resource/relations.d.ts +99 -0
- package/dist/resource/relations.js +194 -0
- package/dist/resource/resource-relations.d.ts +47 -0
- package/dist/resource/resource-relations.js +154 -0
- package/dist/resource/resource-schema.d.ts +9 -0
- package/dist/resource/resource-schema.js +73 -0
- package/dist/resource/resource-texts.d.ts +18 -0
- package/dist/resource/resource-texts.js +13 -0
- package/dist/resource/resource-types.d.ts +420 -0
- package/dist/resource/resource-types.js +1 -0
- package/dist/resource/resource-words.d.ts +25 -0
- package/dist/resource/resource-words.js +221 -0
- package/dist/resource/resource.d.ts +15 -0
- package/dist/resource/resource.js +280 -0
- package/dist/resource/schema.d.ts +57 -0
- package/dist/resource/schema.js +115 -0
- package/dist/services/from-page-source.d.ts +15 -0
- package/dist/services/from-page-source.js +27 -0
- package/dist/services/memory-query.d.ts +8 -0
- package/dist/services/memory-query.js +165 -0
- package/dist/services/memory-service.d.ts +33 -0
- package/dist/services/memory-service.js +291 -0
- package/dist/services/read-only-service.d.ts +18 -0
- package/dist/services/read-only-service.js +25 -0
- package/dist/services/rest-service.d.ts +65 -0
- package/dist/services/rest-service.js +222 -0
- package/dist/services/rng.d.ts +9 -0
- package/dist/services/rng.js +22 -0
- package/dist/services/spring-service.d.ts +58 -0
- package/dist/services/spring-service.js +132 -0
- package/dist/session/better-auth.d.ts +83 -0
- package/dist/session/better-auth.js +86 -0
- package/dist/session/session.d.ts +45 -0
- package/dist/session/session.js +36 -0
- package/dist/view/preferences.d.ts +35 -0
- package/dist/view/preferences.js +93 -0
- package/dist/view/view-types.d.ts +124 -0
- package/dist/view/view-types.js +1 -0
- package/dist/view/view-url.d.ts +7 -0
- package/dist/view/view-url.js +54 -0
- package/dist/view/view.d.ts +4 -0
- package/dist/view/view.js +392 -0
- package/locales/en.json +193 -0
- package/locales/es.json +193 -0
- package/package.json +88 -4
|
@@ -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;
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
import { ErrorReason, Feedback, Idempotency, Operation } from "../core/constants.js";
|
|
2
|
+
import { isServiceError, reasonOf, ServiceFailure, toServiceError } from "../core/errors.js";
|
|
3
|
+
import { lookup, resolveText } from "../i18n/locale.js";
|
|
4
|
+
import { idempotencyKey } from "./idempotency.js";
|
|
5
|
+
const defaultFeedback = {
|
|
6
|
+
[ErrorReason.network]: Feedback.toast,
|
|
7
|
+
[ErrorReason.timeout]: Feedback.toast,
|
|
8
|
+
[ErrorReason.unauthorized]: Feedback.toast,
|
|
9
|
+
[ErrorReason.sessionExpired]: Feedback.toast,
|
|
10
|
+
[ErrorReason.forbidden]: Feedback.toast,
|
|
11
|
+
[ErrorReason.notFound]: Feedback.toast,
|
|
12
|
+
[ErrorReason.conflict]: Feedback.inline,
|
|
13
|
+
[ErrorReason.validation]: Feedback.inline,
|
|
14
|
+
[ErrorReason.rateLimited]: Feedback.toast,
|
|
15
|
+
[ErrorReason.server]: Feedback.toast,
|
|
16
|
+
[ErrorReason.unknown]: Feedback.toast,
|
|
17
|
+
[ErrorReason.aborted]: Feedback.silent,
|
|
18
|
+
};
|
|
19
|
+
const retriedByDefault = new Set([ErrorReason.network, ErrorReason.timeout, ErrorReason.rateLimited]);
|
|
20
|
+
const reauthReasons = new Set([ErrorReason.unauthorized, ErrorReason.sessionExpired]);
|
|
21
|
+
const needsReauth = (error) => reauthReasons.has(error.reason);
|
|
22
|
+
function backoff(attempt) {
|
|
23
|
+
const base = Math.min(300 * 2 ** attempt, 5000);
|
|
24
|
+
return base / 2 + Math.random() * (base / 2);
|
|
25
|
+
}
|
|
26
|
+
const neverAborts = new AbortController().signal;
|
|
27
|
+
function abortFailure(signal) {
|
|
28
|
+
return new ServiceFailure(toServiceError(signal.reason ?? new DOMException("Aborted", "AbortError")));
|
|
29
|
+
}
|
|
30
|
+
function untilAborted(promise, signal) {
|
|
31
|
+
if (signal === neverAborts)
|
|
32
|
+
return promise;
|
|
33
|
+
return new Promise((resolve, reject) => {
|
|
34
|
+
if (signal.aborted) {
|
|
35
|
+
reject(abortFailure(signal));
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
const stop = () => reject(abortFailure(signal));
|
|
39
|
+
signal.addEventListener("abort", stop, { once: true });
|
|
40
|
+
promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", stop));
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
function wait(ms, signal) {
|
|
44
|
+
return untilAborted(new Promise((resolve) => {
|
|
45
|
+
const timer = setTimeout(resolve, ms);
|
|
46
|
+
signal.addEventListener("abort", () => clearTimeout(timer), { once: true });
|
|
47
|
+
}), signal);
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* The app's error policy: how transport errors classify into reasons, how each reason is worded and shown, when calls
|
|
51
|
+
* retry and how an expired session signs in again. Give it to `DataLayer` (`errors`) and every resource call and
|
|
52
|
+
* action goes through it.
|
|
53
|
+
*/
|
|
54
|
+
export function defineErrors(options = {}) {
|
|
55
|
+
const handlers = [];
|
|
56
|
+
const attempts = options.retry?.attempts ?? 2;
|
|
57
|
+
const delay = options.retry?.delay ?? backoff;
|
|
58
|
+
let generation = 0;
|
|
59
|
+
let reauthenticating;
|
|
60
|
+
function classify(raw) {
|
|
61
|
+
const adapted = isServiceError(raw) || raw instanceof ServiceFailure ? undefined : adapt(raw);
|
|
62
|
+
const error = adapted ?? toServiceError(raw);
|
|
63
|
+
const coded = error.code === undefined ? undefined : options.codes?.[error.code];
|
|
64
|
+
return { ...error, reason: coded?.reason ?? reasonOf(error) };
|
|
65
|
+
}
|
|
66
|
+
function adapt(raw) {
|
|
67
|
+
for (const adapter of options.adapters ?? []) {
|
|
68
|
+
const error = adapter(raw);
|
|
69
|
+
if (error)
|
|
70
|
+
return error;
|
|
71
|
+
}
|
|
72
|
+
return undefined;
|
|
73
|
+
}
|
|
74
|
+
const codeOf = (error) => (error.code === undefined ? undefined : options.codes?.[error.code]);
|
|
75
|
+
function retries(error, operation, idempotent) {
|
|
76
|
+
if (operation === Operation.mutation && !idempotent)
|
|
77
|
+
return false;
|
|
78
|
+
const said = options.reasons?.[error.reason]?.retry;
|
|
79
|
+
if (said !== undefined)
|
|
80
|
+
return said;
|
|
81
|
+
if (error.reason === ErrorReason.server)
|
|
82
|
+
return error.retryable;
|
|
83
|
+
return retriedByDefault.has(error.reason);
|
|
84
|
+
}
|
|
85
|
+
function reauthenticate(error, startedAt, signal) {
|
|
86
|
+
if (generation !== startedAt)
|
|
87
|
+
return Promise.resolve(true);
|
|
88
|
+
const handler = handlers.at(-1) ?? options.reauthenticate;
|
|
89
|
+
if (!handler)
|
|
90
|
+
return Promise.resolve(false);
|
|
91
|
+
reauthenticating ??= Promise.resolve()
|
|
92
|
+
.then(() => handler(error))
|
|
93
|
+
.then((done) => {
|
|
94
|
+
if (done)
|
|
95
|
+
generation += 1;
|
|
96
|
+
return done;
|
|
97
|
+
}, () => false)
|
|
98
|
+
.finally(() => {
|
|
99
|
+
reauthenticating = undefined;
|
|
100
|
+
});
|
|
101
|
+
return untilAborted(reauthenticating, signal);
|
|
102
|
+
}
|
|
103
|
+
async function run(call, given) {
|
|
104
|
+
const signal = given.signal ?? neverAborts;
|
|
105
|
+
const keyed = given.idempotencyKey ?? (given.idempotency === Idempotency.key ? idempotencyKey() : undefined);
|
|
106
|
+
const idempotent = keyed !== undefined || given.idempotency === Idempotency.idempotent;
|
|
107
|
+
const context = {
|
|
108
|
+
signal,
|
|
109
|
+
...(given.session === undefined ? {} : { session: given.session }),
|
|
110
|
+
...(keyed === undefined ? {} : { idempotencyKey: keyed }),
|
|
111
|
+
};
|
|
112
|
+
const attempt = async (tries, reauthed) => {
|
|
113
|
+
if (signal.aborted)
|
|
114
|
+
throw abortFailure(signal);
|
|
115
|
+
const startedAt = generation;
|
|
116
|
+
try {
|
|
117
|
+
return await call(context);
|
|
118
|
+
}
|
|
119
|
+
catch (raw) {
|
|
120
|
+
if (signal.aborted)
|
|
121
|
+
throw abortFailure(signal);
|
|
122
|
+
const error = classify(raw);
|
|
123
|
+
if (error.reason === ErrorReason.aborted)
|
|
124
|
+
throw new ServiceFailure(error);
|
|
125
|
+
if (needsReauth(error) && !reauthed) {
|
|
126
|
+
if (await reauthenticate(error, startedAt, signal))
|
|
127
|
+
return attempt(tries, true);
|
|
128
|
+
}
|
|
129
|
+
else if (tries < attempts && retries(error, given.operation, idempotent)) {
|
|
130
|
+
await wait(delay(tries, error), signal);
|
|
131
|
+
return attempt(tries + 1, reauthed);
|
|
132
|
+
}
|
|
133
|
+
throw new ServiceFailure(error);
|
|
134
|
+
}
|
|
135
|
+
};
|
|
136
|
+
return attempt(0, false);
|
|
137
|
+
}
|
|
138
|
+
return {
|
|
139
|
+
classify,
|
|
140
|
+
text(error, locale, fallback) {
|
|
141
|
+
const own = codeOf(error)?.message ?? options.reasons?.[error.reason]?.message;
|
|
142
|
+
if (own !== undefined)
|
|
143
|
+
return resolveText(own, locale);
|
|
144
|
+
const key = `errors.${error.reason}`;
|
|
145
|
+
return fallback?.[error.reason] ?? lookup(locale, key) ?? key;
|
|
146
|
+
},
|
|
147
|
+
feedback(error, { operation = Operation.query, feedback } = {}) {
|
|
148
|
+
return (feedback ??
|
|
149
|
+
codeOf(error)?.feedback ??
|
|
150
|
+
options.reasons?.[error.reason]?.feedback ??
|
|
151
|
+
(operation === Operation.mutation && error.reason !== ErrorReason.aborted
|
|
152
|
+
? options.mutations?.error
|
|
153
|
+
: undefined) ??
|
|
154
|
+
defaultFeedback[error.reason]);
|
|
155
|
+
},
|
|
156
|
+
successFeedback: (feedback) => feedback ?? options.mutations?.success ?? Feedback.toast,
|
|
157
|
+
needsReauth,
|
|
158
|
+
onReauthenticate(handler) {
|
|
159
|
+
handlers.push(handler);
|
|
160
|
+
return () => {
|
|
161
|
+
const index = handlers.lastIndexOf(handler);
|
|
162
|
+
if (index !== -1)
|
|
163
|
+
handlers.splice(index, 1);
|
|
164
|
+
};
|
|
165
|
+
},
|
|
166
|
+
run,
|
|
167
|
+
};
|
|
168
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { ValueType } from "../core/constants.js";
|
|
2
|
+
const hex = (byte) => byte.toString(16).padStart(2, "0");
|
|
3
|
+
/** A random idempotency key (a UUID v4), from `crypto.randomUUID` where the page is a secure context. */
|
|
4
|
+
export function idempotencyKey() {
|
|
5
|
+
if (typeof crypto.randomUUID === ValueType.function)
|
|
6
|
+
return crypto.randomUUID();
|
|
7
|
+
// Spec: RFC 9562 UUID version 4, for an insecure context where `randomUUID` is missing.
|
|
8
|
+
const bytes = crypto.getRandomValues(new Uint8Array(16));
|
|
9
|
+
bytes[6] = (bytes[6] & 0x0f) | 0x40;
|
|
10
|
+
bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
|
11
|
+
const text = [...bytes].map(hex).join("");
|
|
12
|
+
return `${text.slice(0, 8)}-${text.slice(8, 12)}-${text.slice(12, 16)}-${text.slice(16, 20)}-${text.slice(20)}`;
|
|
13
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { Query } from "../core/contracts.js";
|
|
2
|
+
import type { RelationContext } from "../resource/relations.js";
|
|
3
|
+
import { type Refusal } from "../core/refusal.js";
|
|
4
|
+
import type { Resource } from "../resource/resource.js";
|
|
5
|
+
export type CsvColumn<T> = {
|
|
6
|
+
key: string;
|
|
7
|
+
label: string;
|
|
8
|
+
format?: (row: T) => string;
|
|
9
|
+
};
|
|
10
|
+
/** Rows as CSV, with a header of the columns' labels and CRLF line ends (RFC 4180). */
|
|
11
|
+
export declare function toCsv<T>(rows: readonly T[], columns: readonly CsvColumn<T>[]): string;
|
|
12
|
+
export type CsvExportOptions<T> = {
|
|
13
|
+
columns: readonly CsvColumn<T>[];
|
|
14
|
+
context: RelationContext;
|
|
15
|
+
/** The relations the columns reach (`customer.name`), read in batches with each page. Default: the columns' keys. */
|
|
16
|
+
paths?: readonly string[];
|
|
17
|
+
/** Rows per request. Default 500. */
|
|
18
|
+
pageSize?: number;
|
|
19
|
+
onProgress?: (done: number, total: number | undefined) => void;
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* Exports what a query matches as CSV in the browser, page after page, up to the resource's `exportLimit`. Over the
|
|
23
|
+
* limit it answers with a refusal before reading the rest: a server export (`service.export`) is needed then.
|
|
24
|
+
*/
|
|
25
|
+
export declare function exportCsv<T, Id, F>(resource: Resource<T, Id, F>, query: Omit<Query<F>, "position" | "size">, options: CsvExportOptions<T>, tooLarge: (count: number, limit: number) => string): Promise<string | Refusal>;
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { isBoolean, isNumber, isString } from "../core/guards.js";
|
|
2
|
+
import { valueAt } from "../services/memory-query.js";
|
|
3
|
+
import { refuse } from "../core/refusal.js";
|
|
4
|
+
function cellText(value) {
|
|
5
|
+
if (value === undefined || value === null)
|
|
6
|
+
return "";
|
|
7
|
+
if (isString(value))
|
|
8
|
+
return value;
|
|
9
|
+
if (isNumber(value) || isBoolean(value))
|
|
10
|
+
return String(value);
|
|
11
|
+
if (Array.isArray(value))
|
|
12
|
+
return value.map(cellText).join(", ");
|
|
13
|
+
if (value instanceof Date)
|
|
14
|
+
return value.toISOString();
|
|
15
|
+
return JSON.stringify(value);
|
|
16
|
+
}
|
|
17
|
+
const needsQuotes = /[",\r\n]/u;
|
|
18
|
+
// Security: a cell starting with these runs as a formula in spreadsheet apps (CSV injection), so it gets a quote first.
|
|
19
|
+
const formulaStart = /^[=+\-@\t\r]/u;
|
|
20
|
+
function escapeCell(text) {
|
|
21
|
+
const safe = formulaStart.test(text) ? `'${text}` : text;
|
|
22
|
+
return needsQuotes.test(safe) ? `"${safe.replaceAll('"', '""')}"` : safe;
|
|
23
|
+
}
|
|
24
|
+
/** Rows as CSV, with a header of the columns' labels and CRLF line ends (RFC 4180). */
|
|
25
|
+
export function toCsv(rows, columns) {
|
|
26
|
+
const header = columns.map((column) => escapeCell(column.label)).join(",");
|
|
27
|
+
const lines = rows.map((row) => columns
|
|
28
|
+
.map((column) => escapeCell(column.format ? column.format(row) : cellText(valueAt(row, column.key))))
|
|
29
|
+
.join(","));
|
|
30
|
+
return [header, ...lines].join("\r\n");
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Exports what a query matches as CSV in the browser, page after page, up to the resource's `exportLimit`. Over the
|
|
34
|
+
* limit it answers with a refusal before reading the rest: a server export (`service.export`) is needed then.
|
|
35
|
+
*/
|
|
36
|
+
export async function exportCsv(resource, query, options, tooLarge) {
|
|
37
|
+
const limit = resource.exportLimit;
|
|
38
|
+
const size = Math.min(options.pageSize ?? 500, resource.service.capabilities.maxPageSize ?? Number.POSITIVE_INFINITY);
|
|
39
|
+
const rows = [];
|
|
40
|
+
let page = 1;
|
|
41
|
+
let total;
|
|
42
|
+
for (;;) {
|
|
43
|
+
// Perf: pages are read one after another, so a large export doesn't flood the server.
|
|
44
|
+
// oxlint-disable-next-line no-await-in-loop -- each page waits for the one before, by design
|
|
45
|
+
const result = await resource.listWith({ ...query, size, position: { page } }, options.context, options.paths ?? options.columns.map((column) => column.key));
|
|
46
|
+
total = result.total ?? total;
|
|
47
|
+
if (total !== undefined && total > limit)
|
|
48
|
+
return refuse(tooLarge(total, limit));
|
|
49
|
+
rows.push(...result.items);
|
|
50
|
+
options.onProgress?.(rows.length, total);
|
|
51
|
+
if (rows.length > limit)
|
|
52
|
+
return refuse(tooLarge(rows.length, limit));
|
|
53
|
+
const more = result.hasMore ?? (total === undefined ? result.items.length === size : rows.length < total);
|
|
54
|
+
if (!more || result.items.length === 0)
|
|
55
|
+
break;
|
|
56
|
+
page += 1;
|
|
57
|
+
}
|
|
58
|
+
return toCsv(rows, options.columns);
|
|
59
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import type { Locale } from "./locale.js";
|
|
2
|
+
export type AdapterOptions = {
|
|
3
|
+
/** The BCP 47 code `Intl` formats numbers and dates with; give it, so the server and the browser agree. */
|
|
4
|
+
locale: string;
|
|
5
|
+
/** Where a key the library lacks comes from: `defineLocale("es", { messages: es })`. */
|
|
6
|
+
base?: Locale;
|
|
7
|
+
};
|
|
8
|
+
/** A value next-intl formats: what `t`'s second argument takes. */
|
|
9
|
+
export type NextIntlValue = string | number | boolean | Date | null | undefined;
|
|
10
|
+
type Bivariant<Call extends (...args: never[]) => unknown> = {
|
|
11
|
+
call(...args: Parameters<Call>): ReturnType<Call>;
|
|
12
|
+
}["call"];
|
|
13
|
+
/** next-intl's `t`, from `useTranslations("eskais")` or `await getTranslations("eskais")`. */
|
|
14
|
+
export type NextIntlTranslator = Bivariant<(key: string, values?: Record<string, NextIntlValue>) => string> & {
|
|
15
|
+
has?: Bivariant<(key: string) => boolean>;
|
|
16
|
+
raw?: Bivariant<(key: string) => unknown>;
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* next-intl's translator as the App SDK's locale, in a client component (`useTranslations("eskais")`) or on the
|
|
20
|
+
* server (`await getTranslations("eskais")` for `navPage` and `generateMetadata`). next-intl formats the ICU messages
|
|
21
|
+
* itself. Merge the shipped catalog under your namespace in `i18n/request.ts` so every key is there:
|
|
22
|
+
* `messages.eskais = { ...es, ...mine.eskais }`.
|
|
23
|
+
*/
|
|
24
|
+
export declare function fromNextIntl(t: NextIntlTranslator, options: AdapterOptions): Locale;
|
|
25
|
+
/** An i18next instance, with `i18next-icu` so it reads ICU MessageFormat. */
|
|
26
|
+
export type I18nextLike = {
|
|
27
|
+
readonly language: string;
|
|
28
|
+
t(key: string, options?: Record<string, unknown>): unknown;
|
|
29
|
+
exists(key: string, options?: Record<string, unknown>): boolean;
|
|
30
|
+
};
|
|
31
|
+
/**
|
|
32
|
+
* An i18next instance as the App SDK's locale. The catalogs are ICU MessageFormat, so add `i18next-icu`. `namespace`
|
|
33
|
+
* is where the App SDK's keys live (`eskais` by default); the locale's code is `i18n.language` unless given.
|
|
34
|
+
*/
|
|
35
|
+
export declare function fromI18next(i18n: I18nextLike, options?: Partial<AdapterOptions> & {
|
|
36
|
+
namespace?: string;
|
|
37
|
+
}): Locale;
|
|
38
|
+
/** FormatJS's `IntlShape`, from `createIntl` or react-intl's `useIntl()`. */
|
|
39
|
+
export type IntlShapeLike = {
|
|
40
|
+
readonly locale: string;
|
|
41
|
+
readonly messages: Readonly<Record<string, unknown>>;
|
|
42
|
+
formatMessage(descriptor: {
|
|
43
|
+
id: string;
|
|
44
|
+
}, values?: Record<string, unknown>): string;
|
|
45
|
+
};
|
|
46
|
+
/**
|
|
47
|
+
* FormatJS (react-intl) as the App SDK's locale. FormatJS keys are flat, so the App SDK's are prefixed:
|
|
48
|
+
* `eskais.create`, `eskais.resources.orders.one` (`prefix` changes it; `""` for none).
|
|
49
|
+
*/
|
|
50
|
+
export declare function fromIntl(intl: IntlShapeLike, options?: Partial<AdapterOptions> & {
|
|
51
|
+
prefix?: string;
|
|
52
|
+
}): Locale;
|
|
53
|
+
export {};
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { isBoolean, isNumber, isRecord, isString } from "../core/guards.js";
|
|
2
|
+
function adapt(code, own, ownHas, base) {
|
|
3
|
+
const has = (key) => ownHas(key) || base?.has(key) === true;
|
|
4
|
+
const t = (key, values) => {
|
|
5
|
+
if (ownHas(key))
|
|
6
|
+
return own(key, values);
|
|
7
|
+
return base ? base.t(key, values) : key;
|
|
8
|
+
};
|
|
9
|
+
return Object.freeze({ code, t, has });
|
|
10
|
+
}
|
|
11
|
+
function nextIntlValues(values) {
|
|
12
|
+
return Object.fromEntries(Object.entries(values).map(([name, value]) => [
|
|
13
|
+
name,
|
|
14
|
+
value === null ||
|
|
15
|
+
value === undefined ||
|
|
16
|
+
value instanceof Date ||
|
|
17
|
+
isString(value) ||
|
|
18
|
+
isNumber(value) ||
|
|
19
|
+
isBoolean(value)
|
|
20
|
+
? value
|
|
21
|
+
: String(value),
|
|
22
|
+
]));
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* next-intl's translator as the App SDK's locale, in a client component (`useTranslations("eskais")`) or on the
|
|
26
|
+
* server (`await getTranslations("eskais")` for `navPage` and `generateMetadata`). next-intl formats the ICU messages
|
|
27
|
+
* itself. Merge the shipped catalog under your namespace in `i18n/request.ts` so every key is there:
|
|
28
|
+
* `messages.eskais = { ...es, ...mine.eskais }`.
|
|
29
|
+
*/
|
|
30
|
+
export function fromNextIntl(t, options) {
|
|
31
|
+
const has = (key) => (t.has ? t.has(key) && (t.raw ? isString(t.raw(key)) : true) : true);
|
|
32
|
+
return adapt(options.locale, (key, values) => t(key, values === undefined ? undefined : nextIntlValues(values)), has, options.base);
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* An i18next instance as the App SDK's locale. The catalogs are ICU MessageFormat, so add `i18next-icu`. `namespace`
|
|
36
|
+
* is where the App SDK's keys live (`eskais` by default); the locale's code is `i18n.language` unless given.
|
|
37
|
+
*/
|
|
38
|
+
export function fromI18next(i18n, options = {}) {
|
|
39
|
+
const ns = options.namespace ?? "eskais";
|
|
40
|
+
const own = (key, values) => {
|
|
41
|
+
const text = i18n.t(key, { ...values, ns });
|
|
42
|
+
return isString(text) ? text : key;
|
|
43
|
+
};
|
|
44
|
+
const has = (key) => i18n.exists(key, { ns }) && isString(i18n.t(key, { ns, returnObjects: true }));
|
|
45
|
+
return adapt(options.locale ?? i18n.language, own, has, options.base);
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* FormatJS (react-intl) as the App SDK's locale. FormatJS keys are flat, so the App SDK's are prefixed:
|
|
49
|
+
* `eskais.create`, `eskais.resources.orders.one` (`prefix` changes it; `""` for none).
|
|
50
|
+
*/
|
|
51
|
+
export function fromIntl(intl, options = {}) {
|
|
52
|
+
const prefix = options.prefix ?? "eskais";
|
|
53
|
+
const id = (key) => (prefix === "" ? key : `${prefix}.${key}`);
|
|
54
|
+
const has = (key) => isRecord(intl.messages) && id(key) in intl.messages;
|
|
55
|
+
return adapt(options.locale ?? intl.locale, (key, values) => intl.formatMessage({ id: id(key) }, values === undefined ? undefined : { ...values }), has, options.base);
|
|
56
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** The values a message's arguments read: `{ one: "pedido", gender: "m", count: 3 }`. */
|
|
2
|
+
export type MessageValues = Readonly<Record<string, unknown>>;
|
|
3
|
+
/**
|
|
4
|
+
* Formats an ICU MessageFormat message in `code`'s language: `{name}`, `{n, number}` (`integer`, `percent`),
|
|
5
|
+
* `{d, date, short}` and `{d, time, short}`, `{n, plural, =0 {…} one {# item} other {# items}}` (with `offset:`),
|
|
6
|
+
* `{n, selectordinal, …}` and `{gender, select, f {…} other {…}}`. Quotes escape as in ICU: `''` and `'{literal}'`.
|
|
7
|
+
*/
|
|
8
|
+
export declare function formatMessage(message: string, values?: MessageValues, code?: string): string;
|
|
9
|
+
/** Throws a `SyntaxError` that says where, when `message` isn't valid ICU MessageFormat. */
|
|
10
|
+
export declare function checkMessage(message: string): void;
|