@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,194 @@
1
+ import { RelationDenied, RelationKind, RowsMode } from "../core/constants.js";
2
+ import { isNumber, isRecord, isString } from "../core/guards.js";
3
+ import { valueAt } from "../services/memory-query.js";
4
+ import { assumeType } from "../core/assume.js";
5
+ /** This record points at one other: `customer: belongsTo(() => customers, { key: "customerId" })`. */
6
+ export function belongsTo(target, options) {
7
+ return { kind: RelationKind.belongsTo, target, ...options };
8
+ }
9
+ const byKey = new Map();
10
+ /** Lets relations name a resource by its `key`; `defineResource` registers each one it makes. */
11
+ export function registerResource(resource) {
12
+ byKey.set(resource.key, resource);
13
+ }
14
+ function resourceNamed(key) {
15
+ const found = byKey.get(key);
16
+ if (!found)
17
+ throw new Error(`No resource with the key "${key}" has been defined.`);
18
+ return found;
19
+ }
20
+ /**
21
+ * Other records point at this one: `lines: hasMany(() => orderLines, { foreignKey: "orderId" })`. When the two
22
+ * resources point at each other (customers have orders, an order has a customer), name it by its key,
23
+ * `hasMany("orders", …)`: TypeScript can't infer two resources' types from each other.
24
+ */
25
+ export function hasMany(target, options) {
26
+ const thunk = isString(target) ? () => resourceNamed(target) : target;
27
+ return { kind: RelationKind.hasMany, target: thunk, ...options };
28
+ }
29
+ /** This record keeps a list of ids of others: `tags: manyToMany(() => tags, { key: "tagIds" })`. */
30
+ export function manyToMany(target, options) {
31
+ return { kind: RelationKind.manyToMany, target, ...options };
32
+ }
33
+ /** A subdocument, or a list of them, stored inside the record: `address: embeds(addressSchema)`. */
34
+ export function embeds(schema) {
35
+ // Workaround: `InferOutput` reads the output type back from the same schema the relation keeps.
36
+ return assumeType({ kind: RelationKind.embeds, schema });
37
+ }
38
+ /** The relations a set of paths reaches (`customer.name` reaches `customer`), for `Query.include`. */
39
+ export function includeOf(relations, paths) {
40
+ const found = new Set();
41
+ for (const path of paths) {
42
+ const [head = ""] = path.split(".");
43
+ const relation = relations[head] ?? keyRelation(relations, head)?.[1];
44
+ const name = relations[head] ? head : keyRelation(relations, head)?.[0];
45
+ if (relation && name !== undefined && relation.kind !== RelationKind.embeds)
46
+ found.add(name);
47
+ }
48
+ return [...found];
49
+ }
50
+ /** The `belongsTo` or `manyToMany` whose id field is `key` (`customerId` is `customer`'s). */
51
+ export function keyRelation(relations, key) {
52
+ for (const [name, relation] of Object.entries(relations)) {
53
+ if ((relation.kind === RelationKind.belongsTo || relation.kind === RelationKind.manyToMany) && relation.key === key)
54
+ return [name, relation];
55
+ }
56
+ return undefined;
57
+ }
58
+ /** Splits `ids` into lists of at most `size`: Firestore's `in` takes 30, DynamoDB's BatchGetItem 100. */
59
+ export function chunkIds(ids, size) {
60
+ const step = size === undefined || size <= 0 ? Math.max(1, ids.length) : size;
61
+ const chunks = [];
62
+ for (let start = 0; start < ids.length; start += step)
63
+ chunks.push(ids.slice(start, start + step));
64
+ return chunks;
65
+ }
66
+ const isId = (value) => isString(value) || isNumber(value);
67
+ function needsOf(relations, paths) {
68
+ const needs = new Map();
69
+ for (const path of paths) {
70
+ const [head = "", ...rest] = path.split(".");
71
+ const name = relations[head] ? head : keyRelation(relations, head)?.[0];
72
+ if (name === undefined)
73
+ continue;
74
+ const relation = relations[name];
75
+ if (!relation || relation.kind === RelationKind.embeds || relation.kind === RelationKind.hasMany)
76
+ continue;
77
+ const fields = needs.get(name) ?? new Set();
78
+ if (rest.length > 0)
79
+ fields.add(rest.join("."));
80
+ needs.set(name, fields);
81
+ }
82
+ return needs;
83
+ }
84
+ async function fetchAll(target, ids, context) {
85
+ const found = new Map();
86
+ const missing = [];
87
+ for (const id of ids) {
88
+ const known = context.known?.(target, id);
89
+ if (known === undefined)
90
+ missing.push(id);
91
+ else
92
+ found.set(id, known);
93
+ }
94
+ if (missing.length === 0)
95
+ return found;
96
+ const parsed = missing.map((id) => target.parseId(id));
97
+ const call = { signal: context.signal, session: context.session };
98
+ let records;
99
+ const service = context.serviceOf?.(target) ?? target.service;
100
+ const getMany = service.getMany;
101
+ if (getMany) {
102
+ // Perf: one request per chunk of ids, never one per row.
103
+ const chunks = chunkIds(parsed, service.capabilities.batchSize);
104
+ const pages = await Promise.all(chunks.map((chunk) => getMany.call(service, chunk, call)));
105
+ records = pages.flat();
106
+ }
107
+ else {
108
+ context.warn?.(`"${target.key}" has no getMany, so ${String(missing.length)} records were read one by one; add getMany to read them in one request.`);
109
+ records = await Promise.all(parsed.map((id) => service.get(id, call)));
110
+ }
111
+ for (const record of records) {
112
+ const id = target.idKey(target.idOf(record));
113
+ found.set(id, record);
114
+ context.seed?.(target, record);
115
+ }
116
+ return found;
117
+ }
118
+ /**
119
+ * Adds related records to rows, never one request per row: what the server embedded (or a `snapshot` that has every
120
+ * field asked) stays; the rest is read with one `getMany` per relation, in chunks of the service's `batchSize`, or
121
+ * one `get` per distinct id when there's no `getMany`. Paths reach through relations (`customer.country.name`).
122
+ */
123
+ export async function resolveRelations(resource, rows, paths, context) {
124
+ const needs = needsOf(resource.relations, paths);
125
+ let result = [...rows];
126
+ for (const [name, fields] of needs) {
127
+ const relation = resource.relations[name];
128
+ if (!relation || (relation.kind !== RelationKind.belongsTo && relation.kind !== RelationKind.manyToMany))
129
+ continue;
130
+ const target = relation.target();
131
+ if (context.canRead?.(target) === false)
132
+ continue;
133
+ const snapshot = relation.kind === RelationKind.belongsTo ? relation.snapshot : undefined;
134
+ const covered = (row) => {
135
+ const present = valueAt(row, name);
136
+ if (present === undefined || present === null)
137
+ return false;
138
+ if (snapshot === undefined)
139
+ return true;
140
+ return [...fields].every((field) => snapshot.includes(field.split(".")[0] ?? field));
141
+ };
142
+ const idsOfRow = (row) => {
143
+ const raw = valueAt(row, relation.key);
144
+ const list = Array.isArray(raw) ? raw : [raw];
145
+ return list.filter(isId).map(String);
146
+ };
147
+ const wanted = [...new Set(result.filter((row) => !covered(row)).flatMap(idsOfRow))];
148
+ // oxlint-disable-next-line no-await-in-loop -- each relation's batch is one request; relations go one after another
149
+ const records = wanted.length === 0 ? new Map() : await fetchAll(target, wanted, context);
150
+ const nested = [...fields].filter((field) => field.includes("."));
151
+ if (nested.length > 0 && records.size > 0) {
152
+ const values = [...records.values()];
153
+ // oxlint-disable-next-line no-await-in-loop -- a nested relation needs the records this one just read
154
+ const deeper = await resolveRelations(target, values, nested, context);
155
+ for (const record of deeper)
156
+ records.set(target.idKey(target.idOf(record)), record);
157
+ }
158
+ result = result.map((row) => {
159
+ if (covered(row) && nested.length === 0)
160
+ return row;
161
+ const ids = idsOfRow(row);
162
+ if (ids.length === 0)
163
+ return row;
164
+ const present = valueAt(row, name);
165
+ const fetched = records.get(ids[0] ?? "");
166
+ const value = relation.kind === RelationKind.manyToMany
167
+ ? ids.flatMap((id) => (records.has(id) ? [records.get(id)] : []))
168
+ : { ...(isRecord(present) ? present : {}), ...(isRecord(fetched) ? fetched : {}) };
169
+ // Workaround: the row gains its relation under its name, as `RelationRows` types it.
170
+ return assumeType({ ...(isRecord(row) ? row : {}), [name]: value });
171
+ });
172
+ }
173
+ return result;
174
+ }
175
+ /** What to send so the stored children become `rows`: new ones (no id), changed ones, and the ids left out. */
176
+ export function childChanges(rows, previous, idOf) {
177
+ const before = new Map(previous.map((row) => [String(idOf(row)), row]));
178
+ const kept = new Set();
179
+ const create = [];
180
+ const update = [];
181
+ for (const row of rows) {
182
+ const id = idOf(row);
183
+ if (id === undefined || id === null || id === "") {
184
+ create.push(row);
185
+ continue;
186
+ }
187
+ kept.add(String(id));
188
+ const old = before.get(String(id));
189
+ if (!old || JSON.stringify(old) !== JSON.stringify({ ...old, ...row }))
190
+ update.push(row);
191
+ }
192
+ const remove = previous.filter((row) => !kept.has(String(idOf(row)))).map(idOf);
193
+ return { create, update, remove };
194
+ }
@@ -0,0 +1,44 @@
1
+ import { type Relation, type Relations } from "./relations.js";
2
+ import type { FieldDef, FieldGroup, ResolvedField } from "./resource-types.js";
3
+ import { type Introspect, type SchemaProperty } from "./schema.js";
4
+ import type { AnyResource, ResolvedRelation } from "./resource-types.js";
5
+ export declare const defined: Set<AnyResource>;
6
+ /**
7
+ * The resources whose rows show `resource`'s records through a `belongsTo` or `manyToMany`, with the relation's
8
+ * name: changing one of its records refreshes their lists.
9
+ */
10
+ export declare function dependentsOf(resource: {
11
+ key: string;
12
+ }): {
13
+ resource: AnyResource;
14
+ relation: string;
15
+ }[];
16
+ export declare function relationOf(name: string, relation: Relation): ResolvedRelation | undefined;
17
+ type RelationToolsContext = {
18
+ relations: Relations;
19
+ properties: () => readonly SchemaProperty[];
20
+ introspect: Introspect | undefined;
21
+ };
22
+ export declare function relationTools<T>({ relations, properties, introspect }: RelationToolsContext): {
23
+ relationAt: (key: string) => {
24
+ relation: ResolvedRelation;
25
+ rest?: string;
26
+ } | undefined;
27
+ relationField: (field: FieldDef<T>, group?: FieldGroup<T>) => ResolvedField<T> | undefined;
28
+ };
29
+ /** What a column through a relation (`product.price`) takes from the related field: its kind, tones, alignment, labels. */
30
+ export declare function inheritedColumn(related: AnyResource | undefined, rest: string | undefined): {
31
+ tones: Partial<Record<string, string>> | undefined;
32
+ align: import("../index.js").Align | undefined;
33
+ options: import("./resource-types.js").Option[] | undefined;
34
+ kind: (toned: boolean) => import("../index.js").ColumnKind | undefined;
35
+ };
36
+ /** The labels of a key's values, from its field or its column, whichever declares them. */
37
+ export declare function valueLabelsIn(options: {
38
+ fields?: readonly (FieldDef<never> | FieldGroup<never>)[];
39
+ columns?: readonly {
40
+ key: string;
41
+ valueLabels?: Readonly<Record<string, string>>;
42
+ }[];
43
+ }, key: string): Readonly<Record<string, string>> | undefined;
44
+ export {};
@@ -0,0 +1,141 @@
1
+ import { RelationDenied, RelationKind } from "../core/constants.js";
2
+ import { FieldKind, FormStage } from "../core/constants.js";
3
+ import { isFunction } from "../core/guards.js";
4
+ import { keyRelation } from "./relations.js";
5
+ import { columnKindOf, optionsOfEnum, propertyAt, schemaFields } from "./resource-schema.js";
6
+ import { isListSchema } from "./schema.js";
7
+ export const defined = new Set();
8
+ /**
9
+ * The resources whose rows show `resource`'s records through a `belongsTo` or `manyToMany`, with the relation's
10
+ * name: changing one of its records refreshes their lists.
11
+ */
12
+ export function dependentsOf(resource) {
13
+ const found = [];
14
+ for (const candidate of defined) {
15
+ for (const [name, relation] of Object.entries(candidate.relations)) {
16
+ if (relation.kind !== RelationKind.belongsTo && relation.kind !== RelationKind.manyToMany)
17
+ continue;
18
+ if (relation.target().key === resource.key)
19
+ found.push({ resource: candidate, relation: name });
20
+ }
21
+ }
22
+ return found;
23
+ }
24
+ export function relationOf(name, relation) {
25
+ if (relation.kind === RelationKind.embeds)
26
+ return undefined;
27
+ if (relation.kind === RelationKind.hasMany)
28
+ return {
29
+ name,
30
+ kind: relation.kind,
31
+ key: relation.foreignKey,
32
+ target: relation.target,
33
+ denied: RelationDenied.showId,
34
+ };
35
+ return {
36
+ name,
37
+ kind: relation.kind,
38
+ key: relation.key,
39
+ target: relation.target,
40
+ denied: relation.denied ?? RelationDenied.showId,
41
+ ...(relation.kind === RelationKind.belongsTo && relation.snapshot ? { snapshot: relation.snapshot } : {}),
42
+ };
43
+ }
44
+ const always = () => true;
45
+ const never = () => false;
46
+ export function relationTools({ relations, properties, introspect }) {
47
+ const options = { introspect };
48
+ function relationAt(key) {
49
+ const [head = "", ...rest] = key.split(".");
50
+ const named = relations[head];
51
+ const byName = named ? relationOf(head, named) : undefined;
52
+ if (byName)
53
+ return { relation: byName, ...(rest.length > 0 ? { rest: rest.join(".") } : {}) };
54
+ const byKey = rest.length === 0 ? keyRelation(relations, key) : undefined;
55
+ return byKey ? { relation: relationOf(byKey[0], byKey[1]) } : undefined;
56
+ }
57
+ function baseField(field, group) {
58
+ const property = propertyAt(properties(), field.key);
59
+ const readOnly = field.readOnly;
60
+ const hidden = field.hidden;
61
+ return {
62
+ key: field.key,
63
+ label: field.label ?? property?.title ?? field.key,
64
+ kind: FieldKind.text,
65
+ required: property?.required ?? false,
66
+ multiple: false,
67
+ readOnly: isFunction(readOnly) ? readOnly : readOnly === true || property?.readOnly === true ? always : never,
68
+ hidden: isFunction(hidden) ? hidden : hidden === true ? always : never,
69
+ colSpan: field.colSpan ?? 1,
70
+ ...(property?.type === undefined ? {} : { valueType: property.type }),
71
+ ...(field.description === undefined ? {} : { description: field.description }),
72
+ ...(field.placeholder === undefined ? {} : { placeholder: field.placeholder }),
73
+ ...(group
74
+ ? { group: group.group, ...(group.description === undefined ? {} : { groupDescription: group.description }) }
75
+ : {}),
76
+ };
77
+ }
78
+ function relationField(field, group) {
79
+ const named = relations[field.key];
80
+ if (named?.kind === RelationKind.embeds) {
81
+ const children = schemaFields(named.schema, options.introspect);
82
+ const list = isListSchema(named.schema);
83
+ return {
84
+ ...baseField(field, group),
85
+ label: field.label ?? propertyAt(properties(), field.key)?.title ?? field.key,
86
+ kind: list ? FieldKind.rows : FieldKind.object,
87
+ multiple: list,
88
+ fields: children,
89
+ };
90
+ }
91
+ const reached = relationAt(field.key);
92
+ if (!reached || reached.rest !== undefined)
93
+ return undefined;
94
+ const { relation } = reached;
95
+ const target = relation.target();
96
+ if (relation.kind === RelationKind.hasMany) {
97
+ const childKeys = new Set(field.fields?.map((child) => child.key));
98
+ const children = target
99
+ .fields(FormStage.create)
100
+ .filter((child) => child.key !== relation.key && (childKeys.size === 0 || childKeys.has(child.key)));
101
+ return {
102
+ ...baseField(field, group),
103
+ label: field.label ?? target.label(2),
104
+ kind: FieldKind.rows,
105
+ multiple: true,
106
+ relation,
107
+ fields: children,
108
+ };
109
+ }
110
+ const declared = named?.kind === RelationKind.belongsTo ? named.create : undefined;
111
+ return {
112
+ ...baseField({ ...field, key: relation.key }, group),
113
+ label: field.label ??
114
+ propertyAt(properties(), relation.key)?.title ??
115
+ target.label(relation.kind === RelationKind.manyToMany ? 2 : 1),
116
+ kind: FieldKind.resource,
117
+ multiple: relation.kind === RelationKind.manyToMany,
118
+ resource: relation.target,
119
+ relation,
120
+ create: field.create ?? declared ?? true,
121
+ };
122
+ }
123
+ return { relationAt, relationField };
124
+ }
125
+ /** What a column through a relation (`product.price`) takes from the related field: its kind, tones, alignment, labels. */
126
+ export function inheritedColumn(related, rest) {
127
+ const declared = rest === undefined ? undefined : related?.options.columns?.find((entry) => entry.key === rest);
128
+ const property = rest === undefined ? undefined : propertyAt(related?.properties() ?? [], rest);
129
+ return {
130
+ tones: declared?.tones,
131
+ align: declared?.align,
132
+ options: optionsOfEnum(property, declared?.valueLabels),
133
+ kind: (toned) => declared?.as ?? (property ? columnKindOf(property, toned) : undefined),
134
+ };
135
+ }
136
+ /** The labels of a key's values, from its field or its column, whichever declares them. */
137
+ export function valueLabelsIn(options, key) {
138
+ const declared = (options.fields ?? []).flatMap((entry) => ("group" in entry ? entry.fields : [entry]));
139
+ return (declared.find((entry) => entry.key === key)?.valueLabels ??
140
+ options.columns?.find((entry) => entry.key === key)?.valueLabels);
141
+ }
@@ -0,0 +1,9 @@
1
+ import { ColumnKind, FieldKind } from "../core/constants.js";
2
+ import type { FieldDef, FieldGroup, Option, ResolvedField } from "./resource-types.js";
3
+ import { type Introspect, type SchemaProperty } from "./schema.js";
4
+ export declare const optionsOfEnum: (property: SchemaProperty | undefined, labels?: Readonly<Record<string, string>>) => Option[] | undefined;
5
+ export declare function columnKindOf(property: SchemaProperty, tones: boolean): ColumnKind;
6
+ export declare function fieldKindOf(property: SchemaProperty | undefined): FieldKind;
7
+ export declare function propertyAt(properties: readonly SchemaProperty[], path: string): SchemaProperty | undefined;
8
+ export declare function isGroup<T>(entry: FieldDef<T> | FieldGroup<T>): entry is FieldGroup<T>;
9
+ export declare function schemaFields(schema: unknown, introspect?: Introspect): ResolvedField<Record<string, unknown>>[];
@@ -0,0 +1,73 @@
1
+ import { ColumnKind, FieldKind, JsonFormat, JsonType } from "../core/constants.js";
2
+ import { zodIntrospect } from "./schema.js";
3
+ export const optionsOfEnum = (property, labels) => property?.enum?.map((value) => ({ value, label: labels?.[value] ?? value }));
4
+ export function columnKindOf(property, tones) {
5
+ if (property.enum)
6
+ return tones ? ColumnKind.status : ColumnKind.badge;
7
+ if (property.type === JsonType.boolean)
8
+ return ColumnKind.boolean;
9
+ if (property.type === JsonType.number || property.type === JsonType.integer)
10
+ return ColumnKind.number;
11
+ if (property.type === JsonType.array)
12
+ return ColumnKind.tags;
13
+ if (property.format === JsonFormat.uri || property.format === JsonFormat.url)
14
+ return ColumnKind.link;
15
+ if (property.format === JsonFormat.date)
16
+ return ColumnKind.date;
17
+ if (property.format === JsonFormat.dateTime)
18
+ return ColumnKind.datetime;
19
+ return ColumnKind.text;
20
+ }
21
+ const formatKinds = new Map([
22
+ [JsonFormat.email, FieldKind.email],
23
+ [JsonFormat.date, FieldKind.date],
24
+ [JsonFormat.dateTime, FieldKind.datetime],
25
+ [JsonFormat.time, FieldKind.time],
26
+ [JsonFormat.duration, FieldKind.duration],
27
+ ]);
28
+ export function fieldKindOf(property) {
29
+ if (!property)
30
+ return FieldKind.text;
31
+ if (property.enum)
32
+ return property.enum.length <= 4 ? FieldKind.radio : FieldKind.select;
33
+ if (property.type === JsonType.boolean)
34
+ return FieldKind.switch;
35
+ if (property.type === JsonType.number || property.type === JsonType.integer)
36
+ return FieldKind.number;
37
+ if (property.type === JsonType.array)
38
+ return FieldKind.tags;
39
+ const byFormat = property.format === undefined ? undefined : formatKinds.get(property.format);
40
+ return byFormat ?? ((property.maxLength ?? 0) > 255 ? FieldKind.textarea : FieldKind.text);
41
+ }
42
+ export function propertyAt(properties, path) {
43
+ const [head, ...rest] = path.split(".");
44
+ const property = properties.find((entry) => entry.key === head);
45
+ if (!property || rest.length === 0)
46
+ return property;
47
+ return property.properties ? propertyAt(property.properties, rest.join(".")) : undefined;
48
+ }
49
+ export function isGroup(entry) {
50
+ return "group" in entry;
51
+ }
52
+ const always = () => true;
53
+ const never = () => false;
54
+ export function schemaFields(schema, introspect = zodIntrospect) {
55
+ return (introspect(schema) ?? []).map((property) => {
56
+ const options = optionsOfEnum(property);
57
+ return {
58
+ key: property.key,
59
+ label: property.title ?? property.key,
60
+ kind: fieldKindOf(property),
61
+ required: property.required,
62
+ multiple: property.type === JsonType.array,
63
+ readOnly: property.readOnly ? always : never,
64
+ hidden: never,
65
+ colSpan: 1,
66
+ ...(property.description === undefined ? {} : { description: property.description }),
67
+ ...(options ? { options } : {}),
68
+ ...(property.minimum === undefined ? {} : { min: property.minimum }),
69
+ ...(property.maximum === undefined ? {} : { max: property.maximum }),
70
+ ...(property.type === undefined ? {} : { valueType: property.type }),
71
+ };
72
+ });
73
+ }