@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,281 @@
1
+ import type { Align, ColumnKind, CreateMode, RelationDenied, RelationKind, FieldKind, FilterKind, FormStage, JsonType, MobileSlot, ResourceAction, ResourceScreen } from "../core/constants.js";
2
+ import type { Page, PageSourceLike, Query, ResourceService, SortSpec } from "../core/contracts.js";
3
+ import type { Allowed, Refusal } from "../core/refusal.js";
4
+ import type { Introspect, SchemaProperty, StandardSchema } from "./schema.js";
5
+ import type { RelationContext, RelationRows, Relations } from "./relations.js";
6
+ import type { Session } from "../session/session.js";
7
+ type Primitive = string | number | boolean | bigint | symbol | null | undefined | Date;
8
+ /** A dotted path into `T`, three levels deep: `"name"`, `"customer.name"`, `"customer.country.name"`. */
9
+ export type Path<T, Depth extends unknown[] = []> = Depth["length"] extends 3 ? never : T extends Primitive | readonly unknown[] ? never : {
10
+ [Key in keyof T & string]: Key | (NonNullable<T[Key]> extends Primitive | readonly unknown[] ? never : `${Key}.${Path<NonNullable<T[Key]>, [...Depth, unknown]>}`);
11
+ }[keyof T & string];
12
+ export type AnyResource = Resource<any, any, any>;
13
+ export type ToneName = string;
14
+ export type Option = {
15
+ value: string;
16
+ label: string;
17
+ };
18
+ export type ColumnDef<T, Key extends string = Path<T> | (string & {})> = {
19
+ /** A path into the row, through relations too (`"customer.country.name"`); `defineResource` checks it. */
20
+ key: Key;
21
+ label?: string;
22
+ as?: ColumnKind;
23
+ tones?: Partial<Record<string, ToneName>>;
24
+ /** What each value shows as, in pills, badges and filters: `{ pending: "Pendiente" }`. The stored value stays. */
25
+ valueLabels?: Readonly<Record<string, string>>;
26
+ cell?: (row: T) => unknown;
27
+ /** `true` sorts by the key on the server; a string names the server's sort field. */
28
+ sortable?: boolean | string;
29
+ hidden?: boolean;
30
+ width?: string;
31
+ align?: Align;
32
+ /** Where the value goes in `ResourceList` and narrow screens; `false` leaves it out. */
33
+ mobile?: MobileSlot | false;
34
+ };
35
+ export type FieldDef<T> = {
36
+ key: Path<T> | (string & {});
37
+ label?: string;
38
+ description?: string;
39
+ placeholder?: string;
40
+ as?: FieldKind;
41
+ /** For `FieldKind.resource`: a function, so two resources can point at each other. */
42
+ resource?: () => AnyResource;
43
+ /** For `FieldKind.rows`: rows a sub-table edits. Read from the relation by default. */
44
+ fields?: readonly FieldDef<unknown>[];
45
+ /** For `FieldKind.resource`: offers to create what's typed, from the text or (`CreateMode.form`) in a form. */
46
+ create?: boolean | CreateMode;
47
+ /** What each choice shows as, in radios and selects (and the column's pills): `{ pending: "Pendiente" }`. */
48
+ valueLabels?: Readonly<Record<string, string>>;
49
+ multiple?: boolean;
50
+ options?: readonly Option[] | (() => Promise<readonly Option[]>);
51
+ readOnly?: boolean | ((row: T | undefined) => boolean);
52
+ hidden?: boolean | ((values: Partial<T>) => boolean);
53
+ only?: FormStage;
54
+ render?: (field: unknown) => unknown;
55
+ colSpan?: 1 | 2;
56
+ };
57
+ export type FieldGroup<T> = {
58
+ group: string;
59
+ description?: string;
60
+ fields: FieldDef<T>[];
61
+ };
62
+ export type FilterDef<F> = {
63
+ key: keyof F & string;
64
+ label?: string;
65
+ as?: FilterKind;
66
+ resource?: () => AnyResource;
67
+ options?: readonly Option[];
68
+ default?: F[keyof F];
69
+ };
70
+ export type ResourceShortcuts = {
71
+ list?: string;
72
+ create?: string;
73
+ };
74
+ /** The resource's name; `create` names its New button and form when the dictionary's "New {one}" doesn't fit. */
75
+ export type ResourceLabel = {
76
+ one: string;
77
+ other: string;
78
+ create?: string;
79
+ } | ((count: number) => string);
80
+ export type ResourceRoutes<Id> = {
81
+ base?: string;
82
+ create?: string;
83
+ edit?: string;
84
+ detail?: (props: {
85
+ id: Id;
86
+ }) => unknown;
87
+ };
88
+ export type ResourceAudit<T> = {
89
+ createdAt?: keyof T & string;
90
+ createdBy?: keyof T & string;
91
+ updatedAt?: keyof T & string;
92
+ updatedBy?: keyof T & string;
93
+ };
94
+ export type ResourceLabels = Partial<Record<string, unknown>>;
95
+ export type ResourceOptions<T, Id, F> = {
96
+ /** Stable: the cache key, the agents' tool names and saved views' URL. */
97
+ key: string;
98
+ service: ResourceService<T, Id, F>;
99
+ schema?: StandardSchema<unknown, T>;
100
+ createSchema?: StandardSchema;
101
+ updateSchema?: StandardSchema;
102
+ id?: (row: T) => Id;
103
+ label: ResourceLabel;
104
+ icon?: unknown;
105
+ title?: (row: T) => string;
106
+ description?: (row: T) => string;
107
+ columns?: readonly ColumnDef<T>[];
108
+ fields?: readonly (FieldDef<T> | FieldGroup<T>)[];
109
+ filters?: readonly FilterDef<F>[];
110
+ searchable?: boolean;
111
+ defaultSort?: readonly SortSpec[];
112
+ can?: (action: ResourceAction, row?: T) => boolean | Refusal;
113
+ /** Its own actions, in its rows, records and routes; a function when they refer back to the resource. */
114
+ actions?: readonly unknown[] | (() => readonly unknown[]);
115
+ routes?: ResourceRoutes<Id>;
116
+ /** How long data counts as fresh, in ms. Default 30 000. */
117
+ staleTime?: number;
118
+ /** Shows "show deleted" and restore. Default: the service's `capabilities.restore`. */
119
+ softDelete?: boolean;
120
+ audit?: ResourceAudit<T>;
121
+ search?: false | {
122
+ to?: (row: T) => string;
123
+ };
124
+ /** The most rows a browser export reads. Default 10 000. */
125
+ exportLimit?: number;
126
+ /** Keys that go to the list (`navItem` uses it, `"g c"`) and open a new record on its page (`"n"`). */
127
+ shortcuts?: ResourceShortcuts;
128
+ labels?: ResourceLabels;
129
+ /** Reads the schema's properties; Zod 4 by default. */
130
+ introspect?: Introspect;
131
+ /**
132
+ * Other records this one points at or holds: `belongsTo`, `hasMany`, `manyToMany` and `embeds`. Columns, fields,
133
+ * filters and the record's tabs read them; lists read the related records in batches.
134
+ */
135
+ relations?: Relations;
136
+ };
137
+ /** `defineResource`'s options: column keys are checked against the row and its relations. */
138
+ export type DefineResourceOptions<T, Id, F, R extends Relations> = Omit<ResourceOptions<T, Id, F>, "columns" | "relations"> & {
139
+ relations?: R;
140
+ columns?: readonly ColumnDef<T & RelationRows<R>, Path<T & RelationRows<R>>>[];
141
+ };
142
+ /** A relation as a column or a field shows it. */
143
+ export type ResolvedRelation = {
144
+ name: string;
145
+ kind: RelationKind;
146
+ /** The id field of a `belongsTo` or `manyToMany`; the foreign key of a `hasMany`. */
147
+ key: string;
148
+ target: () => AnyResource;
149
+ denied: RelationDenied;
150
+ /** The fields a snapshot keeps under the relation's name. */
151
+ snapshot?: readonly string[];
152
+ };
153
+ export type ResolvedColumn<T> = {
154
+ key: string;
155
+ label: string;
156
+ kind: ColumnKind;
157
+ tones?: Partial<Record<string, ToneName>>;
158
+ cell?: (row: T) => unknown;
159
+ sortField?: string;
160
+ hidden: boolean;
161
+ width?: string;
162
+ align?: Align;
163
+ mobile?: MobileSlot | false;
164
+ options?: readonly Option[];
165
+ /** The field's kind for the same key, so a cell shows a colour, a duration or an image as such. */
166
+ field?: FieldKind;
167
+ /** The relation it shows: a related record's title (`customer`, `customerId`), or a field through it. */
168
+ relation?: ResolvedRelation;
169
+ /** What's left of the key past the relation: `name` in `customer.name`. */
170
+ relationPath?: string;
171
+ };
172
+ export type ResolvedField<T> = {
173
+ key: string;
174
+ label: string;
175
+ kind: FieldKind;
176
+ description?: string;
177
+ placeholder?: string;
178
+ required: boolean;
179
+ resource?: () => AnyResource;
180
+ create?: boolean | CreateMode;
181
+ multiple: boolean;
182
+ options?: readonly Option[] | (() => Promise<readonly Option[]>);
183
+ readOnly: (row: T | undefined) => boolean;
184
+ hidden: (values: Partial<T>) => boolean;
185
+ render?: (field: unknown) => unknown;
186
+ colSpan: 1 | 2;
187
+ min?: number;
188
+ max?: number;
189
+ /** The schema's type for the value, so a control writes it back as such (a duration as text or seconds). */
190
+ valueType?: JsonType;
191
+ relation?: ResolvedRelation;
192
+ /** `FieldKind.rows` and `FieldKind.object`: the fields of each row, or of the subdocument. */
193
+ fields?: readonly ResolvedField<Record<string, unknown>>[];
194
+ group?: string;
195
+ groupDescription?: string;
196
+ };
197
+ export type ResolvedFilter = {
198
+ key: string;
199
+ label: string;
200
+ kind: FilterKind;
201
+ options?: readonly Option[];
202
+ resource?: () => AnyResource;
203
+ default?: unknown;
204
+ };
205
+ export type ResourceMatch = {
206
+ screen: ResourceScreen;
207
+ id?: string;
208
+ tab?: string;
209
+ };
210
+ export type Resource<T, Id = string, F = Record<string, unknown>> = {
211
+ readonly key: string;
212
+ readonly options: ResourceOptions<T, Id, F>;
213
+ readonly service: ResourceService<T, Id, F>;
214
+ readonly schema: StandardSchema<unknown, T> | undefined;
215
+ readonly icon: unknown;
216
+ readonly staleTime: number;
217
+ readonly exportLimit: number;
218
+ readonly shortcuts: ResourceShortcuts;
219
+ readonly searchable: boolean;
220
+ readonly softDelete: boolean;
221
+ readonly defaultSort: readonly SortSpec[];
222
+ readonly queryKey: readonly unknown[];
223
+ label(count?: number): string;
224
+ /** The label's `create`, when it has one. */
225
+ readonly createLabel: string | undefined;
226
+ title(row: T): string;
227
+ /** The field a row's title comes from when `title` isn't given: the schema's first text property. */
228
+ readonly titleField: string | undefined;
229
+ /** A new record's values from a typed text, in `titleField`; `undefined` without one. */
230
+ inputFromText(text: string): Partial<T> | undefined;
231
+ description(row: T): string | undefined;
232
+ idOf(row: T): Id;
233
+ idKey(id: Id): string;
234
+ parseId(raw: string): Id;
235
+ readonly source: PageSourceLike<T, F & {
236
+ q?: string | undefined;
237
+ }>;
238
+ /**
239
+ * The resource's `PageSource` with the session; with `reading.paths` (the visible columns), each page asks the
240
+ * server to embed their relations and reads the rest in batches.
241
+ */
242
+ sourceFor(session: Session | undefined, reading?: {
243
+ paths: readonly string[];
244
+ context?: Omit<RelationContext, "signal" | "session">;
245
+ }): PageSourceLike<T, F & {
246
+ q?: string | undefined;
247
+ }>;
248
+ /** A page with the relations `paths` reach: embedded by the server, or read in batches (`resolveRelations`). */
249
+ listWith(query: Query<F>, context: RelationContext, paths?: readonly string[]): Promise<Page<T>>;
250
+ columns(): ResolvedColumn<T>[];
251
+ fields(stage: FormStage): ResolvedField<T>[];
252
+ filters(): ResolvedFilter[];
253
+ properties(): readonly SchemaProperty[];
254
+ /**
255
+ * Reads a filter from outside TypeScript (the URL, an agent, a form) as the service's: a record keeps its keys and
256
+ * the service checks them, anything else is no filter. `q` stays, as the search text.
257
+ */
258
+ filterOf(value: unknown): F & {
259
+ q?: string | undefined;
260
+ };
261
+ inputOf(value: unknown): Partial<T>;
262
+ check(action: ResourceAction, row?: T, session?: Session, notAllowed?: string): Allowed;
263
+ readonly routes: {
264
+ base: string;
265
+ create: string;
266
+ edit: string;
267
+ };
268
+ readonly paths: {
269
+ list(): string;
270
+ create(): string;
271
+ detail(id: Id): string;
272
+ edit(id: Id): string;
273
+ /** A record's tab of a `hasMany`: `/orders/12/lines`. */
274
+ tab(id: Id, relation: string): string;
275
+ };
276
+ match(pathname: string): ResourceMatch | undefined;
277
+ readonly relations: Relations;
278
+ actions(): readonly unknown[];
279
+ readonly audit: ResourceAudit<T> | undefined;
280
+ };
281
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,11 @@
1
+ import { dependentsOf } from "./resource-relations.js";
2
+ import { type RelationRows, type Relations } from "./relations.js";
3
+ import type { DefineResourceOptions, Resource } from "./resource-types.js";
4
+ export type * from "./resource-types.js";
5
+ export { dependentsOf };
6
+ export declare const searchKey = "q";
7
+ /**
8
+ * Declares a resource. Called twice, `defineResource<Customer>()({ … })`, so `T` is given by hand and the rest is
9
+ * inferred. Columns, fields and filters left out come from the schema (Zod 4 first).
10
+ */
11
+ export declare function defineResource<T>(): <Id = string, F = Record<string, unknown>, const R extends Relations = {}>(options: DefineResourceOptions<T, Id, F, R>) => Resource<T & RelationRows<R>, Id, F>;
@@ -0,0 +1,354 @@
1
+ import { FieldKind, RelationKind, RowsMode, FilterKind, FormStage, JsonType, ResourceAction, ResourceScreen, ColumnKind, } from "../core/constants.js";
2
+ import { assumeType } from "../core/assume.js";
3
+ import { isFunction, isRecord, isString, isText } from "../core/guards.js";
4
+ import { valueAt } from "../services/memory-query.js";
5
+ import { firstRefusal, toAllowed } from "../core/refusal.js";
6
+ import { columnKindOf, fieldKindOf, isGroup, optionsOfEnum, propertyAt } from "./resource-schema.js";
7
+ import { defined, dependentsOf, inheritedColumn, relationTools, valueLabelsIn } from "./resource-relations.js";
8
+ import { includeOf, registerResource, resolveRelations, } from "./relations.js";
9
+ import { zodIntrospect } from "./schema.js";
10
+ export { dependentsOf };
11
+ export const searchKey = "q";
12
+ const always = () => true;
13
+ const never = () => false;
14
+ function segment(value) {
15
+ return value.replace(/^\/+|\/+$/gu, "");
16
+ }
17
+ /**
18
+ * Declares a resource. Called twice, `defineResource<Customer>()({ … })`, so `T` is given by hand and the rest is
19
+ * inferred. Columns, fields and filters left out come from the schema (Zod 4 first).
20
+ */
21
+ export function defineResource() {
22
+ return function define(options) {
23
+ // Workaround: a row read with its relations is `T` with each relation's record added under its name; the
24
+ // options describe `T`, which every such row still is.
25
+ return createResource(assumeType(options));
26
+ };
27
+ }
28
+ function createResource(options) {
29
+ let cachedProperties;
30
+ const properties = () => {
31
+ cachedProperties ??= options.schema ? ((options.introspect ?? zodIntrospect)(options.schema) ?? []) : [];
32
+ return cachedProperties;
33
+ };
34
+ const label = (count = 1) => isFunction(options.label) ? options.label(count) : count === 1 ? options.label.one : options.label.other;
35
+ const idOf = (row) => {
36
+ if (options.id)
37
+ return options.id(row);
38
+ // Workaround: without `id`, a row's id is its `id` property, whose type is the service's `Id`.
39
+ return assumeType(valueAt(row, "id"));
40
+ };
41
+ const firstText = properties().find((property) => property.type === JsonType.string && property.key !== "id");
42
+ const title = (row) => {
43
+ if (options.title)
44
+ return options.title(row);
45
+ const value = firstText ? valueAt(row, firstText.key) : undefined;
46
+ return isText(value) ? value : String(idOf(row));
47
+ };
48
+ const routes = {
49
+ base: segment(options.routes?.base ?? options.key),
50
+ create: segment(options.routes?.create ?? "new"),
51
+ edit: segment(options.routes?.edit ?? "edit"),
52
+ };
53
+ const idKey = (id) => String(id);
54
+ const numericIds = properties().find((property) => property.key === "id");
55
+ const parseId = (raw) => {
56
+ const decoded = decodeURIComponent(raw);
57
+ const asNumber = numericIds?.type === JsonType.number || numericIds?.type === JsonType.integer;
58
+ // Workaround: an id read from a URL is text; the schema says whether the service's `Id` is a number.
59
+ return assumeType(asNumber && decoded.trim() !== "" && !Number.isNaN(Number(decoded)) ? Number(decoded) : decoded);
60
+ };
61
+ const auditKeys = new Set(Object.values(options.audit ?? {}).filter(isString));
62
+ const relations = options.relations ?? {};
63
+ const { relationAt, relationField } = relationTools({
64
+ relations,
65
+ properties,
66
+ introspect: options.introspect,
67
+ });
68
+ function declaredKind(key) {
69
+ const declared = (options.fields ?? []).flatMap((entry) => (isGroup(entry) ? entry.fields : [entry]));
70
+ const field = declared.find((entry) => entry.key === key);
71
+ if (field?.as !== undefined)
72
+ return field.as;
73
+ const property = propertyAt(properties(), key);
74
+ return property ? fieldKindOf(property) : undefined;
75
+ }
76
+ const valueLabelsOf = (key) => valueLabelsIn(options, key);
77
+ function columns() {
78
+ const declared = options.columns ??
79
+ properties()
80
+ .filter((property) => property.type !== JsonType.object &&
81
+ !(property.type === JsonType.array && property.items?.type === JsonType.object))
82
+ .filter((property) => property.key !== "id" || !numericIds)
83
+ .map((property) => ({ key: property.key, ...(auditKeys.has(property.key) ? { hidden: true } : {}) }));
84
+ return declared.map((column) => {
85
+ const property = propertyAt(properties(), column.key);
86
+ const sortField = column.sortable === true ? column.key : isString(column.sortable) ? column.sortable : undefined;
87
+ const enumOptions = optionsOfEnum(property, column.valueLabels ?? valueLabelsOf(column.key));
88
+ const field = declaredKind(column.key);
89
+ const reached = relationAt(column.key);
90
+ const related = reached?.relation.target();
91
+ const relatedLabel = reached
92
+ ? reached.rest === undefined
93
+ ? related?.label(reached.relation.kind === RelationKind.belongsTo ? 1 : 2)
94
+ : `${related?.label(1) ?? reached.relation.name} · ${propertyAt(related?.properties() ?? [], reached.rest)?.title ?? reached.rest}`
95
+ : undefined;
96
+ const sortable = reached === undefined || (reached.rest !== undefined && options.service.capabilities.relationSort === true);
97
+ const inherited = inheritedColumn(related, reached?.rest);
98
+ const tones = column.tones ?? inherited.tones;
99
+ const inheritedKind = inherited.kind(tones !== undefined);
100
+ const align = column.align ?? inherited.align;
101
+ const relatedOptions = inherited.options;
102
+ return {
103
+ key: column.key,
104
+ label: column.label ?? relatedLabel ?? property?.title ?? column.key,
105
+ kind: column.as ??
106
+ (reached
107
+ ? (inheritedKind ?? ColumnKind.text)
108
+ : property
109
+ ? columnKindOf(property, column.tones !== undefined)
110
+ : ColumnKind.text),
111
+ hidden: column.hidden ?? false,
112
+ ...(tones ? { tones } : {}),
113
+ ...(relatedOptions && !enumOptions ? { options: relatedOptions } : {}),
114
+ ...(column.cell ? { cell: column.cell } : {}),
115
+ ...(sortField === undefined || !sortable ? {} : { sortField }),
116
+ ...(reached
117
+ ? { relation: reached.relation, ...(reached.rest === undefined ? {} : { relationPath: reached.rest }) }
118
+ : {}),
119
+ ...(column.width === undefined ? {} : { width: column.width }),
120
+ ...(align === undefined ? {} : { align }),
121
+ ...(column.mobile === undefined ? {} : { mobile: column.mobile }),
122
+ ...(enumOptions ? { options: enumOptions } : {}),
123
+ ...(field === undefined ? {} : { field }),
124
+ };
125
+ });
126
+ }
127
+ function resolveField(field, group) {
128
+ if (field.as === undefined || field.as === FieldKind.resource || field.as === FieldKind.rows) {
129
+ const related = relationField(field, group);
130
+ if (related)
131
+ return related;
132
+ }
133
+ const property = propertyAt(properties(), field.key);
134
+ const readOnly = field.readOnly;
135
+ const hidden = field.hidden;
136
+ const fieldOptions = field.options ?? optionsOfEnum(property, field.valueLabels ?? valueLabelsOf(field.key));
137
+ const description = field.description ?? property?.description;
138
+ return {
139
+ key: field.key,
140
+ label: field.label ?? property?.title ?? field.key,
141
+ kind: field.as ?? (field.resource ? FieldKind.resource : fieldKindOf(property)),
142
+ required: property?.required ?? false,
143
+ multiple: field.multiple ?? property?.type === JsonType.array,
144
+ readOnly: isFunction(readOnly) ? readOnly : readOnly === true || property?.readOnly === true ? always : never,
145
+ hidden: isFunction(hidden) ? hidden : hidden === true ? always : never,
146
+ colSpan: field.colSpan ?? 1,
147
+ ...(description === undefined ? {} : { description }),
148
+ ...(field.placeholder === undefined ? {} : { placeholder: field.placeholder }),
149
+ ...(field.resource ? { resource: field.resource } : {}),
150
+ ...(field.create === undefined ? {} : { create: field.create }),
151
+ ...(fieldOptions ? { options: fieldOptions } : {}),
152
+ ...(field.render ? { render: field.render } : {}),
153
+ ...(property?.minimum === undefined ? {} : { min: property.minimum }),
154
+ ...(property?.maximum === undefined ? {} : { max: property.maximum }),
155
+ ...(property?.type === undefined ? {} : { valueType: property.type }),
156
+ ...(group
157
+ ? { group: group.group, ...(group.description === undefined ? {} : { groupDescription: group.description }) }
158
+ : {}),
159
+ };
160
+ }
161
+ function fields(stage) {
162
+ const declared = options.fields ??
163
+ properties()
164
+ .filter((property) => property.key !== "id" &&
165
+ !auditKeys.has(property.key) &&
166
+ property.type !== JsonType.object &&
167
+ !(property.type === JsonType.array && property.items?.type === JsonType.object))
168
+ .map((property) => ({ key: property.key }))
169
+ .concat(Object.entries(relations).flatMap(([name, relation]) => relation.kind === RelationKind.embeds ||
170
+ (relation.kind === RelationKind.hasMany && relation.mode === RowsMode.inline)
171
+ ? [{ key: name }]
172
+ : []));
173
+ const flat = declared.flatMap((entry) => isGroup(entry) ? entry.fields.map((field) => resolveField(field, entry)) : [resolveField(entry)]);
174
+ const only = new Map(declared.flatMap((entry) => (isGroup(entry) ? entry.fields : [entry])).map((field) => [field.key, field.only]));
175
+ return flat.filter((field) => {
176
+ const wanted = only.get(field.key);
177
+ if (wanted !== undefined && wanted !== stage)
178
+ return false;
179
+ return !(stage === FormStage.create && propertyAt(properties(), field.key)?.readOnly === true);
180
+ });
181
+ }
182
+ function filters() {
183
+ return (options.filters ?? []).map((filter) => {
184
+ const reached = relationAt(filter.key);
185
+ if (reached && reached.rest === undefined && reached.relation.kind !== RelationKind.hasMany) {
186
+ const target = reached.relation.target();
187
+ return {
188
+ key: reached.relation.key,
189
+ label: filter.label ?? target.label(1),
190
+ kind: FilterKind.resource,
191
+ resource: reached.relation.target,
192
+ ...(filter.default === undefined ? {} : { default: filter.default }),
193
+ };
194
+ }
195
+ const property = propertyAt(properties(), filter.key);
196
+ const kind = filter.as ??
197
+ (filter.resource
198
+ ? FilterKind.resource
199
+ : property?.enum
200
+ ? FilterKind.select
201
+ : property?.type === JsonType.boolean
202
+ ? FilterKind.boolean
203
+ : FilterKind.search);
204
+ const filterOptions = filter.options ?? optionsOfEnum(property, valueLabelsOf(filter.key));
205
+ return {
206
+ key: filter.key,
207
+ label: filter.label ?? property?.title ?? filter.key,
208
+ kind,
209
+ ...(filterOptions ? { options: filterOptions } : {}),
210
+ ...(filter.resource ? { resource: filter.resource } : {}),
211
+ ...(filter.default === undefined ? {} : { default: filter.default }),
212
+ };
213
+ });
214
+ }
215
+ // Workaround: a filter that crossed a boundary (URL, agent, table) is a record the service validates as its `F`.
216
+ const filterOf = (value) => assumeType(isRecord(value) ? value : {});
217
+ const softDelete = options.softDelete ?? options.service.capabilities.restore === true;
218
+ const queryKey = ["app-sdk", options.key];
219
+ const sources = new WeakMap();
220
+ async function listWith(query, context, paths = []) {
221
+ const include = includeOf(relations, paths);
222
+ const page = await options.service.list(include.length > 0 ? { ...query, include } : query, context);
223
+ if (include.length === 0)
224
+ return page;
225
+ return { ...page, items: await resolveRelations(resource, page.items, paths, context) };
226
+ }
227
+ function sourceFor(session, reading) {
228
+ if (reading && includeOf(relations, reading.paths).length > 0) {
229
+ const plain = sourceFor(session);
230
+ return {
231
+ ...plain,
232
+ key: [...queryKey, "with", includeOf(relations, reading.paths).toSorted().join(",")],
233
+ fetchPage(request, { signal }) {
234
+ const { [searchKey]: search, ...rest } = isRecord(request.filter) ? request.filter : {};
235
+ return listWith({
236
+ filter: filterOf(rest),
237
+ search: isString(search) ? search : undefined,
238
+ sort: request.sort,
239
+ size: request.size,
240
+ position: request.position,
241
+ }, { ...reading.context, signal, session }, reading.paths);
242
+ },
243
+ };
244
+ }
245
+ if (session) {
246
+ const known = sources.get(session);
247
+ if (known)
248
+ return known;
249
+ }
250
+ const context = (signal) => ({ signal, session });
251
+ const source = {
252
+ key: queryKey,
253
+ getId: (row) => idKey(idOf(row)),
254
+ capabilities: options.service.capabilities,
255
+ fetchPage(request, { signal }) {
256
+ const { [searchKey]: search, ...rest } = isRecord(request.filter) ? request.filter : {};
257
+ const filter = filterOf(rest);
258
+ return options.service.list({
259
+ filter,
260
+ search: isString(search) ? search : undefined,
261
+ sort: request.sort,
262
+ size: request.size,
263
+ position: request.position,
264
+ }, context(signal));
265
+ },
266
+ ...(options.service.count
267
+ ? {
268
+ fetchTotal(filter, { signal }) {
269
+ const { [searchKey]: _search, ...rest } = isRecord(filter) ? filter : {};
270
+ return options.service.count(filterOf(rest), context(signal));
271
+ },
272
+ }
273
+ : {}),
274
+ };
275
+ if (session)
276
+ sources.set(session, source);
277
+ return source;
278
+ }
279
+ const resource = {
280
+ key: options.key,
281
+ options,
282
+ service: options.service,
283
+ schema: options.schema,
284
+ icon: options.icon,
285
+ staleTime: options.staleTime ?? 30_000,
286
+ exportLimit: options.exportLimit ?? 10_000,
287
+ shortcuts: options.shortcuts ?? {},
288
+ searchable: options.searchable ?? true,
289
+ softDelete,
290
+ defaultSort: options.defaultSort ?? [],
291
+ queryKey,
292
+ label,
293
+ createLabel: isFunction(options.label) ? undefined : options.label.create,
294
+ title,
295
+ titleField: firstText?.key,
296
+ // Workaround: the title field is one of `T`'s text properties, so a text in it is part of a `T`.
297
+ inputFromText: (text) => (firstText ? assumeType({ [firstText.key]: text }) : undefined),
298
+ description: (row) => options.description?.(row),
299
+ idOf,
300
+ idKey,
301
+ parseId,
302
+ source: sourceFor(undefined),
303
+ sourceFor,
304
+ listWith,
305
+ columns,
306
+ fields,
307
+ filters,
308
+ properties,
309
+ filterOf,
310
+ // Workaround: as above, the values passed the resource's schema before they reach here.
311
+ inputOf: (value) => assumeType(isRecord(value) ? value : {}),
312
+ check(action, row, session, notAllowed = "") {
313
+ if (action === ResourceAction.restore && !softDelete)
314
+ return { allowed: false, reason: "this resource has no soft delete" };
315
+ return firstRefusal(toAllowed(options.can?.(action, row), notAllowed), toAllowed(session?.can(action, { resource: options.key, row }), notAllowed));
316
+ },
317
+ routes,
318
+ paths: {
319
+ list: () => `/${routes.base}`,
320
+ create: () => `/${routes.base}/${routes.create}`,
321
+ detail: (id) => `/${routes.base}/${encodeURIComponent(idKey(id))}`,
322
+ edit: (id) => `/${routes.base}/${encodeURIComponent(idKey(id))}/${routes.edit}`,
323
+ tab: (id, relation) => `/${routes.base}/${encodeURIComponent(idKey(id))}/${encodeURIComponent(relation)}`,
324
+ },
325
+ relations,
326
+ match(pathname) {
327
+ const parts = segment(pathname).split("/").filter(Boolean);
328
+ const baseParts = routes.base.split("/").filter(Boolean);
329
+ if (baseParts.some((part, index) => parts[index] !== part))
330
+ return undefined;
331
+ const [first, second, ...extra] = parts.slice(baseParts.length);
332
+ if (extra.length > 0)
333
+ return undefined;
334
+ if (first === undefined)
335
+ return { screen: ResourceScreen.list };
336
+ if (first === routes.create && second === undefined)
337
+ return { screen: ResourceScreen.create };
338
+ if (second === undefined)
339
+ return { screen: ResourceScreen.detail, id: decodeURIComponent(first) };
340
+ if (second === routes.edit)
341
+ return { screen: ResourceScreen.edit, id: decodeURIComponent(first) };
342
+ const tab = decodeURIComponent(second);
343
+ if (relations[tab]?.kind === RelationKind.hasMany)
344
+ return { screen: ResourceScreen.detail, id: decodeURIComponent(first), tab };
345
+ return undefined;
346
+ },
347
+ actions: () => (isFunction(options.actions) ? options.actions() : (options.actions ?? [])),
348
+ audit: options.audit,
349
+ };
350
+ if (Object.keys(relations).length > 0)
351
+ defined.add(resource);
352
+ registerResource(resource);
353
+ return resource;
354
+ }