formo-react 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +21 -2
  3. package/dist/components/FormoBlueprint.d.ts +5 -0
  4. package/dist/components/FormoBlueprint.js +30 -0
  5. package/dist/components/FormoButton.d.ts +6 -0
  6. package/dist/components/FormoButton.js +23 -0
  7. package/dist/components/FormoCheckbox.d.ts +7 -0
  8. package/dist/components/FormoCheckbox.js +10 -0
  9. package/dist/components/FormoChecklist.d.ts +5 -0
  10. package/dist/components/FormoChecklist.js +15 -0
  11. package/dist/components/FormoChoices.d.ts +8 -0
  12. package/dist/components/FormoChoices.js +33 -0
  13. package/dist/components/FormoContext.d.ts +27 -0
  14. package/dist/components/FormoContext.js +69 -0
  15. package/dist/components/FormoErrors.d.ts +5 -0
  16. package/dist/components/FormoErrors.js +14 -0
  17. package/dist/components/FormoField.d.ts +17 -0
  18. package/dist/components/FormoField.js +148 -0
  19. package/dist/components/FormoForm.d.ts +15 -0
  20. package/dist/components/FormoForm.js +76 -0
  21. package/dist/components/FormoGroup.d.ts +5 -0
  22. package/dist/components/FormoGroup.js +15 -0
  23. package/dist/components/FormoHelp.d.ts +6 -0
  24. package/dist/components/FormoHelp.js +9 -0
  25. package/dist/components/FormoInput.d.ts +6 -0
  26. package/dist/components/FormoInput.js +24 -0
  27. package/dist/components/FormoLabel.d.ts +6 -0
  28. package/dist/components/FormoLabel.js +9 -0
  29. package/dist/components/FormoProvider.d.ts +11 -0
  30. package/dist/components/FormoProvider.js +13 -0
  31. package/dist/components/FormoRest.d.ts +6 -0
  32. package/dist/components/FormoRest.js +23 -0
  33. package/dist/components/FormoSelect.d.ts +6 -0
  34. package/dist/components/FormoSelect.js +36 -0
  35. package/dist/components/FormoUneditable.d.ts +6 -0
  36. package/dist/components/FormoUneditable.js +12 -0
  37. package/dist/core/builder.d.ts +42 -0
  38. package/dist/core/builder.js +166 -0
  39. package/dist/core/controls.d.ts +27 -0
  40. package/dist/core/controls.js +24 -0
  41. package/dist/core/fields.d.ts +63 -0
  42. package/dist/core/fields.js +177 -0
  43. package/dist/core/messages.d.ts +35 -0
  44. package/dist/core/messages.js +69 -0
  45. package/dist/core/normalize.d.ts +35 -0
  46. package/dist/core/normalize.js +234 -0
  47. package/dist/core/options.d.ts +44 -0
  48. package/dist/core/options.js +146 -0
  49. package/dist/core/rules.d.ts +41 -0
  50. package/dist/core/rules.js +230 -0
  51. package/dist/core/store.d.ts +155 -0
  52. package/dist/core/store.js +830 -0
  53. package/dist/core/theme.d.ts +20 -0
  54. package/dist/core/theme.js +21 -0
  55. package/dist/core/tree.d.ts +74 -0
  56. package/dist/core/tree.js +119 -0
  57. package/dist/core/utils.d.ts +35 -0
  58. package/dist/core/utils.js +206 -0
  59. package/dist/hooks/subscriptions.d.ts +38 -0
  60. package/dist/hooks/subscriptions.js +65 -0
  61. package/dist/hooks/useFormo.d.ts +18 -0
  62. package/dist/hooks/useFormo.js +25 -0
  63. package/dist/index.d.ts +28 -0
  64. package/dist/index.js +27 -0
  65. package/dist/schema/form.d.ts +92 -0
  66. package/dist/schema/form.js +304 -0
  67. package/dist/schema/index.d.ts +22 -0
  68. package/dist/schema/index.js +21 -0
  69. package/dist/schema/ir.d.ts +189 -0
  70. package/dist/schema/ir.js +130 -0
  71. package/dist/schema/json-schema.d.ts +25 -0
  72. package/dist/schema/json-schema.js +351 -0
  73. package/dist/schema/laravel.d.ts +57 -0
  74. package/dist/schema/laravel.js +555 -0
  75. package/dist/schema/openapi.d.ts +24 -0
  76. package/dist/schema/openapi.js +67 -0
  77. package/dist/schema/policy.d.ts +60 -0
  78. package/dist/schema/policy.js +315 -0
  79. package/dist/schema/spec.d.ts +75 -0
  80. package/dist/schema/spec.js +1 -0
  81. package/dist/schema/values.d.ts +35 -0
  82. package/dist/schema/values.js +151 -0
  83. package/dist/schema/zod.d.ts +79 -0
  84. package/dist/schema/zod.js +236 -0
  85. package/dist/types.d.ts +400 -0
  86. package/dist/types.js +1 -0
  87. package/package.json +70 -4
package/dist/index.js ADDED
@@ -0,0 +1,27 @@
1
+ export { Formo } from './core/builder';
2
+ export { normalize, buildInitialValues, isHidden } from './core/normalize';
3
+ export { validateField, evaluateChecklist, parseRules } from './core/rules';
4
+ export { normalizeOptions, flattenOptions, isOptionGroup } from './core/options';
5
+ export { FormoStore } from './core/store';
6
+ export { useFormo } from './hooks/useFormo';
7
+ export { useFormoState, useFormoValue, useFormoField, useFormoFields, } from './hooks/subscriptions';
8
+ export { FormoContext, useFormoContext, useFormoOptions } from './components/FormoContext';
9
+ export { FormoProvider } from './components/FormoProvider';
10
+ export { defineControl, isControl } from './core/controls';
11
+ export { defineTheme } from './core/theme';
12
+ export { FormoForm } from './components/FormoForm';
13
+ export { FormoField, FormoFieldControl, FormoReadOnly } from './components/FormoField';
14
+ export { FormoLabel } from './components/FormoLabel';
15
+ export { FormoHelp } from './components/FormoHelp';
16
+ export { FormoRest } from './components/FormoRest';
17
+ export { FormoInput } from './components/FormoInput';
18
+ export { FormoSelect } from './components/FormoSelect';
19
+ export { FormoCheckbox } from './components/FormoCheckbox';
20
+ export { FormoRadios, FormoCheckboxes } from './components/FormoChoices';
21
+ export { FormoButton } from './components/FormoButton';
22
+ export { FormoErrors } from './components/FormoErrors';
23
+ export { FormoChecklist } from './components/FormoChecklist';
24
+ export { FormoUneditable, readOnlyText } from './components/FormoUneditable';
25
+ export { FormoGroup } from './components/FormoGroup';
26
+ export { FormoBlueprint } from './components/FormoBlueprint';
27
+ export * from './schema';
@@ -0,0 +1,92 @@
1
+ import { type FormoModel, type ModelField, type ModelItem, type WarningHandler } from './ir';
2
+ import { type ModelPolicy, type OptionsInput, type ValidationMode } from './policy';
3
+ import type { FieldSpec } from './spec';
4
+ /**
5
+ * A per-field override:
6
+ * - a definition merged over the generated one (`{ driver: 'radios', attr: { rows: 6 } }`) —
7
+ * `rules`, `opts` and `val` replace the generated ones, objects (`attr`, `props`…) merge
8
+ * - `false` to leave the field out
9
+ * - a function for full control: `(generated, field) => ({ ...generated, rules: [...generated.rules ?? [], 'x'] })`
10
+ *
11
+ * A key that isn't in the model adds a field (`terms: { driver: 'checkbox', required: true }`).
12
+ */
13
+ export type FieldOverride = FieldSpec | false | ((generated: FieldSpec, field: ModelField | ModelItem | undefined) => FieldSpec | false);
14
+ export interface FormFromModelOptions {
15
+ /** The form alias (default: the model's `name`) — ids start with it */
16
+ alias?: string | number;
17
+ /**
18
+ * Input names and request bodies are the model's own keys by default —
19
+ * `email`, `address[street]`, `phones[0][number]`: what the FormRequest / API
20
+ * validates, so a native post (JavaScript off) meets the same rules as
21
+ * `request()`. A `rootKey` wraps both (Rails: `user[email]`, `{ user: {...} }`),
22
+ * and is stripped from the error keys that come back.
23
+ */
24
+ rootKey?: string;
25
+ /** The form's attributes — `{ action: '/users/7', method: 'put' }` lets it post with JavaScript off, and send itself */
26
+ attr?: Record<string, unknown>;
27
+ /** Only these fields — dotted paths: `'address'` (the whole subform), `'address.zip'`, `'phones.number'`. Empty: all */
28
+ only?: string[];
29
+ /** Leave these out (dotted paths) */
30
+ except?: string[];
31
+ /** Overrides and additions, keyed by dotted path (`'address.zip'`) or nested (`address: { fields: { zip } }`) */
32
+ fields?: Record<string, FieldOverride>;
33
+ /** These first, in this order (dotted paths order inside subforms); the rest keep the model's order */
34
+ order?: string[];
35
+ /**
36
+ * `create` (default) or `update`. In update forms read-only fields are shown
37
+ * uneditable, and write-only ones (passwords) become optional: left empty,
38
+ * they're not submitted — "leave blank to keep the current password"
39
+ */
40
+ mode?: 'create' | 'update';
41
+ /**
42
+ * Read-only fields (`readOnly` — set by the server): `uneditable` shows the
43
+ * value as text (not validated, not submitted), `omit` leaves them out.
44
+ * Default: `uneditable` in update forms, `omit` in create forms. Asking for
45
+ * one explicitly (`only`, or an override in `fields`) always includes it, uneditable.
46
+ */
47
+ readOnly?: 'uneditable' | 'omit';
48
+ /**
49
+ * Database bookkeeping fields left out unless asked for explicitly — listed
50
+ * in `only` or given an override in `fields` (default `METADATA_FIELDS`: `id`,
51
+ * `created_at`, `updated_at`…). Inside repeatable rows, `id` becomes a hidden
52
+ * field so existing rows keep their identity. `false` keeps them all.
53
+ */
54
+ metadata?: string[] | false;
55
+ /** `derived` (default), `schema` (needs `fromZod`) or `none` — see `ValidationMode` */
56
+ validation?: ValidationMode;
57
+ /** Options for relations and enums, by dotted path: `{ role_id: roles, 'address.country': countries }` */
58
+ options?: Record<string, OptionsInput>;
59
+ /** Change how types map to drivers: `{ textareaAbove: 500, radiosUpTo: 4, driverFor }` */
60
+ policy?: Partial<ModelPolicy>;
61
+ /**
62
+ * A record to load: read with
63
+ * `toFormValues()` (dates, relations…), restricted to the fields this form has
64
+ * (so what `only` / `except` leave out is never submitted), and set as the
65
+ * form's initial values
66
+ */
67
+ values?: Record<string, any> | null;
68
+ /** Unsupported constructs, unknown paths… Default: `console.warn` (once per message) */
69
+ onWarning?: WarningHandler;
70
+ }
71
+ /** Bookkeeping columns left out of forms by default (Laravel, Rails, JS ORMs) */
72
+ export declare const METADATA_FIELDS: string[];
73
+ /** `phones.*.number` / `phones[].number` → `phones.number` */
74
+ export declare function modelPath(path: string): string;
75
+ /**
76
+ * Turn a Formo model into a form definition — from any backend or schema:
77
+ *
78
+ * ```ts
79
+ * import { formFromModel, fromLaravel } from 'formo-vue/schema'
80
+ *
81
+ * const form = useFormo(formFromModel(props.userModel, {
82
+ * except: ['password'],
83
+ * fields: { bio: { driver: 'textarea' }, role: { driver: 'radios' } },
84
+ * mode: 'update',
85
+ * }), { initialValues: toFormValues(props.userModel, props.user) })
86
+ * ```
87
+ *
88
+ * Accepts a model object or its JSON; see `Formo.fromModel()` for a builder.
89
+ */
90
+ export declare function formFromModel(input: FormoModel | string, options?: FormFromModelOptions): FieldSpec;
91
+ /** The model field at a dotted path (array items are transparent) */
92
+ export declare function findModelField(model: FormoModel, path: string): ModelField | ModelItem | undefined;
@@ -0,0 +1,304 @@
1
+ import { RUNTIME, consoleWarning, parseModel } from './ir';
2
+ import { blueprintSpec, defaultPolicy, groupSpec, leafSpec, mergeSpec, } from './policy';
3
+ import { pickFormValues, toFormValues } from './values';
4
+ /** Bookkeeping columns left out of forms by default (Laravel, Rails, JS ORMs) */
5
+ export const METADATA_FIELDS = [
6
+ 'id',
7
+ '_id',
8
+ 'created_at',
9
+ 'updated_at',
10
+ 'deleted_at',
11
+ 'createdAt',
12
+ 'updatedAt',
13
+ 'deletedAt',
14
+ 'email_verified_at',
15
+ 'remember_token',
16
+ 'lock_version',
17
+ ];
18
+ /** Input types that can carry automatic rules (Formo's `inputRules`) */
19
+ const INPUT_TYPES = ['text', 'email', 'url', 'tel', 'password', 'search', 'color', 'number', 'range', 'date', 'datetime-local', 'time', 'week', 'month'];
20
+ /** `phones.*.number` / `phones[].number` → `phones.number` */
21
+ export function modelPath(path) {
22
+ return path
23
+ .replace(/\[\d*\]/g, '')
24
+ .split('.')
25
+ .filter((s) => s !== '*' && s !== '')
26
+ .join('.');
27
+ }
28
+ const CONFIRMS = /^(?:confirmed|matches):@(.+)$/;
29
+ /** The field a `confirmed:@password` / `matches:@password` rule points to */
30
+ function confirmsField(field) {
31
+ for (const rule of field.rules ?? []) {
32
+ const text = typeof rule === 'string' ? rule : rule.params?.length ? `${rule.rule}:${String(rule.params[0])}` : rule.rule;
33
+ const m = text.match(CONFIRMS);
34
+ if (m)
35
+ return m[1];
36
+ }
37
+ return undefined;
38
+ }
39
+ /** Shown, not validated, not submitted */
40
+ function makeUneditable(spec) {
41
+ const out = { ...spec, editable: false, exclude: true };
42
+ delete out.required;
43
+ delete out.rules;
44
+ if (out.fields)
45
+ out.fields = Object.fromEntries(Object.entries(out.fields).map(([k, child]) => [k, makeUneditable(child)]));
46
+ return out;
47
+ }
48
+ /**
49
+ * Turn a Formo model into a form definition — from any backend or schema:
50
+ *
51
+ * ```ts
52
+ * import { formFromModel, fromLaravel } from 'formo-vue/schema'
53
+ *
54
+ * const form = useFormo(formFromModel(props.userModel, {
55
+ * except: ['password'],
56
+ * fields: { bio: { driver: 'textarea' }, role: { driver: 'radios' } },
57
+ * mode: 'update',
58
+ * }), { initialValues: toFormValues(props.userModel, props.user) })
59
+ * ```
60
+ *
61
+ * Accepts a model object or its JSON; see `Formo.fromModel()` for a builder.
62
+ */
63
+ export function formFromModel(input, options = {}) {
64
+ const warn = options.onWarning ?? consoleWarning;
65
+ const model = parseModel(input, warn);
66
+ const mode = options.mode ?? 'create';
67
+ const readOnlyMode = options.readOnly ?? (mode === 'update' ? 'uneditable' : 'omit');
68
+ const metadata = new Set(options.metadata === false ? [] : (options.metadata ?? METADATA_FIELDS));
69
+ const validation = options.validation ?? 'derived';
70
+ const policy = { ...defaultPolicy, ...options.policy };
71
+ // An empty list is "no filter" (what an empty `only` box in a UI means), not "no fields"
72
+ const only = options.only?.length ? new Set(options.only.map(modelPath)) : undefined;
73
+ const except = new Set((options.except ?? []).map(modelPath));
74
+ const suppliedOptions = {};
75
+ for (const [path, opts] of Object.entries(options.options ?? {}))
76
+ suppliedOptions[modelPath(path)] = opts;
77
+ /** Paths of `only` / `except` that matched something — the rest are typos, warned below */
78
+ const matched = new Set();
79
+ const excludedPaths = new Set();
80
+ const allPaths = modelPaths(model.fields);
81
+ const overrides = flattenOverrides(options.fields ?? {});
82
+ if (validation === 'schema' && !model[RUNTIME]?.validate) {
83
+ warn({ path: '', code: 'no-schema', message: "validation: 'schema' needs a schema-backed model (fromZod) — using derived rules" });
84
+ }
85
+ const ctxFor = (path) => ({ path, policy, validation, warn, options: suppliedOptions });
86
+ function included(field, path, inRow) {
87
+ if (except.has(path)) {
88
+ matched.add(path);
89
+ return 'skip';
90
+ }
91
+ // Listed in `only`, or given an override: asked for explicitly
92
+ const override = overrides.get(path);
93
+ const explicit = !!only?.has(path) || (!!override && (!only || only.has(path) || [...only].some((o) => path.startsWith(`${o}.`))));
94
+ if (only?.has(path))
95
+ matched.add(path);
96
+ // A row's key: without it, the server can't tell which existing row was edited
97
+ const rowKey = inRow && (field.name === 'id' || field.name === '_id');
98
+ if (only && !explicit) {
99
+ const inside = [...only].some((o) => path.startsWith(`${o}.`));
100
+ const around = [...only].some((o) => o.startsWith(`${path}.`));
101
+ if (!inside && !around)
102
+ return rowKey ? 'hidden' : 'skip';
103
+ }
104
+ if (!explicit && metadata.has(field.name)) {
105
+ return rowKey ? 'hidden' : 'skip';
106
+ }
107
+ if (field.fillable === false) {
108
+ if (!explicit)
109
+ return 'skip';
110
+ warn({ path, code: 'not-fillable', message: 'is not mass-assignable (fillable: false) — included because it was asked for explicitly' });
111
+ }
112
+ if (field.readOnly) {
113
+ if (readOnlyMode === 'omit' && !explicit)
114
+ return 'skip';
115
+ return 'uneditable';
116
+ }
117
+ return 'field';
118
+ }
119
+ function specFor(field, path, inRow) {
120
+ const ctx = ctxFor(path);
121
+ if (field.type === 'object')
122
+ return groupSpec(field, build(field.fields ?? [], path, inRow), ctx);
123
+ if (field.type === 'array' && field.items?.type === 'object') {
124
+ return blueprintSpec(field, build(field.items.fields ?? [], path, true), ctx);
125
+ }
126
+ // An override giving a control to a type Formo can't render: build on the model's label, help…
127
+ const override = overrides.get(path);
128
+ if (override && typeof override === 'object' && (override.driver || override.component)) {
129
+ field = { ...field, ui: { ...field.ui, driver: override.driver, component: override.component } };
130
+ }
131
+ return leafSpec(field, ctx);
132
+ }
133
+ function build(fields, prefix, inRow) {
134
+ const out = {};
135
+ const byName = new Map(fields.map((f) => [f.name, f]));
136
+ for (const field of fields) {
137
+ const path = prefix ? `${prefix}.${field.name}` : field.name;
138
+ const decision = included(field, path, inRow);
139
+ if (decision === 'skip') {
140
+ excludedPaths.add(path);
141
+ continue;
142
+ }
143
+ if (decision === 'hidden') {
144
+ out[field.name] = { driver: 'hidden' };
145
+ continue;
146
+ }
147
+ let spec = specFor(field, path, inRow);
148
+ if (!spec)
149
+ continue;
150
+ if (decision === 'uneditable')
151
+ spec = makeUneditable(spec);
152
+ else if (mode === 'update') {
153
+ // Passwords in update forms: optional, and not submitted when left empty
154
+ // (a confirmation field follows the field it confirms, not its own value)
155
+ const target = confirmsField(field) ?? (field.writeOnly ? field.name : undefined);
156
+ if (target && byName.get(target)?.writeOnly) {
157
+ delete spec.required;
158
+ spec.exclude = { when: target, filled: false };
159
+ }
160
+ }
161
+ out[field.name] = spec;
162
+ }
163
+ return out;
164
+ }
165
+ const fields = build(model.fields, '', false);
166
+ for (const path of [...(only ?? []), ...except]) {
167
+ if (!matched.has(path) && !allPaths.has(path)) {
168
+ warn({ path, code: 'unknown-path', message: `listed in ${only?.has(path) ? 'only' : 'except'} but the model has no such field` });
169
+ }
170
+ }
171
+ applyOverrides(fields, options.fields ?? {}, '', model, excludedPaths, warn);
172
+ if (options.order?.length)
173
+ applyOrder(fields, options.order.map(modelPath));
174
+ const root = {};
175
+ const alias = options.alias ?? model.name;
176
+ if (alias !== undefined && alias !== '')
177
+ root.alias = alias;
178
+ if (options.attr)
179
+ root.attr = { ...options.attr };
180
+ root.fields = fields;
181
+ // Names and bodies use the model's keys — what the server validates — not the form alias
182
+ root.config = options.rootKey ? { namePrefix: options.rootKey, request: { rootKey: options.rootKey } } : { namePrefix: false };
183
+ if (model.messages && Object.keys(model.messages).length)
184
+ root.config.messages = { ...model.messages };
185
+ if (options.values) {
186
+ const values = pickFormValues(toFormValues(model, options.values, { onWarning: warn }), fields);
187
+ if (Object.keys(values).length)
188
+ root.val = values;
189
+ }
190
+ const runtime = model[RUNTIME];
191
+ if (validation === 'derived' && runtime?.refine)
192
+ root.callbacks = { pass: [runtime.refine] };
193
+ if (validation === 'schema' && runtime?.validate) {
194
+ root.callbacks = { pass: [runtime.validate] };
195
+ // The schema is the only validator: no rules from input types or HTML attributes.
196
+ // (Config layers deep-merge, so each type is cleared — an empty object would change nothing)
197
+ root.config = {
198
+ ...root.config,
199
+ inputRules: Object.fromEntries(INPUT_TYPES.map((type) => [type, []])),
200
+ htmlConstraintRules: false,
201
+ };
202
+ }
203
+ return root;
204
+ }
205
+ /** Every dotted path of a model (array items are transparent: `phones.number`) */
206
+ function modelPaths(fields, prefix = '', out = new Set()) {
207
+ for (const field of fields ?? []) {
208
+ const path = prefix ? `${prefix}.${field.name}` : field.name;
209
+ out.add(path);
210
+ modelPaths(field.type === 'array' ? field.items?.fields : field.fields, path, out);
211
+ }
212
+ return out;
213
+ }
214
+ /** Overrides by normalized path, nested `fields` included */
215
+ function flattenOverrides(overrides, prefix = '', out = new Map()) {
216
+ for (const [key, override] of Object.entries(overrides)) {
217
+ const path = modelPath(prefix ? `${prefix}.${key}` : key);
218
+ out.set(path, override);
219
+ if (override && typeof override === 'object' && override.fields && typeof override.fields === 'object') {
220
+ flattenOverrides(override.fields, path, out);
221
+ }
222
+ }
223
+ return out;
224
+ }
225
+ /** The model field at a dotted path (array items are transparent) */
226
+ export function findModelField(model, path) {
227
+ let list = model.fields;
228
+ let found;
229
+ for (const segment of path.split('.')) {
230
+ found = list?.find((f) => f.name === segment);
231
+ if (!found)
232
+ return undefined;
233
+ const inner = found.type === 'array' && found.items ? found.items : found;
234
+ list = inner.fields;
235
+ }
236
+ return found;
237
+ }
238
+ function applyOverrides(fields, overrides, prefix, model, excluded, warn) {
239
+ for (const [rawKey, override] of Object.entries(overrides)) {
240
+ const path = modelPath(prefix ? `${prefix}.${rawKey}` : rawKey);
241
+ const segments = modelPath(rawKey).split('.');
242
+ const key = segments.pop();
243
+ // Walk to the container of the overridden field
244
+ let container = fields;
245
+ for (const segment of segments) {
246
+ const next = container?.[segment];
247
+ container = next?.fields;
248
+ if (!container)
249
+ break;
250
+ }
251
+ if (!container) {
252
+ warn({ path, code: 'unknown-path', message: `override ignored: "${segments.join('.')}" is not a subform of this form` });
253
+ continue;
254
+ }
255
+ const field = findModelField(model, path);
256
+ if (field && excluded.has(path) && override !== false) {
257
+ warn({ path, code: 'excluded-override', message: 'override ignored: the field is left out (only / except / metadata / readOnly)' });
258
+ continue;
259
+ }
260
+ const existing = container[key];
261
+ if (override === false) {
262
+ delete container[key];
263
+ }
264
+ else if (typeof override === 'function') {
265
+ const result = override(existing ?? {}, field);
266
+ if (result === false)
267
+ delete container[key];
268
+ else
269
+ container[key] = result;
270
+ }
271
+ else {
272
+ const { fields: childOverrides, ...rest } = override;
273
+ const next = existing ? mergeSpec(existing, rest) : { ...rest };
274
+ container[key] = next;
275
+ if (childOverrides && typeof childOverrides === 'object') {
276
+ next.fields = { ...(next.fields ?? {}) };
277
+ applyOverrides(next.fields, childOverrides, path, model, excluded, warn);
278
+ }
279
+ }
280
+ }
281
+ }
282
+ function applyOrder(fields, order) {
283
+ const byParent = new Map();
284
+ for (const path of order) {
285
+ const segments = path.split('.');
286
+ const key = segments.pop();
287
+ const parent = segments.join('.');
288
+ byParent.set(parent, [...(byParent.get(parent) ?? []), key]);
289
+ }
290
+ for (const [parent, keys] of byParent) {
291
+ let container = fields;
292
+ for (const segment of parent ? parent.split('.') : [])
293
+ container = container?.[segment]?.fields;
294
+ if (!container)
295
+ continue;
296
+ const entries = Object.entries(container);
297
+ const first = keys.filter((k) => k in container).map((k) => [k, container[k]]);
298
+ const rest = entries.filter(([k]) => !keys.includes(k));
299
+ for (const k of Object.keys(container))
300
+ delete container[k];
301
+ for (const [k, v] of [...first, ...rest])
302
+ container[k] = v;
303
+ }
304
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * formo-vue/schema — forms from models and schemas: every field (or `only` / `except`), with types, labels and validation.
3
+ *
4
+ * source ──adapter──▶ Formo model (IR JSON v1) ──formFromModel()──▶ form definition ──▶ useFormo / <FormoForm>
5
+ *
6
+ * - Adapters: `fromLaravel` (FormRequest rules), `fromJsonSchema`, `fromOpenApi`, `fromZod` —
7
+ * or a backend sending the IR JSON directly (`parseModel`)
8
+ * - `formFromModel(model, { only, except, fields, order, mode, validation… })`
9
+ * - `toFormValues(model, record)` loads a record into the form
10
+ *
11
+ * Pure TypeScript — no Vue, no DOM (enforced by `bun run check:pure`), so it can
12
+ * serve other renderers (React Native) as is.
13
+ */
14
+ export { MODEL_VERSION, MODEL_FIELD_TYPES, RUNTIME, parseModel, isFormoModel, consoleWarning, type FormoModel, type ModelField, type ModelFieldType, type ModelItem, type ModelOption, type ModelConstraints, type ModelRule, type ModelRelation, type ModelWarning, type WarningHandler, type FieldRuntime, type ModelRuntime, type RuntimeRule, type RuntimeCallback, type RuntimeCallbackContext, } from './ir';
15
+ export { formFromModel, findModelField, modelPath, METADATA_FIELDS, type FormFromModelOptions, type FieldOverride } from './form';
16
+ export { defaultPolicy, mergeSpec, proposeDriver, type ModelPolicy, type OptionsInput, type ValidationMode } from './policy';
17
+ export { toFormValues, pickFormValues, type ToFormValuesOptions } from './values';
18
+ export { fromJsonSchema, type JsonSchema, type FromJsonSchemaOptions } from './json-schema';
19
+ export { fromOpenApi, type FromOpenApiOptions } from './openapi';
20
+ export { fromLaravel, parseLaravelRule, type LaravelRulesInput, type FromLaravelOptions } from './laravel';
21
+ export { fromZod, type FromZodOptions, type ZodLikeSchema, type ZodLikeIssue, type ZodRefinement } from './zod';
22
+ export type { FieldSpec, SpecRule, SpecOption, SpecCondition, StandardSchemaLike } from './spec';
@@ -0,0 +1,21 @@
1
+ /**
2
+ * formo-vue/schema — forms from models and schemas: every field (or `only` / `except`), with types, labels and validation.
3
+ *
4
+ * source ──adapter──▶ Formo model (IR JSON v1) ──formFromModel()──▶ form definition ──▶ useFormo / <FormoForm>
5
+ *
6
+ * - Adapters: `fromLaravel` (FormRequest rules), `fromJsonSchema`, `fromOpenApi`, `fromZod` —
7
+ * or a backend sending the IR JSON directly (`parseModel`)
8
+ * - `formFromModel(model, { only, except, fields, order, mode, validation… })`
9
+ * - `toFormValues(model, record)` loads a record into the form
10
+ *
11
+ * Pure TypeScript — no Vue, no DOM (enforced by `bun run check:pure`), so it can
12
+ * serve other renderers (React Native) as is.
13
+ */
14
+ export { MODEL_VERSION, MODEL_FIELD_TYPES, RUNTIME, parseModel, isFormoModel, consoleWarning, } from './ir';
15
+ export { formFromModel, findModelField, modelPath, METADATA_FIELDS } from './form';
16
+ export { defaultPolicy, mergeSpec, proposeDriver } from './policy';
17
+ export { toFormValues, pickFormValues } from './values';
18
+ export { fromJsonSchema } from './json-schema';
19
+ export { fromOpenApi } from './openapi';
20
+ export { fromLaravel, parseLaravelRule } from './laravel';
21
+ export { fromZod } from './zod';
@@ -0,0 +1,189 @@
1
+ /**
2
+ * The Formo model — IR JSON, version 1. A PUBLIC, VERSIONED CONTRACT.
3
+ *
4
+ * A neutral description of the *data* a form edits (not of the UI): what a
5
+ * backend (Laravel via Inertia props or a schema endpoint, Rails, an OpenAPI
6
+ * document…) or a frontend schema (JSON Schema, Zod) knows about a model.
7
+ * `formFromModel()` turns it into a Formo form definition.
8
+ *
9
+ * { "version": 1, "name": "user", "fields": [
10
+ * { "name": "email", "type": "string", "format": "email", "required": true, "constraints": { "maxLength": 255 } },
11
+ * { "name": "role", "type": "enum", "options": [{ "value": "admin", "label": "Administrator" }] }
12
+ * ] }
13
+ *
14
+ * Compatibility rules for `version: 1`:
15
+ * - Only additive changes: new optional keys, new `format` values. Readers ignore keys they don't know.
16
+ * - A `type` a reader doesn't know is read as `unknown` (with a warning), never an error.
17
+ * - Anything that changes the meaning of existing keys bumps `version`.
18
+ *
19
+ * The machine-readable contract is `docs/schema/formo-model-v1.schema.json`.
20
+ *
21
+ * Pure TypeScript: no Vue, no DOM — see `scripts/check-pure.ts`.
22
+ */
23
+ export declare const MODEL_VERSION: 1;
24
+ /** Every `type` of version 1 */
25
+ export declare const MODEL_FIELD_TYPES: readonly ["string", "text", "integer", "number", "boolean", "date", "datetime", "time", "enum", "file", "object", "array", "relation", "unknown"];
26
+ export type ModelFieldType = (typeof MODEL_FIELD_TYPES)[number];
27
+ export interface ModelOption {
28
+ value: string | number | boolean | null;
29
+ /** Shown to the user (translated by Formo like any text). Defaults to the humanized value */
30
+ label?: string;
31
+ disabled?: boolean;
32
+ }
33
+ /** Constraints in JSON Schema vocabulary — turned into Formo rules (and HTML attributes) */
34
+ export interface ModelConstraints {
35
+ /** Strings: length */
36
+ minLength?: number;
37
+ maxLength?: number;
38
+ /** Numbers: inclusive bounds */
39
+ min?: number;
40
+ max?: number;
41
+ /** Numbers: exclusive bounds */
42
+ exclusiveMin?: number;
43
+ exclusiveMax?: number;
44
+ /** Numbers: granularity (HTML `step`) */
45
+ step?: number;
46
+ /** Strings: an ECMAScript regular expression source, unanchored (JSON Schema semantics) */
47
+ pattern?: string;
48
+ /** Arrays: number of items */
49
+ minItems?: number;
50
+ maxItems?: number;
51
+ /** Files: maximum size, in kilobytes (Laravel's unit) */
52
+ maxSize?: number;
53
+ /** Files: allowed extensions, without the dot (`pdf`, `png`) */
54
+ extensions?: string[];
55
+ /** Files: allowed MIME types (`image/png`, `image/*`) */
56
+ mimeTypes?: string[];
57
+ /** Booleans: must be checked / accepted (Laravel `accepted`) */
58
+ accepted?: boolean;
59
+ }
60
+ /**
61
+ * An extra client-side rule, in Formo notation: `'required_if:type,business'`,
62
+ * `'matches:@password'`, `{ rule: 'regex', params: ['/^[a-z]+$/i'] }`. The name
63
+ * must be a Formo built-in rule or one the app registers (`createFormo({ rules })`).
64
+ */
65
+ export type ModelRule = string | {
66
+ rule: string;
67
+ params?: unknown[];
68
+ message?: string;
69
+ };
70
+ export interface ModelRelation {
71
+ kind: 'belongsTo' | 'belongsToMany' | 'hasOne' | 'hasMany';
72
+ /** Related model (informative: `role`, `App\\Models\\Role`) */
73
+ model?: string;
74
+ /** Key of the related records holding the value (default `id`) */
75
+ key?: string;
76
+ }
77
+ export interface ModelField {
78
+ /** The attribute name (a form alias: no dots) */
79
+ name: string;
80
+ type: ModelFieldType;
81
+ /** Refines `type`: `email`, `url`, `password`, `tel`, `color`, `uuid`, `ip`, `search`… */
82
+ format?: string;
83
+ label?: string;
84
+ /** Help text */
85
+ description?: string;
86
+ placeholder?: string;
87
+ /** Must be filled (not just present): Laravel `required` semantics */
88
+ required?: boolean;
89
+ /** Empty means `null` */
90
+ nullable?: boolean;
91
+ default?: unknown;
92
+ /** Choices, for `enum` (and `relation`, or `array` items) */
93
+ options?: ModelOption[];
94
+ constraints?: ModelConstraints;
95
+ /** Extra client-side rules (conditional ones: `required_if:…`, cross-field ones: `matches:@…`) */
96
+ rules?: ModelRule[];
97
+ /** Rules only the server can check (`unique:users`, `exists:roles,id`) — informative, never run client-side */
98
+ serverRules?: string[];
99
+ /** Error messages by Formo rule name: `{ required: 'We need your email' }` */
100
+ messages?: Record<string, string>;
101
+ /** Set by the server only (shown read-only in update forms, never submitted) */
102
+ readOnly?: boolean;
103
+ /** Never sent back by the server (passwords): not pre-filled, optional in update forms */
104
+ writeOnly?: boolean;
105
+ /** `false` = not mass-assignable (Laravel `$guarded`): never part of a form unless asked for explicitly */
106
+ fillable?: boolean;
107
+ relation?: ModelRelation;
108
+ /** `object`: its fields */
109
+ fields?: ModelField[];
110
+ /** `array`: one element */
111
+ items?: ModelItem;
112
+ /**
113
+ * Formo definition keys merged over what's generated (`driver`, `component`,
114
+ * `view`, `attr`, `props`, `message`…) — `x-formo` in JSON Schema / OpenAPI
115
+ */
116
+ ui?: Record<string, unknown>;
117
+ /** In-memory only (never serialized): validators attached by schema adapters (Zod) */
118
+ [RUNTIME]?: FieldRuntime;
119
+ }
120
+ /** The element of an `array` field (its `name` is ignored) */
121
+ export type ModelItem = Omit<ModelField, 'name'> & {
122
+ name?: string;
123
+ };
124
+ export interface FormoModel {
125
+ version: typeof MODEL_VERSION;
126
+ /** Suggested form alias (`user`) */
127
+ name?: string;
128
+ label?: string;
129
+ fields: ModelField[];
130
+ /**
131
+ * Error messages for the whole form, keyed like Formo's `config.messages`:
132
+ * `rule`, `field.rule`, `address.street.rule` (Laravel's `messages()`)
133
+ */
134
+ messages?: Record<string, string>;
135
+ /** Anything about where it comes from (`{ source: 'laravel', request: 'StoreUserRequest' }`) */
136
+ meta?: Record<string, unknown>;
137
+ /** In-memory only (never serialized): validators attached by schema adapters (Zod) */
138
+ [RUNTIME]?: ModelRuntime;
139
+ }
140
+ /**
141
+ * Key of the validators a schema adapter (`fromZod`) attaches to a model. A
142
+ * symbol: `JSON.stringify()` leaves it out, spreads keep it.
143
+ */
144
+ export declare const RUNTIME: unique symbol;
145
+ /** `(value, params, ctx) => true | 'message'` — a Formo rule function */
146
+ export type RuntimeRule = (value: any, params: any[], ctx: any) => boolean | string | Promise<boolean | string>;
147
+ /** What a form-level callback receives (a subset of Formo's `CallbackContext`) */
148
+ export interface RuntimeCallbackContext {
149
+ values: Record<string, any>;
150
+ form: {
151
+ setError(path: string, message: string): void;
152
+ find(pathOrAlias: string): {
153
+ path: string;
154
+ } | undefined;
155
+ isIgnored(path: string): boolean;
156
+ };
157
+ }
158
+ export type RuntimeCallback = (ctx: RuntimeCallbackContext) => void | boolean | string | Promise<void | boolean | string>;
159
+ export interface FieldRuntime {
160
+ /** The field's custom refinements only (`validation: 'derived'`) — absent when it has none */
161
+ refine?: RuntimeRule;
162
+ /** The field's whole schema (`validation: 'schema'`) */
163
+ validate?: RuntimeRule;
164
+ }
165
+ export interface ModelRuntime {
166
+ /** Object-level refinements, errors mapped onto fields (`validation: 'derived'`) */
167
+ refine?: RuntimeCallback;
168
+ /** The whole schema (`validation: 'schema'`) */
169
+ validate?: RuntimeCallback;
170
+ }
171
+ export interface ModelWarning {
172
+ /** Dotted path of the field concerned (`''` = the model) */
173
+ path: string;
174
+ /** Stable identifier: `unknown-type`, `unsupported-rule`, `unsupported-keyword`… */
175
+ code: string;
176
+ message: string;
177
+ }
178
+ export type WarningHandler = (warning: ModelWarning) => void;
179
+ /** Default: `console.warn`, once per message. Pass `onWarning` to collect or silence them */
180
+ export declare const consoleWarning: WarningHandler;
181
+ /**
182
+ * Read a Formo model (an object or its JSON): checks the version and the
183
+ * structure, and returns a copy (runtime attachments kept).
184
+ *
185
+ * parseModel(props.userForm) // Inertia prop
186
+ * parseModel(await (await fetch('/formo/models/user')).json())
187
+ */
188
+ export declare function parseModel(input: unknown, onWarning?: WarningHandler): FormoModel;
189
+ export declare function isFormoModel(value: unknown): value is FormoModel;