meta-to-blocks 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.
package/esm/schema.js ADDED
@@ -0,0 +1,239 @@
1
+ /**
2
+ * Column metadata → JSON Schema.
3
+ *
4
+ * Widget selection is not repeated here: a `_meta` column is lowered to the
5
+ * JSON Schema fragment that describes it, and `json-schema-to-blocks` turns
6
+ * that fragment into a node. One rule pipeline therefore serves both
7
+ * database-derived and schema-derived forms, which is the whole point of
8
+ * lowering through JSON Schema rather than emitting nodes directly.
9
+ */
10
+ import { titleize } from './naming';
11
+ /** Columns the database maintains; a create form should not ask for them. */
12
+ const AUDIT_COLUMNS = new Set(['created_at', 'createdAt', 'updated_at', 'updatedAt', 'deleted_at', 'deletedAt']);
13
+ /** GraphQL scalars that map straight onto a JSON Schema type. */
14
+ const scalarTypes = {
15
+ Boolean: { type: 'boolean' },
16
+ Int: { type: 'integer' },
17
+ Float: { type: 'number' },
18
+ BigInt: { type: 'integer' },
19
+ BigFloat: { type: 'number' },
20
+ Datetime: { type: 'string', format: 'date-time' },
21
+ Date: { type: 'string', format: 'date' },
22
+ Time: { type: 'string', format: 'time' },
23
+ UUID: { type: 'string', format: 'uuid', maxLength: 36 },
24
+ JSON: { type: 'string', format: 'json' },
25
+ Cursor: { type: 'string', maxLength: 255 },
26
+ InternetAddress: { type: 'string', maxLength: 45 },
27
+ Interval: { type: 'string', format: 'json' },
28
+ GeoJSON: { type: 'string', format: 'json' },
29
+ };
30
+ /** Postgres types whose GraphQL scalar is too coarse to pick a widget from. */
31
+ const pgTypes = {
32
+ text: { type: 'string' },
33
+ json: { type: 'string', format: 'json' },
34
+ jsonb: { type: 'string', format: 'json' },
35
+ bytea: { type: 'string', format: 'data-url' },
36
+ date: { type: 'string', format: 'date' },
37
+ time: { type: 'string', format: 'time' },
38
+ timetz: { type: 'string', format: 'time' },
39
+ timestamp: { type: 'string', format: 'date-time' },
40
+ timestamptz: { type: 'string', format: 'date-time' },
41
+ uuid: { type: 'string', format: 'uuid', maxLength: 36 },
42
+ bool: { type: 'boolean' },
43
+ int2: { type: 'integer' },
44
+ int4: { type: 'integer' },
45
+ int8: { type: 'integer' },
46
+ float4: { type: 'number' },
47
+ float8: { type: 'number' },
48
+ numeric: { type: 'number' },
49
+ money: { type: 'number' },
50
+ inet: { type: 'string', maxLength: 45 },
51
+ cidr: { type: 'string', maxLength: 45 },
52
+ macaddr: { type: 'string', maxLength: 17 },
53
+ ltree: { type: 'string', maxLength: 255 },
54
+ interval: { type: 'string', format: 'json' },
55
+ point: { type: 'string', format: 'json' },
56
+ geometry: { type: 'string', format: 'json' },
57
+ geography: { type: 'string', format: 'json' },
58
+ vector: { type: 'string', format: 'json' },
59
+ tsvector: { type: 'string', format: 'json' },
60
+ email: { type: 'string', format: 'email', maxLength: 320 },
61
+ citext: { type: 'string', maxLength: 255 },
62
+ };
63
+ /** `_meta` scalar encodings, which are more specific than either type name. */
64
+ const encodings = {
65
+ datetime: { type: 'string', format: 'date-time' },
66
+ date: { type: 'string', format: 'date' },
67
+ time: { type: 'string', format: 'time' },
68
+ uuid: { type: 'string', format: 'uuid', maxLength: 36 },
69
+ bigint: { type: 'integer' },
70
+ bytea: { type: 'string', format: 'data-url' },
71
+ interval: { type: 'string', format: 'json' },
72
+ geojson: { type: 'string', format: 'json' },
73
+ point: { type: 'string', format: 'json' },
74
+ vector: { type: 'string', format: 'json' },
75
+ composite: { type: 'string', format: 'json' },
76
+ inet: { type: 'string', maxLength: 45 },
77
+ ltree: { type: 'string', maxLength: 255 },
78
+ };
79
+ function unwrap(gqlType) {
80
+ return gqlType?.replace(/[[\]!]/g, '') || undefined;
81
+ }
82
+ /** `character varying(80)` / `varchar(80)` → 80. */
83
+ function varcharLength(pgType) {
84
+ const match = /^(?:character varying|varchar)\((\d+)\)$/.exec(pgType ?? '');
85
+ return match ? Number(match[1]) : undefined;
86
+ }
87
+ function baseType(pgType) {
88
+ return pgType?.replace(/^_/, '').replace(/\[\]$/, '').replace(/\(.*\)$/, '').trim() || undefined;
89
+ }
90
+ /**
91
+ * The scalar fragment for a column, most specific source first: `_meta`
92
+ * encoding, then Postgres type, then GraphQL scalar. An unrecognised type stays
93
+ * a bounded string so it lowers to an Input rather than a Textarea.
94
+ */
95
+ export function typeToSchema(type) {
96
+ const encoding = type?.encoding?.kind ? encodings[type.encoding.kind] : undefined;
97
+ if (encoding)
98
+ return { ...encoding };
99
+ const pg = baseType(type?.pgType);
100
+ if (pg && pgTypes[pg])
101
+ return { ...pgTypes[pg] };
102
+ const length = varcharLength(type?.pgType);
103
+ if (length != null)
104
+ return { type: 'string', maxLength: length };
105
+ const gql = unwrap(type?.gqlType);
106
+ if (gql && scalarTypes[gql])
107
+ return { ...scalarTypes[gql] };
108
+ return { type: 'string', maxLength: 255 };
109
+ }
110
+ /**
111
+ * `constraints` is the current grouped shape; cached pre-July metadata sends a
112
+ * flat array instead, which carries none of the fields read here.
113
+ */
114
+ export function structuredConstraints(table) {
115
+ const constraints = table.constraints;
116
+ if (!constraints || Array.isArray(constraints))
117
+ return undefined;
118
+ return constraints;
119
+ }
120
+ function isArrayColumn(field) {
121
+ return Boolean(field.type?.isArray) || Boolean(field.type?.pgType?.endsWith('[]')) || field.type?.pgType?.startsWith('_') === true;
122
+ }
123
+ function enumValues(field) {
124
+ const values = field.enumValues?.values?.filter((value) => typeof value === 'string');
125
+ return values?.length ? values : undefined;
126
+ }
127
+ /** Foreign keys are a picker over the referenced table, not a raw id input. */
128
+ function foreignKeyAnnotation(table, field) {
129
+ if (!field.isForeignKey)
130
+ return undefined;
131
+ const candidates = [
132
+ ...(structuredConstraints(table)?.foreignKey ?? []),
133
+ ...(table.foreignKeyConstraints ?? []),
134
+ ];
135
+ for (const constraint of candidates) {
136
+ if (!constraint)
137
+ continue;
138
+ const names = (constraint.fields ?? []).map((entry) => entry?.name);
139
+ if (!names.includes(field.name))
140
+ continue;
141
+ const referencedTable = constraint.referencedTable ?? constraint.refTable?.name ?? undefined;
142
+ const referencedField = constraint.referencedFields?.find((name) => typeof name === 'string') ??
143
+ constraint.refFields?.find((entry) => entry?.name)?.name ??
144
+ undefined;
145
+ return {
146
+ widget: 'Select',
147
+ props: {
148
+ relation: {
149
+ table: referencedTable,
150
+ ...(referencedField ? { field: referencedField } : {}),
151
+ },
152
+ },
153
+ };
154
+ }
155
+ return { widget: 'Select' };
156
+ }
157
+ /** A column the database fills in, so a create form should not ask for it. */
158
+ export function isSystemField(field) {
159
+ if (field.isPrimaryKey)
160
+ return true;
161
+ if (AUDIT_COLUMNS.has(field.name))
162
+ return true;
163
+ return false;
164
+ }
165
+ export function selectFields(table, options = {}) {
166
+ const omitted = new Set(options.omitFields ?? []);
167
+ const overrides = options.fields ?? {};
168
+ const fields = (table.fields ?? []).filter((field) => Boolean(field?.name));
169
+ const kept = fields.filter((field) => {
170
+ if (omitted.has(field.name) || overrides[field.name]?.omit)
171
+ return false;
172
+ if (!options.includeSystemFields && isSystemField(field))
173
+ return false;
174
+ return true;
175
+ });
176
+ const order = options.fieldOrder;
177
+ if (!order?.length)
178
+ return kept;
179
+ const rank = new Map(order.map((name, index) => [name, index]));
180
+ return [...kept].sort((left, right) => (rank.get(left.name) ?? order.length) - (rank.get(right.name) ?? order.length));
181
+ }
182
+ /** One column → its JSON Schema property (including `x-ui` presentation). */
183
+ export function fieldToSchema(table, field, override) {
184
+ const values = enumValues(field);
185
+ const scalar = values
186
+ ? { type: 'string', enum: values }
187
+ : typeToSchema(field.type);
188
+ const inner = {
189
+ ...scalar,
190
+ ...(field.description ? { description: field.description } : {}),
191
+ };
192
+ const fk = foreignKeyAnnotation(table, field);
193
+ const ui = {
194
+ ...fk,
195
+ // `author_id` picks an author, so the label loses the id suffix.
196
+ ...(fk ? { label: titleize(field.name) } : {}),
197
+ ...(override?.widget ? { widget: override.widget } : {}),
198
+ ...(override?.label ? { label: override.label } : {}),
199
+ ...(override?.description ? { description: override.description } : {}),
200
+ ...(override?.placeholder ? { placeholder: override.placeholder } : {}),
201
+ ...(override?.hidden ? { hidden: true } : {}),
202
+ ...(override?.disabled ? { disabled: true } : {}),
203
+ ...(override?.order != null ? { order: override.order } : {}),
204
+ ...(fk?.props || override?.props
205
+ ? { props: { ...fk?.props, ...override?.props } }
206
+ : {}),
207
+ };
208
+ const schema = isArrayColumn(field) ? { type: 'array', items: inner } : inner;
209
+ // A nullable column keeps its widget but accepts an explicit null.
210
+ if (!field.isNotNull)
211
+ schema.type = [schema.type, 'null'];
212
+ return {
213
+ ...schema,
214
+ ...(Object.keys(ui).length > 0 ? { 'x-ui': ui } : {}),
215
+ };
216
+ }
217
+ /**
218
+ * A whole table → one JSON Schema object, ready for
219
+ * `json-schema-to-blocks`. Useful on its own for validating writes.
220
+ */
221
+ export function tableToSchema(table, options = {}) {
222
+ const fields = selectFields(table, options);
223
+ const properties = {};
224
+ const required = [];
225
+ for (const field of fields) {
226
+ properties[field.name] = fieldToSchema(table, field, options.fields?.[field.name]);
227
+ // A NOT NULL column without a default is the only column a form must have.
228
+ if (field.isNotNull && !field.hasDefault)
229
+ required.push(field.name);
230
+ }
231
+ return {
232
+ $id: options.id ?? table.name,
233
+ type: 'object',
234
+ ...(options.title ? { title: options.title } : {}),
235
+ ...(table.description ? { description: table.description } : {}),
236
+ properties,
237
+ ...(required.length > 0 ? { required } : {}),
238
+ };
239
+ }
package/esm/types.js ADDED
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Structural types for the slice of Constructive's `_meta` contract this
3
+ * package reads.
4
+ *
5
+ * These mirror `@constructive-io/data`'s `Metaschema*` types but are declared
6
+ * locally and permissively (nullable, optional) so a `_meta` payload from that
7
+ * package — or from a raw GraphQL response — is assignable without this package
8
+ * depending on a GraphQL client.
9
+ */
10
+ export {};
package/index.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ export * from './convert';
2
+ export * from './naming';
3
+ export * from './schema';
4
+ export * from './types';
package/index.js ADDED
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./convert"), exports);
18
+ __exportStar(require("./naming"), exports);
19
+ __exportStar(require("./schema"), exports);
20
+ __exportStar(require("./types"), exports);
package/naming.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Column and table names → human labels.
3
+ *
4
+ * Sentence case, not title case, and all-caps words are left alone so acronyms
5
+ * survive (`api_url` → `Api URL`). Trailing `_id`/`Id` is dropped because a
6
+ * foreign key renders as a picker over the referenced row, not as an id.
7
+ */
8
+ export declare function titleize(name: string): string;
package/naming.js ADDED
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ /**
3
+ * Column and table names → human labels.
4
+ *
5
+ * Sentence case, not title case, and all-caps words are left alone so acronyms
6
+ * survive (`api_url` → `Api URL`). Trailing `_id`/`Id` is dropped because a
7
+ * foreign key renders as a picker over the referenced row, not as an id.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.titleize = titleize;
11
+ function titleize(name) {
12
+ if (!name)
13
+ return '';
14
+ const words = name
15
+ .replace(/[_-]+/g, ' ')
16
+ .replace(/([a-z0-9])([A-Z])/g, '$1 $2')
17
+ .trim()
18
+ .split(/\s+/)
19
+ .map((word) => (word === word.toUpperCase() ? word : word.toLowerCase()));
20
+ const trimmed = words.length > 1 && words[words.length - 1].toLowerCase() === 'id' ? words.slice(0, -1) : words;
21
+ return trimmed.join(' ').replace(/^./, (character) => character.toUpperCase());
22
+ }
package/package.json ADDED
@@ -0,0 +1,52 @@
1
+ {
2
+ "name": "meta-to-blocks",
3
+ "version": "0.1.0",
4
+ "description": "Lower database metadata into blocks-schema UI documents: generated form, list, and detail screens",
5
+ "private": false,
6
+ "license": "MIT",
7
+ "homepage": "https://constructive-io.github.io/blocks/",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/constructive-io/blocks.git",
11
+ "directory": "packages/meta-to-blocks"
12
+ },
13
+ "bugs": {
14
+ "url": "https://github.com/constructive-io/blocks/issues"
15
+ },
16
+ "publishConfig": {
17
+ "access": "public",
18
+ "directory": "dist"
19
+ },
20
+ "sideEffects": false,
21
+ "main": "index.js",
22
+ "module": "esm/index.js",
23
+ "types": "index.d.ts",
24
+ "scripts": {
25
+ "build": "makage clean && makage build-ts && makage assets",
26
+ "build:dev": "makage clean && makage build-ts --dev && makage assets",
27
+ "lint:types": "tsc --noEmit -p tsconfig.lint.json",
28
+ "test": "vitest run",
29
+ "test:watch": "vitest",
30
+ "clean": "makage clean"
31
+ },
32
+ "keywords": [
33
+ "metadata",
34
+ "admin",
35
+ "form",
36
+ "ui-schema",
37
+ "blocks",
38
+ "renderer"
39
+ ],
40
+ "dependencies": {
41
+ "blocks-schema": "workspace:^",
42
+ "json-schema-to-blocks": "workspace:^"
43
+ },
44
+ "devDependencies": {
45
+ "makage": "^0.6.0",
46
+ "typescript": "^5.9.3",
47
+ "vitest": "^3.2.4"
48
+ },
49
+ "engines": {
50
+ "node": ">=24.0.0"
51
+ }
52
+ }
package/schema.d.ts ADDED
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Column metadata → JSON Schema.
3
+ *
4
+ * Widget selection is not repeated here: a `_meta` column is lowered to the
5
+ * JSON Schema fragment that describes it, and `json-schema-to-blocks` turns
6
+ * that fragment into a node. One rule pipeline therefore serves both
7
+ * database-derived and schema-derived forms, which is the whole point of
8
+ * lowering through JSON Schema rather than emitting nodes directly.
9
+ */
10
+ import type { JSONSchema } from 'json-schema-to-blocks';
11
+ import type { FieldOverride, MetaConstraints, MetaField, MetaOptions, MetaTable, MetaType } from './types';
12
+ /**
13
+ * The scalar fragment for a column, most specific source first: `_meta`
14
+ * encoding, then Postgres type, then GraphQL scalar. An unrecognised type stays
15
+ * a bounded string so it lowers to an Input rather than a Textarea.
16
+ */
17
+ export declare function typeToSchema(type: MetaType | null | undefined): JSONSchema;
18
+ /**
19
+ * `constraints` is the current grouped shape; cached pre-July metadata sends a
20
+ * flat array instead, which carries none of the fields read here.
21
+ */
22
+ export declare function structuredConstraints(table: MetaTable): MetaConstraints | undefined;
23
+ /** A column the database fills in, so a create form should not ask for it. */
24
+ export declare function isSystemField(field: MetaField): boolean;
25
+ export declare function selectFields(table: MetaTable, options?: MetaOptions): MetaField[];
26
+ /** One column → its JSON Schema property (including `x-ui` presentation). */
27
+ export declare function fieldToSchema(table: MetaTable, field: MetaField, override?: FieldOverride): JSONSchema;
28
+ /**
29
+ * A whole table → one JSON Schema object, ready for
30
+ * `json-schema-to-blocks`. Useful on its own for validating writes.
31
+ */
32
+ export declare function tableToSchema(table: MetaTable, options?: MetaOptions): JSONSchema;
package/schema.js ADDED
@@ -0,0 +1,247 @@
1
+ "use strict";
2
+ /**
3
+ * Column metadata → JSON Schema.
4
+ *
5
+ * Widget selection is not repeated here: a `_meta` column is lowered to the
6
+ * JSON Schema fragment that describes it, and `json-schema-to-blocks` turns
7
+ * that fragment into a node. One rule pipeline therefore serves both
8
+ * database-derived and schema-derived forms, which is the whole point of
9
+ * lowering through JSON Schema rather than emitting nodes directly.
10
+ */
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.typeToSchema = typeToSchema;
13
+ exports.structuredConstraints = structuredConstraints;
14
+ exports.isSystemField = isSystemField;
15
+ exports.selectFields = selectFields;
16
+ exports.fieldToSchema = fieldToSchema;
17
+ exports.tableToSchema = tableToSchema;
18
+ const naming_1 = require("./naming");
19
+ /** Columns the database maintains; a create form should not ask for them. */
20
+ const AUDIT_COLUMNS = new Set(['created_at', 'createdAt', 'updated_at', 'updatedAt', 'deleted_at', 'deletedAt']);
21
+ /** GraphQL scalars that map straight onto a JSON Schema type. */
22
+ const scalarTypes = {
23
+ Boolean: { type: 'boolean' },
24
+ Int: { type: 'integer' },
25
+ Float: { type: 'number' },
26
+ BigInt: { type: 'integer' },
27
+ BigFloat: { type: 'number' },
28
+ Datetime: { type: 'string', format: 'date-time' },
29
+ Date: { type: 'string', format: 'date' },
30
+ Time: { type: 'string', format: 'time' },
31
+ UUID: { type: 'string', format: 'uuid', maxLength: 36 },
32
+ JSON: { type: 'string', format: 'json' },
33
+ Cursor: { type: 'string', maxLength: 255 },
34
+ InternetAddress: { type: 'string', maxLength: 45 },
35
+ Interval: { type: 'string', format: 'json' },
36
+ GeoJSON: { type: 'string', format: 'json' },
37
+ };
38
+ /** Postgres types whose GraphQL scalar is too coarse to pick a widget from. */
39
+ const pgTypes = {
40
+ text: { type: 'string' },
41
+ json: { type: 'string', format: 'json' },
42
+ jsonb: { type: 'string', format: 'json' },
43
+ bytea: { type: 'string', format: 'data-url' },
44
+ date: { type: 'string', format: 'date' },
45
+ time: { type: 'string', format: 'time' },
46
+ timetz: { type: 'string', format: 'time' },
47
+ timestamp: { type: 'string', format: 'date-time' },
48
+ timestamptz: { type: 'string', format: 'date-time' },
49
+ uuid: { type: 'string', format: 'uuid', maxLength: 36 },
50
+ bool: { type: 'boolean' },
51
+ int2: { type: 'integer' },
52
+ int4: { type: 'integer' },
53
+ int8: { type: 'integer' },
54
+ float4: { type: 'number' },
55
+ float8: { type: 'number' },
56
+ numeric: { type: 'number' },
57
+ money: { type: 'number' },
58
+ inet: { type: 'string', maxLength: 45 },
59
+ cidr: { type: 'string', maxLength: 45 },
60
+ macaddr: { type: 'string', maxLength: 17 },
61
+ ltree: { type: 'string', maxLength: 255 },
62
+ interval: { type: 'string', format: 'json' },
63
+ point: { type: 'string', format: 'json' },
64
+ geometry: { type: 'string', format: 'json' },
65
+ geography: { type: 'string', format: 'json' },
66
+ vector: { type: 'string', format: 'json' },
67
+ tsvector: { type: 'string', format: 'json' },
68
+ email: { type: 'string', format: 'email', maxLength: 320 },
69
+ citext: { type: 'string', maxLength: 255 },
70
+ };
71
+ /** `_meta` scalar encodings, which are more specific than either type name. */
72
+ const encodings = {
73
+ datetime: { type: 'string', format: 'date-time' },
74
+ date: { type: 'string', format: 'date' },
75
+ time: { type: 'string', format: 'time' },
76
+ uuid: { type: 'string', format: 'uuid', maxLength: 36 },
77
+ bigint: { type: 'integer' },
78
+ bytea: { type: 'string', format: 'data-url' },
79
+ interval: { type: 'string', format: 'json' },
80
+ geojson: { type: 'string', format: 'json' },
81
+ point: { type: 'string', format: 'json' },
82
+ vector: { type: 'string', format: 'json' },
83
+ composite: { type: 'string', format: 'json' },
84
+ inet: { type: 'string', maxLength: 45 },
85
+ ltree: { type: 'string', maxLength: 255 },
86
+ };
87
+ function unwrap(gqlType) {
88
+ return gqlType?.replace(/[[\]!]/g, '') || undefined;
89
+ }
90
+ /** `character varying(80)` / `varchar(80)` → 80. */
91
+ function varcharLength(pgType) {
92
+ const match = /^(?:character varying|varchar)\((\d+)\)$/.exec(pgType ?? '');
93
+ return match ? Number(match[1]) : undefined;
94
+ }
95
+ function baseType(pgType) {
96
+ return pgType?.replace(/^_/, '').replace(/\[\]$/, '').replace(/\(.*\)$/, '').trim() || undefined;
97
+ }
98
+ /**
99
+ * The scalar fragment for a column, most specific source first: `_meta`
100
+ * encoding, then Postgres type, then GraphQL scalar. An unrecognised type stays
101
+ * a bounded string so it lowers to an Input rather than a Textarea.
102
+ */
103
+ function typeToSchema(type) {
104
+ const encoding = type?.encoding?.kind ? encodings[type.encoding.kind] : undefined;
105
+ if (encoding)
106
+ return { ...encoding };
107
+ const pg = baseType(type?.pgType);
108
+ if (pg && pgTypes[pg])
109
+ return { ...pgTypes[pg] };
110
+ const length = varcharLength(type?.pgType);
111
+ if (length != null)
112
+ return { type: 'string', maxLength: length };
113
+ const gql = unwrap(type?.gqlType);
114
+ if (gql && scalarTypes[gql])
115
+ return { ...scalarTypes[gql] };
116
+ return { type: 'string', maxLength: 255 };
117
+ }
118
+ /**
119
+ * `constraints` is the current grouped shape; cached pre-July metadata sends a
120
+ * flat array instead, which carries none of the fields read here.
121
+ */
122
+ function structuredConstraints(table) {
123
+ const constraints = table.constraints;
124
+ if (!constraints || Array.isArray(constraints))
125
+ return undefined;
126
+ return constraints;
127
+ }
128
+ function isArrayColumn(field) {
129
+ return Boolean(field.type?.isArray) || Boolean(field.type?.pgType?.endsWith('[]')) || field.type?.pgType?.startsWith('_') === true;
130
+ }
131
+ function enumValues(field) {
132
+ const values = field.enumValues?.values?.filter((value) => typeof value === 'string');
133
+ return values?.length ? values : undefined;
134
+ }
135
+ /** Foreign keys are a picker over the referenced table, not a raw id input. */
136
+ function foreignKeyAnnotation(table, field) {
137
+ if (!field.isForeignKey)
138
+ return undefined;
139
+ const candidates = [
140
+ ...(structuredConstraints(table)?.foreignKey ?? []),
141
+ ...(table.foreignKeyConstraints ?? []),
142
+ ];
143
+ for (const constraint of candidates) {
144
+ if (!constraint)
145
+ continue;
146
+ const names = (constraint.fields ?? []).map((entry) => entry?.name);
147
+ if (!names.includes(field.name))
148
+ continue;
149
+ const referencedTable = constraint.referencedTable ?? constraint.refTable?.name ?? undefined;
150
+ const referencedField = constraint.referencedFields?.find((name) => typeof name === 'string') ??
151
+ constraint.refFields?.find((entry) => entry?.name)?.name ??
152
+ undefined;
153
+ return {
154
+ widget: 'Select',
155
+ props: {
156
+ relation: {
157
+ table: referencedTable,
158
+ ...(referencedField ? { field: referencedField } : {}),
159
+ },
160
+ },
161
+ };
162
+ }
163
+ return { widget: 'Select' };
164
+ }
165
+ /** A column the database fills in, so a create form should not ask for it. */
166
+ function isSystemField(field) {
167
+ if (field.isPrimaryKey)
168
+ return true;
169
+ if (AUDIT_COLUMNS.has(field.name))
170
+ return true;
171
+ return false;
172
+ }
173
+ function selectFields(table, options = {}) {
174
+ const omitted = new Set(options.omitFields ?? []);
175
+ const overrides = options.fields ?? {};
176
+ const fields = (table.fields ?? []).filter((field) => Boolean(field?.name));
177
+ const kept = fields.filter((field) => {
178
+ if (omitted.has(field.name) || overrides[field.name]?.omit)
179
+ return false;
180
+ if (!options.includeSystemFields && isSystemField(field))
181
+ return false;
182
+ return true;
183
+ });
184
+ const order = options.fieldOrder;
185
+ if (!order?.length)
186
+ return kept;
187
+ const rank = new Map(order.map((name, index) => [name, index]));
188
+ return [...kept].sort((left, right) => (rank.get(left.name) ?? order.length) - (rank.get(right.name) ?? order.length));
189
+ }
190
+ /** One column → its JSON Schema property (including `x-ui` presentation). */
191
+ function fieldToSchema(table, field, override) {
192
+ const values = enumValues(field);
193
+ const scalar = values
194
+ ? { type: 'string', enum: values }
195
+ : typeToSchema(field.type);
196
+ const inner = {
197
+ ...scalar,
198
+ ...(field.description ? { description: field.description } : {}),
199
+ };
200
+ const fk = foreignKeyAnnotation(table, field);
201
+ const ui = {
202
+ ...fk,
203
+ // `author_id` picks an author, so the label loses the id suffix.
204
+ ...(fk ? { label: (0, naming_1.titleize)(field.name) } : {}),
205
+ ...(override?.widget ? { widget: override.widget } : {}),
206
+ ...(override?.label ? { label: override.label } : {}),
207
+ ...(override?.description ? { description: override.description } : {}),
208
+ ...(override?.placeholder ? { placeholder: override.placeholder } : {}),
209
+ ...(override?.hidden ? { hidden: true } : {}),
210
+ ...(override?.disabled ? { disabled: true } : {}),
211
+ ...(override?.order != null ? { order: override.order } : {}),
212
+ ...(fk?.props || override?.props
213
+ ? { props: { ...fk?.props, ...override?.props } }
214
+ : {}),
215
+ };
216
+ const schema = isArrayColumn(field) ? { type: 'array', items: inner } : inner;
217
+ // A nullable column keeps its widget but accepts an explicit null.
218
+ if (!field.isNotNull)
219
+ schema.type = [schema.type, 'null'];
220
+ return {
221
+ ...schema,
222
+ ...(Object.keys(ui).length > 0 ? { 'x-ui': ui } : {}),
223
+ };
224
+ }
225
+ /**
226
+ * A whole table → one JSON Schema object, ready for
227
+ * `json-schema-to-blocks`. Useful on its own for validating writes.
228
+ */
229
+ function tableToSchema(table, options = {}) {
230
+ const fields = selectFields(table, options);
231
+ const properties = {};
232
+ const required = [];
233
+ for (const field of fields) {
234
+ properties[field.name] = fieldToSchema(table, field, options.fields?.[field.name]);
235
+ // A NOT NULL column without a default is the only column a form must have.
236
+ if (field.isNotNull && !field.hasDefault)
237
+ required.push(field.name);
238
+ }
239
+ return {
240
+ $id: options.id ?? table.name,
241
+ type: 'object',
242
+ ...(options.title ? { title: options.title } : {}),
243
+ ...(table.description ? { description: table.description } : {}),
244
+ properties,
245
+ ...(required.length > 0 ? { required } : {}),
246
+ };
247
+ }