@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
@@ -2,16 +2,40 @@
2
2
  import { jsx as _jsx } from "react/jsx-runtime";
3
3
  import { QueryClient, QueryClientContext, QueryClientProvider } from "@tanstack/react-query";
4
4
  import { createContext, use, useMemo, useState } from "react";
5
+ import { createDialogQueue } from "../dialogs/dialogs.js";
6
+ import { isString } from "../core/guards.js";
7
+ import { defineErrors } from "../errors/define-errors.js";
8
+ import { dataLabelsOf } from "../i18n/labels.js";
5
9
  const DataLayerContext = createContext(null);
10
+ const defaultErrors = defineErrors();
6
11
  function newClient() {
7
12
  return new QueryClient({
8
13
  defaultOptions: { queries: { staleTime: 30_000, refetchOnWindowFocus: false }, mutations: { retry: false } },
9
14
  });
10
15
  }
11
- export function DataLayer({ client, session, router, labels, preferences, locale, children }) {
16
+ function labelsFor(i18n, labels) {
17
+ if (labels)
18
+ return labels;
19
+ if (i18n)
20
+ return dataLabelsOf(i18n);
21
+ throw new Error("<DataLayer> needs a `locale` from defineLocale(…) (or the deprecated `labels`).");
22
+ }
23
+ export function DataLayer({ client, session, router, labels, preferences, locale, errors, children }) {
12
24
  const existing = use(QueryClientContext);
13
25
  const [own] = useState(() => client ?? existing ?? newClient());
14
- const value = useMemo(() => ({ session, router, labels, preferences, locale }), [session, router, labels, preferences, locale]);
26
+ const [dialogs] = useState(createDialogQueue);
27
+ const i18n = isString(locale) ? undefined : locale;
28
+ const code = isString(locale) ? locale : locale?.code;
29
+ const value = useMemo(() => ({
30
+ session,
31
+ router,
32
+ labels: labelsFor(i18n, labels),
33
+ preferences,
34
+ locale: code,
35
+ i18n,
36
+ errors: errors ?? defaultErrors,
37
+ dialogs,
38
+ }), [session, router, labels, preferences, code, i18n, errors, dialogs]);
15
39
  const content = _jsx(DataLayerContext, { value: value, children: children });
16
40
  if (existing && client === undefined)
17
41
  return content;
@@ -26,6 +50,27 @@ export function useDataLayer() {
26
50
  export function useSession() {
27
51
  return useDataLayer().session;
28
52
  }
29
- export function useLabels() {
30
- return useDataLayer().labels;
53
+ function gendered(layer, gender) {
54
+ const { labels, i18n } = layer;
55
+ if (!i18n || gender === undefined || labels !== dataLabelsOf(i18n))
56
+ return labels;
57
+ return dataLabelsOf(i18n, gender);
58
+ }
59
+ /**
60
+ * The generic texts. Given the resource they're about, messages with a `{gender, select, …}` agree with it
61
+ * ("Nueva línea", "Nuevo pedido").
62
+ */
63
+ export function useLabels(resource) {
64
+ const layer = useDataLayer();
65
+ return resource ? gendered(layer, resource.in(layer.i18n).gender) : layer.labels;
66
+ }
67
+ /** A resource or an action with its texts in the `DataLayer`'s locale: `useLocalized(customers).label(2)`. */
68
+ export function useLocalized(value) {
69
+ return value.in(useDataLayer().i18n);
70
+ }
71
+ /** The `DataLayer` for a block about one resource: the resource in its locale, and the texts in its gender. */
72
+ export function useResourceLayer(resource) {
73
+ const layer = useDataLayer();
74
+ const localized = resource.in(layer.i18n);
75
+ return { ...layer, labels: gendered(layer, localized.gender), resource: localized };
31
76
  }
@@ -0,0 +1,25 @@
1
+ import type { Action, ActionTarget } from "../../action/action.js";
2
+ import { type ActionState } from "./use-action.js";
3
+ export type ActionDialogOptions<R> = {
4
+ target?: ActionTarget<unknown>;
5
+ /** Closes once it succeeds; `true` by default. A failure always keeps it open, with the error inside. */
6
+ closeOnSuccess?: boolean;
7
+ onSuccess?: (result: R | undefined) => void;
8
+ };
9
+ export type ActionDialogState<R> = Omit<ActionState<R>, "run"> & {
10
+ open: boolean;
11
+ /** Opens or closes it; closing forgets the error, and a submit still running finishes on its own. */
12
+ setOpen(open: boolean): void;
13
+ /**
14
+ * Runs the action with the dialog's input. A second press while it runs gets the same promise; an error stays in
15
+ * the dialog (`error`, `errorText`, `error.fields`), and the next submit of the same input keeps its idempotency
16
+ * key. Resolves `undefined` instead of rejecting, so a form's submit handler needn't catch.
17
+ */
18
+ submit(input?: unknown): Promise<R | undefined>;
19
+ };
20
+ /**
21
+ * An action that opens a dialog: its open state, a guarded submit, its error kept inside the dialog rather than in a
22
+ * toast, and the dialog closing when it succeeds. The action's `invalidates` refresh after it succeeds, as `useAction`
23
+ * does.
24
+ */
25
+ export declare function useActionDialog<T, I, R>(action: Action<T, I, R>, options?: ActionDialogOptions<R>): ActionDialogState<R>;
@@ -0,0 +1,31 @@
1
+ "use client";
2
+ import { useCallback, useState } from "react";
3
+ import { useAction } from "./use-action.js";
4
+ /**
5
+ * An action that opens a dialog: its open state, a guarded submit, its error kept inside the dialog rather than in a
6
+ * toast, and the dialog closing when it succeeds. The action's `invalidates` refresh after it succeeds, as `useAction`
7
+ * does.
8
+ */
9
+ export function useActionDialog(action, options = {}) {
10
+ const { run, reset, ...state } = useAction(action);
11
+ const [open, setOpenState] = useState(false);
12
+ const { target, closeOnSuccess = true, onSuccess } = options;
13
+ const setOpen = useCallback((next) => {
14
+ setOpenState(next);
15
+ if (!next)
16
+ reset();
17
+ }, [reset]);
18
+ const submit = useCallback(async (input) => {
19
+ try {
20
+ const result = await run(input, target === undefined ? {} : { target });
21
+ if (closeOnSuccess)
22
+ setOpenState(false);
23
+ onSuccess?.(result);
24
+ return result;
25
+ }
26
+ catch {
27
+ return undefined;
28
+ }
29
+ }, [closeOnSuccess, onSuccess, run, target]);
30
+ return { ...state, reset, open, setOpen, submit };
31
+ }
@@ -1,12 +1,37 @@
1
+ import { type QueryClient } from "@tanstack/react-query";
1
2
  import type { Action, ActionTarget } from "../../action/action.js";
2
- import { type ServiceError } from "../../core/errors.js";
3
+ import { ActionStatus, Feedback } from "../../core/constants.js";
3
4
  import type { Allowed } from "../../core/refusal.js";
5
+ import type { AppError } from "../../errors/define-errors.js";
6
+ import type { AnyResource } from "../../resource/resource.js";
7
+ /** Refreshes what an action changed: its resource, the resources showing it, and its `invalidates`. */
8
+ export declare function invalidateAfter(client: QueryClient, action: {
9
+ refreshes(): readonly AnyResource[];
10
+ }): Promise<void>;
11
+ export type ActionSubmitOptions = {
12
+ target?: ActionTarget<unknown>;
13
+ /** The submit's key; by default one per submit, kept when the same input runs again after a failure. */
14
+ idempotencyKey?: string;
15
+ };
4
16
  export type ActionState<R> = {
5
- run(input?: unknown, options?: {
6
- target?: ActionTarget<unknown>;
7
- }): Promise<R | undefined>;
17
+ /**
18
+ * Runs it, refusing first what `can` or the session refuses. While a run of a `block` action is going, another
19
+ * press gets the same promise rather than a second run.
20
+ */
21
+ run(input?: unknown, options?: ActionSubmitOptions): Promise<R | undefined>;
22
+ status: ActionStatus;
8
23
  pending: boolean;
9
24
  allowed: Allowed;
10
- error: ServiceError | undefined;
25
+ /** The last run's error, with its reason. */
26
+ error: AppError | undefined;
27
+ /** The last run's error as a person reads it, in the `DataLayer`'s language. */
28
+ errorText: string | undefined;
29
+ /** Where the last run's error shows: the action's `feedback.error`, or the policy's for its reason. */
30
+ feedback: Feedback | undefined;
31
+ result: R | undefined;
32
+ /** Back to idle: forgets the last result and error. */
33
+ reset(): void;
11
34
  };
35
+ /** The sentence a person reads for an error, through the `DataLayer`'s `defineErrors` policy and language. */
36
+ export declare function useErrorText(): (error: AppError) => string;
12
37
  export declare function useAction<T, I, R>(action: Action<T, I, R>, target?: ActionTarget<T>): ActionState<R>;
@@ -1,9 +1,10 @@
1
1
  "use client";
2
2
  import { useQueryClient } from "@tanstack/react-query";
3
- import { useCallback, useState } from "react";
3
+ import { useCallback, useRef, useState } from "react";
4
4
  import { assumeType } from "../../core/assume.js";
5
- import { ActionTargetKind, ServiceErrorKind } from "../../core/constants.js";
6
- import { ServiceFailure, serviceError, toServiceError } from "../../core/errors.js";
5
+ import { ActionStatus, ActionTargetKind, Concurrency, ErrorReason, Feedback, Idempotency, Operation, ServiceErrorKind, } from "../../core/constants.js";
6
+ import { ServiceFailure, serviceError } from "../../core/errors.js";
7
+ import { idempotencyKey } from "../../errors/idempotency.js";
7
8
  import { useDataLayer } from "../data-layer.js";
8
9
  import { invalidateResource } from "./use-resource.js";
9
10
  const noTarget = { kind: ActionTargetKind.none };
@@ -18,7 +19,11 @@ function applyOptimistic(client, resource, rows, update, input) {
18
19
  : page);
19
20
  return snapshot;
20
21
  }
21
- async function perform(client, action, target, input, session) {
22
+ /** Refreshes what an action changed: its resource, the resources showing it, and its `invalidates`. */
23
+ export async function invalidateAfter(client, action) {
24
+ await Promise.all(action.refreshes().map((entry) => invalidateResource(client, entry)));
25
+ }
26
+ async function perform(client, action, target, input, layer, key) {
22
27
  const resource = action.options.resource;
23
28
  let snapshot = [];
24
29
  try {
@@ -26,42 +31,95 @@ async function perform(client, action, target, input, session) {
26
31
  const optimistic = action.options.optimistic;
27
32
  if (optimistic && resource)
28
33
  snapshot = applyOptimistic(client, resource, action.rowsOf(target), optimistic, parsed);
29
- const result = await action.execute(target, parsed, { session });
30
- const refreshed = [resource, ...(action.options.invalidates ?? [])].flatMap((entry) => entry ? [invalidateResource(client, entry)] : []);
31
- await Promise.all(refreshed);
34
+ const result = await action.execute(target, parsed, {
35
+ session: layer.session,
36
+ errors: layer.errors,
37
+ idempotencyKey: key,
38
+ });
39
+ await invalidateAfter(client, action);
32
40
  return { ok: true, result };
33
41
  }
34
42
  catch (failure) {
35
- for (const [key, data] of snapshot)
36
- client.setQueryData(key, data);
37
- const error = toServiceError(failure);
43
+ for (const [queryKey, data] of snapshot)
44
+ client.setQueryData(queryKey, data);
45
+ const error = layer.errors.classify(failure);
38
46
  return { ok: false, error, failure: failure instanceof ServiceFailure ? failure : new ServiceFailure(error) };
39
47
  }
40
48
  }
49
+ function fingerprint(target, input) {
50
+ try {
51
+ return JSON.stringify([target, input]);
52
+ }
53
+ catch {
54
+ return undefined;
55
+ }
56
+ }
57
+ /** The sentence a person reads for an error, through the `DataLayer`'s `defineErrors` policy and language. */
58
+ export function useErrorText() {
59
+ const { errors, i18n, labels } = useDataLayer();
60
+ return useCallback((error) => errors.text(error, i18n, labels.errors), [errors, i18n, labels.errors]);
61
+ }
62
+ const idle = { status: ActionStatus.idle, result: undefined, error: undefined };
41
63
  export function useAction(action, target) {
42
- const { session, labels } = useDataLayer();
64
+ const layer = useDataLayer();
65
+ const { session, labels, errors } = layer;
43
66
  const client = useQueryClient();
44
- const [pending, setPending] = useState(false);
45
- const [error, setError] = useState();
67
+ const errorText = useErrorText();
68
+ const [state, setState] = useState(idle);
69
+ const inFlight = useRef(undefined);
70
+ const lastFailed = useRef(undefined);
46
71
  const fixed = target ?? noTarget;
47
72
  const allowed = action.check(fixed, session, labels.notAllowed);
48
- const run = useCallback(async (input, options = {}) => {
73
+ const guarded = (action.options.concurrency ?? Concurrency.block) === Concurrency.block;
74
+ const keyFor = useCallback((chosen, input, given) => {
75
+ if (given !== undefined)
76
+ return { key: given, print: undefined };
77
+ if (action.options.idempotency !== Idempotency.key)
78
+ return { key: undefined, print: undefined };
79
+ const print = fingerprint(chosen, input);
80
+ const reused = print !== undefined && lastFailed.current?.print === print ? lastFailed.current.key : undefined;
81
+ return { key: reused ?? idempotencyKey(), print };
82
+ }, [action]);
83
+ const run = useCallback((input, options = {}) => {
84
+ if (guarded && inFlight.current)
85
+ return inFlight.current;
49
86
  // Workaround: a target passed to `run` is for this action's rows; React hooks can't carry `T` through options.
50
87
  const chosen = options.target ? assumeType(options.target) : fixed;
51
88
  const permitted = action.check(chosen, session, labels.notAllowed);
52
89
  if (permitted !== true) {
53
- const refusal = serviceError(ServiceErrorKind.forbidden, permitted.reason);
54
- setError(refusal);
55
- throw new ServiceFailure(refusal);
90
+ const refusal = { ...serviceError(ServiceErrorKind.forbidden, permitted.reason), reason: ErrorReason.forbidden };
91
+ setState({ status: ActionStatus.error, result: undefined, error: refusal });
92
+ return Promise.reject(new ServiceFailure(refusal));
56
93
  }
57
- setPending(true);
58
- setError(undefined);
59
- const outcome = await perform(client, action, chosen, input, session);
60
- setPending(false);
61
- if (outcome.ok)
62
- return outcome.result;
63
- setError(outcome.error);
64
- throw outcome.failure;
65
- }, [action, client, fixed, labels.notAllowed, session]);
66
- return { run, pending: pending || action.running(), allowed, error };
94
+ const { key, print } = keyFor(chosen, input, options.idempotencyKey);
95
+ setState({ status: ActionStatus.pending, result: undefined, error: undefined });
96
+ const running = perform(client, action, chosen, input, { session, errors }, key).then((outcome) => {
97
+ inFlight.current = undefined;
98
+ if (outcome.ok) {
99
+ lastFailed.current = undefined;
100
+ setState({ status: ActionStatus.success, result: outcome.result, error: undefined });
101
+ return outcome.result;
102
+ }
103
+ lastFailed.current = key !== undefined && print !== undefined ? { print, key } : undefined;
104
+ setState({ status: ActionStatus.error, result: undefined, error: outcome.error });
105
+ throw outcome.failure;
106
+ });
107
+ inFlight.current = running;
108
+ return running;
109
+ }, [action, client, errors, fixed, guarded, keyFor, labels.notAllowed, session]);
110
+ const reset = useCallback(() => setState(idle), []);
111
+ const { error } = state;
112
+ return {
113
+ run,
114
+ status: state.status,
115
+ pending: state.status === ActionStatus.pending || action.running(),
116
+ allowed,
117
+ error,
118
+ errorText: error ? errorText(error) : undefined,
119
+ feedback: error
120
+ ? errors.feedback(error, { operation: Operation.mutation, feedback: action.options.feedback?.error })
121
+ : undefined,
122
+ result: state.result,
123
+ reset,
124
+ };
67
125
  }
@@ -0,0 +1,20 @@
1
+ import type { Action, ActionTarget } from "../../action/action.js";
2
+ import { type BulkResult } from "../../action/bulk.js";
3
+ import { type ActionState } from "./use-action.js";
4
+ /** What keeps the rows selected: a view's `selection`, or anything with `select(ids)`. */
5
+ export type BulkSelection = {
6
+ select(ids: readonly string[]): void;
7
+ };
8
+ export type UseBulkActionOptions = {
9
+ selection?: BulkSelection | undefined;
10
+ };
11
+ export type BulkActionState<T> = Omit<ActionState<BulkResult<T>>, "run"> & {
12
+ /** Runs it on `target`; the rows that failed stay selected, the others leave the selection. */
13
+ run(target: ActionTarget<T>, input?: unknown): Promise<BulkResult<T> | undefined>;
14
+ /** Runs it again on the rows that failed only, with each row's idempotency key. */
15
+ retryFailed(input?: unknown): Promise<BulkResult<T> | undefined>;
16
+ /** The rows that failed last time, with their reasons. */
17
+ failed: BulkResult<T>["failed"];
18
+ };
19
+ /** A `defineBulkAction` run over selected rows, reporting per row and offering a retry of the failed ones. */
20
+ export declare function useBulkAction<T, I>(action: Action<T, I, BulkResult<T>>, options?: UseBulkActionOptions): BulkActionState<T>;
@@ -0,0 +1,24 @@
1
+ "use client";
2
+ import { useCallback } from "react";
3
+ import { failedTarget } from "../../action/bulk.js";
4
+ import { useAction } from "./use-action.js";
5
+ /** A `defineBulkAction` run over selected rows, reporting per row and offering a retry of the failed ones. */
6
+ export function useBulkAction(action, options = {}) {
7
+ const { run: runAction, ...state } = useAction(action);
8
+ const resource = action.options.resource;
9
+ const { selection } = options;
10
+ const last = state.result;
11
+ const settle = useCallback((result) => {
12
+ if (result && selection && resource)
13
+ selection.select(result.failed.map((entry) => resource.idKey(resource.idOf(entry.row))));
14
+ return result;
15
+ }, [resource, selection]);
16
+ const run = useCallback(async (target, input) => settle(await runAction(input, { target })), [runAction, settle]);
17
+ const retryFailed = useCallback(async (input) => {
18
+ if (!last || last.failed.length === 0)
19
+ return last;
20
+ const key = last.idempotencyKey;
21
+ return settle(await runAction(input, { target: failedTarget(last), ...(key === undefined ? {} : { idempotencyKey: key }) }));
22
+ }, [last, runAction, settle]);
23
+ return { ...state, run, retryFailed, failed: last?.failed ?? [] };
24
+ }
@@ -0,0 +1,14 @@
1
+ import type { DialogAnswer, DialogEntry, Dialogs } from "../../dialogs/dialogs.js";
2
+ /**
3
+ * Promise-based dialogs in the `DataLayer`'s language: `await dialogs.confirm({ title, destructive: true })` is true
4
+ * when confirmed and false when cancelled or dismissed with Escape, `prompt` gives the text or `null`, `alert` waits
5
+ * for OK. One shows at a time; the rest wait in order. An `NavDialogs` (from the blocks) draws them.
6
+ */
7
+ export declare function useDialogs(): Dialogs;
8
+ export type DialogHost = {
9
+ /** The dialog to draw, when this host is the one that draws (the first attached under the `DataLayer`). */
10
+ current: DialogEntry | undefined;
11
+ settle(id: number, answer: DialogAnswer): void;
12
+ };
13
+ /** For the component that draws `useDialogs`' dialogs: it attaches while mounted. */
14
+ export declare function useDialogHost(): DialogHost;
@@ -0,0 +1,20 @@
1
+ "use client";
2
+ import { useEffect, useMemo, useState, useSyncExternalStore } from "react";
3
+ import { useDataLayer } from "../data-layer.js";
4
+ /**
5
+ * Promise-based dialogs in the `DataLayer`'s language: `await dialogs.confirm({ title, destructive: true })` is true
6
+ * when confirmed and false when cancelled or dismissed with Escape, `prompt` gives the text or `null`, `alert` waits
7
+ * for OK. One shows at a time; the rest wait in order. An `NavDialogs` (from the blocks) draws them.
8
+ */
9
+ export function useDialogs() {
10
+ const { dialogs } = useDataLayer();
11
+ return useMemo(() => ({ confirm: dialogs.confirm, alert: dialogs.alert, prompt: dialogs.prompt }), [dialogs]);
12
+ }
13
+ /** For the component that draws `useDialogs`' dialogs: it attaches while mounted. */
14
+ export function useDialogHost() {
15
+ const { dialogs } = useDataLayer();
16
+ const [token] = useState(() => ({}));
17
+ const snapshot = useSyncExternalStore(dialogs.subscribe, dialogs.getSnapshot, dialogs.getSnapshot);
18
+ useEffect(() => dialogs.attach(token), [dialogs, token]);
19
+ return { current: snapshot.host === token ? snapshot.current : undefined, settle: dialogs.settle };
20
+ }
@@ -16,13 +16,14 @@ export function useNav(nav) {
16
16
  };
17
17
  }
18
18
  export function useDocumentTitle(nav, pathname, enabled = true) {
19
+ const { i18n } = useDataLayer();
19
20
  useEffect(() => {
20
21
  if (!enabled)
21
22
  return;
22
- const title = nav.documentTitle(pathname);
23
+ const title = nav.documentTitle(pathname, i18n);
23
24
  if (title !== undefined)
24
25
  document.title = title;
25
- }, [nav, pathname, enabled]);
26
+ }, [nav, pathname, enabled, i18n]);
26
27
  }
27
28
  /**
28
29
  * The manifest over the `DataLayer`'s router, for a `defineNav` without one: a definition shared with server code,
@@ -0,0 +1,22 @@
1
+ import { type QueryKey } from "@tanstack/react-query";
2
+ import type { NewRows } from "../../core/constants.js";
3
+ import type { PageSourceLike } from "../../core/contracts.js";
4
+ type Identified<T, Id> = {
5
+ readonly key: string;
6
+ idOf(row: T): Id;
7
+ idKey(id: Id): string;
8
+ };
9
+ /**
10
+ * A resource's `PageSource` whose reloads don't move the rows on screen: rows that changed update in place, and rows
11
+ * the list didn't show wait for `useNewRows(key).apply()`. The key stays the source's, so the cache is shared.
12
+ */
13
+ export declare function useHeldSource<T, Id, F, Source extends PageSourceLike<T, F>>(resource: Identified<T, Id>, source: Source, newRows: NewRows): Source;
14
+ export type NewRowsState = {
15
+ /** Rows a reload found that the list holds back. */
16
+ count: number;
17
+ /** Shows them, in the order the reload read. Selection and scroll stay. */
18
+ apply(): void;
19
+ };
20
+ /** The rows held back for a page query (`sourcePageKey` or `resourcePageKey`). */
21
+ export declare function useNewRows(queryKey: QueryKey): NewRowsState;
22
+ export {};
@@ -0,0 +1,24 @@
1
+ "use client";
2
+ import { useQueryClient } from "@tanstack/react-query";
3
+ import { useCallback, useMemo, useSyncExternalStore } from "react";
4
+ import { sourcePageKey } from "../keys.js";
5
+ import { applyNewRows, heldRead, newRowsOf, subscribeNewRows } from "../new-rows.js";
6
+ /**
7
+ * A resource's `PageSource` whose reloads don't move the rows on screen: rows that changed update in place, and rows
8
+ * the list didn't show wait for `useNewRows(key).apply()`. The key stays the source's, so the cache is shared.
9
+ */
10
+ export function useHeldSource(resource, source, newRows) {
11
+ const client = useQueryClient();
12
+ return useMemo(() => ({
13
+ ...source,
14
+ fetchPage: (request, context) => heldRead(client, resource, sourcePageKey(source, request), newRows, () => source.fetchPage(request, context)),
15
+ }), [client, resource, source, newRows]);
16
+ }
17
+ /** The rows held back for a page query (`sourcePageKey` or `resourcePageKey`). */
18
+ export function useNewRows(queryKey) {
19
+ const client = useQueryClient();
20
+ const subscribe = useCallback((listener) => subscribeNewRows(client, listener), [client]);
21
+ const read = () => newRowsOf(client, queryKey);
22
+ const count = useSyncExternalStore(subscribe, read, read);
23
+ return { count, apply: () => void applyNewRows(client, queryKey) };
24
+ }
@@ -0,0 +1,13 @@
1
+ import type { Allowed } from "../../core/refusal.js";
2
+ import type { Locale } from "../../i18n/locale.js";
3
+ import { type Operations, type Permissions, type PermissionSession, type PermissionTarget, type RegisteredOperation, type SessionPayload } from "../../permissions/permissions.js";
4
+ /**
5
+ * Whether the `DataLayer`'s session allows an operation, on a resource and a row: `usePermission(Op.approve,
6
+ * { resource: orders, row })`. A refusal carries its reason, or the catalog's "not allowed".
7
+ */
8
+ export declare function usePermission(operation: RegisteredOperation, target?: PermissionTarget): Allowed;
9
+ /**
10
+ * The session a server made, rebuilt in the browser from its payload (`sessionPayload(session)` in a server
11
+ * component): the same rules over the same claims, so both answer alike. `null` is nobody.
12
+ */
13
+ export declare function usePermissionSession<Ops extends Operations, Claims, User>(permissions: Permissions<Ops, Claims>, payload: SessionPayload<User, Claims> | null, locale?: Locale): PermissionSession<User, Claims> | undefined;
@@ -0,0 +1,19 @@
1
+ "use client";
2
+ import { useMemo } from "react";
3
+ import { allows, } from "../../permissions/permissions.js";
4
+ import { useDataLayer } from "../data-layer.js";
5
+ /**
6
+ * Whether the `DataLayer`'s session allows an operation, on a resource and a row: `usePermission(Op.approve,
7
+ * { resource: orders, row })`. A refusal carries its reason, or the catalog's "not allowed".
8
+ */
9
+ export function usePermission(operation, target = {}) {
10
+ const { session, labels } = useDataLayer();
11
+ return allows(session, operation, target, labels.notAllowed);
12
+ }
13
+ /**
14
+ * The session a server made, rebuilt in the browser from its payload (`sessionPayload(session)` in a server
15
+ * component): the same rules over the same claims, so both answer alike. `null` is nobody.
16
+ */
17
+ export function usePermissionSession(permissions, payload, locale) {
18
+ return useMemo(() => (payload === null ? undefined : permissions.session({ ...payload, locale })), [permissions, payload, locale]);
19
+ }
@@ -0,0 +1,6 @@
1
+ import type { Reauthenticate } from "../../errors/define-errors.js";
2
+ /**
3
+ * Makes `handler` the way the person signs in again while the component is mounted: a re-login or MFA dialog that
4
+ * resolves `true` once they did. Calls that failed with `unauthorized` or `session-expired` wait for it, then run again.
5
+ */
6
+ export declare function useReauthenticate(handler: Reauthenticate): void;
@@ -0,0 +1,11 @@
1
+ "use client";
2
+ import { useEffect } from "react";
3
+ import { useDataLayer } from "../data-layer.js";
4
+ /**
5
+ * Makes `handler` the way the person signs in again while the component is mounted: a re-login or MFA dialog that
6
+ * resolves `true` once they did. Calls that failed with `unauthorized` or `session-expired` wait for it, then run again.
7
+ */
8
+ export function useReauthenticate(handler) {
9
+ const { errors } = useDataLayer();
10
+ useEffect(() => errors.onReauthenticate(handler), [errors, handler]);
11
+ }
@@ -2,7 +2,8 @@ import { type QueryClient } from "@tanstack/react-query";
2
2
  import { TotalKind } from "../../core/constants.js";
3
3
  import type { Target, Version } from "../../core/contracts.js";
4
4
  import { type ServiceError } from "../../core/errors.js";
5
- import { type Resource } from "../../resource/resource.js";
5
+ import { type RefreshPolicy, type Resource } from "../../resource/resource.js";
6
+ import type { ResolvedRefresh } from "../../resource/resource-types.js";
6
7
  import type { View, ViewState } from "../../view/view.js";
7
8
  export type TotalInfo = {
8
9
  kind: typeof TotalKind.exact;
@@ -22,11 +23,24 @@ export type ResourceListState<T, F> = {
22
23
  isFetching: boolean;
23
24
  error: ServiceError | undefined;
24
25
  refetch(): void;
26
+ /** Rows a background reload found and holds back, under `refresh.newRows: NewRows.hold`. */
27
+ newRows: number;
28
+ /** Shows the held rows; the rows already shown keep their place. */
29
+ showNewRows(): void;
25
30
  };
26
31
  export type ResourceListOptions<T, F, Id> = {
27
32
  view?: View<T, F, Id>;
28
33
  filter?: Partial<F>;
29
34
  enabled?: boolean;
35
+ /** This list's own refresh policy, over the resource's. */
36
+ refresh?: RefreshPolicy;
37
+ };
38
+ /** A refresh policy as TanStack Query's options. */
39
+ export declare function refreshOptions(policy: ResolvedRefresh): {
40
+ staleTime: number;
41
+ refetchOnWindowFocus: boolean;
42
+ refetchOnReconnect: boolean;
43
+ refetchInterval: number | false;
30
44
  };
31
45
  export declare function useResourceList<T, Id, F>(resource: Resource<T, Id, F>, options?: ResourceListOptions<T, F, Id>): ResourceListState<T, F>;
32
46
  export type ResourceState<T> = {
@@ -52,13 +66,22 @@ export declare function invalidateResource(client: QueryClient, resource: {
52
66
  queryKey: readonly unknown[];
53
67
  }): Promise<undefined>;
54
68
  export declare function writeRow<T, Id, F>(client: QueryClient, resource: Resource<T, Id, F>, row: T): void;
69
+ /** A write's own signal, and the submit's idempotency key when it outlives the call (a form's next submit). */
70
+ export type WriteOptions = {
71
+ signal?: AbortSignal | undefined;
72
+ idempotencyKey?: string | undefined;
73
+ };
74
+ /**
75
+ * Writes through the `DataLayer`'s policy: an expired session signs in again and the write runs once more, and it
76
+ * retries on a network error only when the resource declares it `idempotency` for that write.
77
+ */
55
78
  export type ResourceMutations<T, Id, F> = {
56
- create(input: Partial<T>): Promise<T>;
57
- update(id: Id, patch: Partial<T>, options?: {
79
+ create(input: Partial<T>, options?: WriteOptions): Promise<T>;
80
+ update(id: Id, patch: Partial<T>, options?: WriteOptions & {
58
81
  version?: Version | undefined;
59
82
  }): Promise<T>;
60
- remove(target: Target<Id, F>): Promise<void>;
61
- restore(target: Target<Id, F>): Promise<void>;
83
+ remove(target: Target<Id, F>, options?: WriteOptions): Promise<void>;
84
+ restore(target: Target<Id, F>, options?: WriteOptions): Promise<void>;
62
85
  };
63
86
  export declare function useResourceMutations<T, Id, F>(resource: Resource<T, Id, F>): ResourceMutations<T, Id, F>;
64
87
  export declare function useResourceCount<T, Id, F>(resource: Resource<T, Id, F>, filter: Partial<F>, options?: {