formo-react 0.0.0-stage → 0.3.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/LICENSE +201 -0
- package/README.md +21 -2
- package/dist/components/FormoBlueprint.d.ts +5 -0
- package/dist/components/FormoBlueprint.js +30 -0
- package/dist/components/FormoButton.d.ts +6 -0
- package/dist/components/FormoButton.js +23 -0
- package/dist/components/FormoCheckbox.d.ts +7 -0
- package/dist/components/FormoCheckbox.js +10 -0
- package/dist/components/FormoChecklist.d.ts +5 -0
- package/dist/components/FormoChecklist.js +15 -0
- package/dist/components/FormoChoices.d.ts +8 -0
- package/dist/components/FormoChoices.js +33 -0
- package/dist/components/FormoContext.d.ts +27 -0
- package/dist/components/FormoContext.js +69 -0
- package/dist/components/FormoErrors.d.ts +5 -0
- package/dist/components/FormoErrors.js +14 -0
- package/dist/components/FormoField.d.ts +17 -0
- package/dist/components/FormoField.js +148 -0
- package/dist/components/FormoForm.d.ts +15 -0
- package/dist/components/FormoForm.js +76 -0
- package/dist/components/FormoGroup.d.ts +5 -0
- package/dist/components/FormoGroup.js +15 -0
- package/dist/components/FormoHelp.d.ts +6 -0
- package/dist/components/FormoHelp.js +9 -0
- package/dist/components/FormoInput.d.ts +6 -0
- package/dist/components/FormoInput.js +24 -0
- package/dist/components/FormoLabel.d.ts +6 -0
- package/dist/components/FormoLabel.js +9 -0
- package/dist/components/FormoProvider.d.ts +11 -0
- package/dist/components/FormoProvider.js +13 -0
- package/dist/components/FormoRest.d.ts +6 -0
- package/dist/components/FormoRest.js +23 -0
- package/dist/components/FormoSelect.d.ts +6 -0
- package/dist/components/FormoSelect.js +36 -0
- package/dist/components/FormoUneditable.d.ts +6 -0
- package/dist/components/FormoUneditable.js +12 -0
- package/dist/core/builder.d.ts +42 -0
- package/dist/core/builder.js +166 -0
- package/dist/core/controls.d.ts +27 -0
- package/dist/core/controls.js +24 -0
- package/dist/core/fields.d.ts +63 -0
- package/dist/core/fields.js +177 -0
- package/dist/core/messages.d.ts +35 -0
- package/dist/core/messages.js +69 -0
- package/dist/core/normalize.d.ts +35 -0
- package/dist/core/normalize.js +234 -0
- package/dist/core/options.d.ts +44 -0
- package/dist/core/options.js +146 -0
- package/dist/core/rules.d.ts +41 -0
- package/dist/core/rules.js +230 -0
- package/dist/core/store.d.ts +155 -0
- package/dist/core/store.js +830 -0
- package/dist/core/theme.d.ts +20 -0
- package/dist/core/theme.js +21 -0
- package/dist/core/tree.d.ts +74 -0
- package/dist/core/tree.js +119 -0
- package/dist/core/utils.d.ts +35 -0
- package/dist/core/utils.js +206 -0
- package/dist/hooks/subscriptions.d.ts +38 -0
- package/dist/hooks/subscriptions.js +65 -0
- package/dist/hooks/useFormo.d.ts +18 -0
- package/dist/hooks/useFormo.js +25 -0
- package/dist/index.d.ts +28 -0
- package/dist/index.js +27 -0
- package/dist/schema/form.d.ts +92 -0
- package/dist/schema/form.js +304 -0
- package/dist/schema/index.d.ts +22 -0
- package/dist/schema/index.js +21 -0
- package/dist/schema/ir.d.ts +189 -0
- package/dist/schema/ir.js +130 -0
- package/dist/schema/json-schema.d.ts +25 -0
- package/dist/schema/json-schema.js +351 -0
- package/dist/schema/laravel.d.ts +57 -0
- package/dist/schema/laravel.js +555 -0
- package/dist/schema/openapi.d.ts +24 -0
- package/dist/schema/openapi.js +67 -0
- package/dist/schema/policy.d.ts +60 -0
- package/dist/schema/policy.js +315 -0
- package/dist/schema/spec.d.ts +75 -0
- package/dist/schema/spec.js +1 -0
- package/dist/schema/values.d.ts +35 -0
- package/dist/schema/values.js +151 -0
- package/dist/schema/zod.d.ts +79 -0
- package/dist/schema/zod.js +236 -0
- package/dist/types.d.ts +400 -0
- package/dist/types.js +1 -0
- package/package.json +70 -4
|
@@ -0,0 +1,555 @@
|
|
|
1
|
+
import { MODEL_VERSION, consoleWarning, } from './ir';
|
|
2
|
+
/* ---- Parsing ------------------------------------------------------------- */
|
|
3
|
+
/** `a,"b, c",d` → ['a', 'b, c', 'd'] (Laravel reads params with str_getcsv; Rule::in() quotes its values) */
|
|
4
|
+
export function parseCsv(input) {
|
|
5
|
+
const out = [];
|
|
6
|
+
let current = '';
|
|
7
|
+
let quoted = false;
|
|
8
|
+
let wasQuoted = false;
|
|
9
|
+
for (let i = 0; i < input.length; i++) {
|
|
10
|
+
const ch = input[i];
|
|
11
|
+
if (quoted) {
|
|
12
|
+
if (ch === '"' && input[i + 1] === '"') {
|
|
13
|
+
current += '"';
|
|
14
|
+
i++;
|
|
15
|
+
}
|
|
16
|
+
else if (ch === '"')
|
|
17
|
+
quoted = false;
|
|
18
|
+
else
|
|
19
|
+
current += ch;
|
|
20
|
+
continue;
|
|
21
|
+
}
|
|
22
|
+
if (ch === '"' && current.trim() === '') {
|
|
23
|
+
quoted = true;
|
|
24
|
+
wasQuoted = true;
|
|
25
|
+
current = '';
|
|
26
|
+
}
|
|
27
|
+
else if (ch === ',') {
|
|
28
|
+
out.push(wasQuoted ? current : current.trim());
|
|
29
|
+
current = '';
|
|
30
|
+
wasQuoted = false;
|
|
31
|
+
}
|
|
32
|
+
else
|
|
33
|
+
current += ch;
|
|
34
|
+
}
|
|
35
|
+
out.push(wasQuoted ? current : current.trim());
|
|
36
|
+
return out;
|
|
37
|
+
}
|
|
38
|
+
/** `'min:3'` → `{ name: 'min', params: ['3'] }` (regex patterns keep their commas) */
|
|
39
|
+
export function parseLaravelRule(text) {
|
|
40
|
+
const idx = text.indexOf(':');
|
|
41
|
+
if (idx === -1)
|
|
42
|
+
return { name: text.trim().toLowerCase(), params: [], raw: text.trim() };
|
|
43
|
+
const name = text.slice(0, idx).trim().toLowerCase();
|
|
44
|
+
const rest = text.slice(idx + 1);
|
|
45
|
+
return { name, params: name === 'regex' || name === 'not_regex' ? [rest] : parseCsv(rest), raw: text.trim() };
|
|
46
|
+
}
|
|
47
|
+
function ruleList(value, key, warn) {
|
|
48
|
+
if (typeof value === 'string')
|
|
49
|
+
return value.split('|').filter((r) => r.trim()).map(parseLaravelRule);
|
|
50
|
+
if (!Array.isArray(value)) {
|
|
51
|
+
warn({ path: key, code: 'invalid-rules', message: 'rules must be a string or an array' });
|
|
52
|
+
return [];
|
|
53
|
+
}
|
|
54
|
+
const out = [];
|
|
55
|
+
for (const item of value) {
|
|
56
|
+
if (typeof item === 'string') {
|
|
57
|
+
if (item.trim())
|
|
58
|
+
out.push(parseLaravelRule(item));
|
|
59
|
+
}
|
|
60
|
+
else {
|
|
61
|
+
warn({
|
|
62
|
+
path: key,
|
|
63
|
+
code: 'rule-object',
|
|
64
|
+
message: 'a rule object reached the client (json_encode turns it into {}) — cast Stringable rules to strings server-side, or describe it in the Formo model',
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return out;
|
|
69
|
+
}
|
|
70
|
+
function newNode(key, name) {
|
|
71
|
+
return { key, name, rules: [], children: new Map() };
|
|
72
|
+
}
|
|
73
|
+
function buildTree(rules, warn) {
|
|
74
|
+
const root = newNode('');
|
|
75
|
+
for (const [key, value] of Object.entries(rules)) {
|
|
76
|
+
let node = root;
|
|
77
|
+
for (const segment of key.split('.')) {
|
|
78
|
+
const childKey = node.key ? `${node.key}.${segment}` : segment;
|
|
79
|
+
if (segment === '*')
|
|
80
|
+
node = node.item ??= newNode(childKey);
|
|
81
|
+
else {
|
|
82
|
+
let child = node.children.get(segment);
|
|
83
|
+
if (!child)
|
|
84
|
+
node.children.set(segment, (child = newNode(childKey, segment)));
|
|
85
|
+
node = child;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
node.rules.push(...ruleList(value, key, warn));
|
|
89
|
+
}
|
|
90
|
+
return root;
|
|
91
|
+
}
|
|
92
|
+
/* ---- Rule knowledge ------------------------------------------------------- */
|
|
93
|
+
const FILE_RULES = ['file', 'image', 'mimes', 'mimetypes', 'extensions', 'dimensions'];
|
|
94
|
+
const DATE_RULES = ['date', 'date_format', 'after', 'before', 'after_or_equal', 'before_or_equal', 'date_equals'];
|
|
95
|
+
const CONDITIONAL = ['required_if', 'required_unless', 'required_with', 'required_with_all', 'required_without', 'required_without_all', 'exclude_if', 'exclude_unless'];
|
|
96
|
+
/** Conditional rules whose every param is a field (the others: first param only) */
|
|
97
|
+
const ALL_FIELDS = ['required_with', 'required_with_all', 'required_without', 'required_without_all'];
|
|
98
|
+
/** Rules only the server can check — listed in `serverRules`, silently */
|
|
99
|
+
const SERVER_ONLY = new Set([
|
|
100
|
+
'unique', 'exists', 'current_password', 'distinct', 'dimensions', 'after', 'before', 'after_or_equal',
|
|
101
|
+
'before_or_equal', 'date_equals', 'not_regex', 'timezone', 'mac_address', 'ulid', 'json', 'lowercase',
|
|
102
|
+
'uppercase', 'starts_with', 'ends_with', 'doesnt_start_with', 'doesnt_end_with', 'prohibited', 'prohibited_if',
|
|
103
|
+
'prohibited_unless', 'prohibits', 'missing', 'missing_if', 'missing_unless', 'missing_with', 'missing_with_all',
|
|
104
|
+
'present_if', 'present_unless', 'present_with', 'present_with_all', 'required_if_accepted', 'required_if_declined',
|
|
105
|
+
'required_array_keys', 'accepted_if', 'declined', 'declined_if', 'exclude_with', 'exclude_without', 'max_digits',
|
|
106
|
+
'min_digits', 'multiple_of', 'in_array', 'ascii', 'enum', 'contains', 'doesnt_contain',
|
|
107
|
+
]);
|
|
108
|
+
/** Rules that only say something about the type / presence — consumed while reading the field */
|
|
109
|
+
const STRUCTURAL = new Set([
|
|
110
|
+
'bail', 'sometimes', 'nullable', 'present', 'filled', 'required', 'string', 'array', 'list', 'integer', 'int',
|
|
111
|
+
'numeric', 'boolean', 'bool', 'date', 'date_format', 'file', 'image', 'mimes', 'mimetypes', 'extensions', 'email',
|
|
112
|
+
'url', 'active_url', 'uuid', 'ip', 'ipv4', 'ipv6', 'hex_color', 'in', 'not_in', 'min', 'max', 'between', 'size',
|
|
113
|
+
'gt', 'gte', 'lt', 'lte', 'digits', 'digits_between', 'decimal', 'regex', 'same', 'different', 'confirmed',
|
|
114
|
+
'accepted', 'alpha', 'alpha_num', 'alpha_dash', 'exclude', ...CONDITIONAL,
|
|
115
|
+
]);
|
|
116
|
+
function kindOf(type, item) {
|
|
117
|
+
if (type === 'string' || type === 'text' || type === 'enum')
|
|
118
|
+
return 'string';
|
|
119
|
+
if (type === 'integer' || type === 'number')
|
|
120
|
+
return 'number';
|
|
121
|
+
if (type === 'file')
|
|
122
|
+
return 'file';
|
|
123
|
+
if (type === 'array')
|
|
124
|
+
return item?.type === 'file' ? 'file' : 'array';
|
|
125
|
+
return 'other';
|
|
126
|
+
}
|
|
127
|
+
/** A Laravel rule → the Formo rule(s) it becomes, for a field of this kind (message keys) */
|
|
128
|
+
function formoNames(rule, kind) {
|
|
129
|
+
const bySize = (s, n, a, f) => kind === 'any' ? [...s, ...n, ...a, ...f] : kind === 'string' ? s : kind === 'number' ? n : kind === 'array' ? a : kind === 'file' ? f : [];
|
|
130
|
+
switch (rule) {
|
|
131
|
+
case 'min':
|
|
132
|
+
return bySize(['min'], ['min_value'], ['min_items'], []);
|
|
133
|
+
case 'max':
|
|
134
|
+
return bySize(['max'], ['max_value'], ['max_items'], ['size']);
|
|
135
|
+
case 'between':
|
|
136
|
+
case 'size':
|
|
137
|
+
return bySize(['min', 'max'], ['min_value', 'max_value'], ['min_items', 'max_items'], ['size']);
|
|
138
|
+
case 'gte':
|
|
139
|
+
return ['min_value', 'gte'];
|
|
140
|
+
case 'lte':
|
|
141
|
+
return ['max_value', 'lte'];
|
|
142
|
+
case 'numeric':
|
|
143
|
+
return ['decimal'];
|
|
144
|
+
case 'int':
|
|
145
|
+
return ['integer'];
|
|
146
|
+
case 'in':
|
|
147
|
+
return ['one_of'];
|
|
148
|
+
case 'not_in':
|
|
149
|
+
return ['not_one_of'];
|
|
150
|
+
case 'same':
|
|
151
|
+
return ['matches'];
|
|
152
|
+
case 'different':
|
|
153
|
+
return ['is_not'];
|
|
154
|
+
case 'mimes':
|
|
155
|
+
case 'extensions':
|
|
156
|
+
return ['ext'];
|
|
157
|
+
case 'mimetypes':
|
|
158
|
+
return ['mimes'];
|
|
159
|
+
case 'digits_between':
|
|
160
|
+
case 'uuid':
|
|
161
|
+
return ['regex'];
|
|
162
|
+
case 'hex_color':
|
|
163
|
+
return ['color'];
|
|
164
|
+
case 'ipv4':
|
|
165
|
+
case 'ipv6':
|
|
166
|
+
return ['ip'];
|
|
167
|
+
case 'active_url':
|
|
168
|
+
return ['url'];
|
|
169
|
+
case 'date_format':
|
|
170
|
+
return ['date'];
|
|
171
|
+
default:
|
|
172
|
+
return [rule];
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
/** Laravel's typed size message keys: `min.string`, `max.numeric`, `between.array`, `max.file` */
|
|
176
|
+
const TYPED_KINDS = { string: 'string', numeric: 'number', array: 'array', file: 'file' };
|
|
177
|
+
/** A field reference in a rule param, relative to the row when both live in the same `*` rows */
|
|
178
|
+
function fieldRef(param, key) {
|
|
179
|
+
if (!param.includes('*'))
|
|
180
|
+
return param;
|
|
181
|
+
const star = param.lastIndexOf('.*.');
|
|
182
|
+
const prefix = star === -1 ? '' : param.slice(0, star + 3);
|
|
183
|
+
return prefix && key.startsWith(prefix) ? param.slice(prefix.length) : param.replace(/\.\*/g, '');
|
|
184
|
+
}
|
|
185
|
+
const numeric = (v) => v !== undefined && v.trim() !== '' && !Number.isNaN(Number(v));
|
|
186
|
+
function inferType(node, has) {
|
|
187
|
+
if (node.children.size)
|
|
188
|
+
return 'object';
|
|
189
|
+
if (node.item || has('array') || has('list'))
|
|
190
|
+
return 'array';
|
|
191
|
+
if (FILE_RULES.some(has))
|
|
192
|
+
return 'file';
|
|
193
|
+
if (has('boolean') || has('bool') || has('accepted'))
|
|
194
|
+
return 'boolean';
|
|
195
|
+
// `integer|in:1,2,3`: a choice (with number values)
|
|
196
|
+
if (has('in'))
|
|
197
|
+
return 'enum';
|
|
198
|
+
if (has('integer') || has('int'))
|
|
199
|
+
return 'integer';
|
|
200
|
+
if (has('numeric') || has('decimal'))
|
|
201
|
+
return 'number';
|
|
202
|
+
if (DATE_RULES.some(has)) {
|
|
203
|
+
const format = node.rules.find((r) => r.name === 'date_format')?.params[0];
|
|
204
|
+
if (format) {
|
|
205
|
+
const hasDate = /[dDjlNSwzWFmMntLoYyUc]/.test(format.replace(/\\./g, ''));
|
|
206
|
+
const hasTime = /[aABgGhHisvu]/.test(format.replace(/\\./g, ''));
|
|
207
|
+
if (hasTime && !hasDate)
|
|
208
|
+
return 'time';
|
|
209
|
+
if (hasTime)
|
|
210
|
+
return 'datetime';
|
|
211
|
+
}
|
|
212
|
+
return 'date';
|
|
213
|
+
}
|
|
214
|
+
if (has('json'))
|
|
215
|
+
return 'text';
|
|
216
|
+
return 'string';
|
|
217
|
+
}
|
|
218
|
+
function convert(node, ctx) {
|
|
219
|
+
const names = new Set(node.rules.map((r) => r.name));
|
|
220
|
+
const has = (n) => names.has(n);
|
|
221
|
+
const rule = (n) => node.rules.find((r) => r.name === n);
|
|
222
|
+
if (has('exclude'))
|
|
223
|
+
return undefined;
|
|
224
|
+
const field = { type: inferType(node, has) };
|
|
225
|
+
if (node.name !== undefined)
|
|
226
|
+
field.name = node.name;
|
|
227
|
+
const label = ctx.attributes[node.key];
|
|
228
|
+
if (label)
|
|
229
|
+
field.label = label;
|
|
230
|
+
if (has('required'))
|
|
231
|
+
field.required = true;
|
|
232
|
+
if (has('nullable'))
|
|
233
|
+
field.nullable = true;
|
|
234
|
+
const c = {};
|
|
235
|
+
const rules = [];
|
|
236
|
+
const serverRules = [];
|
|
237
|
+
// Relations: `role_id` => exists:roles,id — and list items: `roles.*` => exists:roles,id
|
|
238
|
+
const exists = rule('exists');
|
|
239
|
+
if (exists && !['object', 'array', 'file', 'boolean', 'enum'].includes(field.type) && (node.name === undefined || node.name.endsWith('_id'))) {
|
|
240
|
+
field.type = 'relation';
|
|
241
|
+
field.relation = { kind: 'belongsTo', model: exists.params[0] };
|
|
242
|
+
if (exists.params[1] && exists.params[1] !== 'NULL')
|
|
243
|
+
field.relation.key = exists.params[1];
|
|
244
|
+
}
|
|
245
|
+
// Formats
|
|
246
|
+
if (has('email'))
|
|
247
|
+
field.format = 'email';
|
|
248
|
+
else if (has('url') || has('active_url'))
|
|
249
|
+
field.format = 'url';
|
|
250
|
+
else if (has('uuid'))
|
|
251
|
+
field.format = 'uuid';
|
|
252
|
+
else if (has('ip') || has('ipv4') || has('ipv6'))
|
|
253
|
+
field.format = 'ip';
|
|
254
|
+
else if (has('hex_color'))
|
|
255
|
+
field.format = 'color';
|
|
256
|
+
if (field.type === 'string' && !field.format && (has('current_password') || /password/i.test(node.name ?? ''))) {
|
|
257
|
+
field.format = 'password';
|
|
258
|
+
field.writeOnly = true;
|
|
259
|
+
}
|
|
260
|
+
// Children
|
|
261
|
+
if (field.type === 'object') {
|
|
262
|
+
field.fields = convertChildren(node.children.values(), ctx);
|
|
263
|
+
}
|
|
264
|
+
if (field.type === 'array') {
|
|
265
|
+
const inRule = rule('in');
|
|
266
|
+
if (node.item)
|
|
267
|
+
field.items = convert(node.item, ctx) ?? { type: 'unknown' };
|
|
268
|
+
else if (inRule)
|
|
269
|
+
field.items = { type: 'enum' };
|
|
270
|
+
else
|
|
271
|
+
field.items = { type: 'unknown' };
|
|
272
|
+
// `array|in:a,b` checks every element
|
|
273
|
+
if (inRule && field.items.type !== 'object') {
|
|
274
|
+
field.items = { ...field.items, type: field.items.type === 'relation' ? 'relation' : 'enum', options: options(inRule.params, field.items.type) };
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
const kind = kindOf(field.type, field.items);
|
|
278
|
+
ctx.kinds.set(node.key, kind);
|
|
279
|
+
for (const r of node.rules) {
|
|
280
|
+
const [p1, p2] = r.params;
|
|
281
|
+
switch (r.name) {
|
|
282
|
+
case 'min':
|
|
283
|
+
case 'max':
|
|
284
|
+
case 'between':
|
|
285
|
+
case 'size': {
|
|
286
|
+
const lo = r.name === 'max' ? undefined : p1;
|
|
287
|
+
const hi = r.name === 'min' ? undefined : r.name === 'between' ? p2 : r.name === 'size' ? p1 : p1;
|
|
288
|
+
if (kind === 'string') {
|
|
289
|
+
if (numeric(lo))
|
|
290
|
+
c.minLength = Number(lo);
|
|
291
|
+
if (numeric(hi))
|
|
292
|
+
c.maxLength = Number(hi);
|
|
293
|
+
}
|
|
294
|
+
else if (kind === 'number') {
|
|
295
|
+
if (numeric(lo))
|
|
296
|
+
c.min = Number(lo);
|
|
297
|
+
if (numeric(hi))
|
|
298
|
+
c.max = Number(hi);
|
|
299
|
+
}
|
|
300
|
+
else if (kind === 'array') {
|
|
301
|
+
if (numeric(lo))
|
|
302
|
+
c.minItems = Number(lo);
|
|
303
|
+
if (numeric(hi))
|
|
304
|
+
c.maxItems = Number(hi);
|
|
305
|
+
}
|
|
306
|
+
else if (kind === 'file' && numeric(hi) && r.name !== 'size') {
|
|
307
|
+
c.maxSize = Number(hi);
|
|
308
|
+
if (r.name === 'between')
|
|
309
|
+
serverRules.push(r.raw);
|
|
310
|
+
}
|
|
311
|
+
else
|
|
312
|
+
serverRules.push(r.raw);
|
|
313
|
+
break;
|
|
314
|
+
}
|
|
315
|
+
case 'gt':
|
|
316
|
+
case 'gte':
|
|
317
|
+
case 'lt':
|
|
318
|
+
case 'lte':
|
|
319
|
+
if (kind === 'number' && numeric(p1)) {
|
|
320
|
+
if (r.name === 'gt')
|
|
321
|
+
c.exclusiveMin = Number(p1);
|
|
322
|
+
if (r.name === 'gte')
|
|
323
|
+
c.min = Number(p1);
|
|
324
|
+
if (r.name === 'lt')
|
|
325
|
+
c.exclusiveMax = Number(p1);
|
|
326
|
+
if (r.name === 'lte')
|
|
327
|
+
c.max = Number(p1);
|
|
328
|
+
}
|
|
329
|
+
else if (kind === 'number' && p1)
|
|
330
|
+
rules.push(`${r.name}:@${fieldRef(p1, node.key)}`);
|
|
331
|
+
else
|
|
332
|
+
serverRules.push(r.raw);
|
|
333
|
+
break;
|
|
334
|
+
case 'digits':
|
|
335
|
+
if (numeric(p1))
|
|
336
|
+
rules.push(`digits:${p1}`);
|
|
337
|
+
break;
|
|
338
|
+
case 'digits_between':
|
|
339
|
+
if (numeric(p1) && numeric(p2))
|
|
340
|
+
c.pattern = `^\\d{${Number(p1)},${Number(p2)}}$`;
|
|
341
|
+
break;
|
|
342
|
+
case 'decimal':
|
|
343
|
+
rules.push(`decimal:${p2 ?? p1}`);
|
|
344
|
+
break;
|
|
345
|
+
case 'regex':
|
|
346
|
+
if (p1)
|
|
347
|
+
rules.push({ rule: 'regex', params: [p1] });
|
|
348
|
+
break;
|
|
349
|
+
case 'in':
|
|
350
|
+
if (field.type === 'enum')
|
|
351
|
+
field.options = options(r.params, field.type, has('integer') || has('numeric'));
|
|
352
|
+
break;
|
|
353
|
+
case 'not_in':
|
|
354
|
+
rules.push({ rule: 'not_one_of', params: [...r.params] });
|
|
355
|
+
break;
|
|
356
|
+
case 'same':
|
|
357
|
+
if (p1)
|
|
358
|
+
rules.push(`matches:@${fieldRef(p1, node.key)}`);
|
|
359
|
+
break;
|
|
360
|
+
case 'different':
|
|
361
|
+
if (p1)
|
|
362
|
+
rules.push(`is_not:@${fieldRef(p1, node.key)}`);
|
|
363
|
+
break;
|
|
364
|
+
case 'accepted':
|
|
365
|
+
c.accepted = true;
|
|
366
|
+
break;
|
|
367
|
+
case 'alpha':
|
|
368
|
+
case 'alpha_num':
|
|
369
|
+
case 'alpha_dash':
|
|
370
|
+
rules.push(r.name);
|
|
371
|
+
break;
|
|
372
|
+
case 'mimes':
|
|
373
|
+
case 'extensions':
|
|
374
|
+
c.extensions = [...(c.extensions ?? []), ...r.params.map((e) => e.replace(/^\./, ''))];
|
|
375
|
+
break;
|
|
376
|
+
case 'mimetypes':
|
|
377
|
+
c.mimeTypes = [...(c.mimeTypes ?? []), ...r.params];
|
|
378
|
+
break;
|
|
379
|
+
case 'image':
|
|
380
|
+
rules.push('image');
|
|
381
|
+
break;
|
|
382
|
+
default:
|
|
383
|
+
if (CONDITIONAL.includes(r.name)) {
|
|
384
|
+
const params = r.params.map((p, i) => (i === 0 || ALL_FIELDS.includes(r.name) ? fieldRef(p, node.key) : p));
|
|
385
|
+
rules.push({ rule: r.name, params });
|
|
386
|
+
}
|
|
387
|
+
else if (ctx.clientRules.has(r.name)) {
|
|
388
|
+
rules.push(r.raw);
|
|
389
|
+
}
|
|
390
|
+
else if (SERVER_ONLY.has(r.name)) {
|
|
391
|
+
serverRules.push(r.raw);
|
|
392
|
+
}
|
|
393
|
+
else if (!STRUCTURAL.has(r.name)) {
|
|
394
|
+
serverRules.push(r.raw);
|
|
395
|
+
ctx.warn({ path: node.key, code: 'unsupported-rule', message: `"${r.name}" has no client-side equivalent — left to the server (register it and list it in clientRules to run it in the browser)` });
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
// An image with no explicit types: let the file picker show images
|
|
400
|
+
if (has('image') && !c.mimeTypes && !c.extensions)
|
|
401
|
+
field.ui = { attr: { accept: 'image/*' } };
|
|
402
|
+
// A file field's constraints live on the item when it's a list of files
|
|
403
|
+
if (field.type === 'array' && field.items?.type === 'file') {
|
|
404
|
+
const { maxSize, extensions, mimeTypes, ...rest } = c;
|
|
405
|
+
const itemConstraints = { ...field.items.constraints };
|
|
406
|
+
if (maxSize !== undefined)
|
|
407
|
+
itemConstraints.maxSize = maxSize;
|
|
408
|
+
if (extensions)
|
|
409
|
+
itemConstraints.extensions = extensions;
|
|
410
|
+
if (mimeTypes)
|
|
411
|
+
itemConstraints.mimeTypes = mimeTypes;
|
|
412
|
+
if (Object.keys(itemConstraints).length)
|
|
413
|
+
field.items = { ...field.items, constraints: itemConstraints };
|
|
414
|
+
Object.keys(c).forEach((k) => delete c[k]);
|
|
415
|
+
Object.assign(c, rest);
|
|
416
|
+
}
|
|
417
|
+
if (Object.keys(c).length)
|
|
418
|
+
field.constraints = c;
|
|
419
|
+
if (rules.length)
|
|
420
|
+
field.rules = rules;
|
|
421
|
+
if (serverRules.length)
|
|
422
|
+
field.serverRules = serverRules;
|
|
423
|
+
return field;
|
|
424
|
+
}
|
|
425
|
+
function options(values, type, forceNumbers = false) {
|
|
426
|
+
const asNumbers = (forceNumbers || type === 'integer' || type === 'number') && values.every((v) => numeric(v));
|
|
427
|
+
return values.map((v) => ({ value: asNumbers ? Number(v) : v }));
|
|
428
|
+
}
|
|
429
|
+
/** A named node → its field, plus the confirmation field `confirmed` asks for */
|
|
430
|
+
function convertNamed(node, ctx) {
|
|
431
|
+
const field = convert(node, ctx);
|
|
432
|
+
if (!field)
|
|
433
|
+
return [];
|
|
434
|
+
const confirmed = node.rules.find((r) => r.name === 'confirmed');
|
|
435
|
+
if (!confirmed)
|
|
436
|
+
return [field];
|
|
437
|
+
// Laravel: `password` => 'confirmed' expects `password_confirmation` (or `confirmed:repeat_password`)
|
|
438
|
+
const name = confirmed.params[0] || `${field.name}_confirmation`;
|
|
439
|
+
const parentKey = node.key.slice(0, node.key.length - (node.name?.length ?? 0));
|
|
440
|
+
const key = `${parentKey}${name}`;
|
|
441
|
+
ctx.confirmations.set(node.key, key);
|
|
442
|
+
const confirmation = { name, type: field.type };
|
|
443
|
+
if (field.format)
|
|
444
|
+
confirmation.format = field.format;
|
|
445
|
+
if (field.writeOnly)
|
|
446
|
+
confirmation.writeOnly = true;
|
|
447
|
+
if (field.required)
|
|
448
|
+
confirmation.required = true;
|
|
449
|
+
const label = ctx.attributes[key];
|
|
450
|
+
if (label)
|
|
451
|
+
confirmation.label = label;
|
|
452
|
+
confirmation.rules = [`confirmed:@${field.name}`];
|
|
453
|
+
ctx.kinds.set(key, 'string');
|
|
454
|
+
return [field, confirmation];
|
|
455
|
+
}
|
|
456
|
+
/**
|
|
457
|
+
* Sibling nodes → fields. A `password_confirmation` declared explicitly is
|
|
458
|
+
* merged into the one `confirmed` generates (its rules added up).
|
|
459
|
+
*/
|
|
460
|
+
function convertChildren(nodes, ctx) {
|
|
461
|
+
const fields = [];
|
|
462
|
+
for (const node of nodes) {
|
|
463
|
+
for (const field of convertNamed(node, ctx)) {
|
|
464
|
+
const i = fields.findIndex((f) => f.name === field.name);
|
|
465
|
+
if (i === -1) {
|
|
466
|
+
fields.push(field);
|
|
467
|
+
continue;
|
|
468
|
+
}
|
|
469
|
+
const rules = [...(fields[i].rules ?? []), ...(field.rules ?? [])];
|
|
470
|
+
fields[i] = { ...fields[i], ...field };
|
|
471
|
+
if (rules.length)
|
|
472
|
+
fields[i].rules = rules;
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
return fields;
|
|
476
|
+
}
|
|
477
|
+
/** `messages()` → Formo message keys (`path.rule` / `rule`), Laravel rules renamed to Formo's */
|
|
478
|
+
function readMessages(messages, ctx, fieldKeys) {
|
|
479
|
+
const out = {};
|
|
480
|
+
const plain = (key) => key.replace(/\.\*(?=\.|$)/g, '');
|
|
481
|
+
for (const [key, message] of Object.entries(messages)) {
|
|
482
|
+
const idx = key.lastIndexOf('.');
|
|
483
|
+
const attribute = idx === -1 ? '' : key.slice(0, idx);
|
|
484
|
+
const rule = (idx === -1 ? key : key.slice(idx + 1)).toLowerCase();
|
|
485
|
+
if (attribute && fieldKeys.has(attribute)) {
|
|
486
|
+
// email.required / phones.*.number.required / password.confirmed (shown on the confirmation field)
|
|
487
|
+
if (rule === 'confirmed' && ctx.confirmations.has(attribute)) {
|
|
488
|
+
out[`${plain(ctx.confirmations.get(attribute))}.confirmed`] = message;
|
|
489
|
+
continue;
|
|
490
|
+
}
|
|
491
|
+
for (const name of formoNames(rule, ctx.kinds.get(attribute) ?? 'other'))
|
|
492
|
+
out[`${plain(attribute)}.${name}`] = message;
|
|
493
|
+
continue;
|
|
494
|
+
}
|
|
495
|
+
// min.string / email.min.numeric
|
|
496
|
+
const typed = TYPED_KINDS[rule];
|
|
497
|
+
if (typed && attribute) {
|
|
498
|
+
const split = attribute.lastIndexOf('.');
|
|
499
|
+
const sizeRule = split === -1 ? attribute : attribute.slice(split + 1);
|
|
500
|
+
const field = split === -1 ? '' : attribute.slice(0, split);
|
|
501
|
+
if (['min', 'max', 'between', 'size', 'gt', 'gte', 'lt', 'lte'].includes(sizeRule) && (!field || fieldKeys.has(field))) {
|
|
502
|
+
for (const name of formoNames(sizeRule, typed))
|
|
503
|
+
out[field ? `${plain(field)}.${name}` : name] = message;
|
|
504
|
+
continue;
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
if (!attribute) {
|
|
508
|
+
for (const name of formoNames(rule, 'any'))
|
|
509
|
+
out[name] = message;
|
|
510
|
+
continue;
|
|
511
|
+
}
|
|
512
|
+
ctx.warn({ path: attribute, code: 'unknown-path', message: `message "${key}" is for a field the rules don't have` });
|
|
513
|
+
}
|
|
514
|
+
return out;
|
|
515
|
+
}
|
|
516
|
+
function allKeys(node, out = new Set()) {
|
|
517
|
+
for (const child of node.children.values()) {
|
|
518
|
+
out.add(child.key);
|
|
519
|
+
allKeys(child, out);
|
|
520
|
+
}
|
|
521
|
+
if (node.item) {
|
|
522
|
+
out.add(node.item.key);
|
|
523
|
+
allKeys(node.item, out);
|
|
524
|
+
}
|
|
525
|
+
return out;
|
|
526
|
+
}
|
|
527
|
+
export function fromLaravel(input, options = {}) {
|
|
528
|
+
if (!input || typeof input !== 'object' || !input.rules || typeof input.rules !== 'object') {
|
|
529
|
+
throw new Error('[formo] fromLaravel: expected { rules, attributes?, messages? }');
|
|
530
|
+
}
|
|
531
|
+
const warn = options.onWarning ?? consoleWarning;
|
|
532
|
+
const ctx = {
|
|
533
|
+
attributes: input.attributes ?? {},
|
|
534
|
+
clientRules: new Set((options.clientRules ?? []).map((r) => r.toLowerCase())),
|
|
535
|
+
warn,
|
|
536
|
+
kinds: new Map(),
|
|
537
|
+
confirmations: new Map(),
|
|
538
|
+
};
|
|
539
|
+
const tree = buildTree(input.rules, warn);
|
|
540
|
+
const fields = convertChildren(tree.children.values(), ctx);
|
|
541
|
+
const model = { version: MODEL_VERSION, fields, meta: { source: 'laravel' } };
|
|
542
|
+
if (input.name)
|
|
543
|
+
model.name = input.name;
|
|
544
|
+
if (input.label)
|
|
545
|
+
model.label = input.label;
|
|
546
|
+
if (input.messages && Object.keys(input.messages).length) {
|
|
547
|
+
const keys = allKeys(tree);
|
|
548
|
+
for (const key of ctx.confirmations.values())
|
|
549
|
+
keys.add(key);
|
|
550
|
+
const messages = readMessages(input.messages, ctx, keys);
|
|
551
|
+
if (Object.keys(messages).length)
|
|
552
|
+
model.messages = messages;
|
|
553
|
+
}
|
|
554
|
+
return model;
|
|
555
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { type FormoModel, type WarningHandler } from './ir';
|
|
2
|
+
/**
|
|
3
|
+
* OpenAPI 3.0 / 3.1 → Formo model, from an operation's request body (create and
|
|
4
|
+
* update bodies often differ) or a named schema:
|
|
5
|
+
*
|
|
6
|
+
* fromOpenApi(doc, { operation: 'POST /users' }) // or an operationId: 'createUser'
|
|
7
|
+
* fromOpenApi(doc, { schema: 'User' }) // #/components/schemas/User
|
|
8
|
+
*
|
|
9
|
+
* Rails (rswag), Laravel (Scramble), FastAPI, NestJS… all publish one.
|
|
10
|
+
* `readOnly` properties are server-set, `writeOnly` ones never come back
|
|
11
|
+
* (passwords), `format: binary` is a file upload, `x-formo` carries Formo keys.
|
|
12
|
+
*/
|
|
13
|
+
export interface FromOpenApiOptions {
|
|
14
|
+
/** `'POST /users'`, `'put /users/{user}'` or an `operationId` */
|
|
15
|
+
operation?: string;
|
|
16
|
+
/** A schema name (`User`) or a JSON pointer (`#/components/schemas/User`) */
|
|
17
|
+
schema?: string;
|
|
18
|
+
/** Request body media type to read (default: JSON, then multipart, then urlencoded) */
|
|
19
|
+
contentType?: string;
|
|
20
|
+
/** The model's name (suggested form alias) */
|
|
21
|
+
name?: string;
|
|
22
|
+
onWarning?: WarningHandler;
|
|
23
|
+
}
|
|
24
|
+
export declare function fromOpenApi(doc: Record<string, any>, options: FromOpenApiOptions): FormoModel;
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { isPlainObject } from '../core/utils';
|
|
2
|
+
import { consoleWarning } from './ir';
|
|
3
|
+
import { fromJsonSchema } from './json-schema';
|
|
4
|
+
const METHODS = ['get', 'put', 'post', 'delete', 'options', 'head', 'patch', 'trace'];
|
|
5
|
+
function deref(doc, value) {
|
|
6
|
+
let cur = value;
|
|
7
|
+
const seen = new Set();
|
|
8
|
+
while (isPlainObject(cur) && typeof cur.$ref === 'string' && !seen.has(cur.$ref)) {
|
|
9
|
+
seen.add(cur.$ref);
|
|
10
|
+
const parts = cur.$ref.replace(/^#\//, '').split('/').map((p) => decodeURIComponent(p).replace(/~1/g, '/').replace(/~0/g, '~'));
|
|
11
|
+
cur = parts.reduce((o, p) => (o && typeof o === 'object' ? o[p] : undefined), doc);
|
|
12
|
+
}
|
|
13
|
+
return cur;
|
|
14
|
+
}
|
|
15
|
+
function findOperation(doc, operation) {
|
|
16
|
+
const m = operation.trim().match(/^([a-z]+)\s+(\S+)$/i);
|
|
17
|
+
const paths = isPlainObject(doc.paths) ? doc.paths : {};
|
|
18
|
+
if (m && METHODS.includes(m[1].toLowerCase())) {
|
|
19
|
+
const method = m[1].toLowerCase();
|
|
20
|
+
const op = deref(doc, paths[m[2]])?.[method];
|
|
21
|
+
return op ? { method, path: m[2], op } : undefined;
|
|
22
|
+
}
|
|
23
|
+
for (const [path, item] of Object.entries(paths)) {
|
|
24
|
+
const pathItem = deref(doc, item);
|
|
25
|
+
for (const method of METHODS) {
|
|
26
|
+
if (pathItem?.[method]?.operationId === operation)
|
|
27
|
+
return { method, path, op: pathItem[method] };
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
return undefined;
|
|
31
|
+
}
|
|
32
|
+
function pickContent(content, wanted) {
|
|
33
|
+
const types = Object.keys(content);
|
|
34
|
+
const type = (wanted && types.find((t) => t === wanted)) ??
|
|
35
|
+
types.find((t) => t === 'application/json' || /\+json$/.test(t)) ??
|
|
36
|
+
types.find((t) => t === 'multipart/form-data') ??
|
|
37
|
+
types.find((t) => t === 'application/x-www-form-urlencoded') ??
|
|
38
|
+
types[0];
|
|
39
|
+
return type ? { type, media: content[type] } : undefined;
|
|
40
|
+
}
|
|
41
|
+
export function fromOpenApi(doc, options) {
|
|
42
|
+
if (!isPlainObject(doc) || typeof doc.openapi !== 'string' || !doc.openapi.startsWith('3.')) {
|
|
43
|
+
throw new Error('[formo] fromOpenApi: expected an OpenAPI 3.0 / 3.1 document (Swagger 2 is not supported)');
|
|
44
|
+
}
|
|
45
|
+
const warn = options.onWarning ?? consoleWarning;
|
|
46
|
+
const base = { document: doc, onWarning: warn, name: options.name };
|
|
47
|
+
if (options.schema) {
|
|
48
|
+
const ref = options.schema.startsWith('#') ? options.schema : `#/components/schemas/${options.schema}`;
|
|
49
|
+
const model = fromJsonSchema({ $ref: ref }, base);
|
|
50
|
+
model.meta = { source: 'openapi', schema: ref };
|
|
51
|
+
return model;
|
|
52
|
+
}
|
|
53
|
+
if (!options.operation)
|
|
54
|
+
throw new Error('[formo] fromOpenApi: pass `operation` (\'POST /users\' or an operationId) or `schema`');
|
|
55
|
+
const found = findOperation(doc, options.operation);
|
|
56
|
+
if (!found)
|
|
57
|
+
throw new Error(`[formo] fromOpenApi: no operation "${options.operation}" in this document`);
|
|
58
|
+
const body = deref(doc, found.op.requestBody);
|
|
59
|
+
const content = isPlainObject(body?.content) ? pickContent(body.content, options.contentType) : undefined;
|
|
60
|
+
if (!content?.media?.schema)
|
|
61
|
+
throw new Error(`[formo] fromOpenApi: "${options.operation}" has no request body schema`);
|
|
62
|
+
const model = fromJsonSchema(content.media.schema, base);
|
|
63
|
+
model.meta = { source: 'openapi', operation: `${found.method.toUpperCase()} ${found.path}`, contentType: content.type };
|
|
64
|
+
if (found.op.operationId)
|
|
65
|
+
model.meta.operationId = found.op.operationId;
|
|
66
|
+
return model;
|
|
67
|
+
}
|