@20baht/engine 0.3.2 → 0.3.3
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/README.md +2 -0
- package/dist/define-registry.d.ts +55 -0
- package/dist/define-registry.js +3 -0
- package/dist/form-values.d.ts +95 -2
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/json-schema.d.ts +24 -0
- package/dist/json-schema.js +85 -0
- package/dist/type-schema.d.ts +10 -0
- package/dist/type-schema.js +92 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -19,6 +19,8 @@ on its own when there is no UI to render: a server, a worker, an agent, a render
|
|
|
19
19
|
| Schema types | `FormDefinition`, `WorkflowDefinition`, `FieldDescriptor`, `Rule`, `Registry`, ... |
|
|
20
20
|
| Field types | the 22 built-in ones (`BUILT_IN_FIELD_TYPES`, `isBuiltInFieldType`; `BUILT_IN_TYPES` / `builtInType(type)` is the table of them: per type its `tag`, `empty` default, `display`, `check` and default `maxLength`) and the app's own: `registry.fieldTypes[type]` is a `FieldTypeSpec` (`tag`, `check`, `display`), found with `fieldTypeSpec(registry, type)`; `validateField` runs its `check`, `displayValue(field, value, options, registry)` its `display` (spec 01 §5.1) |
|
|
21
21
|
| Typed data | `defineForm` / `defineWorkflow` keep a schema's literal types; from them `FormValues<F>` (a form's data as held), `ValidValues<F>` (after validation: a `required` field is never null), `WorkflowValues<W>` (a workflow's data by form name; forms and fields optional, since a rule may hide either). A field type of the app's own names its value in `CustomFieldValues` (declaration merging). Types only: no codegen, nothing at run time |
|
|
22
|
+
| Checked names | `defineWorkflow` refuses a rule or transition that points at nothing: a condition's `field` / `value_field`, an expression's `ref`, an action's `target`, a transition's `from` / `to` (the compile error lists the refs at fault). `defineRegistry(schemas, registry)` refuses a registry that lacks a function the schemas name (`fn`, `formatter`, `options_from`, `uploader`, `reference`, a script's `handler`, an app's own field type). Both judge only schemas declared in TypeScript |
|
|
23
|
+
| JSON Schema | `jsonSchemaOf(schema, { io?, form? })`: a form or workflow as JSON Schema (draft 2020-12 / draft-07), for an OpenAPI document and the tools made from one. Each built-in type's shape is its entry in `TYPE_SCHEMAS`, a table of its own so a browser bundle that never calls it does not carry it. A description, not the check: a workflow lists nothing as required |
|
|
22
24
|
| Rules | `evaluate(workflow, data)` → per-field and per-form state plus the cleaned data, to a fixpoint |
|
|
23
25
|
| Validation | `validateField`, `validateShownField`, the built-in validators, pattern safety |
|
|
24
26
|
| Routing | `visibleForms`, `resolveNext`, `walkPath`, `stepFieldStates` (one step's field states, for a run kept on a server), `advanceRun(workflow, { form_name, data }, move)` (where such a run goes once a form step is submitted or an approval step is settled: moved, bounced, ended or stayed; spec 03 §5.1) |
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import type { BuiltInFieldType, FormDefinition, Registry, WorkflowDefinition } from './types.js';
|
|
2
|
+
type Schema = FormDefinition | WorkflowDefinition;
|
|
3
|
+
type FormsOf<S> = S extends {
|
|
4
|
+
readonly forms: readonly (infer F)[];
|
|
5
|
+
} ? F : S;
|
|
6
|
+
/** Every descriptor of every form, a repeater's columns included. */
|
|
7
|
+
type FieldsOf<S> = FormsOf<S> extends infer F ? F extends {
|
|
8
|
+
readonly fields: readonly (infer D)[];
|
|
9
|
+
} ? D | (D extends {
|
|
10
|
+
readonly fields: readonly (infer Column)[];
|
|
11
|
+
} ? Column : never) : never : never;
|
|
12
|
+
/** A name written in the schema; a plain `string` (not known until run time) is not one. */
|
|
13
|
+
type Literal<N> = N extends string ? (string extends N ? never : N) : never;
|
|
14
|
+
type Named<D, Key extends string> = D extends Readonly<Record<Key, infer N>> ? Literal<N> : never;
|
|
15
|
+
/** The names a schema uses, by the part of the registry that holds each. */
|
|
16
|
+
interface NamesOf<S> {
|
|
17
|
+
validators: FieldsOf<S> extends infer D ? D extends {
|
|
18
|
+
readonly validators: readonly (infer V)[];
|
|
19
|
+
} ? V extends {
|
|
20
|
+
readonly type: 'custom';
|
|
21
|
+
readonly fn: infer N;
|
|
22
|
+
} ? Literal<N> : never : never : never;
|
|
23
|
+
formatters: Named<FieldsOf<S>, 'formatter'>;
|
|
24
|
+
options: Named<FieldsOf<S>, 'options_from'>;
|
|
25
|
+
uploaders: Named<FieldsOf<S>, 'uploader'>;
|
|
26
|
+
references: Named<FieldsOf<S>, 'reference'>;
|
|
27
|
+
scripts: FormsOf<S> extends infer F ? F extends {
|
|
28
|
+
readonly scripts: readonly (infer Script)[];
|
|
29
|
+
} ? Named<Script, 'handler'> : never : never;
|
|
30
|
+
fieldTypes: Exclude<Named<FieldsOf<S>, 'type'>, BuiltInFieldType>;
|
|
31
|
+
}
|
|
32
|
+
type Held<R, Part extends string> = R extends Readonly<Record<Part, infer Entries>> ? keyof Entries : never;
|
|
33
|
+
type Part = 'validators' | 'formatters' | 'options' | 'uploaders' | 'references' | 'scripts' | 'fieldTypes';
|
|
34
|
+
/** `part.name` for every name of `S` the registry `R` has no entry for. */
|
|
35
|
+
type MissingNames<S, R> = {
|
|
36
|
+
[P in Part]: Exclude<NamesOf<S>[P], Held<R, P>> extends infer N ? N extends string ? `${P}.${N}` : never : never;
|
|
37
|
+
}[Part];
|
|
38
|
+
type SchemasOf<S> = S extends readonly (infer Each)[] ? Each : S;
|
|
39
|
+
type CheckedNames<S, R> = [MissingNames<SchemasOf<S>, R>] extends [never] ? unknown : {
|
|
40
|
+
readonly 'names the schema uses that this registry lacks': MissingNames<SchemasOf<S>, R>;
|
|
41
|
+
};
|
|
42
|
+
/**
|
|
43
|
+
* Returns `registry` unchanged, checked against the schema (or schemas) it serves: every
|
|
44
|
+
* `custom` validator's `fn`, every `formatter`, `options_from`, `uploader` and `reference`, every
|
|
45
|
+
* script's `handler` and every field type of the app's own must have an entry. A missing one is a
|
|
46
|
+
* compile error on the call, whose message lists them as `validators.thaiTaxId`.
|
|
47
|
+
*
|
|
48
|
+
* export const registry = defineRegistry([orderForm, leaveWorkflow], { validators: { … }, … });
|
|
49
|
+
*
|
|
50
|
+
* Needs schemas declared with `defineForm` / `defineWorkflow` (or generated by `20baht g types`);
|
|
51
|
+
* one typed `FormDefinition` names nothing the compiler can see. Hand the same registry to the
|
|
52
|
+
* browser and the server, and the check holds for both.
|
|
53
|
+
*/
|
|
54
|
+
export declare function defineRegistry<const S extends Schema | readonly Schema[], R extends Registry>(_schema: S, registry: R & CheckedNames<S, R>): R;
|
|
55
|
+
export {};
|
package/dist/form-values.d.ts
CHANGED
|
@@ -141,6 +141,99 @@ export type WorkflowValues<W extends {
|
|
|
141
141
|
* `FormDefinition` does not accept.
|
|
142
142
|
*/
|
|
143
143
|
export declare function defineForm<const F extends FormDefinition>(form: F): F;
|
|
144
|
-
|
|
145
|
-
|
|
144
|
+
type FormName<W> = W extends {
|
|
145
|
+
readonly forms: readonly (infer F)[];
|
|
146
|
+
} ? F extends {
|
|
147
|
+
readonly form_name: infer N extends string;
|
|
148
|
+
} ? N : never : never;
|
|
149
|
+
/** The keys a rule may name in one form: a field, a row column as `rows[].sub`, and an approval step's two. */
|
|
150
|
+
type KeysOfForm<F> = (F extends {
|
|
151
|
+
readonly fields: readonly (infer D)[];
|
|
152
|
+
} ? D extends {
|
|
153
|
+
readonly key: infer K extends string;
|
|
154
|
+
} ? K | (D extends {
|
|
155
|
+
readonly type: 'repeater';
|
|
156
|
+
readonly fields: readonly (infer S)[];
|
|
157
|
+
} ? S extends {
|
|
158
|
+
readonly key: infer SK extends string;
|
|
159
|
+
} ? `${K}[].${SK}` : never : never) : never : never) | (F extends {
|
|
160
|
+
readonly kind: 'approval';
|
|
161
|
+
} ? 'decision' | 'comment' : never);
|
|
162
|
+
type FormNamed<W, N> = W extends {
|
|
163
|
+
readonly forms: readonly (infer F)[];
|
|
164
|
+
} ? F extends {
|
|
165
|
+
readonly form_name: N;
|
|
166
|
+
} ? F : never : never;
|
|
167
|
+
/** Every `Form.key` of the workflow. */
|
|
168
|
+
type RefOf<W> = W extends {
|
|
169
|
+
readonly forms: readonly (infer F)[];
|
|
170
|
+
} ? F extends {
|
|
171
|
+
readonly form_name: infer N extends string;
|
|
172
|
+
} ? `${N}.${KeysOfForm<F>}` : never : never;
|
|
173
|
+
type Unknown<V, Allowed> = V extends string ? string extends V ? never : V extends Allowed ? never : V : never;
|
|
174
|
+
type BadCondition<C, W> = C extends {
|
|
175
|
+
readonly and: readonly (infer E)[];
|
|
176
|
+
} ? BadCondition<E, W> : C extends {
|
|
177
|
+
readonly or: readonly (infer E)[];
|
|
178
|
+
} ? BadCondition<E, W> : C extends {
|
|
179
|
+
readonly not: infer N;
|
|
180
|
+
} ? BadCondition<N, W> : (C extends {
|
|
181
|
+
readonly field: infer F;
|
|
182
|
+
} ? Unknown<F, RefOf<W>> : never) | (C extends {
|
|
183
|
+
readonly value_field: infer F;
|
|
184
|
+
} ? Unknown<F, RefOf<W>> : never);
|
|
185
|
+
type BadExpr<E, W> = E extends {
|
|
186
|
+
readonly ref: infer R;
|
|
187
|
+
} ? Unknown<R, RefOf<W>> : E extends {
|
|
188
|
+
readonly args: readonly (infer X)[];
|
|
189
|
+
} ? BadExpr<X, W> : E extends {
|
|
190
|
+
readonly if: readonly [infer C, infer A, infer B];
|
|
191
|
+
} ? BadCondition<C, W> | BadExpr<A, W> | BadExpr<B, W> : never;
|
|
192
|
+
type BadTarget<T, W> = T extends {
|
|
193
|
+
readonly form: infer F extends string;
|
|
194
|
+
} ? string extends F ? never : F extends FormName<W> ? T extends {
|
|
195
|
+
readonly field: infer K extends string;
|
|
196
|
+
} ? string extends K ? never : K extends KeysOfForm<FormNamed<W, F>> ? never : `${F}.${K}` : never : F : never;
|
|
197
|
+
type BadAction<A, W> = (A extends {
|
|
198
|
+
readonly target: infer T;
|
|
199
|
+
} ? BadTarget<T, W> : never) | (A extends {
|
|
200
|
+
readonly value: infer V;
|
|
201
|
+
} ? BadExpr<V, W> : never);
|
|
202
|
+
type BadRule<R, W> = (R extends {
|
|
203
|
+
readonly when: infer C;
|
|
204
|
+
} ? BadCondition<C, W> : never) | (R extends {
|
|
205
|
+
readonly then: readonly (infer A)[];
|
|
206
|
+
} ? BadAction<A, W> : never) | (R extends {
|
|
207
|
+
readonly else: readonly (infer A)[];
|
|
208
|
+
} ? BadAction<A, W> : never);
|
|
209
|
+
type BadTransition<T, W> = (T extends {
|
|
210
|
+
readonly from: infer F;
|
|
211
|
+
} ? Unknown<F, FormName<W>> : never) | (T extends {
|
|
212
|
+
readonly to: infer F;
|
|
213
|
+
} ? Unknown<F, FormName<W> | 'end'> : never) | (T extends {
|
|
214
|
+
readonly when: infer C;
|
|
215
|
+
} ? BadCondition<C, W> : never);
|
|
216
|
+
/** Every ref in the rules and transitions of `W` that names no form or field of it. */
|
|
217
|
+
type UnknownRefs<W> = string extends FormName<W> ? never : (W extends {
|
|
218
|
+
readonly rules: readonly (infer R)[];
|
|
219
|
+
} ? BadRule<R, W> : never) | (W extends {
|
|
220
|
+
readonly transitions: readonly (infer T)[];
|
|
221
|
+
} ? BadTransition<T, W> : never);
|
|
222
|
+
/**
|
|
223
|
+
* Nothing when every ref of `W` names something; else a property no workflow has, typed as the
|
|
224
|
+
* refs at fault, so the compiler's message spells them out.
|
|
225
|
+
*/
|
|
226
|
+
type CheckedRefs<W> = [UnknownRefs<W>] extends [never] ? unknown : {
|
|
227
|
+
readonly 'refs that name no form or field of this workflow': UnknownRefs<W>;
|
|
228
|
+
};
|
|
229
|
+
/**
|
|
230
|
+
* `defineForm` for a workflow: `WorkflowValues<typeof wf>` is exact. It also checks what the
|
|
231
|
+
* rules point at as they are written: a condition's `field` / `value_field` and an expression's
|
|
232
|
+
* `ref` must be a `Form.key` of this workflow (`Form.rows[].sub` for a repeater column, spec 02
|
|
233
|
+
* §2a; `decision` / `comment` on an approval step), an action's `target` a form and a field of
|
|
234
|
+
* it, a transition's `from` / `to` a form (or `end`). A ref that names nothing is a compile
|
|
235
|
+
* error on the call, whose message lists the refs at fault. The engine reports the same at run
|
|
236
|
+
* time (`derived.errors`, `parseSchema`); here the compiler does first.
|
|
237
|
+
*/
|
|
238
|
+
export declare function defineWorkflow<const W extends WorkflowDefinition>(workflow: W & CheckedRefs<W>): W;
|
|
146
239
|
export {};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
export * from './types.js';
|
|
2
2
|
export { defineForm, defineWorkflow, type FormValues, type ValidValues, type WorkflowFormValues, type WorkflowValues, } from './form-values.js';
|
|
3
|
+
export { defineRegistry } from './define-registry.js';
|
|
3
4
|
export { defaultValue } from './defaults.js';
|
|
5
|
+
export { jsonSchemaOf, type JsonSchema, type JsonSchemaOptions } from './json-schema.js';
|
|
4
6
|
export { BUILT_IN_FIELD_TYPES, fieldTypeSpec, isBuiltInFieldType } from './field-types.js';
|
|
5
7
|
export { BUILT_IN_TYPES, builtInType, type BuiltInTypeSpec } from './built-in-types.js';
|
|
6
8
|
export { approvalCommentRequired, approvalFields } from './approval.js';
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
export * from './types.js';
|
|
2
2
|
export { defineForm, defineWorkflow, } from './form-values.js';
|
|
3
|
+
export { defineRegistry } from './define-registry.js';
|
|
3
4
|
export { defaultValue } from './defaults.js';
|
|
5
|
+
export { jsonSchemaOf } from './json-schema.js';
|
|
4
6
|
export { BUILT_IN_FIELD_TYPES, fieldTypeSpec, isBuiltInFieldType } from './field-types.js';
|
|
5
7
|
export { BUILT_IN_TYPES, builtInType } from './built-in-types.js';
|
|
6
8
|
export { approvalCommentRequired, approvalFields } from './approval.js';
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { type JsonSchema } from './type-schema.js';
|
|
2
|
+
import type { FormDefinition, WorkflowDefinition } from './types.js';
|
|
3
|
+
export type { JsonSchema } from './type-schema.js';
|
|
4
|
+
export interface JsonSchemaOptions {
|
|
5
|
+
/**
|
|
6
|
+
* `input` (default): what a client may send. `output`: the canonical data a validation
|
|
7
|
+
* returns, where a form on its own holds every key.
|
|
8
|
+
*/
|
|
9
|
+
io?: 'input' | 'output';
|
|
10
|
+
/** Workflows only: the flat body of this one form, as `validateSubmission`'s `form` reads it. */
|
|
11
|
+
form?: string;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* `schema` as JSON Schema (draft 2020-12), each built-in type's shape from `TYPE_SCHEMAS`:
|
|
15
|
+
*
|
|
16
|
+
* - a form: an object of its fields; a `required` one is listed and never null;
|
|
17
|
+
* - a workflow: an object of its forms by name, nothing required (a rule may hide a form or a
|
|
18
|
+
* field, or lift `required`);
|
|
19
|
+
* - a workflow with `form`: that one form's flat body, nothing required.
|
|
20
|
+
*
|
|
21
|
+
* It carries what a schema can say (types, option keys, lengths, bounds). What it cannot
|
|
22
|
+
* (`compare`, `custom`, `options_from`, rules) is the validator's alone.
|
|
23
|
+
*/
|
|
24
|
+
export declare function jsonSchemaOf(schema: FormDefinition | WorkflowDefinition, options?: JsonSchemaOptions): JsonSchema;
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { approvalFields } from './approval.js';
|
|
2
|
+
import { rowSubFields } from './keys.js';
|
|
3
|
+
import { TYPE_SCHEMAS } from './type-schema.js';
|
|
4
|
+
const isRequired = (field) => field.required === true || (field.validators ?? []).some((spec) => spec.type === 'required');
|
|
5
|
+
const sorted = (fields) => [...fields].sort((a, b) => a.order - b.order);
|
|
6
|
+
const holdsValue = (field) => field.type !== 'label' && field.type !== 'section';
|
|
7
|
+
function withEmptiness(schema, required) {
|
|
8
|
+
if (schema.type === 'array')
|
|
9
|
+
return required ? { ...schema, minItems: schema.minItems ?? 1 } : schema;
|
|
10
|
+
if (schema.type === 'boolean')
|
|
11
|
+
return required ? { const: true } : schema;
|
|
12
|
+
return required ? schema : { anyOf: [schema, { type: 'null' }] };
|
|
13
|
+
}
|
|
14
|
+
function rowsSchema(field, mode) {
|
|
15
|
+
return {
|
|
16
|
+
type: 'array',
|
|
17
|
+
items: objectSchema(rowSubFields(field), mode),
|
|
18
|
+
...(field.min_rows === undefined ? {} : { minItems: field.min_rows }),
|
|
19
|
+
...(field.max_rows === undefined ? {} : { maxItems: field.max_rows }),
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
function fieldSchema(field, mode) {
|
|
23
|
+
const described = {
|
|
24
|
+
...(field.label === undefined ? {} : { title: field.label }),
|
|
25
|
+
...(field.help === undefined ? {} : { description: field.help }),
|
|
26
|
+
};
|
|
27
|
+
if (field.type === 'repeater')
|
|
28
|
+
return { ...rowsSchema(field, mode), ...described };
|
|
29
|
+
const value = Object.hasOwn(TYPE_SCHEMAS, field.type)
|
|
30
|
+
? TYPE_SCHEMAS[field.type]?.(field)
|
|
31
|
+
: undefined;
|
|
32
|
+
if (value === undefined)
|
|
33
|
+
return described;
|
|
34
|
+
return { ...withEmptiness(value, mode.strict && isRequired(field)), ...described };
|
|
35
|
+
}
|
|
36
|
+
function objectSchema(fields, mode) {
|
|
37
|
+
const valued = sorted(fields).filter(holdsValue);
|
|
38
|
+
const required = valued
|
|
39
|
+
.filter((field) => mode.strict && (mode.output || isRequired(field)))
|
|
40
|
+
.map((field) => field.key);
|
|
41
|
+
return {
|
|
42
|
+
type: 'object',
|
|
43
|
+
properties: Object.fromEntries(valued.map((field) => [field.key, fieldSchema(field, mode)])),
|
|
44
|
+
...(required.length > 0 ? { required } : {}),
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
function stepFields(form) {
|
|
48
|
+
return [
|
|
49
|
+
...form.fields,
|
|
50
|
+
...approvalFields(form).map((field) => field.key === 'decision' ? { ...field, type: 'radio', options: DECISIONS } : field),
|
|
51
|
+
];
|
|
52
|
+
}
|
|
53
|
+
const DECISIONS = [
|
|
54
|
+
{ key: 'approved', label: 'approved' },
|
|
55
|
+
{ key: 'rejected', label: 'rejected' },
|
|
56
|
+
];
|
|
57
|
+
function stepSchema(form, mode) {
|
|
58
|
+
const { type, ...rest } = objectSchema(stepFields(form).map((field) => {
|
|
59
|
+
if (form.fields.includes(field))
|
|
60
|
+
return field;
|
|
61
|
+
const { label: _label, ...bare } = field;
|
|
62
|
+
return bare;
|
|
63
|
+
}), mode);
|
|
64
|
+
return { type, title: form.form_name, ...rest };
|
|
65
|
+
}
|
|
66
|
+
export function jsonSchemaOf(schema, options = {}) {
|
|
67
|
+
const output = options.io === 'output';
|
|
68
|
+
if (!('forms' in schema)) {
|
|
69
|
+
const { type, ...rest } = objectSchema(schema.fields, { strict: true, output });
|
|
70
|
+
return { type, title: schema.form_name, ...rest };
|
|
71
|
+
}
|
|
72
|
+
const mode = { strict: false, output };
|
|
73
|
+
const ordered = [...schema.forms].sort((a, b) => a.order - b.order);
|
|
74
|
+
if (options.form !== undefined) {
|
|
75
|
+
const form = ordered.find((candidate) => candidate.form_name === options.form);
|
|
76
|
+
if (!form)
|
|
77
|
+
throw new Error(`jsonSchemaOf: no form named ${JSON.stringify(options.form)}`);
|
|
78
|
+
return stepSchema(form, mode);
|
|
79
|
+
}
|
|
80
|
+
return {
|
|
81
|
+
type: 'object',
|
|
82
|
+
title: schema.workflow_id,
|
|
83
|
+
properties: Object.fromEntries(ordered.map((form) => [form.form_name, stepSchema(form, mode)])),
|
|
84
|
+
};
|
|
85
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { BuiltInFieldType, FieldDescriptor } from './types.js';
|
|
2
|
+
/** A JSON Schema, as plain data. */
|
|
3
|
+
export type JsonSchema = Record<string, unknown>;
|
|
4
|
+
/** The schema of a value that is there (the field's own emptiness is the caller's to add). */
|
|
5
|
+
export type TypeSchema = (field: FieldDescriptor) => JsonSchema;
|
|
6
|
+
/**
|
|
7
|
+
* A value of each built-in type as JSON Schema. `null`: the type holds no value (a static
|
|
8
|
+
* block), or `jsonSchemaOf` describes it itself (a repeater's rows).
|
|
9
|
+
*/
|
|
10
|
+
export declare const TYPE_SCHEMAS: Record<BuiltInFieldType, TypeSchema | null>;
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { builtInType } from './built-in-types.js';
|
|
2
|
+
import { ratingMax, rangeBounds } from './type-checks.js';
|
|
3
|
+
const validator = (field, type) => field.validators?.find((spec) => spec.type === type)?.value;
|
|
4
|
+
const whole = (value) => typeof value === 'number' && Number.isInteger(value) && value >= 0 ? value : undefined;
|
|
5
|
+
const finite = (value) => typeof value === 'number' && Number.isFinite(value) ? value : undefined;
|
|
6
|
+
function compact(schema) {
|
|
7
|
+
return Object.fromEntries(Object.entries(schema).filter(([, value]) => value !== undefined));
|
|
8
|
+
}
|
|
9
|
+
const textSchema = (more = {}) => (field) => {
|
|
10
|
+
const defaultMax = builtInType(field.type)?.maxLength;
|
|
11
|
+
const pattern = validator(field, 'pattern');
|
|
12
|
+
return compact({
|
|
13
|
+
type: 'string',
|
|
14
|
+
minLength: whole(validator(field, 'minLength') ?? field.min_length),
|
|
15
|
+
maxLength: whole(validator(field, 'maxLength') ?? field.max_length ?? defaultMax),
|
|
16
|
+
pattern: typeof pattern === 'string' ? pattern : undefined,
|
|
17
|
+
...more,
|
|
18
|
+
});
|
|
19
|
+
};
|
|
20
|
+
const numberSchema = (field) => compact({
|
|
21
|
+
type: field.integer ? 'integer' : 'number',
|
|
22
|
+
minimum: finite(validator(field, 'min') ?? field.min),
|
|
23
|
+
maximum: finite(validator(field, 'max') ?? field.max),
|
|
24
|
+
});
|
|
25
|
+
const ratingSchema = (field) => ({
|
|
26
|
+
type: 'integer',
|
|
27
|
+
minimum: 1,
|
|
28
|
+
maximum: ratingMax(field),
|
|
29
|
+
});
|
|
30
|
+
const rangeSchema = (field) => {
|
|
31
|
+
const { min, max } = rangeBounds(field);
|
|
32
|
+
return { type: 'number', minimum: min, maximum: max };
|
|
33
|
+
};
|
|
34
|
+
const booleanSchema = () => ({ type: 'boolean' });
|
|
35
|
+
const optionSchema = (field, more = {}) => field.options_from === undefined && field.options !== undefined
|
|
36
|
+
? { type: 'string', enum: field.options.map((option) => option.key) }
|
|
37
|
+
: { type: 'string', ...more };
|
|
38
|
+
const choiceSchema = (field) => optionSchema(field);
|
|
39
|
+
const choicesSchema = (field) => ({ type: 'array', items: optionSchema(field) });
|
|
40
|
+
const tagsSchema = (field) => {
|
|
41
|
+
const text = { type: 'string', maxLength: whole(field.max_length) ?? 32 };
|
|
42
|
+
return compact({
|
|
43
|
+
type: 'array',
|
|
44
|
+
items: field.allow_new === false ? optionSchema(field, { maxLength: text.maxLength }) : text,
|
|
45
|
+
maxItems: whole(field.max_items),
|
|
46
|
+
});
|
|
47
|
+
};
|
|
48
|
+
const dateSchema = (field) => {
|
|
49
|
+
const one = field.enable_time
|
|
50
|
+
? { type: 'string', pattern: '^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}$' }
|
|
51
|
+
: { type: 'string', format: 'date' };
|
|
52
|
+
if (field.date_mode === 'range')
|
|
53
|
+
return { type: 'array', items: one, minItems: 2, maxItems: 2 };
|
|
54
|
+
if (field.date_mode === 'multiple')
|
|
55
|
+
return { type: 'array', items: one };
|
|
56
|
+
return one;
|
|
57
|
+
};
|
|
58
|
+
const UPLOADED_FILE = {
|
|
59
|
+
type: 'object',
|
|
60
|
+
properties: {
|
|
61
|
+
name: { type: 'string' },
|
|
62
|
+
size: { type: 'number' },
|
|
63
|
+
type: { type: 'string' },
|
|
64
|
+
url: { type: 'string' },
|
|
65
|
+
},
|
|
66
|
+
required: ['name', 'size', 'url'],
|
|
67
|
+
};
|
|
68
|
+
const fileSchema = (field) => field.multiple ? { type: 'array', items: UPLOADED_FILE } : UPLOADED_FILE;
|
|
69
|
+
export const TYPE_SCHEMAS = {
|
|
70
|
+
text: textSchema(),
|
|
71
|
+
textarea: textSchema(),
|
|
72
|
+
markdown: textSchema(),
|
|
73
|
+
number: numberSchema,
|
|
74
|
+
currency: numberSchema,
|
|
75
|
+
email: textSchema({ format: 'email' }),
|
|
76
|
+
password: textSchema(),
|
|
77
|
+
dropdown: choiceSchema,
|
|
78
|
+
multiselect: choicesSchema,
|
|
79
|
+
checkbox: booleanSchema,
|
|
80
|
+
radio: choiceSchema,
|
|
81
|
+
toggle: booleanSchema,
|
|
82
|
+
date: dateSchema,
|
|
83
|
+
time: () => ({ type: 'string', pattern: '^([01]\\d|2[0-3]):[0-5]\\d$' }),
|
|
84
|
+
file: fileSchema,
|
|
85
|
+
label: null,
|
|
86
|
+
section: null,
|
|
87
|
+
repeater: null,
|
|
88
|
+
tags: tagsSchema,
|
|
89
|
+
rating: ratingSchema,
|
|
90
|
+
range: rangeSchema,
|
|
91
|
+
reference: () => ({ type: 'string' }),
|
|
92
|
+
};
|