@eskais/app-sdk 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +68 -2
- package/dist/action/action.d.ts +74 -0
- package/dist/action/action.js +106 -0
- package/dist/cli/cli.d.ts +2 -0
- package/dist/cli/cli.js +51 -0
- package/dist/cli/routes.d.ts +17 -0
- package/dist/cli/routes.js +36 -0
- package/dist/core/assume.d.ts +1 -0
- package/dist/core/assume.js +8 -0
- package/dist/core/constants.d.ts +302 -0
- package/dist/core/constants.js +156 -0
- package/dist/core/contracts.d.ts +100 -0
- package/dist/core/contracts.js +3 -0
- package/dist/core/data-labels.d.ts +196 -0
- package/dist/core/data-labels.js +345 -0
- package/dist/core/errors.d.ts +46 -0
- package/dist/core/errors.js +166 -0
- package/dist/core/guards.d.ts +9 -0
- package/dist/core/guards.js +14 -0
- package/dist/core/refusal.d.ts +30 -0
- package/dist/core/refusal.js +53 -0
- package/dist/draft/draft.d.ts +36 -0
- package/dist/draft/draft.js +87 -0
- package/dist/export/csv.d.ts +25 -0
- package/dist/export/csv.js +59 -0
- package/dist/import/csv-parse.d.ts +11 -0
- package/dist/import/csv-parse.js +70 -0
- package/dist/import/import.d.ts +102 -0
- package/dist/import/import.js +263 -0
- package/dist/index.d.ts +31 -0
- package/dist/index.js +30 -0
- package/dist/navigation/nav.d.ts +119 -0
- package/dist/navigation/nav.js +278 -0
- package/dist/navigation/router.d.ts +81 -0
- package/dist/navigation/router.js +249 -0
- package/dist/navigation/shortcuts.d.ts +37 -0
- package/dist/navigation/shortcuts.js +93 -0
- package/dist/next/index.d.ts +3 -0
- package/dist/next/index.js +3 -0
- package/dist/next/screen-hydration.d.ts +12 -0
- package/dist/next/screen-hydration.js +26 -0
- package/dist/next/screen.d.ts +25 -0
- package/dist/next/screen.js +44 -0
- package/dist/next/server/handler.d.ts +39 -0
- package/dist/next/server/handler.js +190 -0
- package/dist/next/server/index.d.ts +5 -0
- package/dist/next/server/index.js +5 -0
- package/dist/next/server/page.d.ts +57 -0
- package/dist/next/server/page.js +103 -0
- package/dist/next/server/prefetch.d.ts +29 -0
- package/dist/next/server/prefetch.js +97 -0
- package/dist/next/server/session.d.ts +12 -0
- package/dist/next/server/session.js +10 -0
- package/dist/next/use-next-router.d.ts +21 -0
- package/dist/next/use-next-router.js +104 -0
- package/dist/react/data-layer.d.ts +31 -0
- package/dist/react/data-layer.js +31 -0
- package/dist/react/hooks/use-action.d.ts +12 -0
- package/dist/react/hooks/use-action.js +67 -0
- package/dist/react/hooks/use-better-auth.d.ts +12 -0
- package/dist/react/hooks/use-better-auth.js +11 -0
- package/dist/react/hooks/use-draft.d.ts +5 -0
- package/dist/react/hooks/use-draft.js +17 -0
- package/dist/react/hooks/use-nav.d.ts +17 -0
- package/dist/react/hooks/use-nav.js +34 -0
- package/dist/react/hooks/use-resource.d.ts +69 -0
- package/dist/react/hooks/use-resource.js +218 -0
- package/dist/react/hooks/use-view.d.ts +6 -0
- package/dist/react/hooks/use-view.js +24 -0
- package/dist/react/index.d.ts +8 -0
- package/dist/react/index.js +8 -0
- package/dist/react/keys.d.ts +51 -0
- package/dist/react/keys.js +67 -0
- package/dist/resource/form-schema.d.ts +11 -0
- package/dist/resource/form-schema.js +51 -0
- package/dist/resource/relations.d.ts +99 -0
- package/dist/resource/relations.js +194 -0
- package/dist/resource/resource-relations.d.ts +44 -0
- package/dist/resource/resource-relations.js +141 -0
- package/dist/resource/resource-schema.d.ts +9 -0
- package/dist/resource/resource-schema.js +73 -0
- package/dist/resource/resource-types.d.ts +281 -0
- package/dist/resource/resource-types.js +1 -0
- package/dist/resource/resource.d.ts +11 -0
- package/dist/resource/resource.js +354 -0
- package/dist/resource/schema.d.ts +57 -0
- package/dist/resource/schema.js +115 -0
- package/dist/services/from-page-source.d.ts +15 -0
- package/dist/services/from-page-source.js +27 -0
- package/dist/services/memory-query.d.ts +8 -0
- package/dist/services/memory-query.js +165 -0
- package/dist/services/memory-service.d.ts +33 -0
- package/dist/services/memory-service.js +291 -0
- package/dist/services/rest-service.d.ts +62 -0
- package/dist/services/rest-service.js +220 -0
- package/dist/services/rng.d.ts +9 -0
- package/dist/services/rng.js +22 -0
- package/dist/services/spring-service.d.ts +58 -0
- package/dist/services/spring-service.js +132 -0
- package/dist/session/better-auth.d.ts +83 -0
- package/dist/session/better-auth.js +86 -0
- package/dist/session/session.d.ts +45 -0
- package/dist/session/session.js +36 -0
- package/dist/view/preferences.d.ts +35 -0
- package/dist/view/preferences.js +93 -0
- package/dist/view/view-types.d.ts +122 -0
- package/dist/view/view-types.js +1 -0
- package/dist/view/view-url.d.ts +7 -0
- package/dist/view/view-url.js +54 -0
- package/dist/view/view.d.ts +4 -0
- package/dist/view/view.js +392 -0
- package/package.json +85 -4
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { RelationKind, ResourceAction, ResourceScreen, ServiceErrorKind } from "../../core/constants.js";
|
|
2
|
+
import { toServiceError } from "../../core/errors.js";
|
|
3
|
+
import { defineView } from "../../view/view.js";
|
|
4
|
+
import { resourceDetailKey, resourceDetailWithKey, resourceTableQuery, shownPaths } from "../../react/keys.js";
|
|
5
|
+
import { includeOf, resolveRelations } from "../../resource/relations.js";
|
|
6
|
+
function allowed(resource, action, session) {
|
|
7
|
+
return resource.check(action, undefined, session) === true;
|
|
8
|
+
}
|
|
9
|
+
function relationsOn(client, options, signal) {
|
|
10
|
+
const { session } = options;
|
|
11
|
+
return {
|
|
12
|
+
signal,
|
|
13
|
+
session,
|
|
14
|
+
known: (target, id) => client.getQueryData(resourceDetailKey(target, id)),
|
|
15
|
+
seed: (target, record) => client.setQueryData(resourceDetailKey(target, target.idKey(target.idOf(record))), record),
|
|
16
|
+
canRead: (target) => allowed(target, ResourceAction.get, session),
|
|
17
|
+
serviceOf: (target) => options.services?.[target.key] ?? target.service,
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
async function prefetchTable(client, resource, service, options) {
|
|
21
|
+
const { session } = options;
|
|
22
|
+
const view = defineView(resource, { ...options.view, search: options.search });
|
|
23
|
+
const paths = shownPaths(resource, options.except);
|
|
24
|
+
const table = resourceTableQuery(resource, view, options.fixed ?? {}, paths);
|
|
25
|
+
const count = service.count;
|
|
26
|
+
await Promise.all([
|
|
27
|
+
client.prefetchQuery({
|
|
28
|
+
queryKey: table.page,
|
|
29
|
+
queryFn: async ({ signal }) => {
|
|
30
|
+
const page = await service.list(table.query, { signal, session });
|
|
31
|
+
const items = await resolveRelations(resource, page.items, paths, relationsOn(client, options, signal));
|
|
32
|
+
return { ...page, items };
|
|
33
|
+
},
|
|
34
|
+
}),
|
|
35
|
+
table.total && count
|
|
36
|
+
? client.prefetchQuery({
|
|
37
|
+
queryKey: table.total,
|
|
38
|
+
queryFn: ({ signal }) => count.call(service, table.query.filter, { signal, session }),
|
|
39
|
+
})
|
|
40
|
+
: undefined,
|
|
41
|
+
]);
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Fetches a screen's first queries into `client` under the keys the blocks read: a list's first page with its
|
|
45
|
+
* relations, or a record with its relations and its `hasMany` tab's first page. A failed list stays out for the
|
|
46
|
+
* client to show; a missing record is `notFound`; a screen the session may not see fetches nothing.
|
|
47
|
+
*/
|
|
48
|
+
export async function prefetchScreen(client, screen, options = {}) {
|
|
49
|
+
const { resource, id } = screen;
|
|
50
|
+
const service = options.service ?? options.services?.[resource.key] ?? resource.service;
|
|
51
|
+
const { session } = options;
|
|
52
|
+
if (screen.screen === ResourceScreen.create)
|
|
53
|
+
return { notFound: false };
|
|
54
|
+
if (screen.screen === ResourceScreen.list) {
|
|
55
|
+
if (!allowed(resource, ResourceAction.list, session))
|
|
56
|
+
return { notFound: false };
|
|
57
|
+
await prefetchTable(client, resource, service, { ...options, search: options.search ?? "" });
|
|
58
|
+
return { notFound: false };
|
|
59
|
+
}
|
|
60
|
+
if (!allowed(resource, ResourceAction.get, session))
|
|
61
|
+
return { notFound: false };
|
|
62
|
+
try {
|
|
63
|
+
const row = await client.fetchQuery({
|
|
64
|
+
queryKey: resourceDetailKey(resource, resource.idKey(id)),
|
|
65
|
+
queryFn: ({ signal }) => service.get(id, { signal, session }),
|
|
66
|
+
staleTime: resource.staleTime,
|
|
67
|
+
});
|
|
68
|
+
const paths = shownPaths(resource);
|
|
69
|
+
const include = includeOf(resource.relations, paths);
|
|
70
|
+
if (include.length > 0 && screen.screen === ResourceScreen.detail)
|
|
71
|
+
await client.prefetchQuery({
|
|
72
|
+
queryKey: resourceDetailWithKey(resource, resource.idKey(id), include),
|
|
73
|
+
queryFn: async ({ signal }) => {
|
|
74
|
+
const [resolved] = await resolveRelations(resource, [row], paths, relationsOn(client, options, signal));
|
|
75
|
+
return resolved;
|
|
76
|
+
},
|
|
77
|
+
});
|
|
78
|
+
const tab = screen.tab === undefined ? undefined : resource.relations[screen.tab];
|
|
79
|
+
if (tab?.kind === RelationKind.hasMany) {
|
|
80
|
+
const target = tab.target();
|
|
81
|
+
if (allowed(target, ResourceAction.list, session))
|
|
82
|
+
await prefetchTable(client, target, options.services?.[target.key] ?? target.service, {
|
|
83
|
+
...options,
|
|
84
|
+
search: "",
|
|
85
|
+
view: undefined,
|
|
86
|
+
fixed: { [tab.foreignKey]: id },
|
|
87
|
+
except: tab.foreignKey,
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
return { row, notFound: false };
|
|
91
|
+
}
|
|
92
|
+
catch (error) {
|
|
93
|
+
if (toServiceError(error).kind === ServiceErrorKind.notFound)
|
|
94
|
+
return { notFound: true };
|
|
95
|
+
return { notFound: false };
|
|
96
|
+
}
|
|
97
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { cookies, headers } from "next/headers";
|
|
2
|
+
import type { Session } from "../../session/session.js";
|
|
3
|
+
export type NextRequestScope = {
|
|
4
|
+
cookies: Awaited<ReturnType<typeof cookies>>;
|
|
5
|
+
headers: Awaited<ReturnType<typeof headers>>;
|
|
6
|
+
};
|
|
7
|
+
/**
|
|
8
|
+
* The session of the request being rendered, from its cookies and headers, read once per request: pages,
|
|
9
|
+
* `generateMetadata`, layouts and route handlers all get the same one. `read` verifies the cookie or token with your
|
|
10
|
+
* auth library and returns `undefined` for nobody.
|
|
11
|
+
*/
|
|
12
|
+
export declare function nextSession<User>(read: (request: NextRequestScope) => Session<User> | undefined | Promise<Session<User> | undefined>): () => Promise<Session<User> | undefined>;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { cookies, headers } from "next/headers";
|
|
2
|
+
import { cache } from "react";
|
|
3
|
+
/**
|
|
4
|
+
* The session of the request being rendered, from its cookies and headers, read once per request: pages,
|
|
5
|
+
* `generateMetadata`, layouts and route handlers all get the same one. `read` verifies the cookie or token with your
|
|
6
|
+
* auth library and returns `undefined` for nobody.
|
|
7
|
+
*/
|
|
8
|
+
export function nextSession(read) {
|
|
9
|
+
return cache(async () => read({ cookies: await cookies(), headers: await headers() }));
|
|
10
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { type RouterAdapter } from "../navigation/router.js";
|
|
2
|
+
/** The part of Next's `useRouter()` the adapter uses. */
|
|
3
|
+
export type NextAppRouter = {
|
|
4
|
+
push(href: string, options?: {
|
|
5
|
+
scroll?: boolean;
|
|
6
|
+
}): void;
|
|
7
|
+
replace(href: string, options?: {
|
|
8
|
+
scroll?: boolean;
|
|
9
|
+
}): void;
|
|
10
|
+
};
|
|
11
|
+
export type NextRouterOptions = {
|
|
12
|
+
/** Where the app is mounted, as `app/admin/[[...path]]` is at `/admin`. The resources' paths go below it. */
|
|
13
|
+
base?: string;
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* The Next.js App Router as a `RouterAdapter`: the location from `usePathname` and `useSearchParams` (the server and
|
|
17
|
+
* the first client render agree), a new path through `useRouter().push`, a new query alone through the History API.
|
|
18
|
+
* Render it in a dynamic layout (one that reads cookies, headers or `connection()`), not under `<Suspense>`: a stream
|
|
19
|
+
* that starts before the page's `notFound()` answers 200.
|
|
20
|
+
*/
|
|
21
|
+
export declare function useNextRouter(options?: NextRouterOptions): RouterAdapter;
|
|
@@ -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,31 @@
|
|
|
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 { PreferencesStore } from "../view/preferences.js";
|
|
5
|
+
import type { RouterAdapter } from "../navigation/router.js";
|
|
6
|
+
import type { Session } from "../session/session.js";
|
|
7
|
+
export type DataLayerValue = {
|
|
8
|
+
session: Session | undefined;
|
|
9
|
+
router: RouterAdapter | undefined;
|
|
10
|
+
labels: DataLabels;
|
|
11
|
+
preferences: PreferencesStore | undefined;
|
|
12
|
+
locale: string | undefined;
|
|
13
|
+
};
|
|
14
|
+
export type DataLayerProps = {
|
|
15
|
+
/**
|
|
16
|
+
* The app's TanStack Query client, the one `server-data`'s `DataProvider` uses too (`createDataClient()`), so
|
|
17
|
+
* `Server…` and `Resource…` components share one cache. Without it, the client already provided, or a new one.
|
|
18
|
+
*/
|
|
19
|
+
client?: QueryClient;
|
|
20
|
+
session?: Session;
|
|
21
|
+
router?: RouterAdapter;
|
|
22
|
+
/** Every generic text: `dataLabelsEn`, `dataLabelsEs` or your own. */
|
|
23
|
+
labels: DataLabels;
|
|
24
|
+
preferences?: PreferencesStore;
|
|
25
|
+
locale?: string;
|
|
26
|
+
children: ReactNode;
|
|
27
|
+
};
|
|
28
|
+
export declare function DataLayer({ client, session, router, labels, preferences, locale, children }: DataLayerProps): import("react").JSX.Element;
|
|
29
|
+
export declare function useDataLayer(): DataLayerValue;
|
|
30
|
+
export declare function useSession(): Session | undefined;
|
|
31
|
+
export declare function useLabels(): DataLabels;
|
|
@@ -0,0 +1,31 @@
|
|
|
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
|
+
const DataLayerContext = createContext(null);
|
|
6
|
+
function newClient() {
|
|
7
|
+
return new QueryClient({
|
|
8
|
+
defaultOptions: { queries: { staleTime: 30_000, refetchOnWindowFocus: false }, mutations: { retry: false } },
|
|
9
|
+
});
|
|
10
|
+
}
|
|
11
|
+
export function DataLayer({ client, session, router, labels, preferences, locale, children }) {
|
|
12
|
+
const existing = use(QueryClientContext);
|
|
13
|
+
const [own] = useState(() => client ?? existing ?? newClient());
|
|
14
|
+
const value = useMemo(() => ({ session, router, labels, preferences, locale }), [session, router, labels, preferences, locale]);
|
|
15
|
+
const content = _jsx(DataLayerContext, { value: value, children: children });
|
|
16
|
+
if (existing && client === undefined)
|
|
17
|
+
return content;
|
|
18
|
+
return _jsx(QueryClientProvider, { client: client ?? own, children: content });
|
|
19
|
+
}
|
|
20
|
+
export function useDataLayer() {
|
|
21
|
+
const value = use(DataLayerContext);
|
|
22
|
+
if (!value)
|
|
23
|
+
throw new Error("App SDK hooks and components need a <DataLayer> above them.");
|
|
24
|
+
return value;
|
|
25
|
+
}
|
|
26
|
+
export function useSession() {
|
|
27
|
+
return useDataLayer().session;
|
|
28
|
+
}
|
|
29
|
+
export function useLabels() {
|
|
30
|
+
return useDataLayer().labels;
|
|
31
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { Action, ActionTarget } from "../../action/action.js";
|
|
2
|
+
import { type ServiceError } from "../../core/errors.js";
|
|
3
|
+
import type { Allowed } from "../../core/refusal.js";
|
|
4
|
+
export type ActionState<R> = {
|
|
5
|
+
run(input?: unknown, options?: {
|
|
6
|
+
target?: ActionTarget<unknown>;
|
|
7
|
+
}): Promise<R | undefined>;
|
|
8
|
+
pending: boolean;
|
|
9
|
+
allowed: Allowed;
|
|
10
|
+
error: ServiceError | undefined;
|
|
11
|
+
};
|
|
12
|
+
export declare function useAction<T, I, R>(action: Action<T, I, R>, target?: ActionTarget<T>): ActionState<R>;
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { useQueryClient } from "@tanstack/react-query";
|
|
3
|
+
import { useCallback, useState } from "react";
|
|
4
|
+
import { assumeType } from "../../core/assume.js";
|
|
5
|
+
import { ActionTargetKind, ServiceErrorKind } from "../../core/constants.js";
|
|
6
|
+
import { ServiceFailure, serviceError, toServiceError } from "../../core/errors.js";
|
|
7
|
+
import { useDataLayer } from "../data-layer.js";
|
|
8
|
+
import { invalidateResource } from "./use-resource.js";
|
|
9
|
+
const noTarget = { kind: ActionTargetKind.none };
|
|
10
|
+
function applyOptimistic(client, resource, rows, update, input) {
|
|
11
|
+
const ids = new Set(rows.map((row) => resource.idKey(resource.idOf(row))));
|
|
12
|
+
const snapshot = client.getQueriesData({ queryKey: resource.queryKey });
|
|
13
|
+
client.setQueriesData({ queryKey: [...resource.queryKey, "page"] }, (page) => page
|
|
14
|
+
? {
|
|
15
|
+
...page,
|
|
16
|
+
items: page.items.map((row) => (ids.has(resource.idKey(resource.idOf(row))) ? update(row, input) : row)),
|
|
17
|
+
}
|
|
18
|
+
: page);
|
|
19
|
+
return snapshot;
|
|
20
|
+
}
|
|
21
|
+
async function perform(client, action, target, input, session) {
|
|
22
|
+
const resource = action.options.resource;
|
|
23
|
+
let snapshot = [];
|
|
24
|
+
try {
|
|
25
|
+
const parsed = await action.parseInput(input);
|
|
26
|
+
const optimistic = action.options.optimistic;
|
|
27
|
+
if (optimistic && resource)
|
|
28
|
+
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);
|
|
32
|
+
return { ok: true, result };
|
|
33
|
+
}
|
|
34
|
+
catch (failure) {
|
|
35
|
+
for (const [key, data] of snapshot)
|
|
36
|
+
client.setQueryData(key, data);
|
|
37
|
+
const error = toServiceError(failure);
|
|
38
|
+
return { ok: false, error, failure: failure instanceof ServiceFailure ? failure : new ServiceFailure(error) };
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
export function useAction(action, target) {
|
|
42
|
+
const { session, labels } = useDataLayer();
|
|
43
|
+
const client = useQueryClient();
|
|
44
|
+
const [pending, setPending] = useState(false);
|
|
45
|
+
const [error, setError] = useState();
|
|
46
|
+
const fixed = target ?? noTarget;
|
|
47
|
+
const allowed = action.check(fixed, session, labels.notAllowed);
|
|
48
|
+
const run = useCallback(async (input, options = {}) => {
|
|
49
|
+
// Workaround: a target passed to `run` is for this action's rows; React hooks can't carry `T` through options.
|
|
50
|
+
const chosen = options.target ? assumeType(options.target) : fixed;
|
|
51
|
+
const permitted = action.check(chosen, session, labels.notAllowed);
|
|
52
|
+
if (permitted !== true) {
|
|
53
|
+
const refusal = serviceError(ServiceErrorKind.forbidden, permitted.reason);
|
|
54
|
+
setError(refusal);
|
|
55
|
+
throw new ServiceFailure(refusal);
|
|
56
|
+
}
|
|
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 };
|
|
67
|
+
}
|
|
@@ -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,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,34 @@
|
|
|
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
|
+
useEffect(() => {
|
|
20
|
+
if (!enabled)
|
|
21
|
+
return;
|
|
22
|
+
const title = nav.documentTitle(pathname);
|
|
23
|
+
if (title !== undefined)
|
|
24
|
+
document.title = title;
|
|
25
|
+
}, [nav, pathname, enabled]);
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* The manifest over the `DataLayer`'s router, for a `defineNav` without one: a definition shared with server code,
|
|
29
|
+
* as in Next.js, where the router exists only in a client component.
|
|
30
|
+
*/
|
|
31
|
+
export function useRoutedNav(nav) {
|
|
32
|
+
const { router } = useDataLayer();
|
|
33
|
+
return useMemo(() => (router === undefined || router === nav.router ? nav : nav.withRouter(router)), [nav, router]);
|
|
34
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
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 Resource } from "../../resource/resource.js";
|
|
6
|
+
import type { View, ViewState } from "../../view/view.js";
|
|
7
|
+
export type TotalInfo = {
|
|
8
|
+
kind: typeof TotalKind.exact;
|
|
9
|
+
value: number;
|
|
10
|
+
} | {
|
|
11
|
+
kind: typeof TotalKind.estimate;
|
|
12
|
+
value: number;
|
|
13
|
+
} | {
|
|
14
|
+
kind: typeof TotalKind.none;
|
|
15
|
+
};
|
|
16
|
+
export type ResourceListState<T, F> = {
|
|
17
|
+
rows: T[];
|
|
18
|
+
total: TotalInfo;
|
|
19
|
+
state: ViewState<F>;
|
|
20
|
+
setState(patch: Partial<ViewState<F>>): void;
|
|
21
|
+
isLoading: boolean;
|
|
22
|
+
isFetching: boolean;
|
|
23
|
+
error: ServiceError | undefined;
|
|
24
|
+
refetch(): void;
|
|
25
|
+
};
|
|
26
|
+
export type ResourceListOptions<T, F, Id> = {
|
|
27
|
+
view?: View<T, F, Id>;
|
|
28
|
+
filter?: Partial<F>;
|
|
29
|
+
enabled?: boolean;
|
|
30
|
+
};
|
|
31
|
+
export declare function useResourceList<T, Id, F>(resource: Resource<T, Id, F>, options?: ResourceListOptions<T, F, Id>): ResourceListState<T, F>;
|
|
32
|
+
export type ResourceState<T> = {
|
|
33
|
+
row: T | undefined;
|
|
34
|
+
version: Version | undefined;
|
|
35
|
+
isLoading: boolean;
|
|
36
|
+
error: ServiceError | undefined;
|
|
37
|
+
refetch(): void;
|
|
38
|
+
};
|
|
39
|
+
/**
|
|
40
|
+
* One record. With `paths` (the fields a record's page shows), its relations come with it: the related records are
|
|
41
|
+
* read in one request per relation, through the cache, and the plain record stays cached on its own.
|
|
42
|
+
*/
|
|
43
|
+
export declare function useResource<T, Id, F>(resource: Resource<T, Id, F>, id: Id | undefined, options?: {
|
|
44
|
+
paths?: readonly string[];
|
|
45
|
+
}): ResourceState<T>;
|
|
46
|
+
/**
|
|
47
|
+
* Refreshes every query of a resource and of the resources that show its records through a relation (orders show
|
|
48
|
+
* their customer, so a customer's change refreshes the orders lists too).
|
|
49
|
+
*/
|
|
50
|
+
export declare function invalidateResource(client: QueryClient, resource: {
|
|
51
|
+
key?: string;
|
|
52
|
+
queryKey: readonly unknown[];
|
|
53
|
+
}): Promise<undefined>;
|
|
54
|
+
export declare function writeRow<T, Id, F>(client: QueryClient, resource: Resource<T, Id, F>, row: T): void;
|
|
55
|
+
export type ResourceMutations<T, Id, F> = {
|
|
56
|
+
create(input: Partial<T>): Promise<T>;
|
|
57
|
+
update(id: Id, patch: Partial<T>, options?: {
|
|
58
|
+
version?: Version | undefined;
|
|
59
|
+
}): Promise<T>;
|
|
60
|
+
remove(target: Target<Id, F>): Promise<void>;
|
|
61
|
+
restore(target: Target<Id, F>): Promise<void>;
|
|
62
|
+
};
|
|
63
|
+
export declare function useResourceMutations<T, Id, F>(resource: Resource<T, Id, F>): ResourceMutations<T, Id, F>;
|
|
64
|
+
export declare function useResourceCount<T, Id, F>(resource: Resource<T, Id, F>, filter: Partial<F>, options?: {
|
|
65
|
+
refetchInterval?: number | undefined;
|
|
66
|
+
}): {
|
|
67
|
+
count: number | undefined;
|
|
68
|
+
error: ServiceError | undefined;
|
|
69
|
+
};
|