@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.
Files changed (159) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +74 -2
  3. package/dist/action/action.d.ts +133 -0
  4. package/dist/action/action.js +224 -0
  5. package/dist/action/bulk.d.ts +24 -0
  6. package/dist/action/bulk.js +24 -0
  7. package/dist/cli/cli.d.ts +2 -0
  8. package/dist/cli/cli.js +51 -0
  9. package/dist/cli/routes.d.ts +17 -0
  10. package/dist/cli/routes.js +36 -0
  11. package/dist/core/assume.d.ts +1 -0
  12. package/dist/core/assume.js +8 -0
  13. package/dist/core/constants.d.ts +359 -0
  14. package/dist/core/constants.js +187 -0
  15. package/dist/core/contracts.d.ts +107 -0
  16. package/dist/core/contracts.js +3 -0
  17. package/dist/core/data-labels.d.ts +210 -0
  18. package/dist/core/data-labels.js +385 -0
  19. package/dist/core/errors.d.ts +52 -0
  20. package/dist/core/errors.js +209 -0
  21. package/dist/core/guards.d.ts +9 -0
  22. package/dist/core/guards.js +14 -0
  23. package/dist/core/refusal.d.ts +30 -0
  24. package/dist/core/refusal.js +53 -0
  25. package/dist/dialogs/dialogs.d.ts +75 -0
  26. package/dist/dialogs/dialogs.js +66 -0
  27. package/dist/draft/draft.d.ts +36 -0
  28. package/dist/draft/draft.js +87 -0
  29. package/dist/errors/adapters.d.ts +21 -0
  30. package/dist/errors/adapters.js +81 -0
  31. package/dist/errors/define-errors.d.ts +88 -0
  32. package/dist/errors/define-errors.js +168 -0
  33. package/dist/errors/idempotency.d.ts +2 -0
  34. package/dist/errors/idempotency.js +13 -0
  35. package/dist/export/csv.d.ts +25 -0
  36. package/dist/export/csv.js +59 -0
  37. package/dist/i18n/adapters.d.ts +53 -0
  38. package/dist/i18n/adapters.js +56 -0
  39. package/dist/i18n/format.d.ts +10 -0
  40. package/dist/i18n/format.js +273 -0
  41. package/dist/i18n/labels.d.ts +10 -0
  42. package/dist/i18n/labels.js +227 -0
  43. package/dist/i18n/locale.d.ts +73 -0
  44. package/dist/i18n/locale.js +74 -0
  45. package/dist/i18n/messages.d.ts +93 -0
  46. package/dist/i18n/messages.js +16 -0
  47. package/dist/import/csv-parse.d.ts +11 -0
  48. package/dist/import/csv-parse.js +70 -0
  49. package/dist/import/import.d.ts +104 -0
  50. package/dist/import/import.js +266 -0
  51. package/dist/index.d.ts +46 -0
  52. package/dist/index.js +45 -0
  53. package/dist/navigation/nav.d.ts +128 -0
  54. package/dist/navigation/nav.js +301 -0
  55. package/dist/navigation/router.d.ts +81 -0
  56. package/dist/navigation/router.js +249 -0
  57. package/dist/navigation/shortcuts.d.ts +37 -0
  58. package/dist/navigation/shortcuts.js +93 -0
  59. package/dist/next/index.d.ts +3 -0
  60. package/dist/next/index.js +3 -0
  61. package/dist/next/screen-hydration.d.ts +12 -0
  62. package/dist/next/screen-hydration.js +26 -0
  63. package/dist/next/screen.d.ts +25 -0
  64. package/dist/next/screen.js +44 -0
  65. package/dist/next/server/handler.d.ts +39 -0
  66. package/dist/next/server/handler.js +190 -0
  67. package/dist/next/server/index.d.ts +6 -0
  68. package/dist/next/server/index.js +6 -0
  69. package/dist/next/server/page.d.ts +63 -0
  70. package/dist/next/server/page.js +110 -0
  71. package/dist/next/server/prefetch.d.ts +29 -0
  72. package/dist/next/server/prefetch.js +97 -0
  73. package/dist/next/server/session.d.ts +25 -0
  74. package/dist/next/server/session.js +23 -0
  75. package/dist/next/use-next-router.d.ts +21 -0
  76. package/dist/next/use-next-router.js +104 -0
  77. package/dist/permissions/permissions.d.ts +134 -0
  78. package/dist/permissions/permissions.js +121 -0
  79. package/dist/react/data-layer.d.ts +68 -0
  80. package/dist/react/data-layer.js +76 -0
  81. package/dist/react/hooks/use-action-dialog.d.ts +25 -0
  82. package/dist/react/hooks/use-action-dialog.js +31 -0
  83. package/dist/react/hooks/use-action.d.ts +37 -0
  84. package/dist/react/hooks/use-action.js +125 -0
  85. package/dist/react/hooks/use-better-auth.d.ts +12 -0
  86. package/dist/react/hooks/use-better-auth.js +11 -0
  87. package/dist/react/hooks/use-bulk-action.d.ts +20 -0
  88. package/dist/react/hooks/use-bulk-action.js +24 -0
  89. package/dist/react/hooks/use-dialogs.d.ts +14 -0
  90. package/dist/react/hooks/use-dialogs.js +20 -0
  91. package/dist/react/hooks/use-draft.d.ts +5 -0
  92. package/dist/react/hooks/use-draft.js +17 -0
  93. package/dist/react/hooks/use-nav.d.ts +17 -0
  94. package/dist/react/hooks/use-nav.js +35 -0
  95. package/dist/react/hooks/use-new-rows.d.ts +22 -0
  96. package/dist/react/hooks/use-new-rows.js +24 -0
  97. package/dist/react/hooks/use-permissions.d.ts +13 -0
  98. package/dist/react/hooks/use-permissions.js +19 -0
  99. package/dist/react/hooks/use-reauthenticate.d.ts +6 -0
  100. package/dist/react/hooks/use-reauthenticate.js +11 -0
  101. package/dist/react/hooks/use-resource.d.ts +92 -0
  102. package/dist/react/hooks/use-resource.js +255 -0
  103. package/dist/react/hooks/use-view.d.ts +6 -0
  104. package/dist/react/hooks/use-view.js +24 -0
  105. package/dist/react/index.d.ts +15 -0
  106. package/dist/react/index.js +15 -0
  107. package/dist/react/keys.d.ts +60 -0
  108. package/dist/react/keys.js +71 -0
  109. package/dist/react/new-rows.d.ts +22 -0
  110. package/dist/react/new-rows.js +72 -0
  111. package/dist/refresh/new-rows.d.ts +13 -0
  112. package/dist/refresh/new-rows.js +18 -0
  113. package/dist/resource/form-schema.d.ts +11 -0
  114. package/dist/resource/form-schema.js +51 -0
  115. package/dist/resource/relations.d.ts +99 -0
  116. package/dist/resource/relations.js +194 -0
  117. package/dist/resource/resource-relations.d.ts +47 -0
  118. package/dist/resource/resource-relations.js +154 -0
  119. package/dist/resource/resource-schema.d.ts +9 -0
  120. package/dist/resource/resource-schema.js +73 -0
  121. package/dist/resource/resource-texts.d.ts +18 -0
  122. package/dist/resource/resource-texts.js +13 -0
  123. package/dist/resource/resource-types.d.ts +420 -0
  124. package/dist/resource/resource-types.js +1 -0
  125. package/dist/resource/resource-words.d.ts +25 -0
  126. package/dist/resource/resource-words.js +221 -0
  127. package/dist/resource/resource.d.ts +15 -0
  128. package/dist/resource/resource.js +280 -0
  129. package/dist/resource/schema.d.ts +57 -0
  130. package/dist/resource/schema.js +115 -0
  131. package/dist/services/from-page-source.d.ts +15 -0
  132. package/dist/services/from-page-source.js +27 -0
  133. package/dist/services/memory-query.d.ts +8 -0
  134. package/dist/services/memory-query.js +165 -0
  135. package/dist/services/memory-service.d.ts +33 -0
  136. package/dist/services/memory-service.js +291 -0
  137. package/dist/services/read-only-service.d.ts +18 -0
  138. package/dist/services/read-only-service.js +25 -0
  139. package/dist/services/rest-service.d.ts +65 -0
  140. package/dist/services/rest-service.js +222 -0
  141. package/dist/services/rng.d.ts +9 -0
  142. package/dist/services/rng.js +22 -0
  143. package/dist/services/spring-service.d.ts +58 -0
  144. package/dist/services/spring-service.js +132 -0
  145. package/dist/session/better-auth.d.ts +83 -0
  146. package/dist/session/better-auth.js +86 -0
  147. package/dist/session/session.d.ts +45 -0
  148. package/dist/session/session.js +36 -0
  149. package/dist/view/preferences.d.ts +35 -0
  150. package/dist/view/preferences.js +93 -0
  151. package/dist/view/view-types.d.ts +124 -0
  152. package/dist/view/view-types.js +1 -0
  153. package/dist/view/view-url.d.ts +7 -0
  154. package/dist/view/view-url.js +54 -0
  155. package/dist/view/view.d.ts +4 -0
  156. package/dist/view/view.js +392 -0
  157. package/locales/en.json +193 -0
  158. package/locales/es.json +193 -0
  159. package/package.json +88 -4
@@ -0,0 +1,125 @@
1
+ "use client";
2
+ import { useQueryClient } from "@tanstack/react-query";
3
+ import { useCallback, useRef, useState } from "react";
4
+ import { assumeType } from "../../core/assume.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";
8
+ import { useDataLayer } from "../data-layer.js";
9
+ import { invalidateResource } from "./use-resource.js";
10
+ const noTarget = { kind: ActionTargetKind.none };
11
+ function applyOptimistic(client, resource, rows, update, input) {
12
+ const ids = new Set(rows.map((row) => resource.idKey(resource.idOf(row))));
13
+ const snapshot = client.getQueriesData({ queryKey: resource.queryKey });
14
+ client.setQueriesData({ queryKey: [...resource.queryKey, "page"] }, (page) => page
15
+ ? {
16
+ ...page,
17
+ items: page.items.map((row) => (ids.has(resource.idKey(resource.idOf(row))) ? update(row, input) : row)),
18
+ }
19
+ : page);
20
+ return snapshot;
21
+ }
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) {
27
+ const resource = action.options.resource;
28
+ let snapshot = [];
29
+ try {
30
+ const parsed = await action.parseInput(input);
31
+ const optimistic = action.options.optimistic;
32
+ if (optimistic && resource)
33
+ snapshot = applyOptimistic(client, resource, action.rowsOf(target), optimistic, parsed);
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);
40
+ return { ok: true, result };
41
+ }
42
+ catch (failure) {
43
+ for (const [queryKey, data] of snapshot)
44
+ client.setQueryData(queryKey, data);
45
+ const error = layer.errors.classify(failure);
46
+ return { ok: false, error, failure: failure instanceof ServiceFailure ? failure : new ServiceFailure(error) };
47
+ }
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 };
63
+ export function useAction(action, target) {
64
+ const layer = useDataLayer();
65
+ const { session, labels, errors } = layer;
66
+ const client = useQueryClient();
67
+ const errorText = useErrorText();
68
+ const [state, setState] = useState(idle);
69
+ const inFlight = useRef(undefined);
70
+ const lastFailed = useRef(undefined);
71
+ const fixed = target ?? noTarget;
72
+ const allowed = action.check(fixed, session, labels.notAllowed);
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;
86
+ // Workaround: a target passed to `run` is for this action's rows; React hooks can't carry `T` through options.
87
+ const chosen = options.target ? assumeType(options.target) : fixed;
88
+ const permitted = action.check(chosen, session, labels.notAllowed);
89
+ if (permitted !== true) {
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));
93
+ }
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
+ };
125
+ }
@@ -0,0 +1,12 @@
1
+ import { type BetterAuthSessionData, type BetterAuthSessionOptions, type BetterAuthUser } from "../../session/better-auth.js";
2
+ import type { Session } from "../../session/session.js";
3
+ /** What `authClient.useSession()` returns in Better Auth's React client (`better-auth/react`). */
4
+ export type BetterAuthSessionState<User = BetterAuthUser> = {
5
+ data: BetterAuthSessionData<User> | undefined;
6
+ isPending?: boolean;
7
+ };
8
+ /**
9
+ * The signed-in person as a `Session`, from what `authClient.useSession()` returns: pass it to `DataLayer`. A new
10
+ * one comes when they sign in or out or switch organization; keep `options` outside the component.
11
+ */
12
+ export declare function useBetterAuthSession<User = BetterAuthUser>(state: BetterAuthSessionState<User>, options?: BetterAuthSessionOptions<User>): Session<User>;
@@ -0,0 +1,11 @@
1
+ "use client";
2
+ import { useMemo } from "react";
3
+ import { betterAuthSession, } from "../../session/better-auth.js";
4
+ /**
5
+ * The signed-in person as a `Session`, from what `authClient.useSession()` returns: pass it to `DataLayer`. A new
6
+ * one comes when they sign in or out or switch organization; keep `options` outside the component.
7
+ */
8
+ export function useBetterAuthSession(state, options) {
9
+ const { data } = state;
10
+ return useMemo(() => betterAuthSession(data, options), [data, options]);
11
+ }
@@ -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
+ }
@@ -0,0 +1,5 @@
1
+ import { type Draft, type DraftOptions, type DraftSnapshot } from "../../draft/draft.js";
2
+ export declare function useDraft<V>(options: DraftOptions | undefined): {
3
+ draft: Draft<V> | undefined;
4
+ snapshot: DraftSnapshot;
5
+ };
@@ -0,0 +1,17 @@
1
+ "use client";
2
+ import { useEffect, useState, useSyncExternalStore } from "react";
3
+ import { defineDraft } from "../../draft/draft.js";
4
+ import { useDataLayer } from "../data-layer.js";
5
+ export function useDraft(options) {
6
+ const { router } = useDataLayer();
7
+ const [draft] = useState(() => (options ? defineDraft(options) : undefined));
8
+ const snapshot = useSyncExternalStore((listener) => draft?.subscribe(listener) ?? (() => { }), () => draft?.getSnapshot() ?? idle, () => draft?.getSnapshot() ?? idle);
9
+ useEffect(() => {
10
+ if (!draft)
11
+ return undefined;
12
+ void draft.load();
13
+ return draft.guard(router);
14
+ }, [draft, router]);
15
+ return { draft, snapshot };
16
+ }
17
+ const idle = { dirty: false, stored: undefined };
@@ -0,0 +1,17 @@
1
+ import type { Nav, NavItem, NavSnapshot, TrailEntry } from "../../navigation/nav.js";
2
+ import type { RouterLocation } from "../../navigation/router.js";
3
+ export type NavState = {
4
+ location: RouterLocation;
5
+ current: NavItem | undefined;
6
+ trail: readonly TrailEntry[];
7
+ items: readonly NavItem[];
8
+ snapshot: NavSnapshot;
9
+ navigate(id: string): void;
10
+ };
11
+ export declare function useNav<Route>(nav: Nav<Route>): NavState;
12
+ export declare function useDocumentTitle<Route>(nav: Nav<Route>, pathname: string, enabled?: boolean): void;
13
+ /**
14
+ * The manifest over the `DataLayer`'s router, for a `defineNav` without one: a definition shared with server code,
15
+ * as in Next.js, where the router exists only in a client component.
16
+ */
17
+ export declare function useRoutedNav<Route>(nav: Nav<Route>): Nav<Route>;
@@ -0,0 +1,35 @@
1
+ "use client";
2
+ import { useCallback, useEffect, useMemo, useSyncExternalStore } from "react";
3
+ import { useDataLayer } from "../data-layer.js";
4
+ export function useNav(nav) {
5
+ const location = useSyncExternalStore(nav.router.subscribe, nav.router.location, nav.router.location);
6
+ const snapshot = useSyncExternalStore(nav.subscribe, nav.getSnapshot, nav.getSnapshot);
7
+ useEffect(() => nav.attach(), [nav]);
8
+ const navigate = useCallback((id) => nav.navigate(id), [nav]);
9
+ return {
10
+ location,
11
+ current: nav.current(location.pathname),
12
+ trail: nav.trail(location.pathname),
13
+ items: nav.visibleItems(),
14
+ snapshot,
15
+ navigate,
16
+ };
17
+ }
18
+ export function useDocumentTitle(nav, pathname, enabled = true) {
19
+ const { i18n } = useDataLayer();
20
+ useEffect(() => {
21
+ if (!enabled)
22
+ return;
23
+ const title = nav.documentTitle(pathname, i18n);
24
+ if (title !== undefined)
25
+ document.title = title;
26
+ }, [nav, pathname, enabled, i18n]);
27
+ }
28
+ /**
29
+ * The manifest over the `DataLayer`'s router, for a `defineNav` without one: a definition shared with server code,
30
+ * as in Next.js, where the router exists only in a client component.
31
+ */
32
+ export function useRoutedNav(nav) {
33
+ const { router } = useDataLayer();
34
+ return useMemo(() => (router === undefined || router === nav.router ? nav : nav.withRouter(router)), [nav, router]);
35
+ }
@@ -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
+ }
@@ -0,0 +1,92 @@
1
+ import { type QueryClient } from "@tanstack/react-query";
2
+ import { TotalKind } from "../../core/constants.js";
3
+ import type { Target, Version } from "../../core/contracts.js";
4
+ import { type ServiceError } from "../../core/errors.js";
5
+ import { type RefreshPolicy, type Resource } from "../../resource/resource.js";
6
+ import type { ResolvedRefresh } from "../../resource/resource-types.js";
7
+ import type { View, ViewState } from "../../view/view.js";
8
+ export type TotalInfo = {
9
+ kind: typeof TotalKind.exact;
10
+ value: number;
11
+ } | {
12
+ kind: typeof TotalKind.estimate;
13
+ value: number;
14
+ } | {
15
+ kind: typeof TotalKind.none;
16
+ };
17
+ export type ResourceListState<T, F> = {
18
+ rows: T[];
19
+ total: TotalInfo;
20
+ state: ViewState<F>;
21
+ setState(patch: Partial<ViewState<F>>): void;
22
+ isLoading: boolean;
23
+ isFetching: boolean;
24
+ error: ServiceError | undefined;
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;
30
+ };
31
+ export type ResourceListOptions<T, F, Id> = {
32
+ view?: View<T, F, Id>;
33
+ filter?: Partial<F>;
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;
44
+ };
45
+ export declare function useResourceList<T, Id, F>(resource: Resource<T, Id, F>, options?: ResourceListOptions<T, F, Id>): ResourceListState<T, F>;
46
+ export type ResourceState<T> = {
47
+ row: T | undefined;
48
+ version: Version | undefined;
49
+ isLoading: boolean;
50
+ error: ServiceError | undefined;
51
+ refetch(): void;
52
+ };
53
+ /**
54
+ * One record. With `paths` (the fields a record's page shows), its relations come with it: the related records are
55
+ * read in one request per relation, through the cache, and the plain record stays cached on its own.
56
+ */
57
+ export declare function useResource<T, Id, F>(resource: Resource<T, Id, F>, id: Id | undefined, options?: {
58
+ paths?: readonly string[];
59
+ }): ResourceState<T>;
60
+ /**
61
+ * Refreshes every query of a resource and of the resources that show its records through a relation (orders show
62
+ * their customer, so a customer's change refreshes the orders lists too).
63
+ */
64
+ export declare function invalidateResource(client: QueryClient, resource: {
65
+ key?: string;
66
+ queryKey: readonly unknown[];
67
+ }): Promise<undefined>;
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
+ */
78
+ export type ResourceMutations<T, Id, F> = {
79
+ create(input: Partial<T>, options?: WriteOptions): Promise<T>;
80
+ update(id: Id, patch: Partial<T>, options?: WriteOptions & {
81
+ version?: Version | undefined;
82
+ }): Promise<T>;
83
+ remove(target: Target<Id, F>, options?: WriteOptions): Promise<void>;
84
+ restore(target: Target<Id, F>, options?: WriteOptions): Promise<void>;
85
+ };
86
+ export declare function useResourceMutations<T, Id, F>(resource: Resource<T, Id, F>): ResourceMutations<T, Id, F>;
87
+ export declare function useResourceCount<T, Id, F>(resource: Resource<T, Id, F>, filter: Partial<F>, options?: {
88
+ refetchInterval?: number | undefined;
89
+ }): {
90
+ count: number | undefined;
91
+ error: ServiceError | undefined;
92
+ };