@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.
Files changed (113) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +68 -2
  3. package/dist/action/action.d.ts +74 -0
  4. package/dist/action/action.js +106 -0
  5. package/dist/cli/cli.d.ts +2 -0
  6. package/dist/cli/cli.js +51 -0
  7. package/dist/cli/routes.d.ts +17 -0
  8. package/dist/cli/routes.js +36 -0
  9. package/dist/core/assume.d.ts +1 -0
  10. package/dist/core/assume.js +8 -0
  11. package/dist/core/constants.d.ts +302 -0
  12. package/dist/core/constants.js +156 -0
  13. package/dist/core/contracts.d.ts +100 -0
  14. package/dist/core/contracts.js +3 -0
  15. package/dist/core/data-labels.d.ts +196 -0
  16. package/dist/core/data-labels.js +345 -0
  17. package/dist/core/errors.d.ts +46 -0
  18. package/dist/core/errors.js +166 -0
  19. package/dist/core/guards.d.ts +9 -0
  20. package/dist/core/guards.js +14 -0
  21. package/dist/core/refusal.d.ts +30 -0
  22. package/dist/core/refusal.js +53 -0
  23. package/dist/draft/draft.d.ts +36 -0
  24. package/dist/draft/draft.js +87 -0
  25. package/dist/export/csv.d.ts +25 -0
  26. package/dist/export/csv.js +59 -0
  27. package/dist/import/csv-parse.d.ts +11 -0
  28. package/dist/import/csv-parse.js +70 -0
  29. package/dist/import/import.d.ts +102 -0
  30. package/dist/import/import.js +263 -0
  31. package/dist/index.d.ts +31 -0
  32. package/dist/index.js +30 -0
  33. package/dist/navigation/nav.d.ts +119 -0
  34. package/dist/navigation/nav.js +278 -0
  35. package/dist/navigation/router.d.ts +81 -0
  36. package/dist/navigation/router.js +249 -0
  37. package/dist/navigation/shortcuts.d.ts +37 -0
  38. package/dist/navigation/shortcuts.js +93 -0
  39. package/dist/next/index.d.ts +3 -0
  40. package/dist/next/index.js +3 -0
  41. package/dist/next/screen-hydration.d.ts +12 -0
  42. package/dist/next/screen-hydration.js +26 -0
  43. package/dist/next/screen.d.ts +25 -0
  44. package/dist/next/screen.js +44 -0
  45. package/dist/next/server/handler.d.ts +39 -0
  46. package/dist/next/server/handler.js +190 -0
  47. package/dist/next/server/index.d.ts +5 -0
  48. package/dist/next/server/index.js +5 -0
  49. package/dist/next/server/page.d.ts +57 -0
  50. package/dist/next/server/page.js +103 -0
  51. package/dist/next/server/prefetch.d.ts +29 -0
  52. package/dist/next/server/prefetch.js +97 -0
  53. package/dist/next/server/session.d.ts +12 -0
  54. package/dist/next/server/session.js +10 -0
  55. package/dist/next/use-next-router.d.ts +21 -0
  56. package/dist/next/use-next-router.js +104 -0
  57. package/dist/react/data-layer.d.ts +31 -0
  58. package/dist/react/data-layer.js +31 -0
  59. package/dist/react/hooks/use-action.d.ts +12 -0
  60. package/dist/react/hooks/use-action.js +67 -0
  61. package/dist/react/hooks/use-better-auth.d.ts +12 -0
  62. package/dist/react/hooks/use-better-auth.js +11 -0
  63. package/dist/react/hooks/use-draft.d.ts +5 -0
  64. package/dist/react/hooks/use-draft.js +17 -0
  65. package/dist/react/hooks/use-nav.d.ts +17 -0
  66. package/dist/react/hooks/use-nav.js +34 -0
  67. package/dist/react/hooks/use-resource.d.ts +69 -0
  68. package/dist/react/hooks/use-resource.js +218 -0
  69. package/dist/react/hooks/use-view.d.ts +6 -0
  70. package/dist/react/hooks/use-view.js +24 -0
  71. package/dist/react/index.d.ts +8 -0
  72. package/dist/react/index.js +8 -0
  73. package/dist/react/keys.d.ts +51 -0
  74. package/dist/react/keys.js +67 -0
  75. package/dist/resource/form-schema.d.ts +11 -0
  76. package/dist/resource/form-schema.js +51 -0
  77. package/dist/resource/relations.d.ts +99 -0
  78. package/dist/resource/relations.js +194 -0
  79. package/dist/resource/resource-relations.d.ts +44 -0
  80. package/dist/resource/resource-relations.js +141 -0
  81. package/dist/resource/resource-schema.d.ts +9 -0
  82. package/dist/resource/resource-schema.js +73 -0
  83. package/dist/resource/resource-types.d.ts +281 -0
  84. package/dist/resource/resource-types.js +1 -0
  85. package/dist/resource/resource.d.ts +11 -0
  86. package/dist/resource/resource.js +354 -0
  87. package/dist/resource/schema.d.ts +57 -0
  88. package/dist/resource/schema.js +115 -0
  89. package/dist/services/from-page-source.d.ts +15 -0
  90. package/dist/services/from-page-source.js +27 -0
  91. package/dist/services/memory-query.d.ts +8 -0
  92. package/dist/services/memory-query.js +165 -0
  93. package/dist/services/memory-service.d.ts +33 -0
  94. package/dist/services/memory-service.js +291 -0
  95. package/dist/services/rest-service.d.ts +62 -0
  96. package/dist/services/rest-service.js +220 -0
  97. package/dist/services/rng.d.ts +9 -0
  98. package/dist/services/rng.js +22 -0
  99. package/dist/services/spring-service.d.ts +58 -0
  100. package/dist/services/spring-service.js +132 -0
  101. package/dist/session/better-auth.d.ts +83 -0
  102. package/dist/session/better-auth.js +86 -0
  103. package/dist/session/session.d.ts +45 -0
  104. package/dist/session/session.js +36 -0
  105. package/dist/view/preferences.d.ts +35 -0
  106. package/dist/view/preferences.js +93 -0
  107. package/dist/view/view-types.d.ts +122 -0
  108. package/dist/view/view-types.js +1 -0
  109. package/dist/view/view-url.d.ts +7 -0
  110. package/dist/view/view-url.js +54 -0
  111. package/dist/view/view.d.ts +4 -0
  112. package/dist/view/view.js +392 -0
  113. package/package.json +85 -4
@@ -0,0 +1,93 @@
1
+ import { isRecord, isString } from "../core/guards.js";
2
+ const modifierOrder = ["mod", "ctrl", "meta", "alt", "shift"];
3
+ /** The keys in one spelling: lower case, modifiers in a fixed order, `cmd` as `meta`, steps one space apart. */
4
+ export function normalizeShortcut(keys) {
5
+ return keys
6
+ .trim()
7
+ .split(/\s+/u)
8
+ .map((step) => {
9
+ const parts = step
10
+ .toLowerCase()
11
+ .split("+")
12
+ .filter((part) => part !== "")
13
+ .map((part) => (part === "cmd" || part === "command" ? "meta" : part === "control" ? "ctrl" : part));
14
+ const key = parts.at(-1) ?? "";
15
+ const modifiers = parts.slice(0, -1).toSorted((a, b) => modifierOrder.indexOf(a) - modifierOrder.indexOf(b));
16
+ return [...modifiers, key].join("+");
17
+ })
18
+ .join(" ");
19
+ }
20
+ const overlaps = (a, b) => a === undefined || b === undefined || a === b;
21
+ function collides(a, b) {
22
+ if (a === b)
23
+ return true;
24
+ const [first] = a.split(" ");
25
+ const [other] = b.split(" ");
26
+ return a.includes(" ") !== b.includes(" ") && (a === other || b === first);
27
+ }
28
+ /**
29
+ * Shortcuts that collide where they can both run: the same keys, or a key that starts another's sequence (`g`
30
+ * against `g c`), in the same scope or with one of them global. One owner registering twice is no conflict.
31
+ */
32
+ export function shortcutConflicts(entries) {
33
+ const conflicts = [];
34
+ const seen = new Set();
35
+ for (const [index, entry] of entries.entries()) {
36
+ const keys = normalizeShortcut(entry.keys);
37
+ const ids = [entry.id];
38
+ for (const other of entries.slice(index + 1)) {
39
+ if (other.id === entry.id || ids.includes(other.id))
40
+ continue;
41
+ if (overlaps(entry.scope, other.scope) && collides(keys, normalizeShortcut(other.keys)))
42
+ ids.push(other.id);
43
+ }
44
+ const key = `${keys}|${entry.scope ?? ""}`;
45
+ if (ids.length > 1 && !seen.has(key)) {
46
+ seen.add(key);
47
+ conflicts.push({ keys, scope: entry.scope, ids });
48
+ }
49
+ }
50
+ return conflicts;
51
+ }
52
+ /** Tracks the shortcuts registered now and reports a new one that collides with one already there. */
53
+ export function createShortcutRegistry(options = {}) {
54
+ const current = new Set();
55
+ return {
56
+ add(entry) {
57
+ const own = { ...entry };
58
+ const before = shortcutConflicts([...current]).length;
59
+ current.add(own);
60
+ const found = shortcutConflicts([...current]);
61
+ if (found.length > before) {
62
+ for (const conflict of found)
63
+ if (conflict.ids.includes(own.id))
64
+ options.onConflict?.(conflict);
65
+ }
66
+ return () => {
67
+ current.delete(own);
68
+ };
69
+ },
70
+ entries: () => [...current],
71
+ conflicts: () => shortcutConflicts([...current]),
72
+ };
73
+ }
74
+ function inProduction() {
75
+ const runtime = Reflect.get(globalThis, "process");
76
+ return isRecord(runtime) && isRecord(runtime.env) && isString(runtime.env.NODE_ENV)
77
+ ? runtime.env.NODE_ENV === "production"
78
+ : false;
79
+ }
80
+ /** A warning for the developer, in the console, outside production builds. */
81
+ export function warnInDevelopment(message) {
82
+ if (inProduction())
83
+ return;
84
+ // oxlint-disable-next-line no-console -- Spec: conflicts and slow reads are reported to the developer in the console
85
+ console.warn(message);
86
+ }
87
+ /** Says which owners collide, in the console, outside production builds. */
88
+ export function warnShortcutConflict(conflict) {
89
+ const where = conflict.scope === undefined ? "" : ` in ${conflict.scope}`;
90
+ warnInDevelopment(`Shortcut "${conflict.keys}"${where} is taken by ${conflict.ids.map((id) => `"${id}"`).join(" and ")}.`);
91
+ }
92
+ /** The app's registered shortcuts: `NavShell`, `NavCommand` and the resource blocks add theirs here. */
93
+ export const appShortcuts = createShortcutRegistry({ onConflict: warnShortcutConflict });
@@ -0,0 +1,3 @@
1
+ export { useNextRouter, type NextAppRouter, type NextRouterOptions } from "./use-next-router.js";
2
+ export { isRecordScreen, navScreen, pathOfParams, resourceScreen, type NextScreen, type RouteParams } from "./screen.js";
3
+ export { ScreenHydration, type ScreenHydrationProps } from "./screen-hydration.js";
@@ -0,0 +1,3 @@
1
+ export { useNextRouter } from "./use-next-router.js";
2
+ export { isRecordScreen, navScreen, pathOfParams, resourceScreen } from "./screen.js";
3
+ export { ScreenHydration } from "./screen-hydration.js";
@@ -0,0 +1,12 @@
1
+ import { type DehydratedState } from "@tanstack/react-query";
2
+ import { type ReactNode } from "react";
3
+ export type ScreenHydrationProps = {
4
+ state: DehydratedState;
5
+ children?: ReactNode;
6
+ };
7
+ /**
8
+ * `HydrationBoundary` that also fills, during render, the queries already in the cache with no data yet. A layout
9
+ * above the page creates them (a breadcrumb asking for the record's title), and TanStack would only fill them in an
10
+ * effect: the server render and the first client render would show a spinner instead of the record.
11
+ */
12
+ export declare function ScreenHydration({ state, children }: ScreenHydrationProps): import("react").JSX.Element;
@@ -0,0 +1,26 @@
1
+ "use client";
2
+ import { jsx as _jsx } from "react/jsx-runtime";
3
+ import { hydrate, HydrationBoundary, QueryClientContext } from "@tanstack/react-query";
4
+ import { use, useMemo } from "react";
5
+ /**
6
+ * `HydrationBoundary` that also fills, during render, the queries already in the cache with no data yet. A layout
7
+ * above the page creates them (a breadcrumb asking for the record's title), and TanStack would only fill them in an
8
+ * effect: the server render and the first client render would show a spinner instead of the record.
9
+ */
10
+ export function ScreenHydration({ state, children }) {
11
+ const client = use(QueryClientContext);
12
+ if (!client)
13
+ throw new Error("A Next.js page from navPage or resourcePage renders inside the DataLayer: put it in a layout above.");
14
+ const ready = useMemo(() => {
15
+ const cache = client.getQueryCache();
16
+ const waiting = state.queries.filter((query) => {
17
+ const existing = cache.get(query.queryHash);
18
+ return existing !== undefined && existing.state.data === undefined;
19
+ });
20
+ // Perf: TanStack's boundary hydrates the new queries; only those it would leave empty until an effect go here.
21
+ if (waiting.length > 0)
22
+ hydrate(client, { mutations: [], queries: waiting });
23
+ return state;
24
+ }, [client, state]);
25
+ return _jsx(HydrationBoundary, { state: ready, children: children });
26
+ }
@@ -0,0 +1,25 @@
1
+ import { ResourceScreen } from "../core/constants.js";
2
+ import type { Nav } from "../navigation/nav.js";
3
+ import type { AnyResource } from "../resource/resource.js";
4
+ /** The screen a path shows: one of a resource's four, with the record's id on a detail or edit path. */
5
+ export type NextScreen = {
6
+ resource: AnyResource;
7
+ screen: ResourceScreen;
8
+ /** The id as the resource parses it (a number for numeric ids). */
9
+ id: unknown;
10
+ /** The path inside the app, without the mount `base`: `/customers/7/edit`. */
11
+ pathname: string;
12
+ /** A record's `hasMany` tab on its path, `orders` in `/customers/7/orders`. */
13
+ tab?: string;
14
+ };
15
+ export type RouteParams = Record<string, string | readonly string[] | undefined>;
16
+ export declare function isSegments(value: string | readonly string[] | undefined): value is readonly string[];
17
+ /**
18
+ * The path a catch-all route's params stand for: the first array param (`[[...path]]`, `[[...slug]]`) joined under
19
+ * `prefix`. An empty optional catch-all is no param at all, so the path is the prefix itself.
20
+ */
21
+ export declare function pathOfParams(params: RouteParams, prefix?: string): string;
22
+ export declare function resourceScreen(resource: AnyResource, pathname: string): NextScreen | undefined;
23
+ /** The resource screen of the manifest a path shows, or undefined when no resource of it has that path. */
24
+ export declare function navScreen<Route>(nav: Nav<Route>, pathname: string): NextScreen | undefined;
25
+ export declare function isRecordScreen(screen: NextScreen): boolean;
@@ -0,0 +1,44 @@
1
+ import { ResourceScreen } from "../core/constants.js";
2
+ function trimBase(base) {
3
+ return (base ?? "").replace(/\/+$/u, "");
4
+ }
5
+ export function isSegments(value) {
6
+ return Array.isArray(value);
7
+ }
8
+ function decoded(segment) {
9
+ try {
10
+ return decodeURIComponent(segment);
11
+ }
12
+ catch {
13
+ return segment;
14
+ }
15
+ }
16
+ /**
17
+ * The path a catch-all route's params stand for: the first array param (`[[...path]]`, `[[...slug]]`) joined under
18
+ * `prefix`. An empty optional catch-all is no param at all, so the path is the prefix itself.
19
+ */
20
+ export function pathOfParams(params, prefix = "") {
21
+ const segments = Object.values(params).find(isSegments) ?? [];
22
+ const joined = segments.map((segment) => encodeURIComponent(decoded(segment))).join("/");
23
+ const path = `${trimBase(prefix)}/${joined}`.replace(/\/+$/u, "");
24
+ return path === "" ? "/" : path;
25
+ }
26
+ export function resourceScreen(resource, pathname) {
27
+ const match = resource.match(pathname);
28
+ if (!match)
29
+ return undefined;
30
+ const id = match.id === undefined ? undefined : resource.parseId(match.id);
31
+ return { resource, screen: match.screen, id, pathname, ...(match.tab === undefined ? {} : { tab: match.tab }) };
32
+ }
33
+ /** The resource screen of the manifest a path shows, or undefined when no resource of it has that path. */
34
+ export function navScreen(nav, pathname) {
35
+ for (const resource of nav.resources()) {
36
+ const screen = resourceScreen(resource, pathname);
37
+ if (screen)
38
+ return screen;
39
+ }
40
+ return undefined;
41
+ }
42
+ export function isRecordScreen(screen) {
43
+ return screen.screen === ResourceScreen.detail || screen.screen === ResourceScreen.edit;
44
+ }
@@ -0,0 +1,39 @@
1
+ import type { Query } from "../../core/contracts.js";
2
+ import { type ServiceError } from "../../core/errors.js";
3
+ import { type AnyResource } from "../../resource/resource.js";
4
+ import type { Session } from "../../session/session.js";
5
+ import type { RouteParams } from "../screen.js";
6
+ import type { AnyService } from "./prefetch.js";
7
+ /** The second argument Next.js passes a route handler. */
8
+ export type NextRouteContext = {
9
+ params: Promise<RouteParams>;
10
+ };
11
+ export type RouteHandler = (request: Request, context: NextRouteContext) => Promise<Response>;
12
+ export type ResourceHandler = {
13
+ GET: RouteHandler;
14
+ POST: RouteHandler;
15
+ PATCH: RouteHandler;
16
+ PUT: RouteHandler;
17
+ DELETE: RouteHandler;
18
+ };
19
+ export type ResourceHandlerOptions = {
20
+ /** The backend service; the resource's own by default. */
21
+ service?: AnyService;
22
+ /** The request's session, as `nextSession(…)` gives it. */
23
+ session?: () => Session | undefined | Promise<Session | undefined>;
24
+ /** The most rows one page may ask for. Default: the service's `maxPageSize`, or 100. */
25
+ maxPageSize?: number;
26
+ };
27
+ /**
28
+ * A `ServiceError` as an RFC 9457 problem: the status of its kind, the message as `detail`, field errors as
29
+ * `errors[{ field, message, code }]` and a conflict's `current` row. `restService` reads it back into the same error.
30
+ */
31
+ export declare function problemResponse(error: ServiceError): Response;
32
+ /** The `Query` a `restService` list request carries: filters by their declared kind, `q`, `sort`, `size`, `page`. */
33
+ export declare function queryOfSearch(resource: AnyResource, params: URLSearchParams, maxPageSize?: number): Query<unknown>;
34
+ /**
35
+ * Route handlers (`app/api/customers/[[...id]]/route.ts`) that serve a service the way `restService` calls it: `GET`,
36
+ * `POST`, `PATCH`/`PUT` (`If-Match` is the version), `DELETE`. Each asks the resource's `can` with the request's
37
+ * session first; every error goes back as a problem `restService` reads into the same `ServiceError`.
38
+ */
39
+ export declare function resourceHandler(resource: AnyResource, options?: ResourceHandlerOptions): ResourceHandler;
@@ -0,0 +1,190 @@
1
+ import { FilterKind, ResourceAction, ServiceErrorKind, SortDirection, TargetKind } from "../../core/constants.js";
2
+ import { ServiceFailure, isServiceError, serviceError, toServiceError } from "../../core/errors.js";
3
+ import { isOneOf, isString, valuesOf } from "../../core/guards.js";
4
+ import { searchKey } from "../../resource/resource.js";
5
+ const statusOf = {
6
+ [ServiceErrorKind.validation]: 422,
7
+ [ServiceErrorKind.conflict]: 409,
8
+ [ServiceErrorKind.forbidden]: 403,
9
+ [ServiceErrorKind.notFound]: 404,
10
+ [ServiceErrorKind.network]: 502,
11
+ [ServiceErrorKind.server]: 500,
12
+ [ServiceErrorKind.aborted]: 499,
13
+ };
14
+ const reserved = new Set(["page", "size", "sort", searchKey, "except", "ids", "include"]);
15
+ const sortDirections = valuesOf(SortDirection);
16
+ function fail(kind, message) {
17
+ throw new ServiceFailure(serviceError(kind, message));
18
+ }
19
+ /**
20
+ * A `ServiceError` as an RFC 9457 problem: the status of its kind, the message as `detail`, field errors as
21
+ * `errors[{ field, message, code }]` and a conflict's `current` row. `restService` reads it back into the same error.
22
+ */
23
+ export function problemResponse(error) {
24
+ const status = error.status ?? statusOf[error.kind];
25
+ const body = {
26
+ type: "about:blank",
27
+ title: error.kind,
28
+ status,
29
+ detail: error.message,
30
+ ...(error.fields
31
+ ? { errors: error.fields.map((field) => ({ field: field.path, message: field.message, code: field.code })) }
32
+ : {}),
33
+ ...(error.kind === ServiceErrorKind.conflict && error.current !== undefined ? { current: error.current } : {}),
34
+ };
35
+ return Response.json(body, { status, headers: { "content-type": "application/problem+json" } });
36
+ }
37
+ function safeError(error) {
38
+ if (error instanceof ServiceFailure || isServiceError(error))
39
+ return toServiceError(error);
40
+ const normalized = toServiceError(error);
41
+ if (normalized.kind === ServiceErrorKind.aborted)
42
+ return normalized;
43
+ // Security: an unexpected exception's message can name tables, paths or queries; the client gets a generic one.
44
+ return serviceError(ServiceErrorKind.server, "Something went wrong.");
45
+ }
46
+ function parseJson(raw) {
47
+ try {
48
+ return JSON.parse(raw);
49
+ }
50
+ catch {
51
+ return undefined;
52
+ }
53
+ }
54
+ function sortOf(values) {
55
+ return values.flatMap((value) => {
56
+ const at = value.lastIndexOf(",");
57
+ const direction = value.slice(at + 1);
58
+ return at > 0 && isOneOf(sortDirections, direction) ? [{ field: value.slice(0, at), direction }] : [];
59
+ });
60
+ }
61
+ function wholeNumber(raw, fallback) {
62
+ const value = Number(raw ?? "");
63
+ return Number.isInteger(value) && value > 0 ? value : fallback;
64
+ }
65
+ /** The `Query` a `restService` list request carries: filters by their declared kind, `q`, `sort`, `size`, `page`. */
66
+ export function queryOfSearch(resource, params, maxPageSize = 100) {
67
+ const kinds = new Map(resource.filters().map((filter) => [filter.key, filter.kind]));
68
+ const filter = {};
69
+ for (const name of new Set(params.keys())) {
70
+ if (reserved.has(name))
71
+ continue;
72
+ const values = params.getAll(name);
73
+ const first = values[0] ?? "";
74
+ const kind = kinds.get(name);
75
+ if (kind === FilterKind.multiSelect)
76
+ filter[name] = values;
77
+ else if (kind === FilterKind.boolean)
78
+ filter[name] = first === "true";
79
+ else if (kind === FilterKind.dateRange || kind === FilterKind.numberRange)
80
+ filter[name] = parseJson(first);
81
+ else
82
+ filter[name] = values.length > 1 ? values : first;
83
+ }
84
+ const search = params.get(searchKey);
85
+ const include = (params.get("include") ?? "").split(",").filter((name) => name !== "");
86
+ return {
87
+ ...(include.length > 0 ? { include } : {}),
88
+ filter: resource.filterOf(filter),
89
+ search: search === null || search === "" ? undefined : search,
90
+ sort: sortOf(params.getAll("sort")),
91
+ size: Math.min(wholeNumber(params.get("size"), 25), maxPageSize),
92
+ position: { page: wholeNumber(params.get("page"), 1) },
93
+ };
94
+ }
95
+ async function bodyOf(request) {
96
+ const raw = await request.text();
97
+ const body = raw === "" ? undefined : parseJson(raw);
98
+ if (body === undefined)
99
+ fail(ServiceErrorKind.validation, "The request body isn't JSON.");
100
+ return body;
101
+ }
102
+ const ctx = (request, session) => ({ signal: request.signal, session });
103
+ function idParam(params) {
104
+ const raw = Object.values(params).find((value) => value !== undefined);
105
+ const segments = raw === undefined ? [] : isString(raw) ? [raw] : raw;
106
+ if (segments.length > 1)
107
+ return null;
108
+ return segments[0];
109
+ }
110
+ /**
111
+ * Route handlers (`app/api/customers/[[...id]]/route.ts`) that serve a service the way `restService` calls it: `GET`,
112
+ * `POST`, `PATCH`/`PUT` (`If-Match` is the version), `DELETE`. Each asks the resource's `can` with the request's
113
+ * session first; every error goes back as a problem `restService` reads into the same `ServiceError`.
114
+ */
115
+ export function resourceHandler(resource, options = {}) {
116
+ const service = options.service ?? resource.service;
117
+ const maxPageSize = options.maxPageSize ?? service.capabilities.maxPageSize ?? 100;
118
+ function demand(action, row, session) {
119
+ const allowed = resource.check(action, row, session, "not allowed");
120
+ if (allowed !== true)
121
+ fail(ServiceErrorKind.forbidden, allowed.reason === "" ? "Not allowed." : allowed.reason);
122
+ }
123
+ function handle(run) {
124
+ return async (request, context) => {
125
+ try {
126
+ const id = idParam(await context.params);
127
+ if (id === null)
128
+ fail(ServiceErrorKind.notFound, "No such path.");
129
+ return await run(request, id, await options.session?.());
130
+ }
131
+ catch (error) {
132
+ return problemResponse(safeError(error));
133
+ }
134
+ };
135
+ }
136
+ async function existing(id, request, session) {
137
+ return service.get(resource.parseId(id), ctx(request, session));
138
+ }
139
+ const update = handle(async (request, id, session) => {
140
+ if (id === undefined)
141
+ fail(ServiceErrorKind.notFound, "Updates need an id.");
142
+ demand(ResourceAction.update, await existing(id, request, session), session);
143
+ const version = request.headers.get("if-match");
144
+ const row = await service.update(resource.parseId(id), await bodyOf(request), {
145
+ ...ctx(request, session),
146
+ ...(version === null ? {} : { version }),
147
+ });
148
+ return Response.json(row);
149
+ });
150
+ return {
151
+ GET: handle(async (request, id, session) => {
152
+ if (id === undefined) {
153
+ demand(ResourceAction.list, undefined, session);
154
+ const params = new URL(request.url).searchParams;
155
+ const ids = params.getAll("ids");
156
+ if (ids.length > 0) {
157
+ const parsed = ids.slice(0, maxPageSize).map((raw) => resource.parseId(raw));
158
+ const getMany = service.getMany;
159
+ const rows = getMany
160
+ ? await getMany.call(service, parsed, ctx(request, session))
161
+ : await Promise.all(parsed.map((one) => service.get(one, ctx(request, session))));
162
+ for (const row of rows)
163
+ demand(ResourceAction.get, row, session);
164
+ return Response.json(rows);
165
+ }
166
+ const query = queryOfSearch(resource, params, maxPageSize);
167
+ return Response.json(await service.list(query, ctx(request, session)));
168
+ }
169
+ const row = await existing(id, request, session);
170
+ demand(ResourceAction.get, row, session);
171
+ return Response.json(row);
172
+ }),
173
+ POST: handle(async (request, id, session) => {
174
+ if (id !== undefined)
175
+ fail(ServiceErrorKind.notFound, "Create posts to the collection.");
176
+ demand(ResourceAction.create, undefined, session);
177
+ const row = await service.create(await bodyOf(request), ctx(request, session));
178
+ return Response.json(row, { status: 201 });
179
+ }),
180
+ PATCH: update,
181
+ PUT: update,
182
+ DELETE: handle(async (request, id, session) => {
183
+ if (id === undefined)
184
+ fail(ServiceErrorKind.validation, "This route removes by id only.");
185
+ demand(ResourceAction.remove, await existing(id, request, session), session);
186
+ await service.remove({ kind: TargetKind.ids, ids: [resource.parseId(id)] }, ctx(request, session));
187
+ return new Response(null, { status: 204 });
188
+ }),
189
+ };
190
+ }
@@ -0,0 +1,5 @@
1
+ export { navPage, resourcePage, type NextMetadata, type NextPage, type NextPageOptions, type NextPageProps, type SearchParams, } from "./page.js";
2
+ export { prefetchScreen, type AnyService, type PrefetchOptions, type PrefetchResult } from "./prefetch.js";
3
+ export { nextSession, type NextRequestScope } from "./session.js";
4
+ export { problemResponse, queryOfSearch, resourceHandler, type NextRouteContext, type ResourceHandler, type ResourceHandlerOptions, type RouteHandler, } from "./handler.js";
5
+ export { navScreen, pathOfParams, resourceScreen, type NextScreen, type RouteParams } from "../screen.js";
@@ -0,0 +1,5 @@
1
+ export { navPage, resourcePage, } from "./page.js";
2
+ export { prefetchScreen } from "./prefetch.js";
3
+ export { nextSession } from "./session.js";
4
+ export { problemResponse, queryOfSearch, resourceHandler, } from "./handler.js";
5
+ export { navScreen, pathOfParams, resourceScreen } from "../screen.js";
@@ -0,0 +1,57 @@
1
+ import { QueryClient } from "@tanstack/react-query";
2
+ import { type ReactNode } from "react";
3
+ import { ResourceScreen } from "../../core/constants.js";
4
+ import { type DataLabels } from "../../core/data-labels.js";
5
+ import type { Nav } from "../../navigation/nav.js";
6
+ import type { AnyResource } from "../../resource/resource.js";
7
+ import type { Session } from "../../session/session.js";
8
+ import type { ViewOptions } from "../../view/view.js";
9
+ import { type NextScreen, type RouteParams } from "../screen.js";
10
+ import { type AnyService } from "./prefetch.js";
11
+ export type SearchParams = Record<string, string | readonly string[] | undefined>;
12
+ /** The props Next.js passes a page; `params` holds the catch-all's segments. */
13
+ export type NextPageProps = {
14
+ params: Promise<RouteParams>;
15
+ searchParams: Promise<SearchParams>;
16
+ };
17
+ export type NextMetadata = {
18
+ title?: string;
19
+ };
20
+ export type NextPageOptions = {
21
+ /** The client component that draws the screen (`NavPage` or `ResourcePage` inside a `"use client"` file). */
22
+ render: (screen: NextScreen) => ReactNode;
23
+ /** The request's session, as `nextSession(…)` gives it; services get it in their `CallContext`. */
24
+ session?: () => Session | undefined | Promise<Session | undefined>;
25
+ /** Services that answer on the server, by resource key, when the resources' own call the backend over HTTP. */
26
+ services?: Readonly<Record<string, AnyService>>;
27
+ /** The view options the client screen gives each resource (scopes, base filter, page size). */
28
+ view?: (resource: AnyResource) => ViewOptions<unknown> | undefined;
29
+ /** Where the app is mounted (`/admin`), as given to `useNextRouter`. */
30
+ base?: string;
31
+ /** The words of the default titles: `dataLabelsEn` by default. */
32
+ labels?: DataLabels;
33
+ /** A screen's title, instead of the resource's label, "New …", the record's title or "Edit …". */
34
+ title?: (screen: NextScreen, row: unknown) => string | undefined;
35
+ /** The request's query client; by default a new one per request (React's `cache`). */
36
+ client?: () => QueryClient;
37
+ };
38
+ export type NextPage = {
39
+ /** The page component: `export default page.Page`. */
40
+ Page: (props: NextPageProps) => Promise<ReactNode>;
41
+ /** `export const generateMetadata = page.generateMetadata`: the screen's title, from the same fetch as the page. */
42
+ generateMetadata: (props: NextPageProps) => Promise<NextMetadata>;
43
+ };
44
+ /**
45
+ * One optional catch-all page (`app/(admin)/[[...path]]/page.tsx`) for every resource of the manifest: it fetches the
46
+ * path's screen (list, `new`, a record, its `edit`) with the request's session and renders `render(screen)` already
47
+ * hydrated. An unknown path or record is `notFound()`; the bare root redirects to the manifest's first page.
48
+ */
49
+ export declare function navPage<Route>(nav: Nav<Route>, options: NextPageOptions): NextPage;
50
+ /**
51
+ * A Next.js page for one resource. In an optional catch-all of its own (`app/customers/[[...slug]]/page.tsx`) it
52
+ * reads the screen from the segments; in a folder per screen (`app/customers/[id]/edit/page.tsx`) give `screen`, and
53
+ * the record's id comes from the `id` param.
54
+ */
55
+ export declare function resourcePage(resource: AnyResource, options: NextPageOptions & {
56
+ screen?: ResourceScreen;
57
+ }): NextPage;
@@ -0,0 +1,103 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { dehydrate, QueryClient } from "@tanstack/react-query";
3
+ import { notFound, redirect } from "next/navigation";
4
+ import { cache } from "react";
5
+ import { ResourceScreen } from "../../core/constants.js";
6
+ import { isString } from "../../core/guards.js";
7
+ import { dataLabelsEn } from "../../core/data-labels.js";
8
+ import { isSegments, navScreen, pathOfParams, resourceScreen } from "../screen.js";
9
+ import { ScreenHydration } from "../screen-hydration.js";
10
+ import { prefetchScreen } from "./prefetch.js";
11
+ const requestClient = cache(() => new QueryClient({
12
+ defaultOptions: { queries: { staleTime: 60_000, retry: false } },
13
+ }));
14
+ function searchOf(params) {
15
+ const query = new URLSearchParams();
16
+ for (const [name, value] of Object.entries(params)) {
17
+ if (value === undefined)
18
+ continue;
19
+ for (const entry of isSegments(value) ? value : [value])
20
+ query.append(name, entry);
21
+ }
22
+ const text = query.toString();
23
+ return text === "" ? "" : `?${text}`;
24
+ }
25
+ function defaultTitle(screen, row, labels) {
26
+ const { resource } = screen;
27
+ const one = resource.label(1);
28
+ const named = row === undefined ? one : resource.title(row);
29
+ if (screen.screen === ResourceScreen.list)
30
+ return resource.label(2);
31
+ if (screen.screen === ResourceScreen.create)
32
+ return labels.create(one);
33
+ if (screen.screen === ResourceScreen.edit)
34
+ return `${labels.edit} ${named}`;
35
+ return named;
36
+ }
37
+ function screenPage(resolve, options) {
38
+ const clientOf = options.client ?? requestClient;
39
+ const labels = options.labels ?? dataLabelsEn;
40
+ const base = (options.base ?? "").replace(/\/+$/u, "");
41
+ async function load(props) {
42
+ const screen = resolve(await props.params);
43
+ if (screen && "home" in screen && screen.home !== undefined)
44
+ redirect(`${base}${screen.home}`);
45
+ if (!screen || "home" in screen)
46
+ notFound();
47
+ const session = await options.session?.();
48
+ const client = clientOf();
49
+ const result = await prefetchScreen(client, screen, {
50
+ session,
51
+ services: options.services,
52
+ search: searchOf(await props.searchParams),
53
+ view: options.view?.(screen.resource),
54
+ });
55
+ if (result.notFound)
56
+ notFound();
57
+ return { screen, client, row: result.row };
58
+ }
59
+ return {
60
+ async Page(props) {
61
+ const { screen, client } = await load(props);
62
+ return _jsx(ScreenHydration, { state: dehydrate(client), children: options.render(screen) });
63
+ },
64
+ async generateMetadata(props) {
65
+ const { screen, row } = await load(props);
66
+ return { title: options.title?.(screen, row) ?? defaultTitle(screen, row, labels) };
67
+ },
68
+ };
69
+ }
70
+ /**
71
+ * One optional catch-all page (`app/(admin)/[[...path]]/page.tsx`) for every resource of the manifest: it fetches the
72
+ * path's screen (list, `new`, a record, its `edit`) with the request's session and renders `render(screen)` already
73
+ * hydrated. An unknown path or record is `notFound()`; the bare root redirects to the manifest's first page.
74
+ */
75
+ export function navPage(nav, options) {
76
+ return screenPage((params) => {
77
+ const pathname = pathOfParams(params);
78
+ return pathname === "/" ? { home: nav.visibleItems()[0]?.to } : navScreen(nav, pathname);
79
+ }, options);
80
+ }
81
+ /**
82
+ * A Next.js page for one resource. In an optional catch-all of its own (`app/customers/[[...slug]]/page.tsx`) it
83
+ * reads the screen from the segments; in a folder per screen (`app/customers/[id]/edit/page.tsx`) give `screen`, and
84
+ * the record's id comes from the `id` param.
85
+ */
86
+ export function resourcePage(resource, options) {
87
+ const fixed = options.screen;
88
+ return screenPage((params) => {
89
+ if (fixed === undefined)
90
+ return resourceScreen(resource, pathOfParams(params, resource.paths.list()));
91
+ const raw = params.id;
92
+ const id = isSegments(raw) ? raw[0] : raw;
93
+ if (fixed === ResourceScreen.list)
94
+ return resourceScreen(resource, resource.paths.list());
95
+ if (fixed === ResourceScreen.create)
96
+ return resourceScreen(resource, resource.paths.create());
97
+ if (!isString(id))
98
+ return undefined;
99
+ const parsed = resource.parseId(id);
100
+ const path = fixed === ResourceScreen.edit ? resource.paths.edit(parsed) : resource.paths.detail(parsed);
101
+ return resourceScreen(resource, path);
102
+ }, options);
103
+ }
@@ -0,0 +1,29 @@
1
+ import type { QueryClient } from "@tanstack/react-query";
2
+ import type { ResourceService } from "../../core/contracts.js";
3
+ import type { Session } from "../../session/session.js";
4
+ import { type ViewOptions } from "../../view/view.js";
5
+ import type { NextScreen } from "../screen.js";
6
+ export type AnyService = ResourceService<any, any, any, any, any>;
7
+ export type PrefetchOptions = {
8
+ session?: Session | undefined;
9
+ /** The service that answers on the server, when the resource's own calls the backend over HTTP. */
10
+ service?: AnyService | undefined;
11
+ /** Services that answer on the server for the related resources too, by key; their own otherwise. */
12
+ services?: Readonly<Record<string, AnyService>> | undefined;
13
+ /** The page's query string: `?status=blocked&page=2`. */
14
+ search?: string;
15
+ /** The view options the client screen uses (scopes, base filter, page size), so both ask for the same page. */
16
+ view?: ViewOptions<unknown> | undefined;
17
+ };
18
+ export type PrefetchResult = {
19
+ /** The record of a detail or edit screen. */
20
+ row?: unknown;
21
+ /** True when the record doesn't exist: the service answered `ServiceErrorKind.notFound`. */
22
+ notFound: boolean;
23
+ };
24
+ /**
25
+ * Fetches a screen's first queries into `client` under the keys the blocks read: a list's first page with its
26
+ * relations, or a record with its relations and its `hasMany` tab's first page. A failed list stays out for the
27
+ * client to show; a missing record is `notFound`; a screen the session may not see fetches nothing.
28
+ */
29
+ export declare function prefetchScreen(client: QueryClient, screen: NextScreen, options?: PrefetchOptions): Promise<PrefetchResult>;