@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,218 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { keepPreviousData, useQuery, useQueryClient } from "@tanstack/react-query";
|
|
3
|
+
import { useCallback, useMemo, useState, useSyncExternalStore } from "react";
|
|
4
|
+
import { assumeType } from "../../core/assume.js";
|
|
5
|
+
import { ResourceAction, ServiceErrorKind, TotalKind } from "../../core/constants.js";
|
|
6
|
+
import { ServiceFailure, serviceError, toServiceError } from "../../core/errors.js";
|
|
7
|
+
import { isRecord } from "../../core/guards.js";
|
|
8
|
+
import { dependentsOf } from "../../resource/resource.js";
|
|
9
|
+
import { includeOf, resolveRelations } from "../../resource/relations.js";
|
|
10
|
+
import { warnInDevelopment } from "../../navigation/shortcuts.js";
|
|
11
|
+
import { useDataLayer } from "../data-layer.js";
|
|
12
|
+
import { resourceCountKey, resourceDetailKey, resourceDetailWithKey, resourcePageKey } from "../keys.js";
|
|
13
|
+
const pageMeta = { serverData: "page" };
|
|
14
|
+
const resourceMeta = { serverData: "resource" };
|
|
15
|
+
function totalOf(page) {
|
|
16
|
+
if (page?.total !== undefined)
|
|
17
|
+
return { kind: TotalKind.exact, value: page.total };
|
|
18
|
+
if (page?.totalEstimate !== undefined)
|
|
19
|
+
return { kind: TotalKind.estimate, value: page.totalEstimate };
|
|
20
|
+
return { kind: TotalKind.none };
|
|
21
|
+
}
|
|
22
|
+
const toError = (error) => error === null || error === undefined ? undefined : toServiceError(error);
|
|
23
|
+
const emptyFilter = {};
|
|
24
|
+
export function useResourceList(resource, options = {}) {
|
|
25
|
+
const { session } = useDataLayer();
|
|
26
|
+
const [own, setOwn] = useState(() => ({
|
|
27
|
+
filter: {},
|
|
28
|
+
search: "",
|
|
29
|
+
sort: resource.defaultSort,
|
|
30
|
+
page: 1,
|
|
31
|
+
size: 25,
|
|
32
|
+
}));
|
|
33
|
+
const view = options.view;
|
|
34
|
+
const subscribe = useCallback((listener) => view?.subscribe(listener) ?? (() => { }), [view]);
|
|
35
|
+
const viewed = useSyncExternalStore(subscribe, () => view?.getState(), () => view?.getState());
|
|
36
|
+
const state = viewed ?? own;
|
|
37
|
+
const fixed = options.filter ?? emptyFilter;
|
|
38
|
+
const query = useMemo(() => {
|
|
39
|
+
const base = view ? view.filter() : state.filter;
|
|
40
|
+
const filter = resource.filterOf({ ...base, ...fixed });
|
|
41
|
+
return {
|
|
42
|
+
filter,
|
|
43
|
+
search: state.search === "" ? undefined : state.search,
|
|
44
|
+
sort: state.sort,
|
|
45
|
+
size: state.size,
|
|
46
|
+
position: { page: state.page },
|
|
47
|
+
};
|
|
48
|
+
}, [resource, view, state, fixed]);
|
|
49
|
+
const result = useQuery({
|
|
50
|
+
queryKey: resourcePageKey(resource, query),
|
|
51
|
+
queryFn: ({ signal }) => resource.service.list(query, { signal, session }),
|
|
52
|
+
enabled: options.enabled !== false,
|
|
53
|
+
staleTime: resource.staleTime,
|
|
54
|
+
placeholderData: keepPreviousData,
|
|
55
|
+
meta: pageMeta,
|
|
56
|
+
});
|
|
57
|
+
const setState = useCallback((patch) => {
|
|
58
|
+
if (view)
|
|
59
|
+
view.setState(patch);
|
|
60
|
+
else
|
|
61
|
+
setOwn((previous) => ({ ...previous, ...patch }));
|
|
62
|
+
}, [view]);
|
|
63
|
+
const { refetch } = result;
|
|
64
|
+
return {
|
|
65
|
+
rows: result.data?.items ?? [],
|
|
66
|
+
total: totalOf(result.data),
|
|
67
|
+
state,
|
|
68
|
+
setState,
|
|
69
|
+
isLoading: result.isPending,
|
|
70
|
+
isFetching: result.isFetching,
|
|
71
|
+
error: toError(result.error),
|
|
72
|
+
refetch: () => void refetch(),
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* One record. With `paths` (the fields a record's page shows), its relations come with it: the related records are
|
|
77
|
+
* read in one request per relation, through the cache, and the plain record stays cached on its own.
|
|
78
|
+
*/
|
|
79
|
+
export function useResource(resource, id, options = {}) {
|
|
80
|
+
const { session } = useDataLayer();
|
|
81
|
+
const client = useQueryClient();
|
|
82
|
+
const key = id === undefined ? "" : resource.idKey(id);
|
|
83
|
+
const include = includeOf(resource.relations, options.paths ?? []);
|
|
84
|
+
const readPlain = (signal) => client.fetchQuery({
|
|
85
|
+
queryKey: resourceDetailKey(resource, key),
|
|
86
|
+
queryFn: () => {
|
|
87
|
+
if (id === undefined)
|
|
88
|
+
return Promise.reject(new TypeError("No id."));
|
|
89
|
+
return resource.service.get(id, { signal, session });
|
|
90
|
+
},
|
|
91
|
+
staleTime: resource.staleTime,
|
|
92
|
+
});
|
|
93
|
+
const result = useQuery({
|
|
94
|
+
queryKey: resourceDetailWithKey(resource, key, include),
|
|
95
|
+
queryFn: async ({ signal }) => {
|
|
96
|
+
if (id === undefined)
|
|
97
|
+
return Promise.reject(new TypeError("No id."));
|
|
98
|
+
if (include.length === 0)
|
|
99
|
+
return resource.service.get(id, { signal, session });
|
|
100
|
+
const [row] = await resolveRelations(resource, [await readPlain(signal)], options.paths ?? [], {
|
|
101
|
+
signal,
|
|
102
|
+
session,
|
|
103
|
+
known: (target, related) => client.getQueryData(resourceDetailKey(target, related)),
|
|
104
|
+
seed: (target, record) => client.setQueryData(resourceDetailKey(target, target.idKey(target.idOf(record))), record),
|
|
105
|
+
warn: warnInDevelopment,
|
|
106
|
+
canRead: (target) => target.check(ResourceAction.get, undefined, session) === true,
|
|
107
|
+
});
|
|
108
|
+
if (row === undefined)
|
|
109
|
+
throw new TypeError("No record.");
|
|
110
|
+
return row;
|
|
111
|
+
},
|
|
112
|
+
enabled: id !== undefined,
|
|
113
|
+
staleTime: resource.staleTime,
|
|
114
|
+
retry: (failures, error) => toServiceError(error).retryable && failures < 2,
|
|
115
|
+
meta: resourceMeta,
|
|
116
|
+
});
|
|
117
|
+
const row = result.data;
|
|
118
|
+
const { refetch } = result;
|
|
119
|
+
return {
|
|
120
|
+
row,
|
|
121
|
+
version: row === undefined ? undefined : resource.service.versionOf?.(row),
|
|
122
|
+
isLoading: id !== undefined && result.isPending,
|
|
123
|
+
error: toError(result.error),
|
|
124
|
+
refetch: () => void refetch(),
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Refreshes every query of a resource and of the resources that show its records through a relation (orders show
|
|
129
|
+
* their customer, so a customer's change refreshes the orders lists too).
|
|
130
|
+
*/
|
|
131
|
+
export function invalidateResource(client, resource) {
|
|
132
|
+
const dependents = resource.key === undefined ? [] : dependentsOf({ key: resource.key });
|
|
133
|
+
return Promise.all([
|
|
134
|
+
client.invalidateQueries({ queryKey: resource.queryKey }),
|
|
135
|
+
...dependents.map((entry) => client.invalidateQueries({ queryKey: entry.resource.queryKey })),
|
|
136
|
+
]).then(() => undefined);
|
|
137
|
+
}
|
|
138
|
+
export function writeRow(client, resource, row) {
|
|
139
|
+
const id = resource.idKey(resource.idOf(row));
|
|
140
|
+
const merged = (old) => (isRecord(old) && isRecord(row) ? { ...old, ...row } : row);
|
|
141
|
+
client.setQueryData(resourceDetailKey(resource, id), row);
|
|
142
|
+
client.setQueriesData({ queryKey: [...resourceDetailKey(resource, id), "with"] }, merged);
|
|
143
|
+
client.setQueriesData({ queryKey: resource.queryKey }, (data) => {
|
|
144
|
+
if (!isRecord(data) || !Array.isArray(data.items))
|
|
145
|
+
return data;
|
|
146
|
+
const items = data.items;
|
|
147
|
+
return {
|
|
148
|
+
...data,
|
|
149
|
+
// Workaround: a cached page of this resource holds its rows; `idOf` reads the id the same way from any of them.
|
|
150
|
+
items: items.map((item) => isRecord(item) && resource.idKey(resource.idOf(assumeType(item))) === id ? merged(item) : item),
|
|
151
|
+
};
|
|
152
|
+
});
|
|
153
|
+
for (const { resource: dependent, relation } of dependentsOf(resource)) {
|
|
154
|
+
client.setQueriesData({ queryKey: dependent.queryKey }, (page) => {
|
|
155
|
+
if (!page || !isRecord(page) || !Array.isArray(page.items))
|
|
156
|
+
return page;
|
|
157
|
+
return { ...page, items: page.items.map((item) => withRelated(item, relation, id, row)) };
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
function withRelated(item, relation, id, row) {
|
|
162
|
+
if (!isRecord(item))
|
|
163
|
+
return item;
|
|
164
|
+
const shown = item[relation];
|
|
165
|
+
const sameId = (entry) => isRecord(entry) && String(entry.id) === id;
|
|
166
|
+
if (Array.isArray(shown)) {
|
|
167
|
+
const list = shown;
|
|
168
|
+
return list.some(sameId) ? { ...item, [relation]: list.map((entry) => (sameId(entry) ? row : entry)) } : item;
|
|
169
|
+
}
|
|
170
|
+
return sameId(shown) ? { ...item, [relation]: row } : item;
|
|
171
|
+
}
|
|
172
|
+
export function useResourceMutations(resource) {
|
|
173
|
+
const { session } = useDataLayer();
|
|
174
|
+
const client = useQueryClient();
|
|
175
|
+
return useMemo(() => {
|
|
176
|
+
const context = () => ({ signal: new AbortController().signal, session });
|
|
177
|
+
return {
|
|
178
|
+
async create(input) {
|
|
179
|
+
const row = await resource.service.create(input, context());
|
|
180
|
+
void invalidateResource(client, resource);
|
|
181
|
+
return row;
|
|
182
|
+
},
|
|
183
|
+
async update(id, patch, options = {}) {
|
|
184
|
+
const row = await resource.service.update(id, patch, { ...context(), version: options.version });
|
|
185
|
+
writeRow(client, resource, row);
|
|
186
|
+
void invalidateResource(client, resource);
|
|
187
|
+
return row;
|
|
188
|
+
},
|
|
189
|
+
async remove(target) {
|
|
190
|
+
await resource.service.remove(target, context());
|
|
191
|
+
void invalidateResource(client, resource);
|
|
192
|
+
},
|
|
193
|
+
async restore(target) {
|
|
194
|
+
const restore = resource.service.restore;
|
|
195
|
+
if (!restore)
|
|
196
|
+
throw new ServiceFailure(serviceError(ServiceErrorKind.forbidden, "This resource has no restore."));
|
|
197
|
+
await restore.call(resource.service, target, context());
|
|
198
|
+
void invalidateResource(client, resource);
|
|
199
|
+
},
|
|
200
|
+
};
|
|
201
|
+
}, [client, resource, session]);
|
|
202
|
+
}
|
|
203
|
+
export function useResourceCount(resource, filter, options = {}) {
|
|
204
|
+
const { session } = useDataLayer();
|
|
205
|
+
const result = useQuery({
|
|
206
|
+
queryKey: resourceCountKey(resource, filter),
|
|
207
|
+
queryFn: async ({ signal }) => {
|
|
208
|
+
const full = resource.filterOf(filter);
|
|
209
|
+
if (resource.service.count)
|
|
210
|
+
return resource.service.count(full, { signal, session });
|
|
211
|
+
const page = await resource.service.list({ filter: full, sort: [], size: 1, position: { page: 1 } }, { signal, session });
|
|
212
|
+
return page.total ?? page.items.length;
|
|
213
|
+
},
|
|
214
|
+
staleTime: resource.staleTime,
|
|
215
|
+
...(options.refetchInterval === undefined ? {} : { refetchInterval: options.refetchInterval }),
|
|
216
|
+
});
|
|
217
|
+
return { count: result.data, error: toError(result.error) };
|
|
218
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { Resource } from "../../resource/resource.js";
|
|
2
|
+
import { type View, type ViewOptions, type ViewSnapshot } from "../../view/view.js";
|
|
3
|
+
export declare function useView<T, Id, F>(resource: Resource<T, Id, F>, given?: View<T, F, Id>, options?: ViewOptions<NoInfer<F>>): {
|
|
4
|
+
view: View<T, F, Id>;
|
|
5
|
+
snapshot: ViewSnapshot<F>;
|
|
6
|
+
};
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { useEffect, useState, useSyncExternalStore } from "react";
|
|
3
|
+
import { defineView } from "../../view/view.js";
|
|
4
|
+
import { useDataLayer } from "../data-layer.js";
|
|
5
|
+
export function useView(resource, given, options) {
|
|
6
|
+
const { router, preferences, session } = useDataLayer();
|
|
7
|
+
const [own] = useState(() => given ??
|
|
8
|
+
defineView(resource, {
|
|
9
|
+
...(preferences ? { preferences } : {}),
|
|
10
|
+
...(router ? { search: router.location().search } : {}),
|
|
11
|
+
...options,
|
|
12
|
+
}));
|
|
13
|
+
const view = given ?? own;
|
|
14
|
+
const snapshot = useSyncExternalStore(view.subscribe, view.getSnapshot, view.getSnapshot);
|
|
15
|
+
useEffect(() => (router ? view.attach(router) : undefined), [router, view]);
|
|
16
|
+
useEffect(() => {
|
|
17
|
+
const controller = new AbortController();
|
|
18
|
+
// Spec: saved views load after hydration, so a server render and the first client render agree; a store that
|
|
19
|
+
// fails leaves the presets.
|
|
20
|
+
view.views.load({ signal: controller.signal, session }).catch(() => undefined);
|
|
21
|
+
return () => controller.abort();
|
|
22
|
+
}, [view, session]);
|
|
23
|
+
return { view, snapshot };
|
|
24
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export { DataLayer, useDataLayer, useLabels, useSession, type DataLayerProps, type DataLayerValue, } from "./data-layer.js";
|
|
2
|
+
export { resourceCountKey, resourceDetailKey, resourcePageKey, resourceSourceKey, resourceTableQuery, type ResourceTableQuery, } from "./keys.js";
|
|
3
|
+
export { invalidateResource, useResource, useResourceCount, useResourceList, useResourceMutations, writeRow, type ResourceListOptions, type ResourceListState, type ResourceMutations, type ResourceState, type TotalInfo, } from "./hooks/use-resource.js";
|
|
4
|
+
export { useAction, type ActionState } from "./hooks/use-action.js";
|
|
5
|
+
export { useView } from "./hooks/use-view.js";
|
|
6
|
+
export { useDocumentTitle, useNav, useRoutedNav, type NavState } from "./hooks/use-nav.js";
|
|
7
|
+
export { useDraft } from "./hooks/use-draft.js";
|
|
8
|
+
export { useBetterAuthSession, type BetterAuthSessionState } from "./hooks/use-better-auth.js";
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export { DataLayer, useDataLayer, useLabels, useSession, } from "./data-layer.js";
|
|
2
|
+
export { resourceCountKey, resourceDetailKey, resourcePageKey, resourceSourceKey, resourceTableQuery, } from "./keys.js";
|
|
3
|
+
export { invalidateResource, useResource, useResourceCount, useResourceList, useResourceMutations, writeRow, } from "./hooks/use-resource.js";
|
|
4
|
+
export { useAction } from "./hooks/use-action.js";
|
|
5
|
+
export { useView } from "./hooks/use-view.js";
|
|
6
|
+
export { useDocumentTitle, useNav, useRoutedNav } from "./hooks/use-nav.js";
|
|
7
|
+
export { useDraft } from "./hooks/use-draft.js";
|
|
8
|
+
export { useBetterAuthSession } from "./hooks/use-better-auth.js";
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import type { QueryKey } from "@tanstack/react-query";
|
|
2
|
+
import type { Query } from "../core/contracts.js";
|
|
3
|
+
import { type Resource } from "../resource/resource.js";
|
|
4
|
+
import type { View } from "../view/view.js";
|
|
5
|
+
/** The key `server-data` gives a page, so a `ServerDataTable` over `resource.source` shares the cached page. */
|
|
6
|
+
export declare function resourcePageKey<F>(resource: {
|
|
7
|
+
queryKey: readonly unknown[];
|
|
8
|
+
}, query: Query<F>): QueryKey;
|
|
9
|
+
export declare function resourceDetailKey(resource: {
|
|
10
|
+
queryKey: readonly unknown[];
|
|
11
|
+
}, id: string): QueryKey;
|
|
12
|
+
/** A record with the relations a page shows (`include`), apart from the plain record. */
|
|
13
|
+
export declare function resourceDetailWithKey(resource: {
|
|
14
|
+
queryKey: readonly unknown[];
|
|
15
|
+
}, id: string, include: readonly string[]): QueryKey;
|
|
16
|
+
export declare function resourceCountKey(resource: {
|
|
17
|
+
queryKey: readonly unknown[];
|
|
18
|
+
}, filter: unknown): QueryKey;
|
|
19
|
+
/**
|
|
20
|
+
* The key of a resource's source with a filter that always applies (a view's base filter and scope, a table's
|
|
21
|
+
* `filter`): its own cache entries, apart from the unfiltered source's.
|
|
22
|
+
*/
|
|
23
|
+
export declare function resourceSourceKey(resource: {
|
|
24
|
+
queryKey: readonly unknown[];
|
|
25
|
+
}, fixed: object, include?: readonly string[]): QueryKey;
|
|
26
|
+
/**
|
|
27
|
+
* The paths a resource's table shows by default: its columns that aren't hidden, without `except` (a `hasMany`
|
|
28
|
+
* tab's foreign key, and the relation column that shows it).
|
|
29
|
+
*/
|
|
30
|
+
export declare function shownPaths(resource: {
|
|
31
|
+
columns(): readonly {
|
|
32
|
+
key: string;
|
|
33
|
+
hidden: boolean;
|
|
34
|
+
relation?: {
|
|
35
|
+
key: string;
|
|
36
|
+
};
|
|
37
|
+
}[];
|
|
38
|
+
}, except?: string): string[];
|
|
39
|
+
export type ResourceTableQuery<F> = {
|
|
40
|
+
/** The page `ResourceTable` shows first for the view's state. */
|
|
41
|
+
page: QueryKey;
|
|
42
|
+
/** Its count, when the service counts apart. */
|
|
43
|
+
total: QueryKey | undefined;
|
|
44
|
+
/** What the service is asked for that page. */
|
|
45
|
+
query: Query<F>;
|
|
46
|
+
};
|
|
47
|
+
/**
|
|
48
|
+
* The queries a `ResourceTable` over `view` runs first, with the keys it caches them under, so a server can fetch
|
|
49
|
+
* them before the table renders (Next.js `HydrationBoundary`).
|
|
50
|
+
*/
|
|
51
|
+
export declare function resourceTableQuery<T, Id, F>(resource: Resource<T, Id, F>, view: View<T, F, Id>, filter?: Partial<F>, paths?: readonly string[]): ResourceTableQuery<F>;
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { isBoolean, isRecord, isString } from "../core/guards.js";
|
|
2
|
+
import { includeOf } from "../resource/relations.js";
|
|
3
|
+
import { searchKey } from "../resource/resource.js";
|
|
4
|
+
/** The key `server-data` gives a page, so a `ServerDataTable` over `resource.source` shares the cached page. */
|
|
5
|
+
export function resourcePageKey(resource, query) {
|
|
6
|
+
const filter = { ...query.filter, ...(query.search === undefined ? {} : { [searchKey]: query.search }) };
|
|
7
|
+
return [...resource.queryKey, "page", filter, query.sort, query.position, query.size];
|
|
8
|
+
}
|
|
9
|
+
export function resourceDetailKey(resource, id) {
|
|
10
|
+
return [...resource.queryKey, "detail", id];
|
|
11
|
+
}
|
|
12
|
+
/** A record with the relations a page shows (`include`), apart from the plain record. */
|
|
13
|
+
export function resourceDetailWithKey(resource, id, include) {
|
|
14
|
+
return include.length === 0 ? resourceDetailKey(resource, id) : [...resourceDetailKey(resource, id), "with", include];
|
|
15
|
+
}
|
|
16
|
+
export function resourceCountKey(resource, filter) {
|
|
17
|
+
return [...resource.queryKey, "count", filter];
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* The key of a resource's source with a filter that always applies (a view's base filter and scope, a table's
|
|
21
|
+
* `filter`): its own cache entries, apart from the unfiltered source's.
|
|
22
|
+
*/
|
|
23
|
+
export function resourceSourceKey(resource, fixed, include = []) {
|
|
24
|
+
const key = JSON.stringify(fixed);
|
|
25
|
+
const base = Object.keys(fixed).length > 0 && key !== "{}" ? [...resource.queryKey, "fixed", key] : resource.queryKey;
|
|
26
|
+
return include.length === 0 ? base : [...base, "with", include.toSorted().join(",")];
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* The paths a resource's table shows by default: its columns that aren't hidden, without `except` (a `hasMany`
|
|
30
|
+
* tab's foreign key, and the relation column that shows it).
|
|
31
|
+
*/
|
|
32
|
+
export function shownPaths(resource, except) {
|
|
33
|
+
return resource
|
|
34
|
+
.columns()
|
|
35
|
+
.filter((column) => !column.hidden && (except === undefined || (column.key !== except && column.relation?.key !== except)))
|
|
36
|
+
.map((column) => column.key);
|
|
37
|
+
}
|
|
38
|
+
// Spec: the values `ResourceTable`'s page controller passes on (text, yes/no, a list, a range or an operator).
|
|
39
|
+
function isFilterValue(value) {
|
|
40
|
+
return isString(value) || isBoolean(value) || Array.isArray(value) || isRecord(value);
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* The queries a `ResourceTable` over `view` runs first, with the keys it caches them under, so a server can fetch
|
|
44
|
+
* them before the table renders (Next.js `HydrationBoundary`).
|
|
45
|
+
*/
|
|
46
|
+
export function resourceTableQuery(resource, view, filter = {}, paths = []) {
|
|
47
|
+
const include = includeOf(resource.relations, paths);
|
|
48
|
+
const state = view.getState();
|
|
49
|
+
const scope = view.scopes.find((entry) => entry.id === state.scope)?.filter;
|
|
50
|
+
const fixed = { ...view.options.baseFilter, ...scope, ...filter };
|
|
51
|
+
const values = Object.fromEntries(Object.entries(state.filter).filter(([, value]) => isFilterValue(value)));
|
|
52
|
+
const shown = state.search === "" ? values : { ...values, [searchKey]: state.search };
|
|
53
|
+
const source = resourceSourceKey(resource, fixed, include);
|
|
54
|
+
const position = { page: state.page };
|
|
55
|
+
return {
|
|
56
|
+
page: [...source, "page", shown, state.sort, position, state.size],
|
|
57
|
+
total: resource.service.count ? [...source, "total", shown] : undefined,
|
|
58
|
+
query: {
|
|
59
|
+
filter: resource.filterOf({ ...values, ...fixed }),
|
|
60
|
+
search: state.search === "" ? undefined : state.search,
|
|
61
|
+
sort: state.sort,
|
|
62
|
+
size: state.size,
|
|
63
|
+
position,
|
|
64
|
+
...(include.length > 0 ? { include } : {}),
|
|
65
|
+
},
|
|
66
|
+
};
|
|
67
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { FormStage } from "../core/constants.js";
|
|
2
|
+
import type { Resource } from "./resource.js";
|
|
3
|
+
import { type StandardIssue, type StandardSchema } from "./schema.js";
|
|
4
|
+
/**
|
|
5
|
+
* A Standard Schema that validates only `keys` of a record against the full schema: a create form that has no `id`,
|
|
6
|
+
* no timestamps and no read-only fields still checks every field it shows, with the schema's own messages. A
|
|
7
|
+
* schema that answers synchronously still does.
|
|
8
|
+
*/
|
|
9
|
+
export declare function fieldsSchema(schema: StandardSchema, keys: readonly string[]): StandardSchema<Record<string, unknown>, Record<string, unknown>>;
|
|
10
|
+
export declare function formSchemaOf<T, Id, F>(resource: Resource<T, Id, F>, stage: FormStage, keys: readonly string[]): StandardSchema<Record<string, unknown>, Record<string, unknown>> | undefined;
|
|
11
|
+
export declare function issueText(issues: readonly StandardIssue[]): string;
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { FormStage } from "../core/constants.js";
|
|
2
|
+
import { isRecord } from "../core/guards.js";
|
|
3
|
+
import { issuePath } from "./schema.js";
|
|
4
|
+
function keep(issues, keys) {
|
|
5
|
+
return issues.filter((issue) => {
|
|
6
|
+
const path = issuePath(issue);
|
|
7
|
+
return path === "" || keys.has(path) || [...keys].some((key) => path.startsWith(`${key}.`));
|
|
8
|
+
});
|
|
9
|
+
}
|
|
10
|
+
function settle(result, value, keys) {
|
|
11
|
+
if (result.issues === undefined)
|
|
12
|
+
return { value: isRecord(result.value) ? result.value : {} };
|
|
13
|
+
const issues = keep(result.issues, keys).filter((issue) => issuePath(issue) !== "");
|
|
14
|
+
if (issues.length > 0)
|
|
15
|
+
return { issues };
|
|
16
|
+
return { value: isRecord(value) ? value : {} };
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* A Standard Schema that validates only `keys` of a record against the full schema: a create form that has no `id`,
|
|
20
|
+
* no timestamps and no read-only fields still checks every field it shows, with the schema's own messages. A
|
|
21
|
+
* schema that answers synchronously still does.
|
|
22
|
+
*/
|
|
23
|
+
export function fieldsSchema(schema, keys) {
|
|
24
|
+
const shown = new Set(keys);
|
|
25
|
+
return {
|
|
26
|
+
"~standard": {
|
|
27
|
+
version: 1,
|
|
28
|
+
vendor: "app-sdk",
|
|
29
|
+
validate(value) {
|
|
30
|
+
const result = schema["~standard"].validate(value);
|
|
31
|
+
if (result instanceof Promise)
|
|
32
|
+
return result.then((settled) => settle(settled, value, shown));
|
|
33
|
+
return settle(result, value, shown);
|
|
34
|
+
},
|
|
35
|
+
},
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
export function formSchemaOf(resource, stage, keys) {
|
|
39
|
+
const own = stage === FormStage.create ? resource.options.createSchema : resource.options.updateSchema;
|
|
40
|
+
if (own)
|
|
41
|
+
return fieldsSchema(own, keys);
|
|
42
|
+
const schema = resource.schema;
|
|
43
|
+
if (!schema)
|
|
44
|
+
return undefined;
|
|
45
|
+
return fieldsSchema(schema, keys);
|
|
46
|
+
}
|
|
47
|
+
export function issueText(issues) {
|
|
48
|
+
return issues
|
|
49
|
+
.map((issue) => (issuePath(issue) === "" ? issue.message : `${issuePath(issue)}: ${issue.message}`))
|
|
50
|
+
.join("; ");
|
|
51
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { RelationDenied, RelationKind, RowsMode } from "../core/constants.js";
|
|
2
|
+
import type { CallContext } from "../core/contracts.js";
|
|
3
|
+
import type { AnyResource, Resource } from "./resource-types.js";
|
|
4
|
+
import type { InferOutput, StandardSchema } from "./schema.js";
|
|
5
|
+
export type BelongsTo<Row = unknown> = {
|
|
6
|
+
readonly kind: typeof RelationKind.belongsTo;
|
|
7
|
+
/** Never set: carries the related row's type to `RelationRows`. */
|
|
8
|
+
readonly rowType?: Row;
|
|
9
|
+
readonly target: () => AnyResource;
|
|
10
|
+
/** The record's field with the related id, like `customerId`. */
|
|
11
|
+
readonly key: string;
|
|
12
|
+
/** Fields the record keeps a copy of under the relation's name (`customer: { name }`): shown without a fetch. */
|
|
13
|
+
readonly snapshot?: readonly string[];
|
|
14
|
+
/** Offers to create the missing record from the form's combobox. Default true. */
|
|
15
|
+
readonly create?: boolean;
|
|
16
|
+
/** When the session can't read the related resource: show the id (default) or hide the column. */
|
|
17
|
+
readonly denied?: RelationDenied;
|
|
18
|
+
};
|
|
19
|
+
export type HasMany = {
|
|
20
|
+
readonly kind: typeof RelationKind.hasMany;
|
|
21
|
+
readonly target: () => AnyResource;
|
|
22
|
+
/** The related records' field with this record's id, like `orderId`. */
|
|
23
|
+
readonly foreignKey: string;
|
|
24
|
+
/** `RowsMode.tab` (default): a tab with its own table and path; `RowsMode.inline`: rows edited in the form. */
|
|
25
|
+
readonly mode?: RowsMode;
|
|
26
|
+
/** The tab's label; the related resource's by default. */
|
|
27
|
+
readonly label?: string;
|
|
28
|
+
};
|
|
29
|
+
export type ManyToMany<Row = unknown> = {
|
|
30
|
+
readonly kind: typeof RelationKind.manyToMany;
|
|
31
|
+
/** Never set: carries the related row's type to `RelationRows`. */
|
|
32
|
+
readonly rowType?: Row;
|
|
33
|
+
readonly target: () => AnyResource;
|
|
34
|
+
/** The record's field with the related ids, like `tagIds`. */
|
|
35
|
+
readonly key: string;
|
|
36
|
+
readonly denied?: RelationDenied;
|
|
37
|
+
};
|
|
38
|
+
export type Embeds<Output = unknown> = {
|
|
39
|
+
readonly kind: typeof RelationKind.embeds;
|
|
40
|
+
/** A subdocument's schema, or a list of them (`z.array(line)`), stored inside the record. */
|
|
41
|
+
readonly schema: StandardSchema<unknown, Output>;
|
|
42
|
+
};
|
|
43
|
+
export type Relation = BelongsTo<any> | HasMany | ManyToMany<any> | Embeds<any>;
|
|
44
|
+
export type Relations = Readonly<Record<string, Relation>>;
|
|
45
|
+
/** What each relation adds to a row once resolved: the related record, its list, or the subdocument. */
|
|
46
|
+
export type RelationRows<R> = string extends keyof R ? unknown : RelationRowsOf<R>;
|
|
47
|
+
type RelationRowsOf<R> = {
|
|
48
|
+
[Name in keyof R]?: R[Name] extends BelongsTo<infer Row> ? Row : R[Name] extends ManyToMany<infer Row> ? readonly Row[] : R[Name] extends Embeds<infer Output> ? Output : readonly unknown[];
|
|
49
|
+
};
|
|
50
|
+
type TargetOf<Row> = () => Resource<Row, any, any>;
|
|
51
|
+
/** This record points at one other: `customer: belongsTo(() => customers, { key: "customerId" })`. */
|
|
52
|
+
export declare function belongsTo<Row>(target: TargetOf<Row>, options: Omit<BelongsTo<Row>, "kind" | "target">): BelongsTo<Row>;
|
|
53
|
+
/** Lets relations name a resource by its `key`; `defineResource` registers each one it makes. */
|
|
54
|
+
export declare function registerResource(resource: AnyResource): void;
|
|
55
|
+
/**
|
|
56
|
+
* Other records point at this one: `lines: hasMany(() => orderLines, { foreignKey: "orderId" })`. When the two
|
|
57
|
+
* resources point at each other (customers have orders, an order has a customer), name it by its key,
|
|
58
|
+
* `hasMany("orders", …)`: TypeScript can't infer two resources' types from each other.
|
|
59
|
+
*/
|
|
60
|
+
export declare function hasMany(target: (() => AnyResource) | string, options: Omit<HasMany, "kind" | "target">): HasMany;
|
|
61
|
+
/** This record keeps a list of ids of others: `tags: manyToMany(() => tags, { key: "tagIds" })`. */
|
|
62
|
+
export declare function manyToMany<Row>(target: TargetOf<Row>, options: Omit<ManyToMany<Row>, "kind" | "target">): ManyToMany<Row>;
|
|
63
|
+
/** A subdocument, or a list of them, stored inside the record: `address: embeds(addressSchema)`. */
|
|
64
|
+
export declare function embeds<Schema extends StandardSchema>(schema: Schema): Embeds<InferOutput<Schema>>;
|
|
65
|
+
/** The relations a set of paths reaches (`customer.name` reaches `customer`), for `Query.include`. */
|
|
66
|
+
export declare function includeOf(relations: Relations, paths: readonly string[]): string[];
|
|
67
|
+
/** The `belongsTo` or `manyToMany` whose id field is `key` (`customerId` is `customer`'s). */
|
|
68
|
+
export declare function keyRelation(relations: Relations, key: string): [string, BelongsTo | ManyToMany] | undefined;
|
|
69
|
+
/** Splits `ids` into lists of at most `size`: Firestore's `in` takes 30, DynamoDB's BatchGetItem 100. */
|
|
70
|
+
export declare function chunkIds<Id>(ids: readonly Id[], size: number | undefined): Id[][];
|
|
71
|
+
export type RelationContext = CallContext & {
|
|
72
|
+
/** A record already at hand (a cache), by resource and id; it isn't fetched again. */
|
|
73
|
+
known?: (resource: AnyResource, id: string) => unknown;
|
|
74
|
+
/** Every record fetched, to seed a detail cache. */
|
|
75
|
+
seed?: (resource: AnyResource, record: unknown) => void;
|
|
76
|
+
/** Told once per resource that has no `getMany` and was read one id at a time. */
|
|
77
|
+
warn?: (message: string) => void;
|
|
78
|
+
/** Whether the session may read a related resource; a refused one is never fetched. */
|
|
79
|
+
canRead?: (resource: AnyResource) => boolean;
|
|
80
|
+
/** The service to read a related resource through: on a server, the one that answers there, not its HTTP client. */
|
|
81
|
+
serviceOf?: (resource: AnyResource) => AnyResource["service"];
|
|
82
|
+
};
|
|
83
|
+
/**
|
|
84
|
+
* Adds related records to rows, never one request per row: what the server embedded (or a `snapshot` that has every
|
|
85
|
+
* field asked) stays; the rest is read with one `getMany` per relation, in chunks of the service's `batchSize`, or
|
|
86
|
+
* one `get` per distinct id when there's no `getMany`. Paths reach through relations (`customer.country.name`).
|
|
87
|
+
*/
|
|
88
|
+
export declare function resolveRelations<T>(resource: {
|
|
89
|
+
readonly relations: Relations;
|
|
90
|
+
}, rows: readonly T[], paths: readonly string[], context: RelationContext): Promise<T[]>;
|
|
91
|
+
/** A resource's records that `hasMany` rows belong to, saved with it: created, changed and removed by id. */
|
|
92
|
+
export type ChildChanges = {
|
|
93
|
+
create: Record<string, unknown>[];
|
|
94
|
+
update: Record<string, unknown>[];
|
|
95
|
+
remove: unknown[];
|
|
96
|
+
};
|
|
97
|
+
/** What to send so the stored children become `rows`: new ones (no id), changed ones, and the ids left out. */
|
|
98
|
+
export declare function childChanges(rows: readonly Record<string, unknown>[], previous: readonly Record<string, unknown>[], idOf: (row: Record<string, unknown>) => unknown): ChildChanges;
|
|
99
|
+
export {};
|