@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,104 @@
1
+ "use client";
2
+ import { usePathname, useRouter, useSearchParams } from "next/navigation";
3
+ import { useLayoutEffect, useState } from "react";
4
+ import { RouterKind, ValueType } from "../core/constants.js";
5
+ import { splitPath } from "../navigation/router.js";
6
+ function browserHistory() {
7
+ return typeof window === ValueType.undefined ? undefined : window.history;
8
+ }
9
+ function inside(base, pathname) {
10
+ if (base === "" || !pathname.startsWith(base))
11
+ return pathname;
12
+ return pathname.slice(base.length) || "/";
13
+ }
14
+ function nextAdapter(initial, pathname, search, base) {
15
+ let next = initial;
16
+ let location = { pathname: inside(base, pathname), search, hash: "" };
17
+ const listeners = new Set();
18
+ let pendingGuard;
19
+ const notify = () => {
20
+ for (const listener of listeners)
21
+ listener();
22
+ };
23
+ const move = (to, replace) => {
24
+ const target = splitPath(to);
25
+ const href = `${base}${to}`;
26
+ const history = browserHistory();
27
+ if (target.pathname === location.pathname && history) {
28
+ // Spec: Next.js (14.1 and later) keeps `usePathname` and `useSearchParams` in step with the History API, so a
29
+ // change of the query alone (a view's filter, sort or page) skips the server round trip a router push makes.
30
+ if (replace)
31
+ history.replaceState(null, "", href);
32
+ else
33
+ history.pushState(null, "", href);
34
+ location = target;
35
+ notify();
36
+ return;
37
+ }
38
+ if (replace)
39
+ next.replace(href, { scroll: false });
40
+ else
41
+ next.push(href);
42
+ };
43
+ const router = {
44
+ kind: RouterKind.next,
45
+ location: () => location,
46
+ subscribe(listener) {
47
+ listeners.add(listener);
48
+ return () => {
49
+ listeners.delete(listener);
50
+ };
51
+ },
52
+ navigate(to, options) {
53
+ const replace = options?.replace === true;
54
+ if (pendingGuard)
55
+ void pendingGuard().then((leave) => leave && move(to, replace));
56
+ else
57
+ move(to, replace);
58
+ },
59
+ href: (to) => `${base}${to}`,
60
+ block(when, ask) {
61
+ const guard = async () => (when() ? ask() : true);
62
+ pendingGuard = guard;
63
+ const onBeforeUnload = (event) => {
64
+ if (when())
65
+ event.preventDefault();
66
+ };
67
+ const target = typeof window === ValueType.undefined ? undefined : window;
68
+ target?.addEventListener("beforeunload", onBeforeUnload);
69
+ return () => {
70
+ if (pendingGuard === guard)
71
+ pendingGuard = undefined;
72
+ target?.removeEventListener("beforeunload", onBeforeUnload);
73
+ };
74
+ },
75
+ };
76
+ return {
77
+ router,
78
+ sync(current, rawPath, query) {
79
+ next = current;
80
+ const path = inside(base, rawPath);
81
+ if (path === location.pathname && query === location.search)
82
+ return;
83
+ location = { pathname: path, search: query, hash: "" };
84
+ notify();
85
+ },
86
+ };
87
+ }
88
+ /**
89
+ * The Next.js App Router as a `RouterAdapter`: the location from `usePathname` and `useSearchParams` (the server and
90
+ * the first client render agree), a new path through `useRouter().push`, a new query alone through the History API.
91
+ * Render it in a dynamic layout (one that reads cookies, headers or `connection()`), not under `<Suspense>`: a stream
92
+ * that starts before the page's `notFound()` answers 200.
93
+ */
94
+ export function useNextRouter(options = {}) {
95
+ const base = (options.base ?? "").replace(/\/+$/u, "");
96
+ const pathname = usePathname();
97
+ const params = useSearchParams();
98
+ const next = useRouter();
99
+ const query = params.toString();
100
+ const search = query === "" ? "" : `?${query}`;
101
+ const [adapter] = useState(() => nextAdapter(next, pathname, search, base));
102
+ useLayoutEffect(() => adapter.sync(next, pathname, search), [adapter, next, pathname, search]);
103
+ return adapter.router;
104
+ }
@@ -0,0 +1,134 @@
1
+ import { ResourceAction } from "../core/constants.js";
2
+ import { type Allowed, type Refusal } from "../core/refusal.js";
3
+ import { type Locale, type TextRefusal } from "../i18n/locale.js";
4
+ import type { PermissionSubject, Session } from "../session/session.js";
5
+ /**
6
+ * Augment it once per app to type every `requires` (actions, columns, fields) with your operations:
7
+ * `declare module "@eskais/app-sdk" { interface Register { permissions: typeof permissions } }`.
8
+ */
9
+ export interface Register {
10
+ }
11
+ /** The operations of a `Register`-like type: its permissions' vocabulary, or any string before one is registered. */
12
+ export type OperationOf<Registered> = Registered extends {
13
+ permissions: {
14
+ readonly operations: infer Ops;
15
+ };
16
+ } ? Ops[keyof Ops] & string : string;
17
+ /** The operations `requires` accepts: the registered permissions' vocabulary, or any string. */
18
+ export type RegisteredOperation = OperationOf<Register>;
19
+ /** An app's vocabulary of operations, as an `as const` object: `{ read: "read", write: "write" }`. */
20
+ export type Operations = Readonly<Record<string, string>>;
21
+ type OperationIn<Ops extends Operations> = Ops[keyof Ops] & string;
22
+ /** The key of a server's grants that holds what applies to every resource. */
23
+ export declare const GrantScope: {
24
+ readonly everyResource: "*";
25
+ };
26
+ export type GrantScope = (typeof GrantScope)[keyof typeof GrantScope];
27
+ export type PermissionContext<Claims, Operation extends string> = {
28
+ readonly claims: Claims;
29
+ readonly roles: readonly string[];
30
+ readonly operation: Operation;
31
+ /** The resource asked about; `undefined` for a page or a global action. */
32
+ readonly resource: string | undefined;
33
+ /** What was asked: a built-in use (`update`), an action's operation or a nav item's `can`. */
34
+ readonly use: string;
35
+ };
36
+ /** A rule's answer: a refusal's reason may be a message (`msg("orders.ownOnly")`), worded in the session's locale. */
37
+ export type PermissionAnswer = boolean | Refusal | TextRefusal;
38
+ type RowRule<Claims, Operation extends string, Row> = {
39
+ rule(context: PermissionContext<Claims, Operation>, row: Row | undefined): PermissionAnswer;
40
+ }["rule"];
41
+ /**
42
+ * `true` or `false`, or a function of the context and the row. Without a row it answers for the resource as a whole
43
+ * (the New button, a column, a route); with one, for that record (its menu, its edit form, an action on it).
44
+ */
45
+ export type PermissionRule<Claims, Operation extends string, Row = unknown> = boolean | RowRule<Claims, Operation, Row>;
46
+ export type OperationRules<Claims, Operation extends string> = {
47
+ readonly [Key in Operation]?: PermissionRule<Claims, Operation, any>;
48
+ };
49
+ /**
50
+ * `roles` grant operations everywhere, by role. `resources` narrow them for one resource: an operation a resource's
51
+ * rule names needs both a role that grants it and the rule.
52
+ */
53
+ export type PermissionRules<Claims, Operation extends string> = {
54
+ readonly roles?: Readonly<Record<string, OperationRules<Claims, Operation>>>;
55
+ readonly resources?: Readonly<Record<string, OperationRules<Claims, Operation>>>;
56
+ };
57
+ /** Which operation each use needs: the built-in ones (`create`, `list`…) and any action id or nav `can`. */
58
+ export type PermissionUses<Operation extends string> = Readonly<Partial<Record<ResourceAction | (string & {}), Operation>>>;
59
+ /** Operations a server granted, by resource key, `GrantScope.everyResource` for all of them: `{ orders: ["approve"] }`. */
60
+ export type Grants<Operation extends string> = Readonly<Record<string, readonly Operation[]>>;
61
+ export type PermissionsOptions<Ops extends Operations, Claims> = {
62
+ operations: Ops;
63
+ uses: PermissionUses<OperationIn<Ops>>;
64
+ /** The roles in the claims, for `rules.roles`. */
65
+ roles?: (claims: Claims) => string | readonly string[] | undefined;
66
+ /** Operations the server granted in the claims, besides what the roles grant. */
67
+ grants?: (claims: Claims) => Grants<OperationIn<Ops>> | undefined;
68
+ rules?: PermissionRules<Claims, OperationIn<Ops>>;
69
+ };
70
+ /** What a check is about: a resource (its key or the resource) and, for a record, the row. */
71
+ export type PermissionTarget = {
72
+ resource?: string | {
73
+ readonly key: string;
74
+ } | undefined;
75
+ row?: unknown;
76
+ };
77
+ /** The permissions of one set of claims. `can` is a `Session`'s; `check` asks for an operation by name. */
78
+ export type GrantedPermissions<Claims, Operation extends string> = {
79
+ readonly claims: Claims;
80
+ check(operation: Operation, target?: PermissionTarget, notAllowed?: string): Allowed;
81
+ can(use: string, subject?: PermissionSubject): boolean | Refusal;
82
+ };
83
+ /** What the browser needs to rebuild a session the server made: JSON, so a server component can pass it down. */
84
+ export type SessionPayload<User, Claims> = {
85
+ user: User | null;
86
+ claims: Claims;
87
+ organization?: string | undefined;
88
+ };
89
+ export type PermissionSessionOptions<User, Claims> = SessionPayload<User, Claims> & {
90
+ token?: () => Promise<string | undefined>;
91
+ subscribe?: (listener: () => void) => () => void;
92
+ /** Words the rules' message refusals. */
93
+ locale?: Locale | undefined;
94
+ };
95
+ export type PermissionSession<User, Claims> = Session<User> & {
96
+ readonly claims: Claims;
97
+ };
98
+ export type Permissions<Ops extends Operations, Claims> = {
99
+ readonly operations: Ops;
100
+ readonly options: PermissionsOptions<Ops, Claims>;
101
+ /** The operation a use needs, or `undefined` when nothing maps it. */
102
+ operationOf(use: string): OperationIn<Ops> | undefined;
103
+ check(operation: OperationIn<Ops>, target: PermissionTarget & {
104
+ claims: Claims;
105
+ locale?: Locale | undefined;
106
+ notAllowed?: string;
107
+ }): Allowed;
108
+ for(claims: Claims, locale?: Locale): GrantedPermissions<Claims, OperationIn<Ops>>;
109
+ /** A `Session` whose `can` answers from these permissions: on the server with the request's claims, or hydrated. */
110
+ session<User>(options: PermissionSessionOptions<User, Claims>): PermissionSession<User, Claims>;
111
+ };
112
+ /**
113
+ * A role check for a rule: `approve: hasRole("manager")`. Any of the roles passes.
114
+ */
115
+ export declare function hasRole(...roles: readonly string[]): (context: {
116
+ readonly roles: readonly string[];
117
+ }) => boolean;
118
+ /**
119
+ * An app's permissions over its own vocabulary of operations. `uses` says which operation each built-in use needs,
120
+ * `rules` grant operations by role and narrow them by resource, per row when a rule is a function. Its `session`
121
+ * answers every `can` the blocks, routes and agents ask.
122
+ */
123
+ export declare function definePermissions<const Ops extends Operations, Claims = unknown>(options: PermissionsOptions<Ops, Claims>): Permissions<Ops, Claims>;
124
+ /** Whether `session` allows `operation` on the resource (and row): a column, a field or a button that `requires` it. */
125
+ export declare function allows(session: Session | undefined, operation: string | undefined, target?: PermissionTarget, notAllowed?: string): Allowed;
126
+ /** The items whose `requires` the session allows on the resource: columns, fields, sections. */
127
+ export declare function permitted<Item extends {
128
+ readonly requires?: string | undefined;
129
+ }>(items: readonly Item[], session: Session | undefined, resource: string | {
130
+ readonly key: string;
131
+ }): Item[];
132
+ /** The JSON a server component passes the browser for `permissions.session(payload)`. */
133
+ export declare function sessionPayload<User, Claims>(session: PermissionSession<User, Claims> | undefined): SessionPayload<User, Claims> | null;
134
+ export {};
@@ -0,0 +1,121 @@
1
+ import { ResourceAction } from "../core/constants.js";
2
+ import { isBoolean, isString } from "../core/guards.js";
3
+ import { isRefusal, toAllowed } from "../core/refusal.js";
4
+ import { refusalIn } from "../i18n/locale.js";
5
+ /** The key of a server's grants that holds what applies to every resource. */
6
+ export const GrantScope = { everyResource: "*" };
7
+ const fallbackUse = {
8
+ [ResourceAction.get]: ResourceAction.list,
9
+ [ResourceAction.restore]: ResourceAction.remove,
10
+ [ResourceAction.import]: ResourceAction.create,
11
+ };
12
+ function keyOf(resource) {
13
+ if (resource === undefined)
14
+ return undefined;
15
+ return isString(resource) ? resource : resource.key;
16
+ }
17
+ function rolesOf(given) {
18
+ if (given === undefined)
19
+ return [];
20
+ return isString(given) ? [given] : given;
21
+ }
22
+ /**
23
+ * A role check for a rule: `approve: hasRole("manager")`. Any of the roles passes.
24
+ */
25
+ export function hasRole(...roles) {
26
+ return (context) => context.roles.some((role) => roles.includes(role));
27
+ }
28
+ /**
29
+ * An app's permissions over its own vocabulary of operations. `uses` says which operation each built-in use needs,
30
+ * `rules` grant operations by role and narrow them by resource, per row when a rule is a function. Its `session`
31
+ * answers every `can` the blocks, routes and agents ask.
32
+ */
33
+ export function definePermissions(options) {
34
+ const declared = new Set(Object.values(options.operations));
35
+ const isOperation = (value) => declared.has(value);
36
+ const roleRules = options.rules?.roles;
37
+ const resourceRules = options.rules?.resources;
38
+ const byRole = roleRules !== undefined || options.grants !== undefined;
39
+ function operationOf(use) {
40
+ const mapped = options.uses[use];
41
+ if (mapped !== undefined)
42
+ return mapped;
43
+ if (isOperation(use))
44
+ return use;
45
+ const fallback = fallbackUse[use];
46
+ return fallback === undefined ? undefined : options.uses[fallback];
47
+ }
48
+ function decide(claims, use, operation, resource, row, locale) {
49
+ const roles = rolesOf(options.roles?.(claims));
50
+ const context = { claims, roles, operation, resource, use };
51
+ const answer = (rule) => {
52
+ if (rule === undefined || isBoolean(rule))
53
+ return rule;
54
+ return refusalIn(rule(context, row), locale);
55
+ };
56
+ if (byRole) {
57
+ const sent = options.grants?.(claims);
58
+ const fromServer = sent !== undefined &&
59
+ [resource ?? GrantScope.everyResource, GrantScope.everyResource].some((scope) => sent[scope]?.includes(operation) === true);
60
+ if (!fromServer) {
61
+ const answers = roles.map((role) => answer(roleRules?.[role]?.[operation]));
62
+ if (!answers.includes(true))
63
+ return answers.find(isRefusal) ?? false;
64
+ }
65
+ }
66
+ const own = resource === undefined ? undefined : answer(resourceRules?.[resource]?.[operation]);
67
+ return own === undefined ? true : own;
68
+ }
69
+ function granted(claims, locale) {
70
+ return {
71
+ claims,
72
+ check: (operation, target = {}, notAllowed = "") => toAllowed(decide(claims, operation, operation, keyOf(target.resource), target.row, locale), notAllowed),
73
+ can(use, subject) {
74
+ const operation = operationOf(use);
75
+ if (operation === undefined)
76
+ return false;
77
+ return decide(claims, use, operation, subject?.resource, subject?.row, locale);
78
+ },
79
+ };
80
+ }
81
+ return {
82
+ operations: options.operations,
83
+ options,
84
+ operationOf,
85
+ check: (operation, target) => granted(target.claims, target.locale).check(operation, target, target.notAllowed ?? ""),
86
+ for: granted,
87
+ session(given) {
88
+ const answers = granted(given.claims, given.locale);
89
+ return {
90
+ user: given.user,
91
+ claims: given.claims,
92
+ organization: given.organization,
93
+ can: answers.can,
94
+ ...(given.token ? { token: given.token } : {}),
95
+ ...(given.subscribe ? { subscribe: given.subscribe } : {}),
96
+ };
97
+ },
98
+ };
99
+ }
100
+ /** Whether `session` allows `operation` on the resource (and row): a column, a field or a button that `requires` it. */
101
+ export function allows(session, operation, target = {}, notAllowed = "") {
102
+ if (operation === undefined || session === undefined)
103
+ return true;
104
+ const resource = keyOf(target.resource);
105
+ const subject = resource === undefined ? undefined : { resource, ...(target.row === undefined ? {} : { row: target.row }) };
106
+ return toAllowed(session.can(operation, subject), notAllowed);
107
+ }
108
+ /** The items whose `requires` the session allows on the resource: columns, fields, sections. */
109
+ export function permitted(items, session, resource) {
110
+ return items.filter((item) => allows(session, item.requires, { resource }) === true);
111
+ }
112
+ /** The JSON a server component passes the browser for `permissions.session(payload)`. */
113
+ export function sessionPayload(session) {
114
+ if (session === undefined)
115
+ return null;
116
+ return {
117
+ user: session.user,
118
+ claims: session.claims,
119
+ ...(session.organization === undefined ? {} : { organization: session.organization }),
120
+ };
121
+ }
@@ -0,0 +1,68 @@
1
+ import { QueryClient } from "@tanstack/react-query";
2
+ import { type ReactNode } from "react";
3
+ import type { DataLabels } from "../core/data-labels.js";
4
+ import { type DialogQueue } from "../dialogs/dialogs.js";
5
+ import { type Errors } from "../errors/define-errors.js";
6
+ import type { Locale } from "../i18n/locale.js";
7
+ import type { PreferencesStore } from "../view/preferences.js";
8
+ import type { RouterAdapter } from "../navigation/router.js";
9
+ import type { Session } from "../session/session.js";
10
+ export type DataLayerValue = {
11
+ session: Session | undefined;
12
+ router: RouterAdapter | undefined;
13
+ labels: DataLabels;
14
+ preferences: PreferencesStore | undefined;
15
+ /** The BCP 47 code numbers and dates format with. */
16
+ locale: string | undefined;
17
+ /** The messages resources and blocks read, when `DataLayer` got a `Locale`. */
18
+ i18n: Locale | undefined;
19
+ /** The error policy every resource call and action goes through. */
20
+ errors: Errors;
21
+ /** The queue `useDialogs` adds to and `NavDialogs` draws. */
22
+ dialogs: DialogQueue;
23
+ };
24
+ export type DataLayerProps = {
25
+ /**
26
+ * The app's TanStack Query client, the one `server-data`'s `DataProvider` uses too (`createDataClient()`), so
27
+ * `Server…` and `Resource…` components share one cache. Without it, the client already provided, or a new one.
28
+ */
29
+ client?: QueryClient;
30
+ session?: Session;
31
+ router?: RouterAdapter;
32
+ /**
33
+ * The language: a `Locale` from `defineLocale`, `fromNextIntl`, `fromI18next` or `fromIntl`, which words the blocks
34
+ * and the resources' labels. A BCP 47 code alone only formats numbers and dates, with `labels` for the words.
35
+ */
36
+ locale?: Locale | string;
37
+ /** @deprecated Give `locale` a `Locale` instead: `dataLabelsEn`, `dataLabelsEs` or your own still work here. */
38
+ labels?: DataLabels;
39
+ preferences?: PreferencesStore;
40
+ /**
41
+ * The app's `defineErrors` policy: how errors classify, read and show, when calls retry and how an expired session
42
+ * signs in again. `defineErrors()`'s defaults without it.
43
+ */
44
+ errors?: Errors;
45
+ children: ReactNode;
46
+ };
47
+ export declare function DataLayer({ client, session, router, labels, preferences, locale, errors, children }: DataLayerProps): import("react").JSX.Element;
48
+ export declare function useDataLayer(): DataLayerValue;
49
+ export declare function useSession(): Session | undefined;
50
+ type Localizable<Value> = {
51
+ in(locale: Locale | undefined): Value;
52
+ };
53
+ /**
54
+ * The generic texts. Given the resource they're about, messages with a `{gender, select, …}` agree with it
55
+ * ("Nueva línea", "Nuevo pedido").
56
+ */
57
+ export declare function useLabels(resource?: Localizable<{
58
+ gender: string | undefined;
59
+ }>): DataLabels;
60
+ /** A resource or an action with its texts in the `DataLayer`'s locale: `useLocalized(customers).label(2)`. */
61
+ export declare function useLocalized<Value extends Localizable<Value>>(value: Value): Value;
62
+ /** The `DataLayer` for a block about one resource: the resource in its locale, and the texts in its gender. */
63
+ export declare function useResourceLayer<Value extends Localizable<Value> & {
64
+ gender: string | undefined;
65
+ }>(resource: Value): DataLayerValue & {
66
+ resource: Value;
67
+ };
68
+ export {};
@@ -0,0 +1,76 @@
1
+ "use client";
2
+ import { jsx as _jsx } from "react/jsx-runtime";
3
+ import { QueryClient, QueryClientContext, QueryClientProvider } from "@tanstack/react-query";
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";
9
+ const DataLayerContext = createContext(null);
10
+ const defaultErrors = defineErrors();
11
+ function newClient() {
12
+ return new QueryClient({
13
+ defaultOptions: { queries: { staleTime: 30_000, refetchOnWindowFocus: false }, mutations: { retry: false } },
14
+ });
15
+ }
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 }) {
24
+ const existing = use(QueryClientContext);
25
+ const [own] = useState(() => client ?? existing ?? newClient());
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]);
39
+ const content = _jsx(DataLayerContext, { value: value, children: children });
40
+ if (existing && client === undefined)
41
+ return content;
42
+ return _jsx(QueryClientProvider, { client: client ?? own, children: content });
43
+ }
44
+ export function useDataLayer() {
45
+ const value = use(DataLayerContext);
46
+ if (!value)
47
+ throw new Error("App SDK hooks and components need a <DataLayer> above them.");
48
+ return value;
49
+ }
50
+ export function useSession() {
51
+ return useDataLayer().session;
52
+ }
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 };
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
+ }
@@ -0,0 +1,37 @@
1
+ import { type QueryClient } from "@tanstack/react-query";
2
+ import type { Action, ActionTarget } from "../../action/action.js";
3
+ import { ActionStatus, Feedback } from "../../core/constants.js";
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
+ };
16
+ export type ActionState<R> = {
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;
23
+ pending: boolean;
24
+ allowed: Allowed;
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;
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;
37
+ export declare function useAction<T, I, R>(action: Action<T, I, R>, target?: ActionTarget<T>): ActionState<R>;