@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,420 @@
1
+ import type { Align, ColumnKind, CreateMode, RelationDenied, RelationKind, FieldKind, FilterKind, FormStage, Idempotency, JsonType, MobileSlot, NewRows, 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 { Locale, Text, TextRefusal } from "../i18n/locale.js";
6
+ import type { RelationContext, RelationRows, Relations } from "./relations.js";
7
+ import type { RegisteredOperation } from "../permissions/permissions.js";
8
+ import type { Session } from "../session/session.js";
9
+ type Primitive = string | number | boolean | bigint | symbol | null | undefined | Date;
10
+ /** A dotted path into `T`, three levels deep: `"name"`, `"customer.name"`, `"customer.country.name"`. */
11
+ export type Path<T, Depth extends unknown[] = []> = Depth["length"] extends 3 ? never : T extends Primitive | readonly unknown[] ? never : {
12
+ [Key in keyof T & string]: Key | (NonNullable<T[Key]> extends Primitive | readonly unknown[] ? never : `${Key}.${Path<NonNullable<T[Key]>, [...Depth, unknown]>}`);
13
+ }[keyof T & string];
14
+ export type AnyResource = Resource<any, any, any>;
15
+ export type ToneName = string;
16
+ export type Option = {
17
+ value: string;
18
+ label: string;
19
+ };
20
+ /** A choice as a definition gives it: its label may be a message (`msg("…")`) or a function of `t`. */
21
+ export type OptionDef = {
22
+ value: string;
23
+ label: Text;
24
+ };
25
+ export type ColumnDef<T, Key extends string = Path<T> | (string & {})> = {
26
+ /** A path into the row, through relations too (`"customer.country.name"`); `defineResource` checks it. */
27
+ key: Key;
28
+ /** By default `resources.<key>.fields.<column>` in the locale, the schema's title, or the key. */
29
+ label?: Text;
30
+ as?: ColumnKind;
31
+ tones?: Partial<Record<string, ToneName>>;
32
+ /**
33
+ * What each value shows as, in pills, badges and filters: `{ pending: "Pendiente" }`. The stored value stays. By
34
+ * default `resources.<key>.values.<column>.<value>` in the locale.
35
+ */
36
+ valueLabels?: Readonly<Record<string, Text>>;
37
+ cell?: (row: T) => unknown;
38
+ /** `true` sorts by the key on the server; a string names the server's sort field. */
39
+ sortable?: boolean | string;
40
+ hidden?: boolean;
41
+ width?: string;
42
+ align?: Align;
43
+ /** Where the value goes in `ResourceList` and narrow screens; `false` leaves it out. */
44
+ mobile?: MobileSlot | false;
45
+ /** The operation the session needs on the resource to see it (`Op.audit`); without it the column isn't there. */
46
+ requires?: RegisteredOperation;
47
+ };
48
+ export type FieldDef<T> = {
49
+ key: Path<T> | (string & {});
50
+ /** By default `resources.<key>.fields.<field>` in the locale, the schema's title, or the key. */
51
+ label?: Text;
52
+ /** By default `resources.<key>.descriptions.<field>` in the locale, or the schema's description. */
53
+ description?: Text;
54
+ placeholder?: Text;
55
+ as?: FieldKind;
56
+ /** For `FieldKind.resource`: a function, so two resources can point at each other. */
57
+ resource?: () => AnyResource;
58
+ /** For `FieldKind.rows`: rows a sub-table edits. Read from the relation by default. */
59
+ fields?: readonly FieldDef<unknown>[];
60
+ /** For `FieldKind.resource`: offers to create what's typed, from the text or (`CreateMode.form`) in a form. */
61
+ create?: boolean | CreateMode;
62
+ /** What each choice shows as, in radios and selects (and the column's pills): `{ pending: "Pendiente" }`. */
63
+ valueLabels?: Readonly<Record<string, Text>>;
64
+ multiple?: boolean;
65
+ options?: readonly OptionDef[] | (() => Promise<readonly Option[]>);
66
+ readOnly?: boolean | ((row: T | undefined) => boolean);
67
+ hidden?: boolean | ((values: Partial<T>) => boolean);
68
+ only?: FormStage;
69
+ render?: (field: unknown) => unknown;
70
+ colSpan?: 1 | 2;
71
+ /** The operation the session needs on the resource to see it, in forms and the record page. */
72
+ requires?: RegisteredOperation;
73
+ };
74
+ /** A `FieldSet`: `group` is its id, and its legend unless `label` or `resources.<key>.groups.<group>` says otherwise. */
75
+ export type FieldGroup<T> = {
76
+ group: string;
77
+ label?: Text;
78
+ description?: Text;
79
+ fields: FieldDef<T>[];
80
+ };
81
+ export type FilterDef<F> = {
82
+ key: keyof F & string;
83
+ label?: Text;
84
+ as?: FilterKind;
85
+ resource?: () => AnyResource;
86
+ options?: readonly OptionDef[];
87
+ default?: F[keyof F];
88
+ };
89
+ export type ResourceShortcuts = {
90
+ list?: string;
91
+ create?: string;
92
+ };
93
+ /**
94
+ * The resource's name; `create` names its New button and form when the catalog's "New {one}" doesn't fit, and
95
+ * `gender` picks a message's `select` branch (`Gender.feminine`). Left out, it comes from the locale's
96
+ * `resources.<key>.one`, `other`, `create` and `gender`.
97
+ */
98
+ export type ResourceLabel = {
99
+ one: Text;
100
+ other: Text;
101
+ create?: Text;
102
+ gender?: string;
103
+ } | ((count: number, t: (key: string, values?: Readonly<Record<string, unknown>>) => string) => string);
104
+ /** A component that draws one of a resource's screens instead of the block's: React's in the blocks. */
105
+ export type ScreenComponent<Props> = (props: Props) => unknown;
106
+ /** A screen with a path segment of its own: `"nuevo"`, a component, or both. */
107
+ export type RoutedScreen<Props> = string | ScreenComponent<Props> | {
108
+ segment?: string;
109
+ screen?: ScreenComponent<Props>;
110
+ };
111
+ /**
112
+ * The resource's paths and screens. `base` is the list's segment; `create` and `edit` a segment (`"nuevo"`), a
113
+ * component that replaces the screen, or both (`{ segment, screen }`); `list` and `detail` a component. `NavScreen`,
114
+ * `nav.routes()`, `resourceRoute.*` and Next's `navPage` and `resourcePage` draw a given one instead of the block's.
115
+ */
116
+ export type ResourceRoutes<Id> = {
117
+ base?: string;
118
+ list?: ScreenComponent<Record<never, never>>;
119
+ create?: RoutedScreen<Record<never, never>>;
120
+ detail?: ScreenComponent<{
121
+ id: Id;
122
+ }>;
123
+ edit?: RoutedScreen<{
124
+ id: Id;
125
+ }>;
126
+ };
127
+ export type ResourceScreens<Id> = {
128
+ list?: ScreenComponent<Record<never, never>>;
129
+ create?: ScreenComponent<Record<never, never>>;
130
+ detail?: ScreenComponent<{
131
+ id: Id;
132
+ }>;
133
+ edit?: ScreenComponent<{
134
+ id: Id;
135
+ }>;
136
+ };
137
+ /** A tab of the record page, before its `hasMany` tabs and on its own path: `/customers/7/<id>`. */
138
+ export type DetailTabDef<T> = {
139
+ id: string;
140
+ /** By default `resources.<key>.tabs.<id>` in the locale, or the id. */
141
+ label?: Text;
142
+ content: (row: T) => unknown;
143
+ };
144
+ /** A section of the record page: its fields in a `DescriptionList`, or content of its own. */
145
+ export type DetailSectionDef<T> = {
146
+ id: string;
147
+ /** By default `resources.<key>.sections.<id>` in the locale. */
148
+ title?: Text;
149
+ } & ({
150
+ fields: readonly string[];
151
+ content?: undefined;
152
+ } | {
153
+ content: (row: T) => unknown;
154
+ fields?: undefined;
155
+ });
156
+ /** What the record page adds to its default one, without replacing it. */
157
+ export type DetailOptions<T> = {
158
+ tabs?: readonly DetailTabDef<T>[];
159
+ /** After the record's fields. */
160
+ sections?: readonly DetailSectionDef<T>[];
161
+ /** A side column beside the sections. */
162
+ aside?: (row: T) => unknown;
163
+ };
164
+ export type DetailTab<T> = {
165
+ id: string;
166
+ label: string;
167
+ content: (row: T) => unknown;
168
+ };
169
+ export type DetailSection<T> = {
170
+ id: string;
171
+ title?: string;
172
+ fields?: readonly string[];
173
+ content?: (row: T) => unknown;
174
+ };
175
+ export type ResolvedDetail<T> = {
176
+ tabs: readonly DetailTab<T>[];
177
+ sections: readonly DetailSection<T>[];
178
+ aside?: (row: T) => unknown;
179
+ };
180
+ export type ResourceAudit<T> = {
181
+ createdAt?: keyof T & string;
182
+ createdBy?: keyof T & string;
183
+ updatedAt?: keyof T & string;
184
+ updatedBy?: keyof T & string;
185
+ };
186
+ export type ResourceLabels = Partial<Record<string, unknown>>;
187
+ /** When a resource's lists and records reload on their own, for every screen; a list may change it. */
188
+ export type RefreshPolicy = {
189
+ /** Reloads stale data when the window gets focus again. Default false. */
190
+ onFocus?: boolean;
191
+ /** Reloads stale data when the browser is back online. Default true. */
192
+ onReconnect?: boolean;
193
+ /** Reloads a shown list every so many ms while the page is visible. Default false. */
194
+ interval?: number | false;
195
+ /** How long data counts as fresh, in ms. By default the resource's `staleTime`, 30 000. */
196
+ staleTime?: number;
197
+ /**
198
+ * Rows a background reload finds that the list didn't show: `NewRows.hold` (default) keeps them behind a
199
+ * "N new rows" banner so the table doesn't move under the person; `NewRows.show` puts them in at once. Rows that
200
+ * changed in place update either way.
201
+ */
202
+ newRows?: NewRows;
203
+ };
204
+ export type ResolvedRefresh = {
205
+ readonly onFocus: boolean;
206
+ readonly onReconnect: boolean;
207
+ readonly interval: number | false;
208
+ readonly staleTime: number;
209
+ readonly newRows: NewRows;
210
+ };
211
+ export type ResourceOptions<T, Id, F, Key extends string = string> = {
212
+ /** Stable: the cache key, the agents' tool names, saved views' URL and the locale's `resources.<key>`. */
213
+ key: Key;
214
+ service: ResourceService<T, Id, F>;
215
+ schema?: StandardSchema<unknown, T>;
216
+ createSchema?: StandardSchema;
217
+ updateSchema?: StandardSchema;
218
+ id?: (row: T) => Id;
219
+ label?: ResourceLabel;
220
+ icon?: unknown;
221
+ title?: (row: T) => string;
222
+ description?: (row: T) => string;
223
+ columns?: readonly ColumnDef<T>[];
224
+ fields?: readonly (FieldDef<T> | FieldGroup<T>)[];
225
+ filters?: readonly FilterDef<F>[];
226
+ searchable?: boolean;
227
+ defaultSort?: readonly SortSpec[];
228
+ /** Its reason may be a message (`msg("customers.blockFirst")`), worded in the `DataLayer`'s locale. */
229
+ can?: (action: ResourceAction, row?: T) => boolean | Refusal | TextRefusal;
230
+ /** Its own actions, in its rows, records and routes; a function when they refer back to the resource. */
231
+ actions?: readonly unknown[] | (() => readonly unknown[]);
232
+ routes?: ResourceRoutes<Id>;
233
+ /** Tabs, sections and a side column the record page adds. */
234
+ detail?: DetailOptions<T>;
235
+ /** How long data counts as fresh, in ms. Default 30 000. */
236
+ staleTime?: number;
237
+ /**
238
+ * Which writes may run again after a failure, by `ResourceAction`: none by default. `Idempotency.key` sends one
239
+ * `idempotencyKey` per submit (`{ create: Idempotency.key, update: Idempotency.idempotent }`).
240
+ */
241
+ idempotency?: Partial<Readonly<Record<ResourceAction, Idempotency>>>;
242
+ /** Reloading on focus, on reconnect and by polling, and what a reload does with new rows. */
243
+ refresh?: RefreshPolicy;
244
+ /** Shows "show deleted" and restore. Default: the service's `capabilities.restore`. */
245
+ softDelete?: boolean;
246
+ audit?: ResourceAudit<T>;
247
+ search?: false | {
248
+ to?: (row: T) => string;
249
+ };
250
+ /** The most rows a browser export reads. Default 10 000. */
251
+ exportLimit?: number;
252
+ /** Keys that go to the list (`navItem` uses it, `"g c"`) and open a new record on its page (`"n"`). */
253
+ shortcuts?: ResourceShortcuts;
254
+ labels?: ResourceLabels;
255
+ /** Reads the schema's properties; Zod 4 by default. */
256
+ introspect?: Introspect;
257
+ /**
258
+ * Other records this one points at or holds: `belongsTo`, `hasMany`, `manyToMany` and `embeds`. Columns, fields,
259
+ * filters and the record's tabs read them; lists read the related records in batches.
260
+ */
261
+ relations?: Relations;
262
+ };
263
+ /** `defineResource`'s options: column keys are checked against the row and its relations. */
264
+ export type DefineResourceOptions<T, Id, F, R extends Relations, Key extends string = string> = Omit<ResourceOptions<T, Id, F, Key>, "columns" | "relations"> & {
265
+ relations?: R;
266
+ columns?: readonly ColumnDef<T & RelationRows<R>, Path<T & RelationRows<R>>>[];
267
+ };
268
+ /** A relation as a column or a field shows it. */
269
+ export type ResolvedRelation = {
270
+ name: string;
271
+ kind: RelationKind;
272
+ /** The id field of a `belongsTo` or `manyToMany`; the foreign key of a `hasMany`. */
273
+ key: string;
274
+ target: () => AnyResource;
275
+ denied: RelationDenied;
276
+ /** The fields a snapshot keeps under the relation's name. */
277
+ snapshot?: readonly string[];
278
+ };
279
+ export type ResolvedColumn<T> = {
280
+ key: string;
281
+ label: string;
282
+ kind: ColumnKind;
283
+ tones?: Partial<Record<string, ToneName>>;
284
+ cell?: (row: T) => unknown;
285
+ sortField?: string;
286
+ hidden: boolean;
287
+ width?: string;
288
+ align?: Align;
289
+ mobile?: MobileSlot | false;
290
+ options?: readonly Option[];
291
+ /** The field's kind for the same key, so a cell shows a colour, a duration or an image as such. */
292
+ field?: FieldKind;
293
+ /** The relation it shows: a related record's title (`customer`, `customerId`), or a field through it. */
294
+ relation?: ResolvedRelation;
295
+ /** What's left of the key past the relation: `name` in `customer.name`. */
296
+ relationPath?: string;
297
+ requires?: string;
298
+ };
299
+ export type ResolvedField<T> = {
300
+ key: string;
301
+ label: string;
302
+ kind: FieldKind;
303
+ description?: string;
304
+ placeholder?: string;
305
+ required: boolean;
306
+ resource?: () => AnyResource;
307
+ create?: boolean | CreateMode;
308
+ multiple: boolean;
309
+ options?: readonly Option[] | (() => Promise<readonly Option[]>);
310
+ readOnly: (row: T | undefined) => boolean;
311
+ hidden: (values: Partial<T>) => boolean;
312
+ render?: (field: unknown) => unknown;
313
+ colSpan: 1 | 2;
314
+ min?: number;
315
+ max?: number;
316
+ /** The schema's type for the value, so a control writes it back as such (a duration as text or seconds). */
317
+ valueType?: JsonType;
318
+ relation?: ResolvedRelation;
319
+ /** `FieldKind.rows` and `FieldKind.object`: the fields of each row, or of the subdocument. */
320
+ fields?: readonly ResolvedField<Record<string, unknown>>[];
321
+ group?: string;
322
+ groupDescription?: string;
323
+ requires?: string;
324
+ };
325
+ export type ResolvedFilter = {
326
+ key: string;
327
+ label: string;
328
+ kind: FilterKind;
329
+ options?: readonly Option[];
330
+ resource?: () => AnyResource;
331
+ default?: unknown;
332
+ };
333
+ export type ResourceMatch = {
334
+ screen: ResourceScreen;
335
+ id?: string;
336
+ tab?: string;
337
+ };
338
+ export type Resource<T, Id = string, F = Record<string, unknown>, Key extends string = string> = {
339
+ readonly key: Key;
340
+ readonly options: ResourceOptions<T, Id, F, Key>;
341
+ /** The locale its texts are in; `undefined` for the definition itself. */
342
+ readonly locale: Locale | undefined;
343
+ /** The same resource with its texts in `locale`: labels, fields, columns, filters, actions, detail. Cached. */
344
+ in(locale: Locale | undefined): Resource<T, Id, F, Key>;
345
+ readonly gender: string | undefined;
346
+ readonly service: ResourceService<T, Id, F>;
347
+ readonly schema: StandardSchema<unknown, T> | undefined;
348
+ readonly icon: unknown;
349
+ readonly staleTime: number;
350
+ readonly refresh: ResolvedRefresh;
351
+ readonly exportLimit: number;
352
+ readonly shortcuts: ResourceShortcuts;
353
+ readonly searchable: boolean;
354
+ readonly softDelete: boolean;
355
+ readonly defaultSort: readonly SortSpec[];
356
+ readonly queryKey: readonly unknown[];
357
+ label(count?: number): string;
358
+ /** The label's `create`, when it has one. */
359
+ readonly createLabel: string | undefined;
360
+ title(row: T): string;
361
+ /** The field a row's title comes from when `title` isn't given: the schema's first text property. */
362
+ readonly titleField: string | undefined;
363
+ /** A new record's values from a typed text, in `titleField`; `undefined` without one. */
364
+ inputFromText(text: string): Partial<T> | undefined;
365
+ description(row: T): string | undefined;
366
+ idOf(row: T): Id;
367
+ idKey(id: Id): string;
368
+ parseId(raw: string): Id;
369
+ readonly source: PageSourceLike<T, F & {
370
+ q?: string | undefined;
371
+ }>;
372
+ /**
373
+ * The resource's `PageSource` with the session; with `reading.paths` (the visible columns), each page asks the
374
+ * server to embed their relations and reads the rest in batches.
375
+ */
376
+ sourceFor(session: Session | undefined, reading?: {
377
+ paths: readonly string[];
378
+ context?: Omit<RelationContext, "signal" | "session">;
379
+ }): PageSourceLike<T, F & {
380
+ q?: string | undefined;
381
+ }>;
382
+ /** A page with the relations `paths` reach: embedded by the server, or read in batches (`resolveRelations`). */
383
+ listWith(query: Query<F>, context: RelationContext, paths?: readonly string[]): Promise<Page<T>>;
384
+ columns(): ResolvedColumn<T>[];
385
+ /** A path's label in its locale (`shipping`, `shipping.city`), or the schema's title. */
386
+ fieldLabel(path: string): string | undefined;
387
+ fields(stage: FormStage): ResolvedField<T>[];
388
+ filters(): ResolvedFilter[];
389
+ properties(): readonly SchemaProperty[];
390
+ /**
391
+ * Reads a filter from outside TypeScript (the URL, an agent, a form) as the service's: a record keeps its keys and
392
+ * the service checks them, anything else is no filter. `q` stays, as the search text.
393
+ */
394
+ filterOf(value: unknown): F & {
395
+ q?: string | undefined;
396
+ };
397
+ inputOf(value: unknown): Partial<T>;
398
+ check(action: ResourceAction, row?: T, session?: Session, notAllowed?: string): Allowed;
399
+ readonly routes: {
400
+ base: string;
401
+ create: string;
402
+ edit: string;
403
+ };
404
+ /** The screens `routes` replaces. */
405
+ readonly screens: ResourceScreens<Id>;
406
+ readonly detail: ResolvedDetail<T>;
407
+ readonly paths: {
408
+ list(): string;
409
+ create(): string;
410
+ detail(id: Id): string;
411
+ edit(id: Id): string;
412
+ /** A record's tab of a `hasMany`: `/orders/12/lines`. */
413
+ tab(id: Id, relation: string): string;
414
+ };
415
+ match(pathname: string): ResourceMatch | undefined;
416
+ readonly relations: Relations;
417
+ actions(): readonly unknown[];
418
+ readonly audit: ResourceAudit<T> | undefined;
419
+ };
420
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,25 @@
1
+ import { FormStage } from "../core/constants.js";
2
+ import type { Relations } from "./relations.js";
3
+ import type { ResourceTexts } from "./resource-texts.js";
4
+ import type { ResolvedColumn, ResolvedDetail, ResolvedField, ResolvedFilter, ResourceOptions } from "./resource-types.js";
5
+ import type { SchemaProperty } from "./schema.js";
6
+ type WordsContext<T, Id, F, Key extends string> = {
7
+ options: ResourceOptions<T, Id, F, Key>;
8
+ properties: () => readonly SchemaProperty[];
9
+ relations: Relations;
10
+ auditKeys: ReadonlySet<string>;
11
+ numericIds: SchemaProperty | undefined;
12
+ };
13
+ /** What a resource says in words, in one locale or (without one) its definition's own text. */
14
+ export declare function resourceWords<T, Id, F, Key extends string>({ options, properties, relations, auditKeys, numericIds, }: WordsContext<T, Id, F, Key>): (texts: ResourceTexts) => {
15
+ gender: string | undefined;
16
+ label: (count?: number) => string;
17
+ createLabel: string | undefined;
18
+ columns: () => ResolvedColumn<T>[];
19
+ fields: (stage: FormStage) => ResolvedField<T>[];
20
+ filters: () => ResolvedFilter[];
21
+ detail: ResolvedDetail<T>;
22
+ actions: () => unknown[];
23
+ fieldLabel: (path: string) => string | undefined;
24
+ };
25
+ export {};
@@ -0,0 +1,221 @@
1
+ import { ColumnKind, FieldKind, FilterKind, FormStage, JsonType, RelationKind, RowsMode } from "../core/constants.js";
2
+ import { isFunction, isString } from "../core/guards.js";
3
+ import { isAction } from "../action/action.js";
4
+ import { resolveText } from "../i18n/locale.js";
5
+ import { columnKindOf, fieldKindOf, isGroup, optionsOfEnum, propertyAt } from "./resource-schema.js";
6
+ import { inheritedColumn, relationTools, valueLabelsIn } from "./resource-relations.js";
7
+ const always = () => true;
8
+ const never = () => false;
9
+ /** What a resource says in words, in one locale or (without one) its definition's own text. */
10
+ export function resourceWords({ options, properties, relations, auditKeys, numericIds, }) {
11
+ function declaredKind(key) {
12
+ const declared = (options.fields ?? []).flatMap((entry) => (isGroup(entry) ? entry.fields : [entry]));
13
+ const field = declared.find((entry) => entry.key === key);
14
+ if (field?.as !== undefined)
15
+ return field.as;
16
+ const property = propertyAt(properties(), key);
17
+ return property ? fieldKindOf(property) : undefined;
18
+ }
19
+ const valueLabelsOf = (key) => valueLabelsIn(options, key);
20
+ return function words(texts) {
21
+ const { relationAt, relationField } = relationTools({
22
+ relations,
23
+ properties,
24
+ introspect: options.introspect,
25
+ texts,
26
+ });
27
+ const declaredLabel = options.label;
28
+ const gender = isFunction(declaredLabel) ? texts.own("gender") : (declaredLabel?.gender ?? texts.own("gender"));
29
+ const label = (count = 1) => {
30
+ if (isFunction(declaredLabel))
31
+ return declaredLabel(count, texts.locale?.t ?? ((key) => key));
32
+ const own = count === 1 ? texts.text(declaredLabel?.one) : texts.text(declaredLabel?.other);
33
+ return own ?? texts.own(count === 1 ? "one" : "other") ?? options.key;
34
+ };
35
+ const createLabel = isFunction(declaredLabel)
36
+ ? texts.own("create")
37
+ : (texts.text(declaredLabel?.create) ?? texts.own("create"));
38
+ const valueLabel = (key, labels = valueLabelsOf(key)) => texts.valueLabel(key, labels);
39
+ function columns() {
40
+ const declared = options.columns ??
41
+ properties()
42
+ .filter((property) => property.type !== JsonType.object &&
43
+ !(property.type === JsonType.array && property.items?.type === JsonType.object))
44
+ .filter((property) => property.key !== "id" || !numericIds)
45
+ .map((property) => ({ key: property.key, ...(auditKeys.has(property.key) ? { hidden: true } : {}) }));
46
+ return declared.map((column) => {
47
+ const property = propertyAt(properties(), column.key);
48
+ const sortField = column.sortable === true ? column.key : isString(column.sortable) ? column.sortable : undefined;
49
+ const enumOptions = optionsOfEnum(property, valueLabel(column.key, column.valueLabels ?? valueLabelsOf(column.key)));
50
+ const field = declaredKind(column.key);
51
+ const reached = relationAt(column.key);
52
+ const target = reached?.relation.target();
53
+ const related = target ? texts.related(target) : undefined;
54
+ const relatedLabel = reached
55
+ ? reached.rest === undefined
56
+ ? related?.label(reached.relation.kind === RelationKind.belongsTo ? 1 : 2)
57
+ : `${related?.label(1) ?? reached.relation.name} · ${propertyAt(related?.properties() ?? [], reached.rest)?.title ?? reached.rest}`
58
+ : undefined;
59
+ const sortable = reached === undefined || (reached.rest !== undefined && options.service.capabilities.relationSort === true);
60
+ const inherited = inheritedColumn(related, reached?.rest);
61
+ const tones = column.tones ?? inherited.tones;
62
+ const inheritedKind = inherited.kind(tones !== undefined);
63
+ const align = column.align ?? inherited.align;
64
+ const relatedOptions = inherited.options;
65
+ return {
66
+ key: column.key,
67
+ label: texts.text(column.label) ?? texts.field(column.key) ?? relatedLabel ?? property?.title ?? column.key,
68
+ kind: column.as ??
69
+ (reached
70
+ ? (inheritedKind ?? ColumnKind.text)
71
+ : property
72
+ ? columnKindOf(property, column.tones !== undefined)
73
+ : ColumnKind.text),
74
+ hidden: column.hidden ?? false,
75
+ ...(tones ? { tones } : {}),
76
+ ...(relatedOptions && !enumOptions ? { options: relatedOptions } : {}),
77
+ ...(column.cell ? { cell: column.cell } : {}),
78
+ ...(sortField === undefined || !sortable ? {} : { sortField }),
79
+ ...(reached
80
+ ? { relation: reached.relation, ...(reached.rest === undefined ? {} : { relationPath: reached.rest }) }
81
+ : {}),
82
+ ...(column.width === undefined ? {} : { width: column.width }),
83
+ ...(align === undefined ? {} : { align }),
84
+ ...(column.mobile === undefined ? {} : { mobile: column.mobile }),
85
+ ...(enumOptions ? { options: enumOptions } : {}),
86
+ ...(field === undefined ? {} : { field }),
87
+ ...(column.requires === undefined ? {} : { requires: column.requires }),
88
+ };
89
+ });
90
+ }
91
+ function resolveField(field, group) {
92
+ if (field.as === undefined || field.as === FieldKind.resource || field.as === FieldKind.rows) {
93
+ const related = relationField(field, group);
94
+ if (related)
95
+ return related;
96
+ }
97
+ const property = propertyAt(properties(), field.key);
98
+ const readOnly = field.readOnly;
99
+ const hidden = field.hidden;
100
+ const fieldOptions = isFunction(field.options)
101
+ ? field.options
102
+ : field.options
103
+ ? field.options.map((option) => ({ value: option.value, label: resolveText(option.label, texts.locale) }))
104
+ : optionsOfEnum(property, valueLabel(field.key, field.valueLabels ?? valueLabelsOf(field.key)));
105
+ const description = texts.text(field.description) ?? texts.own(`descriptions.${field.key}`) ?? property?.description;
106
+ const placeholder = texts.text(field.placeholder);
107
+ const groupLabel = group
108
+ ? (texts.text(group.label) ?? texts.own(`groups.${group.group}`) ?? group.group)
109
+ : undefined;
110
+ const groupDescription = texts.text(group?.description);
111
+ return {
112
+ key: field.key,
113
+ label: texts.text(field.label) ?? texts.field(field.key) ?? property?.title ?? field.key,
114
+ kind: field.as ?? (field.resource ? FieldKind.resource : fieldKindOf(property)),
115
+ required: property?.required ?? false,
116
+ multiple: field.multiple ?? property?.type === JsonType.array,
117
+ readOnly: isFunction(readOnly) ? readOnly : readOnly === true || property?.readOnly === true ? always : never,
118
+ hidden: isFunction(hidden) ? hidden : hidden === true ? always : never,
119
+ colSpan: field.colSpan ?? 1,
120
+ ...(description === undefined ? {} : { description }),
121
+ ...(placeholder === undefined ? {} : { placeholder }),
122
+ ...(field.resource ? { resource: field.resource } : {}),
123
+ ...(field.create === undefined ? {} : { create: field.create }),
124
+ ...(fieldOptions ? { options: fieldOptions } : {}),
125
+ ...(field.render ? { render: field.render } : {}),
126
+ ...(property?.minimum === undefined ? {} : { min: property.minimum }),
127
+ ...(property?.maximum === undefined ? {} : { max: property.maximum }),
128
+ ...(property?.type === undefined ? {} : { valueType: property.type }),
129
+ ...(groupLabel === undefined
130
+ ? {}
131
+ : { group: groupLabel, ...(groupDescription === undefined ? {} : { groupDescription }) }),
132
+ };
133
+ }
134
+ function fields(stage) {
135
+ const declared = options.fields ??
136
+ properties()
137
+ .filter((property) => property.key !== "id" &&
138
+ !auditKeys.has(property.key) &&
139
+ property.type !== JsonType.object &&
140
+ !(property.type === JsonType.array && property.items?.type === JsonType.object))
141
+ .map((property) => ({ key: property.key }))
142
+ .concat(Object.entries(relations).flatMap(([name, relation]) => relation.kind === RelationKind.embeds ||
143
+ (relation.kind === RelationKind.hasMany && relation.mode === RowsMode.inline)
144
+ ? [{ key: name }]
145
+ : []));
146
+ const required = (field, resolved) => field.requires === undefined ? resolved : { ...resolved, requires: field.requires };
147
+ const flat = declared.flatMap((entry) => isGroup(entry)
148
+ ? entry.fields.map((field) => required(field, resolveField(field, entry)))
149
+ : [required(entry, resolveField(entry))]);
150
+ const only = new Map(declared.flatMap((entry) => (isGroup(entry) ? entry.fields : [entry])).map((field) => [field.key, field.only]));
151
+ return flat.filter((field) => {
152
+ const wanted = only.get(field.key);
153
+ if (wanted !== undefined && wanted !== stage)
154
+ return false;
155
+ return !(stage === FormStage.create && propertyAt(properties(), field.key)?.readOnly === true);
156
+ });
157
+ }
158
+ function filters() {
159
+ return (options.filters ?? []).map((filter) => {
160
+ const reached = relationAt(filter.key);
161
+ const ownLabel = texts.text(filter.label) ?? texts.field(filter.key);
162
+ if (reached && reached.rest === undefined && reached.relation.kind !== RelationKind.hasMany) {
163
+ const target = texts.related(reached.relation.target());
164
+ return {
165
+ key: reached.relation.key,
166
+ label: ownLabel ?? target.label(1),
167
+ kind: FilterKind.resource,
168
+ resource: reached.relation.target,
169
+ ...(filter.default === undefined ? {} : { default: filter.default }),
170
+ };
171
+ }
172
+ const property = propertyAt(properties(), filter.key);
173
+ const kind = filter.as ??
174
+ (filter.resource
175
+ ? FilterKind.resource
176
+ : property?.enum
177
+ ? FilterKind.select
178
+ : property?.type === JsonType.boolean
179
+ ? FilterKind.boolean
180
+ : FilterKind.search);
181
+ const filterOptions = filter.options
182
+ ? filter.options.map((option) => ({ value: option.value, label: resolveText(option.label, texts.locale) }))
183
+ : optionsOfEnum(property, valueLabel(filter.key));
184
+ return {
185
+ key: filter.key,
186
+ label: ownLabel ?? texts.field(filter.key) ?? property?.title ?? filter.key,
187
+ kind,
188
+ ...(filterOptions ? { options: filterOptions } : {}),
189
+ ...(filter.resource ? { resource: filter.resource } : {}),
190
+ ...(filter.default === undefined ? {} : { default: filter.default }),
191
+ };
192
+ });
193
+ }
194
+ function detail() {
195
+ const declared = options.detail ?? {};
196
+ return {
197
+ tabs: (declared.tabs ?? []).map((tab) => ({
198
+ id: tab.id,
199
+ label: texts.text(tab.label) ?? texts.own(`tabs.${tab.id}`) ?? tab.id,
200
+ content: tab.content,
201
+ })),
202
+ sections: (declared.sections ?? []).map((section) => {
203
+ const heading = texts.text(section.title) ?? texts.own(`sections.${section.id}`);
204
+ return {
205
+ id: section.id,
206
+ ...(heading === undefined ? {} : { title: heading }),
207
+ ...(section.fields ? { fields: section.fields } : {}),
208
+ ...(section.content ? { content: section.content } : {}),
209
+ };
210
+ }),
211
+ ...(declared.aside ? { aside: declared.aside } : {}),
212
+ };
213
+ }
214
+ const actions = () => {
215
+ const declared = isFunction(options.actions) ? options.actions() : (options.actions ?? []);
216
+ return declared.map((entry) => (isAction(entry) ? entry.in(texts.locale) : entry));
217
+ };
218
+ const fieldLabel = (path) => texts.field(path) ?? propertyAt(properties(), path)?.title;
219
+ return { gender, label, createLabel, columns, fields, filters, detail: detail(), actions, fieldLabel };
220
+ };
221
+ }