@eskais/app-sdk 0.1.0 → 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 (90) hide show
  1. package/README.md +17 -11
  2. package/dist/action/action.d.ts +69 -10
  3. package/dist/action/action.js +147 -29
  4. package/dist/action/bulk.d.ts +24 -0
  5. package/dist/action/bulk.js +24 -0
  6. package/dist/core/constants.d.ts +57 -0
  7. package/dist/core/constants.js +31 -0
  8. package/dist/core/contracts.d.ts +7 -0
  9. package/dist/core/data-labels.d.ts +14 -0
  10. package/dist/core/data-labels.js +40 -0
  11. package/dist/core/errors.d.ts +11 -5
  12. package/dist/core/errors.js +52 -9
  13. package/dist/dialogs/dialogs.d.ts +75 -0
  14. package/dist/dialogs/dialogs.js +66 -0
  15. package/dist/errors/adapters.d.ts +21 -0
  16. package/dist/errors/adapters.js +81 -0
  17. package/dist/errors/define-errors.d.ts +88 -0
  18. package/dist/errors/define-errors.js +168 -0
  19. package/dist/errors/idempotency.d.ts +2 -0
  20. package/dist/errors/idempotency.js +13 -0
  21. package/dist/i18n/adapters.d.ts +53 -0
  22. package/dist/i18n/adapters.js +56 -0
  23. package/dist/i18n/format.d.ts +10 -0
  24. package/dist/i18n/format.js +273 -0
  25. package/dist/i18n/labels.d.ts +10 -0
  26. package/dist/i18n/labels.js +227 -0
  27. package/dist/i18n/locale.d.ts +73 -0
  28. package/dist/i18n/locale.js +74 -0
  29. package/dist/i18n/messages.d.ts +93 -0
  30. package/dist/i18n/messages.js +16 -0
  31. package/dist/import/import.d.ts +4 -2
  32. package/dist/import/import.js +7 -4
  33. package/dist/index.d.ts +18 -3
  34. package/dist/index.js +17 -2
  35. package/dist/navigation/nav.d.ts +14 -5
  36. package/dist/navigation/nav.js +37 -14
  37. package/dist/next/server/index.d.ts +2 -1
  38. package/dist/next/server/index.js +2 -1
  39. package/dist/next/server/page.d.ts +8 -2
  40. package/dist/next/server/page.js +14 -7
  41. package/dist/next/server/session.d.ts +13 -0
  42. package/dist/next/server/session.js +13 -0
  43. package/dist/permissions/permissions.d.ts +134 -0
  44. package/dist/permissions/permissions.js +121 -0
  45. package/dist/react/data-layer.d.ts +42 -5
  46. package/dist/react/data-layer.js +49 -4
  47. package/dist/react/hooks/use-action-dialog.d.ts +25 -0
  48. package/dist/react/hooks/use-action-dialog.js +31 -0
  49. package/dist/react/hooks/use-action.d.ts +30 -5
  50. package/dist/react/hooks/use-action.js +85 -27
  51. package/dist/react/hooks/use-bulk-action.d.ts +20 -0
  52. package/dist/react/hooks/use-bulk-action.js +24 -0
  53. package/dist/react/hooks/use-dialogs.d.ts +14 -0
  54. package/dist/react/hooks/use-dialogs.js +20 -0
  55. package/dist/react/hooks/use-nav.js +3 -2
  56. package/dist/react/hooks/use-new-rows.d.ts +22 -0
  57. package/dist/react/hooks/use-new-rows.js +24 -0
  58. package/dist/react/hooks/use-permissions.d.ts +13 -0
  59. package/dist/react/hooks/use-permissions.js +19 -0
  60. package/dist/react/hooks/use-reauthenticate.d.ts +6 -0
  61. package/dist/react/hooks/use-reauthenticate.js +11 -0
  62. package/dist/react/hooks/use-resource.d.ts +28 -5
  63. package/dist/react/hooks/use-resource.js +63 -26
  64. package/dist/react/index.d.ts +11 -4
  65. package/dist/react/index.js +11 -4
  66. package/dist/react/keys.d.ts +9 -0
  67. package/dist/react/keys.js +4 -0
  68. package/dist/react/new-rows.d.ts +22 -0
  69. package/dist/react/new-rows.js +72 -0
  70. package/dist/refresh/new-rows.d.ts +13 -0
  71. package/dist/refresh/new-rows.js +18 -0
  72. package/dist/resource/resource-relations.d.ts +6 -3
  73. package/dist/resource/resource-relations.js +26 -13
  74. package/dist/resource/resource-schema.d.ts +1 -1
  75. package/dist/resource/resource-schema.js +1 -1
  76. package/dist/resource/resource-texts.d.ts +18 -0
  77. package/dist/resource/resource-texts.js +13 -0
  78. package/dist/resource/resource-types.d.ts +169 -30
  79. package/dist/resource/resource-words.d.ts +25 -0
  80. package/dist/resource/resource-words.js +221 -0
  81. package/dist/resource/resource.d.ts +6 -2
  82. package/dist/resource/resource.js +99 -173
  83. package/dist/services/read-only-service.d.ts +18 -0
  84. package/dist/services/read-only-service.js +25 -0
  85. package/dist/services/rest-service.d.ts +4 -1
  86. package/dist/services/rest-service.js +2 -0
  87. package/dist/view/view-types.d.ts +4 -2
  88. package/locales/en.json +193 -0
  89. package/locales/es.json +193 -0
  90. package/package.json +5 -2
@@ -1,8 +1,10 @@
1
- import type { Align, ColumnKind, CreateMode, RelationDenied, RelationKind, FieldKind, FilterKind, FormStage, JsonType, MobileSlot, ResourceAction, ResourceScreen } from "../core/constants.js";
1
+ import type { Align, ColumnKind, CreateMode, RelationDenied, RelationKind, FieldKind, FilterKind, FormStage, Idempotency, JsonType, MobileSlot, NewRows, ResourceAction, ResourceScreen } from "../core/constants.js";
2
2
  import type { Page, PageSourceLike, Query, ResourceService, SortSpec } from "../core/contracts.js";
3
3
  import type { Allowed, Refusal } from "../core/refusal.js";
4
4
  import type { Introspect, SchemaProperty, StandardSchema } from "./schema.js";
5
+ import type { Locale, Text, TextRefusal } from "../i18n/locale.js";
5
6
  import type { RelationContext, RelationRows, Relations } from "./relations.js";
7
+ import type { RegisteredOperation } from "../permissions/permissions.js";
6
8
  import type { Session } from "../session/session.js";
7
9
  type Primitive = string | number | boolean | bigint | symbol | null | undefined | Date;
8
10
  /** A dotted path into `T`, three levels deep: `"name"`, `"customer.name"`, `"customer.country.name"`. */
@@ -15,14 +17,23 @@ export type Option = {
15
17
  value: string;
16
18
  label: string;
17
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
+ };
18
25
  export type ColumnDef<T, Key extends string = Path<T> | (string & {})> = {
19
26
  /** A path into the row, through relations too (`"customer.country.name"`); `defineResource` checks it. */
20
27
  key: Key;
21
- label?: string;
28
+ /** By default `resources.<key>.fields.<column>` in the locale, the schema's title, or the key. */
29
+ label?: Text;
22
30
  as?: ColumnKind;
23
31
  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>>;
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>>;
26
37
  cell?: (row: T) => unknown;
27
38
  /** `true` sorts by the key on the server; a string names the server's sort field. */
28
39
  sortable?: boolean | string;
@@ -31,12 +42,16 @@ export type ColumnDef<T, Key extends string = Path<T> | (string & {})> = {
31
42
  align?: Align;
32
43
  /** Where the value goes in `ResourceList` and narrow screens; `false` leaves it out. */
33
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;
34
47
  };
35
48
  export type FieldDef<T> = {
36
49
  key: Path<T> | (string & {});
37
- label?: string;
38
- description?: string;
39
- placeholder?: 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;
40
55
  as?: FieldKind;
41
56
  /** For `FieldKind.resource`: a function, so two resources can point at each other. */
42
57
  resource?: () => AnyResource;
@@ -45,45 +60,122 @@ export type FieldDef<T> = {
45
60
  /** For `FieldKind.resource`: offers to create what's typed, from the text or (`CreateMode.form`) in a form. */
46
61
  create?: boolean | CreateMode;
47
62
  /** What each choice shows as, in radios and selects (and the column's pills): `{ pending: "Pendiente" }`. */
48
- valueLabels?: Readonly<Record<string, string>>;
63
+ valueLabels?: Readonly<Record<string, Text>>;
49
64
  multiple?: boolean;
50
- options?: readonly Option[] | (() => Promise<readonly Option[]>);
65
+ options?: readonly OptionDef[] | (() => Promise<readonly Option[]>);
51
66
  readOnly?: boolean | ((row: T | undefined) => boolean);
52
67
  hidden?: boolean | ((values: Partial<T>) => boolean);
53
68
  only?: FormStage;
54
69
  render?: (field: unknown) => unknown;
55
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;
56
73
  };
74
+ /** A `FieldSet`: `group` is its id, and its legend unless `label` or `resources.<key>.groups.<group>` says otherwise. */
57
75
  export type FieldGroup<T> = {
58
76
  group: string;
59
- description?: string;
77
+ label?: Text;
78
+ description?: Text;
60
79
  fields: FieldDef<T>[];
61
80
  };
62
81
  export type FilterDef<F> = {
63
82
  key: keyof F & string;
64
- label?: string;
83
+ label?: Text;
65
84
  as?: FilterKind;
66
85
  resource?: () => AnyResource;
67
- options?: readonly Option[];
86
+ options?: readonly OptionDef[];
68
87
  default?: F[keyof F];
69
88
  };
70
89
  export type ResourceShortcuts = {
71
90
  list?: string;
72
91
  create?: string;
73
92
  };
74
- /** The resource's name; `create` names its New button and form when the dictionary's "New {one}" doesn't fit. */
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
+ */
75
98
  export type ResourceLabel = {
76
- one: string;
77
- other: string;
78
- create?: string;
79
- } | ((count: number) => string);
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
+ */
80
116
  export type ResourceRoutes<Id> = {
81
117
  base?: string;
82
- create?: string;
83
- edit?: string;
84
- detail?: (props: {
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<{
85
134
  id: Id;
86
- }) => unknown;
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;
87
179
  };
88
180
  export type ResourceAudit<T> = {
89
181
  createdAt?: keyof T & string;
@@ -92,15 +184,39 @@ export type ResourceAudit<T> = {
92
184
  updatedBy?: keyof T & string;
93
185
  };
94
186
  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;
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;
98
214
  service: ResourceService<T, Id, F>;
99
215
  schema?: StandardSchema<unknown, T>;
100
216
  createSchema?: StandardSchema;
101
217
  updateSchema?: StandardSchema;
102
218
  id?: (row: T) => Id;
103
- label: ResourceLabel;
219
+ label?: ResourceLabel;
104
220
  icon?: unknown;
105
221
  title?: (row: T) => string;
106
222
  description?: (row: T) => string;
@@ -109,12 +225,22 @@ export type ResourceOptions<T, Id, F> = {
109
225
  filters?: readonly FilterDef<F>[];
110
226
  searchable?: boolean;
111
227
  defaultSort?: readonly SortSpec[];
112
- can?: (action: ResourceAction, row?: T) => boolean | Refusal;
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;
113
230
  /** Its own actions, in its rows, records and routes; a function when they refer back to the resource. */
114
231
  actions?: readonly unknown[] | (() => readonly unknown[]);
115
232
  routes?: ResourceRoutes<Id>;
233
+ /** Tabs, sections and a side column the record page adds. */
234
+ detail?: DetailOptions<T>;
116
235
  /** How long data counts as fresh, in ms. Default 30 000. */
117
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;
118
244
  /** Shows "show deleted" and restore. Default: the service's `capabilities.restore`. */
119
245
  softDelete?: boolean;
120
246
  audit?: ResourceAudit<T>;
@@ -135,7 +261,7 @@ export type ResourceOptions<T, Id, F> = {
135
261
  relations?: Relations;
136
262
  };
137
263
  /** `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"> & {
264
+ export type DefineResourceOptions<T, Id, F, R extends Relations, Key extends string = string> = Omit<ResourceOptions<T, Id, F, Key>, "columns" | "relations"> & {
139
265
  relations?: R;
140
266
  columns?: readonly ColumnDef<T & RelationRows<R>, Path<T & RelationRows<R>>>[];
141
267
  };
@@ -168,6 +294,7 @@ export type ResolvedColumn<T> = {
168
294
  relation?: ResolvedRelation;
169
295
  /** What's left of the key past the relation: `name` in `customer.name`. */
170
296
  relationPath?: string;
297
+ requires?: string;
171
298
  };
172
299
  export type ResolvedField<T> = {
173
300
  key: string;
@@ -193,6 +320,7 @@ export type ResolvedField<T> = {
193
320
  fields?: readonly ResolvedField<Record<string, unknown>>[];
194
321
  group?: string;
195
322
  groupDescription?: string;
323
+ requires?: string;
196
324
  };
197
325
  export type ResolvedFilter = {
198
326
  key: string;
@@ -207,13 +335,19 @@ export type ResourceMatch = {
207
335
  id?: string;
208
336
  tab?: string;
209
337
  };
210
- export type Resource<T, Id = string, F = Record<string, unknown>> = {
211
- readonly key: string;
212
- readonly options: ResourceOptions<T, Id, F>;
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;
213
346
  readonly service: ResourceService<T, Id, F>;
214
347
  readonly schema: StandardSchema<unknown, T> | undefined;
215
348
  readonly icon: unknown;
216
349
  readonly staleTime: number;
350
+ readonly refresh: ResolvedRefresh;
217
351
  readonly exportLimit: number;
218
352
  readonly shortcuts: ResourceShortcuts;
219
353
  readonly searchable: boolean;
@@ -248,6 +382,8 @@ export type Resource<T, Id = string, F = Record<string, unknown>> = {
248
382
  /** A page with the relations `paths` reach: embedded by the server, or read in batches (`resolveRelations`). */
249
383
  listWith(query: Query<F>, context: RelationContext, paths?: readonly string[]): Promise<Page<T>>;
250
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;
251
387
  fields(stage: FormStage): ResolvedField<T>[];
252
388
  filters(): ResolvedFilter[];
253
389
  properties(): readonly SchemaProperty[];
@@ -265,6 +401,9 @@ export type Resource<T, Id = string, F = Record<string, unknown>> = {
265
401
  create: string;
266
402
  edit: string;
267
403
  };
404
+ /** The screens `routes` replaces. */
405
+ readonly screens: ResourceScreens<Id>;
406
+ readonly detail: ResolvedDetail<T>;
268
407
  readonly paths: {
269
408
  list(): string;
270
409
  create(): string;
@@ -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
+ }
@@ -1,11 +1,15 @@
1
1
  import { dependentsOf } from "./resource-relations.js";
2
2
  import { type RelationRows, type Relations } from "./relations.js";
3
- import type { DefineResourceOptions, Resource } from "./resource-types.js";
3
+ import type { DefineResourceOptions, Resource, RefreshPolicy, ResolvedRefresh } from "./resource-types.js";
4
4
  export type * from "./resource-types.js";
5
5
  export { dependentsOf };
6
6
  export declare const searchKey = "q";
7
+ /** A resource's refresh policy with a list's own over it. */
8
+ export declare function refreshPolicy(resource: {
9
+ readonly refresh: ResolvedRefresh;
10
+ }, overrides?: RefreshPolicy): ResolvedRefresh;
7
11
  /**
8
12
  * Declares a resource. Called twice, `defineResource<Customer>()({ … })`, so `T` is given by hand and the rest is
9
13
  * inferred. Columns, fields and filters left out come from the schema (Zod 4 first).
10
14
  */
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>;
15
+ export declare function defineResource<T>(): <Id = string, F = Record<string, unknown>, const R extends Relations = {}, const Key extends string = string>(options: DefineResourceOptions<T, Id, F, R, Key>) => Resource<T & RelationRows<R>, Id, F, Key>;