@eskais/app-sdk 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (159) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +74 -2
  3. package/dist/action/action.d.ts +133 -0
  4. package/dist/action/action.js +224 -0
  5. package/dist/action/bulk.d.ts +24 -0
  6. package/dist/action/bulk.js +24 -0
  7. package/dist/cli/cli.d.ts +2 -0
  8. package/dist/cli/cli.js +51 -0
  9. package/dist/cli/routes.d.ts +17 -0
  10. package/dist/cli/routes.js +36 -0
  11. package/dist/core/assume.d.ts +1 -0
  12. package/dist/core/assume.js +8 -0
  13. package/dist/core/constants.d.ts +359 -0
  14. package/dist/core/constants.js +187 -0
  15. package/dist/core/contracts.d.ts +107 -0
  16. package/dist/core/contracts.js +3 -0
  17. package/dist/core/data-labels.d.ts +210 -0
  18. package/dist/core/data-labels.js +385 -0
  19. package/dist/core/errors.d.ts +52 -0
  20. package/dist/core/errors.js +209 -0
  21. package/dist/core/guards.d.ts +9 -0
  22. package/dist/core/guards.js +14 -0
  23. package/dist/core/refusal.d.ts +30 -0
  24. package/dist/core/refusal.js +53 -0
  25. package/dist/dialogs/dialogs.d.ts +75 -0
  26. package/dist/dialogs/dialogs.js +66 -0
  27. package/dist/draft/draft.d.ts +36 -0
  28. package/dist/draft/draft.js +87 -0
  29. package/dist/errors/adapters.d.ts +21 -0
  30. package/dist/errors/adapters.js +81 -0
  31. package/dist/errors/define-errors.d.ts +88 -0
  32. package/dist/errors/define-errors.js +168 -0
  33. package/dist/errors/idempotency.d.ts +2 -0
  34. package/dist/errors/idempotency.js +13 -0
  35. package/dist/export/csv.d.ts +25 -0
  36. package/dist/export/csv.js +59 -0
  37. package/dist/i18n/adapters.d.ts +53 -0
  38. package/dist/i18n/adapters.js +56 -0
  39. package/dist/i18n/format.d.ts +10 -0
  40. package/dist/i18n/format.js +273 -0
  41. package/dist/i18n/labels.d.ts +10 -0
  42. package/dist/i18n/labels.js +227 -0
  43. package/dist/i18n/locale.d.ts +73 -0
  44. package/dist/i18n/locale.js +74 -0
  45. package/dist/i18n/messages.d.ts +93 -0
  46. package/dist/i18n/messages.js +16 -0
  47. package/dist/import/csv-parse.d.ts +11 -0
  48. package/dist/import/csv-parse.js +70 -0
  49. package/dist/import/import.d.ts +104 -0
  50. package/dist/import/import.js +266 -0
  51. package/dist/index.d.ts +46 -0
  52. package/dist/index.js +45 -0
  53. package/dist/navigation/nav.d.ts +128 -0
  54. package/dist/navigation/nav.js +301 -0
  55. package/dist/navigation/router.d.ts +81 -0
  56. package/dist/navigation/router.js +249 -0
  57. package/dist/navigation/shortcuts.d.ts +37 -0
  58. package/dist/navigation/shortcuts.js +93 -0
  59. package/dist/next/index.d.ts +3 -0
  60. package/dist/next/index.js +3 -0
  61. package/dist/next/screen-hydration.d.ts +12 -0
  62. package/dist/next/screen-hydration.js +26 -0
  63. package/dist/next/screen.d.ts +25 -0
  64. package/dist/next/screen.js +44 -0
  65. package/dist/next/server/handler.d.ts +39 -0
  66. package/dist/next/server/handler.js +190 -0
  67. package/dist/next/server/index.d.ts +6 -0
  68. package/dist/next/server/index.js +6 -0
  69. package/dist/next/server/page.d.ts +63 -0
  70. package/dist/next/server/page.js +110 -0
  71. package/dist/next/server/prefetch.d.ts +29 -0
  72. package/dist/next/server/prefetch.js +97 -0
  73. package/dist/next/server/session.d.ts +25 -0
  74. package/dist/next/server/session.js +23 -0
  75. package/dist/next/use-next-router.d.ts +21 -0
  76. package/dist/next/use-next-router.js +104 -0
  77. package/dist/permissions/permissions.d.ts +134 -0
  78. package/dist/permissions/permissions.js +121 -0
  79. package/dist/react/data-layer.d.ts +68 -0
  80. package/dist/react/data-layer.js +76 -0
  81. package/dist/react/hooks/use-action-dialog.d.ts +25 -0
  82. package/dist/react/hooks/use-action-dialog.js +31 -0
  83. package/dist/react/hooks/use-action.d.ts +37 -0
  84. package/dist/react/hooks/use-action.js +125 -0
  85. package/dist/react/hooks/use-better-auth.d.ts +12 -0
  86. package/dist/react/hooks/use-better-auth.js +11 -0
  87. package/dist/react/hooks/use-bulk-action.d.ts +20 -0
  88. package/dist/react/hooks/use-bulk-action.js +24 -0
  89. package/dist/react/hooks/use-dialogs.d.ts +14 -0
  90. package/dist/react/hooks/use-dialogs.js +20 -0
  91. package/dist/react/hooks/use-draft.d.ts +5 -0
  92. package/dist/react/hooks/use-draft.js +17 -0
  93. package/dist/react/hooks/use-nav.d.ts +17 -0
  94. package/dist/react/hooks/use-nav.js +35 -0
  95. package/dist/react/hooks/use-new-rows.d.ts +22 -0
  96. package/dist/react/hooks/use-new-rows.js +24 -0
  97. package/dist/react/hooks/use-permissions.d.ts +13 -0
  98. package/dist/react/hooks/use-permissions.js +19 -0
  99. package/dist/react/hooks/use-reauthenticate.d.ts +6 -0
  100. package/dist/react/hooks/use-reauthenticate.js +11 -0
  101. package/dist/react/hooks/use-resource.d.ts +92 -0
  102. package/dist/react/hooks/use-resource.js +255 -0
  103. package/dist/react/hooks/use-view.d.ts +6 -0
  104. package/dist/react/hooks/use-view.js +24 -0
  105. package/dist/react/index.d.ts +15 -0
  106. package/dist/react/index.js +15 -0
  107. package/dist/react/keys.d.ts +60 -0
  108. package/dist/react/keys.js +71 -0
  109. package/dist/react/new-rows.d.ts +22 -0
  110. package/dist/react/new-rows.js +72 -0
  111. package/dist/refresh/new-rows.d.ts +13 -0
  112. package/dist/refresh/new-rows.js +18 -0
  113. package/dist/resource/form-schema.d.ts +11 -0
  114. package/dist/resource/form-schema.js +51 -0
  115. package/dist/resource/relations.d.ts +99 -0
  116. package/dist/resource/relations.js +194 -0
  117. package/dist/resource/resource-relations.d.ts +47 -0
  118. package/dist/resource/resource-relations.js +154 -0
  119. package/dist/resource/resource-schema.d.ts +9 -0
  120. package/dist/resource/resource-schema.js +73 -0
  121. package/dist/resource/resource-texts.d.ts +18 -0
  122. package/dist/resource/resource-texts.js +13 -0
  123. package/dist/resource/resource-types.d.ts +420 -0
  124. package/dist/resource/resource-types.js +1 -0
  125. package/dist/resource/resource-words.d.ts +25 -0
  126. package/dist/resource/resource-words.js +221 -0
  127. package/dist/resource/resource.d.ts +15 -0
  128. package/dist/resource/resource.js +280 -0
  129. package/dist/resource/schema.d.ts +57 -0
  130. package/dist/resource/schema.js +115 -0
  131. package/dist/services/from-page-source.d.ts +15 -0
  132. package/dist/services/from-page-source.js +27 -0
  133. package/dist/services/memory-query.d.ts +8 -0
  134. package/dist/services/memory-query.js +165 -0
  135. package/dist/services/memory-service.d.ts +33 -0
  136. package/dist/services/memory-service.js +291 -0
  137. package/dist/services/read-only-service.d.ts +18 -0
  138. package/dist/services/read-only-service.js +25 -0
  139. package/dist/services/rest-service.d.ts +65 -0
  140. package/dist/services/rest-service.js +222 -0
  141. package/dist/services/rng.d.ts +9 -0
  142. package/dist/services/rng.js +22 -0
  143. package/dist/services/spring-service.d.ts +58 -0
  144. package/dist/services/spring-service.js +132 -0
  145. package/dist/session/better-auth.d.ts +83 -0
  146. package/dist/session/better-auth.js +86 -0
  147. package/dist/session/session.d.ts +45 -0
  148. package/dist/session/session.js +36 -0
  149. package/dist/view/preferences.d.ts +35 -0
  150. package/dist/view/preferences.js +93 -0
  151. package/dist/view/view-types.d.ts +124 -0
  152. package/dist/view/view-types.js +1 -0
  153. package/dist/view/view-url.d.ts +7 -0
  154. package/dist/view/view-url.js +54 -0
  155. package/dist/view/view.d.ts +4 -0
  156. package/dist/view/view.js +392 -0
  157. package/locales/en.json +193 -0
  158. package/locales/es.json +193 -0
  159. package/package.json +88 -4
@@ -0,0 +1,255 @@
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 { Idempotency, Operation, 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, refreshPolicy } 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
+ import { heldRead, markOwnChange } from "../new-rows.js";
14
+ import { useNewRows } from "./use-new-rows.js";
15
+ const pageMeta = { serverData: "page" };
16
+ const resourceMeta = { serverData: "resource" };
17
+ function totalOf(page) {
18
+ if (page?.total !== undefined)
19
+ return { kind: TotalKind.exact, value: page.total };
20
+ if (page?.totalEstimate !== undefined)
21
+ return { kind: TotalKind.estimate, value: page.totalEstimate };
22
+ return { kind: TotalKind.none };
23
+ }
24
+ const toError = (error) => error === null || error === undefined ? undefined : toServiceError(error);
25
+ function read(layer, signal, call) {
26
+ return layer.errors.run(call, { operation: Operation.query, signal, session: layer.session });
27
+ }
28
+ /** A refresh policy as TanStack Query's options. */
29
+ export function refreshOptions(policy) {
30
+ return {
31
+ staleTime: policy.staleTime,
32
+ refetchOnWindowFocus: policy.onFocus,
33
+ refetchOnReconnect: policy.onReconnect,
34
+ refetchInterval: policy.interval,
35
+ };
36
+ }
37
+ const emptyFilter = {};
38
+ export function useResourceList(resource, options = {}) {
39
+ const layer = useDataLayer();
40
+ const client = useQueryClient();
41
+ const policy = refreshPolicy(resource, options.refresh);
42
+ const [own, setOwn] = useState(() => ({
43
+ filter: {},
44
+ search: "",
45
+ sort: resource.defaultSort,
46
+ page: 1,
47
+ size: 25,
48
+ }));
49
+ const view = options.view;
50
+ const subscribe = useCallback((listener) => view?.subscribe(listener) ?? (() => { }), [view]);
51
+ const viewed = useSyncExternalStore(subscribe, () => view?.getState(), () => view?.getState());
52
+ const state = viewed ?? own;
53
+ const fixed = options.filter ?? emptyFilter;
54
+ const query = useMemo(() => {
55
+ const base = view ? view.filter() : state.filter;
56
+ const filter = resource.filterOf({ ...base, ...fixed });
57
+ return {
58
+ filter,
59
+ search: state.search === "" ? undefined : state.search,
60
+ sort: state.sort,
61
+ size: state.size,
62
+ position: { page: state.page },
63
+ };
64
+ }, [resource, view, state, fixed]);
65
+ const queryKey = resourcePageKey(resource, query);
66
+ const result = useQuery({
67
+ queryKey,
68
+ queryFn: ({ signal }) => heldRead(client, resource, queryKey, policy.newRows, () => read(layer, signal, (context) => resource.service.list(query, context))),
69
+ retry: false,
70
+ enabled: options.enabled !== false,
71
+ ...refreshOptions(policy),
72
+ placeholderData: keepPreviousData,
73
+ meta: pageMeta,
74
+ });
75
+ const held = useNewRows(queryKey);
76
+ const setState = useCallback((patch) => {
77
+ if (view)
78
+ view.setState(patch);
79
+ else
80
+ setOwn((previous) => ({ ...previous, ...patch }));
81
+ }, [view, setOwn]);
82
+ const { refetch } = result;
83
+ return {
84
+ rows: result.data?.items ?? [],
85
+ total: totalOf(result.data),
86
+ state,
87
+ setState,
88
+ isLoading: result.isPending,
89
+ isFetching: result.isFetching,
90
+ error: toError(result.error),
91
+ refetch: () => void refetch(),
92
+ newRows: held.count,
93
+ showNewRows: held.apply,
94
+ };
95
+ }
96
+ /**
97
+ * One record. With `paths` (the fields a record's page shows), its relations come with it: the related records are
98
+ * read in one request per relation, through the cache, and the plain record stays cached on its own.
99
+ */
100
+ export function useResource(resource, id, options = {}) {
101
+ const layer = useDataLayer();
102
+ const { session } = layer;
103
+ const client = useQueryClient();
104
+ const { onFocus, onReconnect } = resource.refresh;
105
+ const key = id === undefined ? "" : resource.idKey(id);
106
+ const include = includeOf(resource.relations, options.paths ?? []);
107
+ const readPlain = (signal) => client.fetchQuery({
108
+ queryKey: resourceDetailKey(resource, key),
109
+ queryFn: () => {
110
+ if (id === undefined)
111
+ return Promise.reject(new TypeError("No id."));
112
+ return read(layer, signal, (context) => resource.service.get(id, context));
113
+ },
114
+ retry: false,
115
+ staleTime: resource.staleTime,
116
+ });
117
+ const result = useQuery({
118
+ queryKey: resourceDetailWithKey(resource, key, include),
119
+ queryFn: async ({ signal }) => {
120
+ if (id === undefined)
121
+ return Promise.reject(new TypeError("No id."));
122
+ if (include.length === 0)
123
+ return read(layer, signal, (context) => resource.service.get(id, context));
124
+ const [row] = await resolveRelations(resource, [await readPlain(signal)], options.paths ?? [], {
125
+ signal,
126
+ session,
127
+ known: (target, related) => client.getQueryData(resourceDetailKey(target, related)),
128
+ seed: (target, record) => client.setQueryData(resourceDetailKey(target, target.idKey(target.idOf(record))), record),
129
+ warn: warnInDevelopment,
130
+ canRead: (target) => target.check(ResourceAction.get, undefined, session) === true,
131
+ });
132
+ if (row === undefined)
133
+ throw new TypeError("No record.");
134
+ return row;
135
+ },
136
+ enabled: id !== undefined,
137
+ staleTime: resource.staleTime,
138
+ refetchOnWindowFocus: onFocus,
139
+ refetchOnReconnect: onReconnect,
140
+ retry: false,
141
+ meta: resourceMeta,
142
+ });
143
+ const row = result.data;
144
+ const { refetch } = result;
145
+ return {
146
+ row,
147
+ version: row === undefined ? undefined : resource.service.versionOf?.(row),
148
+ isLoading: id !== undefined && result.isPending,
149
+ error: toError(result.error),
150
+ refetch: () => void refetch(),
151
+ };
152
+ }
153
+ /**
154
+ * Refreshes every query of a resource and of the resources that show its records through a relation (orders show
155
+ * their customer, so a customer's change refreshes the orders lists too).
156
+ */
157
+ export function invalidateResource(client, resource) {
158
+ const dependents = resource.key === undefined ? [] : dependentsOf({ key: resource.key });
159
+ for (const changed of [resource.key, ...dependents.map((entry) => entry.resource.key)])
160
+ if (changed !== undefined)
161
+ markOwnChange(client, changed);
162
+ return Promise.all([
163
+ client.invalidateQueries({ queryKey: resource.queryKey }),
164
+ ...dependents.map((entry) => client.invalidateQueries({ queryKey: entry.resource.queryKey })),
165
+ ]).then(() => undefined);
166
+ }
167
+ export function writeRow(client, resource, row) {
168
+ const id = resource.idKey(resource.idOf(row));
169
+ markOwnChange(client, resource.key);
170
+ const merged = (old) => (isRecord(old) && isRecord(row) ? { ...old, ...row } : row);
171
+ client.setQueryData(resourceDetailKey(resource, id), row);
172
+ client.setQueriesData({ queryKey: [...resourceDetailKey(resource, id), "with"] }, merged);
173
+ client.setQueriesData({ queryKey: resource.queryKey }, (data) => {
174
+ if (!isRecord(data) || !Array.isArray(data.items))
175
+ return data;
176
+ const items = data.items;
177
+ return {
178
+ ...data,
179
+ // Workaround: a cached page of this resource holds its rows; `idOf` reads the id the same way from any of them.
180
+ items: items.map((item) => isRecord(item) && resource.idKey(resource.idOf(assumeType(item))) === id ? merged(item) : item),
181
+ };
182
+ });
183
+ for (const { resource: dependent, relation } of dependentsOf(resource)) {
184
+ client.setQueriesData({ queryKey: dependent.queryKey }, (page) => {
185
+ if (!page || !isRecord(page) || !Array.isArray(page.items))
186
+ return page;
187
+ return { ...page, items: page.items.map((item) => withRelated(item, relation, id, row)) };
188
+ });
189
+ }
190
+ }
191
+ function withRelated(item, relation, id, row) {
192
+ if (!isRecord(item))
193
+ return item;
194
+ const shown = item[relation];
195
+ const sameId = (entry) => isRecord(entry) && String(entry.id) === id;
196
+ if (Array.isArray(shown)) {
197
+ const list = shown;
198
+ return list.some(sameId) ? { ...item, [relation]: list.map((entry) => (sameId(entry) ? row : entry)) } : item;
199
+ }
200
+ return sameId(shown) ? { ...item, [relation]: row } : item;
201
+ }
202
+ export function useResourceMutations(resource) {
203
+ const { session, errors } = useDataLayer();
204
+ const client = useQueryClient();
205
+ return useMemo(() => {
206
+ const write = (action, options, call) => errors.run(call, {
207
+ operation: Operation.mutation,
208
+ session,
209
+ signal: options.signal,
210
+ idempotency: resource.options.idempotency?.[action] ?? Idempotency.none,
211
+ idempotencyKey: options.idempotencyKey,
212
+ });
213
+ return {
214
+ async create(input, options = {}) {
215
+ const row = await write(ResourceAction.create, options, (context) => resource.service.create(input, context));
216
+ void invalidateResource(client, resource);
217
+ return row;
218
+ },
219
+ async update(id, patch, options = {}) {
220
+ const row = await write(ResourceAction.update, options, (context) => resource.service.update(id, patch, { ...context, version: options.version }));
221
+ writeRow(client, resource, row);
222
+ void invalidateResource(client, resource);
223
+ return row;
224
+ },
225
+ async remove(target, options = {}) {
226
+ await write(ResourceAction.remove, options, (context) => resource.service.remove(target, context));
227
+ void invalidateResource(client, resource);
228
+ },
229
+ async restore(target, options = {}) {
230
+ const restore = resource.service.restore;
231
+ if (!restore)
232
+ throw new ServiceFailure(serviceError(ServiceErrorKind.forbidden, "This resource has no restore."));
233
+ await write(ResourceAction.restore, options, (context) => restore.call(resource.service, target, context));
234
+ void invalidateResource(client, resource);
235
+ },
236
+ };
237
+ }, [client, resource, session, errors]);
238
+ }
239
+ export function useResourceCount(resource, filter, options = {}) {
240
+ const layer = useDataLayer();
241
+ const result = useQuery({
242
+ queryKey: resourceCountKey(resource, filter),
243
+ queryFn: ({ signal }) => read(layer, signal, async (context) => {
244
+ const full = resource.filterOf(filter);
245
+ if (resource.service.count)
246
+ return resource.service.count(full, context);
247
+ const page = await resource.service.list({ filter: full, sort: [], size: 1, position: { page: 1 } }, context);
248
+ return page.total ?? page.items.length;
249
+ }),
250
+ retry: false,
251
+ staleTime: resource.staleTime,
252
+ ...(options.refetchInterval === undefined ? {} : { refetchInterval: options.refetchInterval }),
253
+ });
254
+ return { count: result.data, error: toError(result.error) };
255
+ }
@@ -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,15 @@
1
+ export { DataLayer, useDataLayer, useLabels, useLocalized, useResourceLayer, useSession, type DataLayerProps, type DataLayerValue, } from "./data-layer.js";
2
+ export { resourceCountKey, resourceDetailKey, resourcePageKey, resourceSourceKey, resourceTableQuery, sourcePageKey, type ResourceTableQuery, } from "./keys.js";
3
+ export { invalidateResource, refreshOptions, useResource, useResourceCount, useResourceList, useResourceMutations, writeRow, type ResourceListOptions, type ResourceListState, type ResourceMutations, type ResourceState, type TotalInfo, type WriteOptions, } from "./hooks/use-resource.js";
4
+ export { invalidateAfter, useAction, useErrorText, type ActionState, type ActionSubmitOptions, } from "./hooks/use-action.js";
5
+ export { useReauthenticate } from "./hooks/use-reauthenticate.js";
6
+ export { useActionDialog, type ActionDialogOptions, type ActionDialogState } from "./hooks/use-action-dialog.js";
7
+ export { useBulkAction, type UseBulkActionOptions, type BulkActionState, type BulkSelection, } from "./hooks/use-bulk-action.js";
8
+ export { useView } from "./hooks/use-view.js";
9
+ export { useDocumentTitle, useNav, useRoutedNav, type NavState } from "./hooks/use-nav.js";
10
+ export { useDraft } from "./hooks/use-draft.js";
11
+ export { useBetterAuthSession, type BetterAuthSessionState } from "./hooks/use-better-auth.js";
12
+ export { usePermission, usePermissionSession } from "./hooks/use-permissions.js";
13
+ export { useDialogHost, useDialogs, type DialogHost } from "./hooks/use-dialogs.js";
14
+ export { useHeldSource, useNewRows, type NewRowsState } from "./hooks/use-new-rows.js";
15
+ export { applyNewRows, heldRead, markOwnChange, newRowsOf } from "./new-rows.js";
@@ -0,0 +1,15 @@
1
+ export { DataLayer, useDataLayer, useLabels, useLocalized, useResourceLayer, useSession, } from "./data-layer.js";
2
+ export { resourceCountKey, resourceDetailKey, resourcePageKey, resourceSourceKey, resourceTableQuery, sourcePageKey, } from "./keys.js";
3
+ export { invalidateResource, refreshOptions, useResource, useResourceCount, useResourceList, useResourceMutations, writeRow, } from "./hooks/use-resource.js";
4
+ export { invalidateAfter, useAction, useErrorText, } from "./hooks/use-action.js";
5
+ export { useReauthenticate } from "./hooks/use-reauthenticate.js";
6
+ export { useActionDialog } from "./hooks/use-action-dialog.js";
7
+ export { useBulkAction, } from "./hooks/use-bulk-action.js";
8
+ export { useView } from "./hooks/use-view.js";
9
+ export { useDocumentTitle, useNav, useRoutedNav } from "./hooks/use-nav.js";
10
+ export { useDraft } from "./hooks/use-draft.js";
11
+ export { useBetterAuthSession } from "./hooks/use-better-auth.js";
12
+ export { usePermission, usePermissionSession } from "./hooks/use-permissions.js";
13
+ export { useDialogHost, useDialogs } from "./hooks/use-dialogs.js";
14
+ export { useHeldSource, useNewRows } from "./hooks/use-new-rows.js";
15
+ export { applyNewRows, heldRead, markOwnChange, newRowsOf } from "./new-rows.js";
@@ -0,0 +1,60 @@
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
+ /** The key a `PageSource` page is cached under, as `server-data`'s `pageKey` writes it. */
10
+ export declare function sourcePageKey(source: {
11
+ key: readonly unknown[];
12
+ }, request: {
13
+ filter: unknown;
14
+ sort: unknown;
15
+ position: unknown;
16
+ size: number;
17
+ }): QueryKey;
18
+ export declare function resourceDetailKey(resource: {
19
+ queryKey: readonly unknown[];
20
+ }, id: string): QueryKey;
21
+ /** A record with the relations a page shows (`include`), apart from the plain record. */
22
+ export declare function resourceDetailWithKey(resource: {
23
+ queryKey: readonly unknown[];
24
+ }, id: string, include: readonly string[]): QueryKey;
25
+ export declare function resourceCountKey(resource: {
26
+ queryKey: readonly unknown[];
27
+ }, filter: unknown): QueryKey;
28
+ /**
29
+ * The key of a resource's source with a filter that always applies (a view's base filter and scope, a table's
30
+ * `filter`): its own cache entries, apart from the unfiltered source's.
31
+ */
32
+ export declare function resourceSourceKey(resource: {
33
+ queryKey: readonly unknown[];
34
+ }, fixed: object, include?: readonly string[]): QueryKey;
35
+ /**
36
+ * The paths a resource's table shows by default: its columns that aren't hidden, without `except` (a `hasMany`
37
+ * tab's foreign key, and the relation column that shows it).
38
+ */
39
+ export declare function shownPaths(resource: {
40
+ columns(): readonly {
41
+ key: string;
42
+ hidden: boolean;
43
+ relation?: {
44
+ key: string;
45
+ };
46
+ }[];
47
+ }, except?: string): string[];
48
+ export type ResourceTableQuery<F> = {
49
+ /** The page `ResourceTable` shows first for the view's state. */
50
+ page: QueryKey;
51
+ /** Its count, when the service counts apart. */
52
+ total: QueryKey | undefined;
53
+ /** What the service is asked for that page. */
54
+ query: Query<F>;
55
+ };
56
+ /**
57
+ * The queries a `ResourceTable` over `view` runs first, with the keys it caches them under, so a server can fetch
58
+ * them before the table renders (Next.js `HydrationBoundary`).
59
+ */
60
+ 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,71 @@
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
+ /** The key a `PageSource` page is cached under, as `server-data`'s `pageKey` writes it. */
10
+ export function sourcePageKey(source, request) {
11
+ return [...source.key, "page", request.filter, request.sort, request.position, request.size];
12
+ }
13
+ export function resourceDetailKey(resource, id) {
14
+ return [...resource.queryKey, "detail", id];
15
+ }
16
+ /** A record with the relations a page shows (`include`), apart from the plain record. */
17
+ export function resourceDetailWithKey(resource, id, include) {
18
+ return include.length === 0 ? resourceDetailKey(resource, id) : [...resourceDetailKey(resource, id), "with", include];
19
+ }
20
+ export function resourceCountKey(resource, filter) {
21
+ return [...resource.queryKey, "count", filter];
22
+ }
23
+ /**
24
+ * The key of a resource's source with a filter that always applies (a view's base filter and scope, a table's
25
+ * `filter`): its own cache entries, apart from the unfiltered source's.
26
+ */
27
+ export function resourceSourceKey(resource, fixed, include = []) {
28
+ const key = JSON.stringify(fixed);
29
+ const base = Object.keys(fixed).length > 0 && key !== "{}" ? [...resource.queryKey, "fixed", key] : resource.queryKey;
30
+ return include.length === 0 ? base : [...base, "with", include.toSorted().join(",")];
31
+ }
32
+ /**
33
+ * The paths a resource's table shows by default: its columns that aren't hidden, without `except` (a `hasMany`
34
+ * tab's foreign key, and the relation column that shows it).
35
+ */
36
+ export function shownPaths(resource, except) {
37
+ return resource
38
+ .columns()
39
+ .filter((column) => !column.hidden && (except === undefined || (column.key !== except && column.relation?.key !== except)))
40
+ .map((column) => column.key);
41
+ }
42
+ // Spec: the values `ResourceTable`'s page controller passes on (text, yes/no, a list, a range or an operator).
43
+ function isFilterValue(value) {
44
+ return isString(value) || isBoolean(value) || Array.isArray(value) || isRecord(value);
45
+ }
46
+ /**
47
+ * The queries a `ResourceTable` over `view` runs first, with the keys it caches them under, so a server can fetch
48
+ * them before the table renders (Next.js `HydrationBoundary`).
49
+ */
50
+ export function resourceTableQuery(resource, view, filter = {}, paths = []) {
51
+ const include = includeOf(resource.relations, paths);
52
+ const state = view.getState();
53
+ const scope = view.scopes.find((entry) => entry.id === state.scope)?.filter;
54
+ const fixed = { ...view.options.baseFilter, ...scope, ...filter };
55
+ const values = Object.fromEntries(Object.entries(state.filter).filter(([, value]) => isFilterValue(value)));
56
+ const shown = state.search === "" ? values : { ...values, [searchKey]: state.search };
57
+ const source = resourceSourceKey(resource, fixed, include);
58
+ const position = { page: state.page };
59
+ return {
60
+ page: [...source, "page", shown, state.sort, position, state.size],
61
+ total: resource.service.count ? [...source, "total", shown] : undefined,
62
+ query: {
63
+ filter: resource.filterOf({ ...values, ...fixed }),
64
+ search: state.search === "" ? undefined : state.search,
65
+ sort: state.sort,
66
+ size: state.size,
67
+ position,
68
+ ...(include.length > 0 ? { include } : {}),
69
+ },
70
+ };
71
+ }
@@ -0,0 +1,22 @@
1
+ import { type QueryClient, type QueryKey } from "@tanstack/react-query";
2
+ import { NewRows } from "../core/constants.js";
3
+ import type { Page } from "../core/contracts.js";
4
+ /** This browser changed the resource: its next reloads are its own doing and show every row at once. */
5
+ export declare function markOwnChange(client: QueryClient, resource: string): void;
6
+ type HeldResource<T, Id> = {
7
+ readonly key: string;
8
+ idOf(row: T): Id;
9
+ idKey(id: Id): string;
10
+ };
11
+ /**
12
+ * Reads a page for a query that may already be on screen. A reload of a shown page (focus, reconnect, a poll, a
13
+ * remount) keeps its rows in place with their new values and holds rows it didn't show for `applyNewRows`; a first
14
+ * read, a reload after this browser's own change and `NewRows.show` take the page as read.
15
+ */
16
+ export declare function heldRead<T, Id>(client: QueryClient, resource: HeldResource<T, Id>, queryKey: QueryKey, newRows: NewRows, read: () => Promise<Page<T>>): Promise<Page<T>>;
17
+ /** How many new rows a reload held back for the query. */
18
+ export declare function newRowsOf(client: QueryClient, queryKey: QueryKey): number;
19
+ /** Shows the rows held back for the query: the page as the reload read it. */
20
+ export declare function applyNewRows(client: QueryClient, queryKey: QueryKey): boolean;
21
+ export declare function subscribeNewRows(client: QueryClient, listener: () => void): () => void;
22
+ export {};
@@ -0,0 +1,72 @@
1
+ import { hashKey } from "@tanstack/react-query";
2
+ import { NewRows } from "../core/constants.js";
3
+ import { holdNewRows } from "../refresh/new-rows.js";
4
+ const states = new WeakMap();
5
+ function stateOf(client) {
6
+ const known = states.get(client);
7
+ if (known)
8
+ return known;
9
+ const state = { held: new Map(), listeners: new Set(), changed: new Map() };
10
+ states.set(client, state);
11
+ return state;
12
+ }
13
+ function notify(state) {
14
+ for (const listener of state.listeners)
15
+ listener();
16
+ }
17
+ function forget(state, hash) {
18
+ if (state.held.delete(hash))
19
+ notify(state);
20
+ }
21
+ /** This browser changed the resource: its next reloads are its own doing and show every row at once. */
22
+ export function markOwnChange(client, resource) {
23
+ stateOf(client).changed.set(resource, Date.now());
24
+ }
25
+ /**
26
+ * Reads a page for a query that may already be on screen. A reload of a shown page (focus, reconnect, a poll, a
27
+ * remount) keeps its rows in place with their new values and holds rows it didn't show for `applyNewRows`; a first
28
+ * read, a reload after this browser's own change and `NewRows.show` take the page as read.
29
+ */
30
+ export async function heldRead(client, resource, queryKey, newRows, read) {
31
+ const fresh = await read();
32
+ const state = stateOf(client);
33
+ const hash = hashKey(queryKey);
34
+ const shown = client.getQueryData(queryKey);
35
+ const updatedAt = client.getQueryState(queryKey)?.dataUpdatedAt ?? 0;
36
+ const ownChange = state.changed.get(resource.key) ?? Number.NEGATIVE_INFINITY;
37
+ if (newRows === NewRows.show || shown === undefined || !Array.isArray(shown.items) || ownChange >= updatedAt) {
38
+ forget(state, hash);
39
+ return fresh;
40
+ }
41
+ const idOf = (row) => resource.idKey(resource.idOf(row));
42
+ const held = holdNewRows(shown, fresh, idOf);
43
+ if (held.added.length === 0) {
44
+ forget(state, hash);
45
+ return held.page;
46
+ }
47
+ state.held.set(hash, { key: queryKey, fresh, count: held.added.length });
48
+ notify(state);
49
+ return held.page;
50
+ }
51
+ /** How many new rows a reload held back for the query. */
52
+ export function newRowsOf(client, queryKey) {
53
+ return stateOf(client).held.get(hashKey(queryKey))?.count ?? 0;
54
+ }
55
+ /** Shows the rows held back for the query: the page as the reload read it. */
56
+ export function applyNewRows(client, queryKey) {
57
+ const state = stateOf(client);
58
+ const hash = hashKey(queryKey);
59
+ const held = state.held.get(hash);
60
+ if (!held)
61
+ return false;
62
+ client.setQueryData(held.key, held.fresh);
63
+ forget(state, hash);
64
+ return true;
65
+ }
66
+ export function subscribeNewRows(client, listener) {
67
+ const { listeners } = stateOf(client);
68
+ listeners.add(listener);
69
+ return () => {
70
+ listeners.delete(listener);
71
+ };
72
+ }
@@ -0,0 +1,13 @@
1
+ import type { Page } from "../core/contracts.js";
2
+ export type HeldPage<T> = {
3
+ /** What the list keeps showing: its rows in their order, each as the reload read it. */
4
+ page: Page<T>;
5
+ /** The rows the reload found that weren't shown, held back. */
6
+ added: readonly T[];
7
+ };
8
+ /**
9
+ * Merges a background reload into the page on screen without moving it: shown rows keep their place and take the
10
+ * reload's values, rows that are gone leave, and rows that are new wait in `added`. A row the reload no longer has
11
+ * stays while new rows are held, since they pushed it to the next page rather than deleting it.
12
+ */
13
+ export declare function holdNewRows<T>(shown: Page<T>, fresh: Page<T>, idOf: (row: T) => string): HeldPage<T>;
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Merges a background reload into the page on screen without moving it: shown rows keep their place and take the
3
+ * reload's values, rows that are gone leave, and rows that are new wait in `added`. A row the reload no longer has
4
+ * stays while new rows are held, since they pushed it to the next page rather than deleting it.
5
+ */
6
+ export function holdNewRows(shown, fresh, idOf) {
7
+ const freshById = new Map(fresh.items.map((row) => [idOf(row), row]));
8
+ const shownIds = new Set(shown.items.map(idOf));
9
+ const added = fresh.items.filter((row) => !shownIds.has(idOf(row)));
10
+ const items = shown.items.flatMap((row) => {
11
+ const latest = freshById.get(idOf(row));
12
+ if (latest !== undefined)
13
+ return [latest];
14
+ return added.length > 0 ? [row] : [];
15
+ });
16
+ const total = fresh.total === undefined ? shown.total : fresh.total - added.length;
17
+ return { page: { ...fresh, items, ...(total === undefined ? {} : { total }) }, added };
18
+ }
@@ -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
+ }