@20baht/engine 0.1.2 → 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.
- package/README.md +3 -1
- package/dist/assignment.d.ts +19 -0
- package/dist/assignment.js +27 -0
- package/dist/built-in-types.d.ts +23 -0
- package/dist/built-in-types.js +47 -0
- package/dist/defaults.d.ts +2 -1
- package/dist/defaults.js +3 -33
- package/dist/display.d.ts +9 -30
- package/dist/display.js +10 -105
- package/dist/engine/advance.d.ts +53 -0
- package/dist/engine/advance.js +42 -0
- package/dist/field-types.d.ts +10 -0
- package/dist/field-types.js +12 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +4 -0
- package/dist/type-checks.d.ts +66 -0
- package/dist/type-checks.js +137 -0
- package/dist/type-display.d.ts +46 -0
- package/dist/type-display.js +93 -0
- package/dist/types.d.ts +108 -1
- package/dist/validators.d.ts +2 -31
- package/dist/validators.js +15 -160
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -17,9 +17,11 @@ on its own when there is no UI to render: a server, a worker, an agent, a render
|
|
|
17
17
|
| | |
|
|
18
18
|
| --- | --- |
|
|
19
19
|
| Schema types | `FormDefinition`, `WorkflowDefinition`, `FieldDescriptor`, `Rule`, `Registry`, ... |
|
|
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) |
|
|
20
21
|
| Rules | `evaluate(workflow, data)` → per-field and per-form state plus the cleaned data, to a fixpoint |
|
|
21
22
|
| Validation | `validateField`, `validateShownField`, the built-in validators, pattern safety |
|
|
22
|
-
| Routing | `visibleForms`, `resolveNext`, `walkPath`, `stepFieldStates` (one step's field states, for a run kept on a server) |
|
|
23
|
+
| 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) |
|
|
24
|
+
| Assignment | who decides an approval step (spec 03 §4.1): the `Assignment` / `AssignTarget` types, `askedTargets(assignment, data)` (the targets whose `when` holds), `settleStep(rule, asked)` (`any` / `all` / quorum → pending, approved or rejected). For a server: `<baht-workflow>` does not read it |
|
|
23
25
|
| Workflow runtime | `updateWorkflow(workflow, state, msg)` → next state and events; `replayWorkflow`, `snapshotOf` |
|
|
24
26
|
| Form session | `updateForm(input, state, msg)` → next state and events; `formData`, `formFieldState` |
|
|
25
27
|
| Client scripts | `createScriptContext`, `runScripts`, `submitScriptErrors` |
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { AskedState, Assignment, AssignTarget, CompletionRule, NestedData, StepOutcome } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* The targets of an assignment this request asks: every one with no `when`, and those whose
|
|
4
|
+
* `when` holds for `data` (spec 03 §4.1). `data` is nested `{ Form_Name: { key } }`, the answers
|
|
5
|
+
* of earlier steps included. Order is the definition's.
|
|
6
|
+
*/
|
|
7
|
+
export declare function askedTargets(assignment: Assignment, data: NestedData): AssignTarget[];
|
|
8
|
+
/**
|
|
9
|
+
* What the people asked on a step add up to (spec 03 §4.1):
|
|
10
|
+
*
|
|
11
|
+
* any approved on the first approval rejected on the first rejection
|
|
12
|
+
* all approved when everyone approved rejected on the first rejection
|
|
13
|
+
* { quorum: k } approved at k approvals rejected once k is out of reach
|
|
14
|
+
*
|
|
15
|
+
* A rejection beside an approval is a rejection under `any` and `all`: the two were decided
|
|
16
|
+
* apart, so the answer must not depend on their order. Nobody asked is never an approval, and
|
|
17
|
+
* neither is a quorum below 1 (a definition `parseSchema` refuses).
|
|
18
|
+
*/
|
|
19
|
+
export declare function settleStep(rule: CompletionRule, asked: readonly AskedState[]): StepOutcome;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { evalCondition } from './engine/conditions.js';
|
|
2
|
+
export function askedTargets(assignment, data) {
|
|
3
|
+
return assignment.assign_to.filter((target) => evalCondition(target.when, data));
|
|
4
|
+
}
|
|
5
|
+
const count = (asked, state) => asked.filter((s) => s === state).length;
|
|
6
|
+
export function settleStep(rule, asked) {
|
|
7
|
+
if (asked.length === 0)
|
|
8
|
+
return 'pending';
|
|
9
|
+
const approvals = count(asked, 'approved');
|
|
10
|
+
const rejected = asked.includes('rejected');
|
|
11
|
+
if (rule === 'any') {
|
|
12
|
+
if (rejected)
|
|
13
|
+
return 'rejected';
|
|
14
|
+
return approvals > 0 ? 'approved' : 'pending';
|
|
15
|
+
}
|
|
16
|
+
if (rule === 'all') {
|
|
17
|
+
if (rejected)
|
|
18
|
+
return 'rejected';
|
|
19
|
+
return approvals === asked.length ? 'approved' : 'pending';
|
|
20
|
+
}
|
|
21
|
+
const k = rule.quorum;
|
|
22
|
+
if (!Number.isInteger(k) || k < 1)
|
|
23
|
+
return 'pending';
|
|
24
|
+
if (approvals >= k)
|
|
25
|
+
return 'approved';
|
|
26
|
+
return approvals + count(asked, 'waiting') < k ? 'rejected' : 'pending';
|
|
27
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { type TypeCheck } from './type-checks.js';
|
|
2
|
+
import { type TypeDisplay } from './type-display.js';
|
|
3
|
+
import type { BuiltInFieldType, FieldDescriptor } from './types.js';
|
|
4
|
+
export interface BuiltInTypeSpec {
|
|
5
|
+
/** The `<baht-*>` element that renders it. A name only: the engine never touches the DOM. */
|
|
6
|
+
tag: string;
|
|
7
|
+
/**
|
|
8
|
+
* The value the field holds before anyone answers (spec 01 §1.1), when the descriptor gives
|
|
9
|
+
* no `value`; clear-on-hide resets to it. Left out: `null`.
|
|
10
|
+
*/
|
|
11
|
+
empty?: (field: FieldDescriptor) => unknown;
|
|
12
|
+
/** How a value that is there reads in the read-only mode. Left out: `String(value)`. */
|
|
13
|
+
display?: TypeDisplay;
|
|
14
|
+
/** What the type checks beyond its declarative validators (spec 01 §4). */
|
|
15
|
+
check?: TypeCheck;
|
|
16
|
+
/** `check` also runs when the value is empty. Left out: only on a value that is there. */
|
|
17
|
+
checkWhenEmpty?: boolean;
|
|
18
|
+
/** `max_length` applied when the field declares none, so no unbounded string is stored. */
|
|
19
|
+
maxLength?: number;
|
|
20
|
+
}
|
|
21
|
+
export declare const BUILT_IN_TYPES: Record<BuiltInFieldType, BuiltInTypeSpec>;
|
|
22
|
+
/** A built-in type's entry, or undefined. Own keys only: `toString` is not a field type. */
|
|
23
|
+
export declare function builtInType(type: unknown): BuiltInTypeSpec | undefined;
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { dateErrors, fileErrors, numberErrors, rangeErrors, ratingErrors, referenceErrors, tagsErrors, timeErrors, } from './type-checks.js';
|
|
2
|
+
import { asChips, asDate, asFiles, asOptionLabel, asRating, asRows, asYesNo, } from './type-display.js';
|
|
3
|
+
const INPUT = 'baht-input';
|
|
4
|
+
const noValue = () => undefined;
|
|
5
|
+
const off = () => false;
|
|
6
|
+
const none = () => [];
|
|
7
|
+
export const BUILT_IN_TYPES = {
|
|
8
|
+
text: { tag: INPUT, maxLength: 1024 },
|
|
9
|
+
textarea: { tag: 'baht-textarea', maxLength: 10_000 },
|
|
10
|
+
markdown: { tag: 'baht-markdown', maxLength: 100_000 },
|
|
11
|
+
number: { tag: 'baht-number', check: numberErrors, checkWhenEmpty: true },
|
|
12
|
+
currency: { tag: 'baht-currency', check: numberErrors, checkWhenEmpty: true },
|
|
13
|
+
email: { tag: INPUT, maxLength: 1024 },
|
|
14
|
+
password: { tag: INPUT, maxLength: 1024 },
|
|
15
|
+
dropdown: { tag: 'baht-select', display: asOptionLabel },
|
|
16
|
+
multiselect: { tag: 'baht-multiselect', empty: none, display: asChips },
|
|
17
|
+
checkbox: { tag: 'baht-checkbox', empty: off, display: asYesNo },
|
|
18
|
+
radio: { tag: 'baht-radio', display: asOptionLabel },
|
|
19
|
+
toggle: { tag: 'baht-toggle', empty: off, display: asYesNo },
|
|
20
|
+
date: { tag: 'baht-datepicker', display: asDate, check: dateErrors },
|
|
21
|
+
time: { tag: INPUT, check: timeErrors },
|
|
22
|
+
file: {
|
|
23
|
+
tag: 'baht-file',
|
|
24
|
+
empty: (field) => (field.multiple ? [] : null),
|
|
25
|
+
display: asFiles,
|
|
26
|
+
check: fileErrors,
|
|
27
|
+
checkWhenEmpty: true,
|
|
28
|
+
},
|
|
29
|
+
label: { tag: 'baht-text', empty: noValue },
|
|
30
|
+
section: { tag: 'baht-section', empty: noValue },
|
|
31
|
+
repeater: { tag: 'baht-repeater', empty: none, display: asRows },
|
|
32
|
+
tags: {
|
|
33
|
+
tag: 'baht-tags',
|
|
34
|
+
empty: none,
|
|
35
|
+
display: asChips,
|
|
36
|
+
check: (field, value) => tagsErrors(field, value),
|
|
37
|
+
checkWhenEmpty: true,
|
|
38
|
+
},
|
|
39
|
+
rating: { tag: 'baht-rating', display: asRating, check: ratingErrors },
|
|
40
|
+
range: { tag: 'baht-range', check: rangeErrors },
|
|
41
|
+
reference: { tag: 'baht-reference-picker', check: referenceErrors },
|
|
42
|
+
};
|
|
43
|
+
export function builtInType(type) {
|
|
44
|
+
return typeof type === 'string' && Object.hasOwn(BUILT_IN_TYPES, type)
|
|
45
|
+
? BUILT_IN_TYPES[type]
|
|
46
|
+
: undefined;
|
|
47
|
+
}
|
package/dist/defaults.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { FieldDescriptor } from './types.js';
|
|
2
2
|
/**
|
|
3
3
|
* A field's default value (spec 01 §1.1): its `value` if given, else the
|
|
4
|
-
* type's empty default. Clear-on-hide/skip resets to this.
|
|
4
|
+
* type's empty default (`BUILT_IN_TYPES`). Clear-on-hide/skip resets to this. A type the engine
|
|
5
|
+
* does not know (the app's own, or untrusted JSON) starts as null.
|
|
5
6
|
*/
|
|
6
7
|
export declare function defaultValue(field: FieldDescriptor): unknown;
|
package/dist/defaults.js
CHANGED
|
@@ -1,37 +1,7 @@
|
|
|
1
|
+
import { builtInType } from './built-in-types.js';
|
|
1
2
|
export function defaultValue(field) {
|
|
2
3
|
if (field.value !== undefined)
|
|
3
4
|
return field.value;
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
case 'toggle':
|
|
7
|
-
return false;
|
|
8
|
-
case 'multiselect':
|
|
9
|
-
case 'repeater':
|
|
10
|
-
case 'tags':
|
|
11
|
-
return [];
|
|
12
|
-
case 'file':
|
|
13
|
-
return field.multiple ? [] : null;
|
|
14
|
-
case 'label':
|
|
15
|
-
case 'section':
|
|
16
|
-
return undefined;
|
|
17
|
-
case 'text':
|
|
18
|
-
case 'textarea':
|
|
19
|
-
case 'markdown':
|
|
20
|
-
case 'number':
|
|
21
|
-
case 'currency':
|
|
22
|
-
case 'email':
|
|
23
|
-
case 'password':
|
|
24
|
-
case 'dropdown':
|
|
25
|
-
case 'radio':
|
|
26
|
-
case 'date':
|
|
27
|
-
case 'time':
|
|
28
|
-
case 'rating':
|
|
29
|
-
case 'range':
|
|
30
|
-
case 'reference':
|
|
31
|
-
return null;
|
|
32
|
-
default: {
|
|
33
|
-
const _exhaustive = field.type;
|
|
34
|
-
return null;
|
|
35
|
-
}
|
|
36
|
-
}
|
|
5
|
+
const empty = builtInType(field.type)?.empty;
|
|
6
|
+
return empty ? empty(field) : null;
|
|
37
7
|
}
|
package/dist/display.d.ts
CHANGED
|
@@ -1,33 +1,12 @@
|
|
|
1
|
-
import
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
} | {
|
|
5
|
-
kind: 'text';
|
|
6
|
-
text: string;
|
|
7
|
-
} | {
|
|
8
|
-
kind: 'chips';
|
|
9
|
-
items: string[];
|
|
10
|
-
}
|
|
11
|
-
/** Files: each name, and a link when it is an uploaded ref with a safe url. */
|
|
12
|
-
| {
|
|
13
|
-
kind: 'files';
|
|
14
|
-
items: {
|
|
15
|
-
name: string;
|
|
16
|
-
url: string | null;
|
|
17
|
-
}[];
|
|
18
|
-
}
|
|
19
|
-
/** Repeater rows: one entry per row, each a list of `label: value` pairs. */
|
|
20
|
-
| {
|
|
21
|
-
kind: 'rows';
|
|
22
|
-
/** `reference`: the column, when `text` is a stored id its lookup can turn into a label. */
|
|
23
|
-
rows: {
|
|
24
|
-
label: string;
|
|
25
|
-
text: string;
|
|
26
|
-
reference?: FieldDescriptor;
|
|
27
|
-
}[][];
|
|
28
|
-
};
|
|
1
|
+
import { type DisplayValue } from './type-display.js';
|
|
2
|
+
import type { FieldDescriptor, FieldOption, Registry } from './types.js';
|
|
3
|
+
export type { DisplayValue };
|
|
29
4
|
/**
|
|
30
5
|
* The read-only rendering of one field's value. `options` overrides the
|
|
31
|
-
* descriptor's own list when they were resolved dynamically (`options_from`).
|
|
6
|
+
* descriptor's own list when they were resolved dynamically (`options_from`). A built-in type
|
|
7
|
+
* reads as its entry in `BUILT_IN_TYPES` says; a type of the app's own through
|
|
8
|
+
* `registry.fieldTypes[type].display`; anything else as `String(value)` (the schema is
|
|
9
|
+
* untrusted JSON, so an unknown type still shows something). A repeater's cells are displayed
|
|
10
|
+
* with the same registry.
|
|
32
11
|
*/
|
|
33
|
-
export declare function displayValue(field: FieldDescriptor, value: unknown, options?: FieldOption[] | undefined): DisplayValue;
|
|
12
|
+
export declare function displayValue(field: FieldDescriptor, value: unknown, options?: FieldOption[] | undefined, registry?: Pick<Registry, 'fieldTypes'>): DisplayValue;
|
package/dist/display.js
CHANGED
|
@@ -1,110 +1,15 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
const isEmpty = (value) => value === null ||
|
|
5
|
-
value === undefined ||
|
|
6
|
-
value === '' ||
|
|
7
|
-
(Array.isArray(value) && value.length === 0);
|
|
8
|
-
const labelFor = (options, key) => {
|
|
9
|
-
const found = options?.find((o) => o.key === String(key));
|
|
10
|
-
return found ? found.label : String(key);
|
|
11
|
-
};
|
|
12
|
-
const fileName = (file) => {
|
|
13
|
-
if (file && typeof file === 'object' && 'name' in file) {
|
|
14
|
-
return String(file.name);
|
|
15
|
-
}
|
|
16
|
-
return String(file);
|
|
17
|
-
};
|
|
18
|
-
const formatDate = (raw) => {
|
|
19
|
-
const asDate = new Date(raw);
|
|
20
|
-
if (Number.isNaN(asDate.getTime()))
|
|
21
|
-
return raw;
|
|
22
|
-
return /^\d{4}-\d{2}-\d{2}$/.test(raw)
|
|
23
|
-
? new Date(raw + 'T00:00:00').toLocaleDateString()
|
|
24
|
-
: asDate.toLocaleString();
|
|
25
|
-
};
|
|
1
|
+
import { builtInType } from './built-in-types.js';
|
|
2
|
+
import { fieldTypeSpec } from './field-types.js';
|
|
3
|
+
import { asText, isEmptyDisplay } from './type-display.js';
|
|
26
4
|
const emptyDisplay = (field) => field.type === 'dropdown' && field.empty_label
|
|
27
5
|
? { kind: 'text', text: field.empty_label }
|
|
28
6
|
: { kind: 'empty' };
|
|
29
|
-
export function displayValue(field, value, options = field.options) {
|
|
30
|
-
if (
|
|
7
|
+
export function displayValue(field, value, options = field.options, registry) {
|
|
8
|
+
if (isEmptyDisplay(value))
|
|
31
9
|
return emptyDisplay(field);
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
case 'radio':
|
|
38
|
-
return { kind: 'text', text: labelFor(options, value) };
|
|
39
|
-
case 'multiselect':
|
|
40
|
-
case 'tags': {
|
|
41
|
-
const keys = Array.isArray(value) ? value : [value];
|
|
42
|
-
return { kind: 'chips', items: keys.map((k) => labelFor(options, k)) };
|
|
43
|
-
}
|
|
44
|
-
case 'date': {
|
|
45
|
-
if (!Array.isArray(value))
|
|
46
|
-
return { kind: 'text', text: formatDate(String(value)) };
|
|
47
|
-
const days = value.map((v) => formatDate(String(v)));
|
|
48
|
-
return field.date_mode === 'range' && days.length === 2
|
|
49
|
-
? { kind: 'text', text: `${days[0]} – ${days[1]}` }
|
|
50
|
-
: { kind: 'chips', items: days };
|
|
51
|
-
}
|
|
52
|
-
case 'file': {
|
|
53
|
-
const files = Array.isArray(value) ? value : [value];
|
|
54
|
-
return {
|
|
55
|
-
kind: 'files',
|
|
56
|
-
items: files.map((file) => {
|
|
57
|
-
const raw = file !== null && typeof file === 'object' && 'url' in file ? file.url : undefined;
|
|
58
|
-
const url = typeof raw === 'string' ? raw : null;
|
|
59
|
-
return { name: fileName(file), url: url !== null && isSafeUrl(url) ? url : null };
|
|
60
|
-
}),
|
|
61
|
-
};
|
|
62
|
-
}
|
|
63
|
-
case 'repeater': {
|
|
64
|
-
const rows = Array.isArray(value) ? value : [];
|
|
65
|
-
const subFields = (field.fields ?? []).filter((f) => f.type !== 'label' && f.type !== 'section' && !f.hidden);
|
|
66
|
-
return {
|
|
67
|
-
kind: 'rows',
|
|
68
|
-
rows: rows.map((row) => subFields.map((f) => {
|
|
69
|
-
const cell = row !== null && typeof row === 'object'
|
|
70
|
-
? row[f.key]
|
|
71
|
-
: undefined;
|
|
72
|
-
const sub = displayValue(f, cell);
|
|
73
|
-
const text = sub.kind === 'text'
|
|
74
|
-
? sub.text
|
|
75
|
-
: sub.kind === 'chips'
|
|
76
|
-
? sub.items.join(', ')
|
|
77
|
-
: sub.kind === 'files'
|
|
78
|
-
? sub.items.map((f) => f.name).join(', ')
|
|
79
|
-
: sub.kind === 'rows'
|
|
80
|
-
? t('rowCount', { n: sub.rows.length })
|
|
81
|
-
: t('emptyValue');
|
|
82
|
-
return {
|
|
83
|
-
label: f.label ?? f.key,
|
|
84
|
-
text,
|
|
85
|
-
...(f.type === 'reference' && sub.kind === 'text' ? { reference: f } : {}),
|
|
86
|
-
};
|
|
87
|
-
})),
|
|
88
|
-
};
|
|
89
|
-
}
|
|
90
|
-
case 'rating':
|
|
91
|
-
return { kind: 'text', text: t('ratingValue', { n: String(value), max: ratingMax(field) }) };
|
|
92
|
-
case 'range':
|
|
93
|
-
case 'reference':
|
|
94
|
-
case 'text':
|
|
95
|
-
case 'textarea':
|
|
96
|
-
case 'markdown':
|
|
97
|
-
case 'number':
|
|
98
|
-
case 'currency':
|
|
99
|
-
case 'email':
|
|
100
|
-
case 'password':
|
|
101
|
-
case 'time':
|
|
102
|
-
case 'label':
|
|
103
|
-
case 'section':
|
|
104
|
-
return { kind: 'text', text: String(value) };
|
|
105
|
-
default: {
|
|
106
|
-
const _exhaustive = field.type;
|
|
107
|
-
return { kind: 'text', text: String(value) };
|
|
108
|
-
}
|
|
109
|
-
}
|
|
10
|
+
const own = fieldTypeSpec(registry, field.type)?.display;
|
|
11
|
+
if (own)
|
|
12
|
+
return { kind: 'text', text: own(value, field) };
|
|
13
|
+
const display = builtInType(field.type)?.display ?? asText;
|
|
14
|
+
return display(field, value, options, (sub, cell) => displayValue(sub, cell, sub.options, registry));
|
|
110
15
|
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import type { ApprovalDecision, NestedData, WorkflowDefinition } from '../types.js';
|
|
2
|
+
import { type WorkflowEnd } from './runtime.js';
|
|
3
|
+
/** Where a run stands: the step, and everything collected so far. */
|
|
4
|
+
export interface RunPosition {
|
|
5
|
+
form_name: string;
|
|
6
|
+
data: NestedData;
|
|
7
|
+
}
|
|
8
|
+
export type RunMove =
|
|
9
|
+
/** A form step was submitted (and validated: `validateSubmission`). On an approval step this approves. */
|
|
10
|
+
{
|
|
11
|
+
type: 'next';
|
|
12
|
+
}
|
|
13
|
+
/** An approval step was settled. `comment` is written to `Form_Name.comment` first. */
|
|
14
|
+
| {
|
|
15
|
+
type: 'decide';
|
|
16
|
+
decision: ApprovalDecision;
|
|
17
|
+
comment?: string;
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* Why a move left the run where it was:
|
|
21
|
+
* `not-a-step` the workflow has no such form, or the rules hide it for this data;
|
|
22
|
+
* `not-an-approval` a decision on a step that takes none;
|
|
23
|
+
* `comment-required` the step's `approval.comment` asks for one (spec 03 §4);
|
|
24
|
+
* `blocked` the only way on is a form the rules hid, the step itself, or data whose rules never settled.
|
|
25
|
+
*/
|
|
26
|
+
export type RunStayReason = 'not-a-step' | 'not-an-approval' | 'comment-required' | 'blocked';
|
|
27
|
+
/** `data` is the run's data after the move: the decision written, rule-cleared values gone. */
|
|
28
|
+
export type RunAdvance =
|
|
29
|
+
/** Forward to another step. */
|
|
30
|
+
{
|
|
31
|
+
kind: 'moved';
|
|
32
|
+
form_name: string;
|
|
33
|
+
data: NestedData;
|
|
34
|
+
}
|
|
35
|
+
/** A rejection sent the run back to the form `on_reject` names. */
|
|
36
|
+
| {
|
|
37
|
+
kind: 'bounced';
|
|
38
|
+
form_name: string;
|
|
39
|
+
data: NestedData;
|
|
40
|
+
} | {
|
|
41
|
+
kind: 'ended';
|
|
42
|
+
status: WorkflowEnd;
|
|
43
|
+
data: NestedData;
|
|
44
|
+
} | {
|
|
45
|
+
kind: 'stayed';
|
|
46
|
+
reason: RunStayReason;
|
|
47
|
+
data: NestedData;
|
|
48
|
+
};
|
|
49
|
+
/**
|
|
50
|
+
* Where a run goes from `at` on this move. Pure: nothing is kept, and `at.data` is not changed.
|
|
51
|
+
* A server stores the answer (`form_name` and `data`) and opens the step it names.
|
|
52
|
+
*/
|
|
53
|
+
export declare function advanceRun(workflow: WorkflowDefinition, at: RunPosition, move: RunMove): RunAdvance;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { currentForm, updateWorkflow, } from './runtime.js';
|
|
2
|
+
const VALID = { valid: true, errors: [] };
|
|
3
|
+
function messages(form_name, move) {
|
|
4
|
+
if (move.type === 'next')
|
|
5
|
+
return [{ type: 'next', validity: VALID, gate: false }];
|
|
6
|
+
const decide = { type: 'decide', decision: move.decision };
|
|
7
|
+
return move.comment === undefined
|
|
8
|
+
? [decide]
|
|
9
|
+
: [{ type: 'comment', form_name, value: move.comment }, decide];
|
|
10
|
+
}
|
|
11
|
+
function outcome(at, state) {
|
|
12
|
+
const data = state.derived.data;
|
|
13
|
+
if (state.ended)
|
|
14
|
+
return { kind: 'ended', status: state.ended, data };
|
|
15
|
+
if (state.current !== null && state.current !== at) {
|
|
16
|
+
const kind = state.direction === 'back' ? 'bounced' : 'moved';
|
|
17
|
+
return { kind, form_name: state.current, data };
|
|
18
|
+
}
|
|
19
|
+
const reason = state.approvalError ? 'comment-required' : 'blocked';
|
|
20
|
+
return { kind: 'stayed', reason, data };
|
|
21
|
+
}
|
|
22
|
+
export function advanceRun(workflow, at, move) {
|
|
23
|
+
const snapshot = {
|
|
24
|
+
workflow_id: workflow.workflow_id,
|
|
25
|
+
data: at.data,
|
|
26
|
+
current: at.form_name,
|
|
27
|
+
history: [],
|
|
28
|
+
ended: null,
|
|
29
|
+
};
|
|
30
|
+
let state = updateWorkflow(workflow, null, { type: 'restore', snapshot }).state;
|
|
31
|
+
const data = state.derived.data;
|
|
32
|
+
const form = currentForm(workflow, state);
|
|
33
|
+
if (form?.form_name !== at.form_name)
|
|
34
|
+
return { kind: 'stayed', reason: 'not-a-step', data };
|
|
35
|
+
if (move.type === 'decide' && form.kind !== 'approval') {
|
|
36
|
+
return { kind: 'stayed', reason: 'not-an-approval', data };
|
|
37
|
+
}
|
|
38
|
+
for (const msg of messages(at.form_name, move)) {
|
|
39
|
+
state = updateWorkflow(workflow, state, msg).state;
|
|
40
|
+
}
|
|
41
|
+
return outcome(at.form_name, state);
|
|
42
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { BuiltInFieldType, FieldTypeSpec, Registry } from './types.js';
|
|
2
|
+
/** Every built-in field type, in the order `BUILT_IN_TYPES` lists them. */
|
|
3
|
+
export declare const BUILT_IN_FIELD_TYPES: BuiltInFieldType[];
|
|
4
|
+
export declare function isBuiltInFieldType(type: unknown): type is BuiltInFieldType;
|
|
5
|
+
/**
|
|
6
|
+
* The app's own entry for a field type (spec 01 §5.1), or undefined: for a built-in type (those
|
|
7
|
+
* are never overridden) and for a name the registry does not have. Own entries only, so
|
|
8
|
+
* `toString` never resolves through `Object.prototype`.
|
|
9
|
+
*/
|
|
10
|
+
export declare function fieldTypeSpec(registry: Pick<Registry, 'fieldTypes'> | undefined, type: unknown): FieldTypeSpec | undefined;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { BUILT_IN_TYPES } from './built-in-types.js';
|
|
2
|
+
export const BUILT_IN_FIELD_TYPES = Object.keys(BUILT_IN_TYPES);
|
|
3
|
+
const BUILT_IN = new Set(BUILT_IN_FIELD_TYPES);
|
|
4
|
+
export function isBuiltInFieldType(type) {
|
|
5
|
+
return typeof type === 'string' && BUILT_IN.has(type);
|
|
6
|
+
}
|
|
7
|
+
export function fieldTypeSpec(registry, type) {
|
|
8
|
+
if (typeof type !== 'string' || BUILT_IN.has(type))
|
|
9
|
+
return undefined;
|
|
10
|
+
const types = registry?.fieldTypes;
|
|
11
|
+
return types && Object.hasOwn(types, type) ? types[type] : undefined;
|
|
12
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
export * from './types.js';
|
|
2
2
|
export { defineForm, defineWorkflow, type FormValues } from './form-values.js';
|
|
3
3
|
export { defaultValue } from './defaults.js';
|
|
4
|
+
export { BUILT_IN_FIELD_TYPES, fieldTypeSpec, isBuiltInFieldType } from './field-types.js';
|
|
5
|
+
export { BUILT_IN_TYPES, builtInType, type BuiltInTypeSpec } from './built-in-types.js';
|
|
4
6
|
export { approvalCommentRequired, approvalFields } from './approval.js';
|
|
7
|
+
export { askedTargets, settleStep } from './assignment.js';
|
|
5
8
|
export { isBlank, validateField, normalizeTagsValue, optionKeyLookup, rangeBounds, ratingMax, isTimeOfDay, isUploadedFile, } from './validators.js';
|
|
6
9
|
export { isUnsafePattern } from './pattern-safety.js';
|
|
7
10
|
export { isSafeUrl } from './urls.js';
|
|
@@ -13,6 +16,7 @@ export type { Locale, MessageCatalog, MessageKey } from './i18n.js';
|
|
|
13
16
|
export { evaluate } from './engine/evaluate.js';
|
|
14
17
|
export { resolveNext, stepFieldStates, visibleForms, walkPath } from './engine/graph.js';
|
|
15
18
|
export { currentForm, nextTarget, replayWorkflow, snapshotOf, updateWorkflow, type StepDirection, type WorkflowEnd, type WorkflowEvent, type WorkflowEventMap, type WorkflowMsg, type WorkflowSnapshot, type WorkflowState, type WorkflowTransition, type WorkflowUpdate, } from './engine/runtime.js';
|
|
19
|
+
export { advanceRun, type RunAdvance, type RunMove, type RunPosition, type RunStayReason, } from './engine/advance.js';
|
|
16
20
|
export { emptyFormState, formData, formFieldState, submitScriptErrors, updateForm, validateShownField, type FormEvent, type FormEventMap, type FormHost, type FormInput, type FormMsg, type FormState, type FormUpdate, } from './engine/form-session.js';
|
|
17
21
|
export { sameData } from './same-data.js';
|
|
18
22
|
export { conditionRowRefs, evalCondition, parseRowRef, readRef } from './engine/conditions.js';
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
export * from './types.js';
|
|
2
2
|
export { defineForm, defineWorkflow } from './form-values.js';
|
|
3
3
|
export { defaultValue } from './defaults.js';
|
|
4
|
+
export { BUILT_IN_FIELD_TYPES, fieldTypeSpec, isBuiltInFieldType } from './field-types.js';
|
|
5
|
+
export { BUILT_IN_TYPES, builtInType } from './built-in-types.js';
|
|
4
6
|
export { approvalCommentRequired, approvalFields } from './approval.js';
|
|
7
|
+
export { askedTargets, settleStep } from './assignment.js';
|
|
5
8
|
export { isBlank, validateField, normalizeTagsValue, optionKeyLookup, rangeBounds, ratingMax, isTimeOfDay, isUploadedFile, } from './validators.js';
|
|
6
9
|
export { isUnsafePattern } from './pattern-safety.js';
|
|
7
10
|
export { isSafeUrl } from './urls.js';
|
|
@@ -12,6 +15,7 @@ export { getCatalog, setCatalog, setLocale, t, withLocale } from './i18n.js';
|
|
|
12
15
|
export { evaluate } from './engine/evaluate.js';
|
|
13
16
|
export { resolveNext, stepFieldStates, visibleForms, walkPath } from './engine/graph.js';
|
|
14
17
|
export { currentForm, nextTarget, replayWorkflow, snapshotOf, updateWorkflow, } from './engine/runtime.js';
|
|
18
|
+
export { advanceRun, } from './engine/advance.js';
|
|
15
19
|
export { emptyFormState, formData, formFieldState, submitScriptErrors, updateForm, validateShownField, } from './engine/form-session.js';
|
|
16
20
|
export { sameData } from './same-data.js';
|
|
17
21
|
export { conditionRowRefs, evalCondition, parseRowRef, readRef } from './engine/conditions.js';
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import type { FieldDescriptor, FieldOption, UploadedFile, ValidationError } from './types.js';
|
|
2
|
+
export type TypeCheck = (field: FieldDescriptor, value: unknown) => ValidationError[];
|
|
3
|
+
/** Star count of a rating field: `max` when it is a whole number 1–10, else 5. */
|
|
4
|
+
export declare function ratingMax(field: FieldDescriptor): number;
|
|
5
|
+
/** A rating is a whole number of stars from 1 to its star count. */
|
|
6
|
+
export declare function ratingErrors(field: FieldDescriptor, value: unknown): ValidationError[];
|
|
7
|
+
/** A range field's slider bounds: numeric `min`/`max`/`step` or 0 / 100 / 1. */
|
|
8
|
+
export declare function rangeBounds(field: FieldDescriptor): {
|
|
9
|
+
min: number;
|
|
10
|
+
max: number;
|
|
11
|
+
step: number;
|
|
12
|
+
};
|
|
13
|
+
/** A range value is a finite number on the step grid counted from `min` (bounds: min/max sugar). */
|
|
14
|
+
export declare function rangeErrors(field: FieldDescriptor, value: unknown): ValidationError[];
|
|
15
|
+
/** A reference holds one record id: a string (whether it exists is `verifyReferences`' job). */
|
|
16
|
+
export declare function referenceErrors(field: FieldDescriptor, value: unknown): ValidationError[];
|
|
17
|
+
/** Numeric shape rules a schema implies without an explicit validator. */
|
|
18
|
+
export declare function numberErrors(field: FieldDescriptor, value: unknown): ValidationError[];
|
|
19
|
+
/**
|
|
20
|
+
* Canonical tags value (spec 01 §4 — tags): trimmed, non-empty strings,
|
|
21
|
+
* de-duplicated case-insensitively (first spelling wins), in entry order.
|
|
22
|
+
* With `options`, a tag matching an option key case-insensitively takes the
|
|
23
|
+
* option's key spelling, so case-sensitive rules (`contains "urgent"`) match.
|
|
24
|
+
* Non-array input (or non-string entries) never reaches canonical data —
|
|
25
|
+
* they're dropped rather than thrown, same as a stray non-string slipping
|
|
26
|
+
* into a `multiselect` array would be filtered by option-key matching.
|
|
27
|
+
* Exported: @20baht/validator applies the identical normalisation to the
|
|
28
|
+
* canonical `data` it persists, so client and server agree byte-for-byte.
|
|
29
|
+
*/
|
|
30
|
+
export declare function normalizeTagsValue(value: unknown, options?: readonly Pick<FieldOption, 'key'>[]): string[];
|
|
31
|
+
/** lower-cased option key -> the option's own key (first one wins). */
|
|
32
|
+
export declare function optionKeyLookup(options: readonly Pick<FieldOption, 'key'>[] | undefined): Map<string, string>;
|
|
33
|
+
/**
|
|
34
|
+
* Business rules on the NORMALISED tags array: `max_items` (chip count) and
|
|
35
|
+
* per-tag `max_length` (default 32). `allow_new` (restricting chips to the
|
|
36
|
+
* static `options` list) is enforced where the value is actually produced —
|
|
37
|
+
* the component blocks it interactively (spec: "Component"), and
|
|
38
|
+
* @20baht/validator re-checks it server-side the same way a dropdown's
|
|
39
|
+
* option membership is checked (skipped entirely for `options_from`, which
|
|
40
|
+
* neither side can resolve here) — never duplicated into this pure engine
|
|
41
|
+
* function, which has no static/dynamic options distinction to draw on.
|
|
42
|
+
*/
|
|
43
|
+
export declare function tagsErrors(field: FieldDescriptor, tags: string[]): ValidationError[];
|
|
44
|
+
/**
|
|
45
|
+
* Calendar constraints of a date field (`disabled_dates` / `disabled_weekdays`)
|
|
46
|
+
* — the picker greys them out, the engine enforces them so a submission that
|
|
47
|
+
* skipped the picker cannot land on a holiday. A range is checked end to end
|
|
48
|
+
* (see rangeInteriorDays for the cap).
|
|
49
|
+
*/
|
|
50
|
+
export declare function dateErrors(field: FieldDescriptor, value: unknown): ValidationError[];
|
|
51
|
+
/** A time of day, 24-hour, minutes and no seconds: `00:00` … `23:59`. */
|
|
52
|
+
export declare const isTimeOfDay: (value: unknown) => value is string;
|
|
53
|
+
/** time: the value is `HH:mm`; `min` / `max` (same shape) order it as text, which is the clock's order. */
|
|
54
|
+
export declare function timeErrors(field: FieldDescriptor, value: unknown): ValidationError[];
|
|
55
|
+
/**
|
|
56
|
+
* The serializable ref an uploader returns (spec 01 §13): a name, a finite non-negative size, a
|
|
57
|
+
* link-safe url and an optional type. The one check core's `file` validation and the
|
|
58
|
+
* server-side validator share.
|
|
59
|
+
*/
|
|
60
|
+
export declare function isUploadedFile(v: unknown): v is UploadedFile;
|
|
61
|
+
/**
|
|
62
|
+
* Validate uploaded-file REFS (metadata) — capture-mode File handles and
|
|
63
|
+
* anything not ref-shaped pass through untouched; actual byte checks belong
|
|
64
|
+
* to the upload endpoint.
|
|
65
|
+
*/
|
|
66
|
+
export declare function fileErrors(field: FieldDescriptor, value: unknown): ValidationError[];
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { dateModeOf, isDateDisabled, isoDaysOf, rangeInteriorDays } from './dates.js';
|
|
2
|
+
import { t } from './i18n.js';
|
|
3
|
+
import { isSafeUrl } from './urls.js';
|
|
4
|
+
function hasAtMostTwoDecimals(n) {
|
|
5
|
+
const cents = n * 100;
|
|
6
|
+
return Math.abs(cents - Math.round(cents)) <= 8 * Number.EPSILON * Math.max(1, Math.abs(cents));
|
|
7
|
+
}
|
|
8
|
+
export function ratingMax(field) {
|
|
9
|
+
const max = field.max;
|
|
10
|
+
return typeof max === 'number' && Number.isInteger(max) && max >= 1 && max <= 10 ? max : 5;
|
|
11
|
+
}
|
|
12
|
+
export function ratingErrors(field, value) {
|
|
13
|
+
const max = ratingMax(field);
|
|
14
|
+
const ok = typeof value === 'number' && Number.isInteger(value) && value >= 1 && value <= max;
|
|
15
|
+
return ok ? [] : [{ key: field.key, message: t('ratingRange', { max }) }];
|
|
16
|
+
}
|
|
17
|
+
export function rangeBounds(field) {
|
|
18
|
+
const num = (v, fallback) => typeof v === 'number' && Number.isFinite(v) ? v : fallback;
|
|
19
|
+
const step = num(field.step, 1);
|
|
20
|
+
return { min: num(field.min, 0), max: num(field.max, 100), step: step > 0 ? step : 1 };
|
|
21
|
+
}
|
|
22
|
+
export function rangeErrors(field, value) {
|
|
23
|
+
if (typeof value !== 'number' || !Number.isFinite(value)) {
|
|
24
|
+
return [{ key: field.key, message: t('pattern') }];
|
|
25
|
+
}
|
|
26
|
+
const { min, step } = rangeBounds(field);
|
|
27
|
+
const steps = (value - min) / step;
|
|
28
|
+
const onGrid = Math.abs(steps - Math.round(steps)) <= 1e-9 * Math.max(1, Math.abs(steps));
|
|
29
|
+
return onGrid ? [] : [{ key: field.key, message: t('stepOf', { step }) }];
|
|
30
|
+
}
|
|
31
|
+
export function referenceErrors(field, value) {
|
|
32
|
+
return typeof value === 'string' ? [] : [{ key: field.key, message: t('pattern') }];
|
|
33
|
+
}
|
|
34
|
+
export function numberErrors(field, value) {
|
|
35
|
+
if (typeof value !== 'number')
|
|
36
|
+
return [];
|
|
37
|
+
if (!Number.isFinite(value))
|
|
38
|
+
return [{ key: field.key, message: t('pattern') }];
|
|
39
|
+
if (field.type === 'currency' && !hasAtMostTwoDecimals(value)) {
|
|
40
|
+
return [{ key: field.key, message: t('decimals') }];
|
|
41
|
+
}
|
|
42
|
+
if (field.integer && !Number.isInteger(value))
|
|
43
|
+
return [{ key: field.key, message: t('integer') }];
|
|
44
|
+
return [];
|
|
45
|
+
}
|
|
46
|
+
export function normalizeTagsValue(value, options) {
|
|
47
|
+
if (!Array.isArray(value))
|
|
48
|
+
return [];
|
|
49
|
+
const keyFor = optionKeyLookup(options);
|
|
50
|
+
const seen = new Set();
|
|
51
|
+
const out = [];
|
|
52
|
+
for (const raw of value) {
|
|
53
|
+
if (typeof raw !== 'string')
|
|
54
|
+
continue;
|
|
55
|
+
const trimmed = raw.trim();
|
|
56
|
+
if (!trimmed)
|
|
57
|
+
continue;
|
|
58
|
+
const lower = trimmed.toLowerCase();
|
|
59
|
+
const tag = keyFor.get(lower) ?? trimmed;
|
|
60
|
+
if (seen.has(lower))
|
|
61
|
+
continue;
|
|
62
|
+
seen.add(lower);
|
|
63
|
+
out.push(tag);
|
|
64
|
+
}
|
|
65
|
+
return out;
|
|
66
|
+
}
|
|
67
|
+
export function optionKeyLookup(options) {
|
|
68
|
+
const map = new Map();
|
|
69
|
+
for (const o of options ?? []) {
|
|
70
|
+
const lower = o.key.toLowerCase();
|
|
71
|
+
if (!map.has(lower))
|
|
72
|
+
map.set(lower, o.key);
|
|
73
|
+
}
|
|
74
|
+
return map;
|
|
75
|
+
}
|
|
76
|
+
export function tagsErrors(field, tags) {
|
|
77
|
+
const errors = [];
|
|
78
|
+
if (field.max_items !== undefined && tags.length > field.max_items) {
|
|
79
|
+
errors.push({ key: field.key, message: t('maxItems', { n: field.max_items }) });
|
|
80
|
+
}
|
|
81
|
+
const maxLen = field.max_length ?? 32;
|
|
82
|
+
if (tags.some((tag) => tag.length > maxLen)) {
|
|
83
|
+
errors.push({ key: field.key, message: t('tagTooLong', { n: maxLen }) });
|
|
84
|
+
}
|
|
85
|
+
return errors;
|
|
86
|
+
}
|
|
87
|
+
export function dateErrors(field, value) {
|
|
88
|
+
if (!field.disabled_dates?.length && !field.disabled_weekdays?.length)
|
|
89
|
+
return [];
|
|
90
|
+
const days = isoDaysOf(value);
|
|
91
|
+
if (dateModeOf(field) === 'range' && days.length === 2) {
|
|
92
|
+
days.push(...rangeInteriorDays(days[0], days[1]));
|
|
93
|
+
}
|
|
94
|
+
return days.some((d) => isDateDisabled(field, d))
|
|
95
|
+
? [{ key: field.key, message: t('dateDisabled') }]
|
|
96
|
+
: [];
|
|
97
|
+
}
|
|
98
|
+
export const isTimeOfDay = (value) => typeof value === 'string' && /^(?:[01]\d|2[0-3]):[0-5]\d$/.test(value);
|
|
99
|
+
export function timeErrors(field, value) {
|
|
100
|
+
return isTimeOfDay(value) ? [] : [{ key: field.key, message: t('timeInvalid') }];
|
|
101
|
+
}
|
|
102
|
+
export function isUploadedFile(v) {
|
|
103
|
+
if (v === null || typeof v !== 'object')
|
|
104
|
+
return false;
|
|
105
|
+
const r = v;
|
|
106
|
+
return (typeof r.name === 'string' &&
|
|
107
|
+
typeof r.size === 'number' &&
|
|
108
|
+
Number.isFinite(r.size) &&
|
|
109
|
+
r.size >= 0 &&
|
|
110
|
+
typeof r.url === 'string' &&
|
|
111
|
+
isSafeUrl(r.url) &&
|
|
112
|
+
(r.type === undefined || typeof r.type === 'string'));
|
|
113
|
+
}
|
|
114
|
+
function acceptMatches(accept, name, type) {
|
|
115
|
+
return accept.split(',').some((raw) => {
|
|
116
|
+
const token = raw.trim().toLowerCase();
|
|
117
|
+
if (!token)
|
|
118
|
+
return false;
|
|
119
|
+
if (token.startsWith('.'))
|
|
120
|
+
return name.toLowerCase().endsWith(token);
|
|
121
|
+
if (token.endsWith('/*'))
|
|
122
|
+
return type.toLowerCase().startsWith(token.slice(0, -1));
|
|
123
|
+
return type.toLowerCase() === token;
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
export function fileErrors(field, value) {
|
|
127
|
+
const errors = [];
|
|
128
|
+
for (const ref of (Array.isArray(value) ? value : [value]).filter(isUploadedFile)) {
|
|
129
|
+
if (field.max_size !== undefined && ref.size > field.max_size) {
|
|
130
|
+
errors.push({ key: field.key, message: t('fileTooLarge') });
|
|
131
|
+
}
|
|
132
|
+
if (field.accept && !acceptMatches(field.accept, ref.name, ref.type ?? '')) {
|
|
133
|
+
errors.push({ key: field.key, message: t('fileTypeNotAllowed') });
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
return errors;
|
|
137
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { FieldDescriptor, FieldOption } from './types.js';
|
|
2
|
+
export type DisplayValue = {
|
|
3
|
+
kind: 'empty';
|
|
4
|
+
} | {
|
|
5
|
+
kind: 'text';
|
|
6
|
+
text: string;
|
|
7
|
+
} | {
|
|
8
|
+
kind: 'chips';
|
|
9
|
+
items: string[];
|
|
10
|
+
}
|
|
11
|
+
/** Files: each name, and a link when it is an uploaded ref with a safe url. */
|
|
12
|
+
| {
|
|
13
|
+
kind: 'files';
|
|
14
|
+
items: {
|
|
15
|
+
name: string;
|
|
16
|
+
url: string | null;
|
|
17
|
+
}[];
|
|
18
|
+
}
|
|
19
|
+
/** Repeater rows: one entry per row, each a list of `label: value` pairs. */
|
|
20
|
+
| {
|
|
21
|
+
kind: 'rows';
|
|
22
|
+
/** `reference`: the column, when `text` is a stored id its lookup can turn into a label. */
|
|
23
|
+
rows: {
|
|
24
|
+
label: string;
|
|
25
|
+
text: string;
|
|
26
|
+
reference?: FieldDescriptor;
|
|
27
|
+
}[][];
|
|
28
|
+
};
|
|
29
|
+
export declare const isEmptyDisplay: (value: unknown) => boolean;
|
|
30
|
+
/**
|
|
31
|
+
* One type's read-only rendering of a value that is there. `displayOf` renders another field
|
|
32
|
+
* (a repeater's cells) without this module importing the table it is listed in.
|
|
33
|
+
*/
|
|
34
|
+
export type TypeDisplay = (field: FieldDescriptor, value: unknown, options: FieldOption[] | undefined, displayOf: (field: FieldDescriptor, value: unknown) => DisplayValue) => DisplayValue;
|
|
35
|
+
export declare const asText: TypeDisplay;
|
|
36
|
+
export declare const asYesNo: TypeDisplay;
|
|
37
|
+
export declare const asOptionLabel: TypeDisplay;
|
|
38
|
+
/**
|
|
39
|
+
* tags: free text IS the value; labelFor only substitutes an option's label when the tag
|
|
40
|
+
* happens to match one, the same fallback multiselect relies on for a key with no option.
|
|
41
|
+
*/
|
|
42
|
+
export declare const asChips: TypeDisplay;
|
|
43
|
+
export declare const asDate: TypeDisplay;
|
|
44
|
+
export declare const asFiles: TypeDisplay;
|
|
45
|
+
export declare const asRows: TypeDisplay;
|
|
46
|
+
export declare const asRating: TypeDisplay;
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { t } from './i18n.js';
|
|
2
|
+
import { ratingMax } from './type-checks.js';
|
|
3
|
+
import { isSafeUrl } from './urls.js';
|
|
4
|
+
export const isEmptyDisplay = (value) => value === null ||
|
|
5
|
+
value === undefined ||
|
|
6
|
+
value === '' ||
|
|
7
|
+
(Array.isArray(value) && value.length === 0);
|
|
8
|
+
const labelFor = (options, key) => {
|
|
9
|
+
const found = options?.find((o) => o.key === String(key));
|
|
10
|
+
return found ? found.label : String(key);
|
|
11
|
+
};
|
|
12
|
+
const fileName = (file) => {
|
|
13
|
+
if (file && typeof file === 'object' && 'name' in file) {
|
|
14
|
+
return String(file.name);
|
|
15
|
+
}
|
|
16
|
+
return String(file);
|
|
17
|
+
};
|
|
18
|
+
const formatDate = (raw) => {
|
|
19
|
+
const asDate = new Date(raw);
|
|
20
|
+
if (Number.isNaN(asDate.getTime()))
|
|
21
|
+
return raw;
|
|
22
|
+
return /^\d{4}-\d{2}-\d{2}$/.test(raw)
|
|
23
|
+
? new Date(raw + 'T00:00:00').toLocaleDateString()
|
|
24
|
+
: asDate.toLocaleString();
|
|
25
|
+
};
|
|
26
|
+
export const asText = (_field, value) => ({ kind: 'text', text: String(value) });
|
|
27
|
+
export const asYesNo = (_field, value) => ({
|
|
28
|
+
kind: 'text',
|
|
29
|
+
text: value ? t('yes') : t('no'),
|
|
30
|
+
});
|
|
31
|
+
export const asOptionLabel = (_field, value, options) => ({
|
|
32
|
+
kind: 'text',
|
|
33
|
+
text: labelFor(options, value),
|
|
34
|
+
});
|
|
35
|
+
export const asChips = (_field, value, options) => {
|
|
36
|
+
const keys = Array.isArray(value) ? value : [value];
|
|
37
|
+
return { kind: 'chips', items: keys.map((k) => labelFor(options, k)) };
|
|
38
|
+
};
|
|
39
|
+
export const asDate = (field, value) => {
|
|
40
|
+
if (!Array.isArray(value))
|
|
41
|
+
return { kind: 'text', text: formatDate(String(value)) };
|
|
42
|
+
const days = value.map((v) => formatDate(String(v)));
|
|
43
|
+
return field.date_mode === 'range' && days.length === 2
|
|
44
|
+
? { kind: 'text', text: `${days[0]} – ${days[1]}` }
|
|
45
|
+
: { kind: 'chips', items: days };
|
|
46
|
+
};
|
|
47
|
+
export const asFiles = (_field, value) => {
|
|
48
|
+
const files = Array.isArray(value) ? value : [value];
|
|
49
|
+
return {
|
|
50
|
+
kind: 'files',
|
|
51
|
+
items: files.map((file) => {
|
|
52
|
+
const raw = file !== null && typeof file === 'object' && 'url' in file ? file.url : undefined;
|
|
53
|
+
const url = typeof raw === 'string' ? raw : null;
|
|
54
|
+
return { name: fileName(file), url: url !== null && isSafeUrl(url) ? url : null };
|
|
55
|
+
}),
|
|
56
|
+
};
|
|
57
|
+
};
|
|
58
|
+
function cellText(sub) {
|
|
59
|
+
switch (sub.kind) {
|
|
60
|
+
case 'text':
|
|
61
|
+
return sub.text;
|
|
62
|
+
case 'chips':
|
|
63
|
+
return sub.items.join(', ');
|
|
64
|
+
case 'files':
|
|
65
|
+
return sub.items.map((f) => f.name).join(', ');
|
|
66
|
+
case 'rows':
|
|
67
|
+
return t('rowCount', { n: sub.rows.length });
|
|
68
|
+
case 'empty':
|
|
69
|
+
return t('emptyValue');
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
export const asRows = (field, value, _options, displayOf) => {
|
|
73
|
+
const rows = Array.isArray(value) ? value : [];
|
|
74
|
+
const subFields = (field.fields ?? []).filter((f) => f.type !== 'label' && f.type !== 'section' && !f.hidden);
|
|
75
|
+
return {
|
|
76
|
+
kind: 'rows',
|
|
77
|
+
rows: rows.map((row) => subFields.map((f) => {
|
|
78
|
+
const cell = row !== null && typeof row === 'object'
|
|
79
|
+
? row[f.key]
|
|
80
|
+
: undefined;
|
|
81
|
+
const sub = displayOf(f, cell);
|
|
82
|
+
return {
|
|
83
|
+
label: f.label ?? f.key,
|
|
84
|
+
text: cellText(sub),
|
|
85
|
+
...(f.type === 'reference' && sub.kind === 'text' ? { reference: f } : {}),
|
|
86
|
+
};
|
|
87
|
+
})),
|
|
88
|
+
};
|
|
89
|
+
};
|
|
90
|
+
export const asRating = (field, value) => ({
|
|
91
|
+
kind: 'text',
|
|
92
|
+
text: t('ratingValue', { n: String(value), max: ratingMax(field) }),
|
|
93
|
+
});
|
package/dist/types.d.ts
CHANGED
|
@@ -1,5 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Field types an app adds to its own registry (spec 01 §5.1), named for TypeScript by
|
|
3
|
+
* declaration merging:
|
|
4
|
+
*
|
|
5
|
+
* declare module '@20baht/engine' {
|
|
6
|
+
* interface CustomFieldTypes { account_number: true }
|
|
7
|
+
* }
|
|
8
|
+
*
|
|
9
|
+
* JSON that is parsed, not written in TS, needs none of it.
|
|
10
|
+
*/
|
|
11
|
+
export interface CustomFieldTypes {
|
|
12
|
+
}
|
|
13
|
+
/** A built-in control type, or one the app registered. */
|
|
14
|
+
export type FieldType = BuiltInFieldType | keyof CustomFieldTypes;
|
|
1
15
|
/** Control types supported by v1 (spec 01 §2). */
|
|
2
|
-
export type
|
|
16
|
+
export type BuiltInFieldType = 'text' | 'textarea' | 'markdown' | 'number' | 'currency' | 'email' | 'password' | 'dropdown' | 'multiselect' | 'checkbox' | 'radio' | 'toggle' | 'date' | 'time' | 'file' | 'label' | 'section' | 'repeater' | 'tags' | 'rating' | 'range' | 'reference';
|
|
3
17
|
export type FieldWidth = '1/4' | '1/2' | '3/4' | 'full';
|
|
4
18
|
/** `date` field selection mode (spec 01 §2). */
|
|
5
19
|
export type DateMode = 'single' | 'range' | 'multiple';
|
|
@@ -285,6 +299,75 @@ export interface ApprovalConfig {
|
|
|
285
299
|
form: string;
|
|
286
300
|
};
|
|
287
301
|
}
|
|
302
|
+
/**
|
|
303
|
+
* One party an approval step is asked of. The engine owns these words and never who they point
|
|
304
|
+
* at: a host answers that. `when` (the rules' condition tree) asks the target only for requests
|
|
305
|
+
* it holds for.
|
|
306
|
+
*/
|
|
307
|
+
export type AssignTarget = ({
|
|
308
|
+
type: 'requester';
|
|
309
|
+
}
|
|
310
|
+
/** The person named in a submitted field of an earlier form. */
|
|
311
|
+
| {
|
|
312
|
+
type: 'field';
|
|
313
|
+
value: string;
|
|
314
|
+
}
|
|
315
|
+
/** A group. With `task`, one piece of work of its own, labelled with it. */
|
|
316
|
+
| {
|
|
317
|
+
type: 'group';
|
|
318
|
+
value: string;
|
|
319
|
+
task?: string;
|
|
320
|
+
}
|
|
321
|
+
/** Everyone holding the role. */
|
|
322
|
+
| {
|
|
323
|
+
type: 'role';
|
|
324
|
+
value: string;
|
|
325
|
+
}
|
|
326
|
+
/** The requester's line manager, `hops` levels up (default 1). */
|
|
327
|
+
| {
|
|
328
|
+
type: 'manager';
|
|
329
|
+
hops?: number;
|
|
330
|
+
}
|
|
331
|
+
/** Head of the named department, or of the requester's own. */
|
|
332
|
+
| {
|
|
333
|
+
type: 'head';
|
|
334
|
+
department?: string;
|
|
335
|
+
}
|
|
336
|
+
/** One piece of work per row of a repeater; the other keys name the row's columns. */
|
|
337
|
+
| {
|
|
338
|
+
type: 'rows';
|
|
339
|
+
field: string;
|
|
340
|
+
assignee?: string;
|
|
341
|
+
group?: string;
|
|
342
|
+
label?: string;
|
|
343
|
+
manager_of_assignee?: boolean;
|
|
344
|
+
}
|
|
345
|
+
/** A target only the host understands, by the name it registered. */
|
|
346
|
+
| {
|
|
347
|
+
type: 'custom';
|
|
348
|
+
fn: string;
|
|
349
|
+
params?: Record<string, unknown>;
|
|
350
|
+
}) & {
|
|
351
|
+
when?: Condition;
|
|
352
|
+
};
|
|
353
|
+
/** When an approval step as a whole is settled (spec 03 §4.1). */
|
|
354
|
+
export type CompletionRule = 'any' | 'all' | {
|
|
355
|
+
quorum: number;
|
|
356
|
+
};
|
|
357
|
+
export interface Assignment {
|
|
358
|
+
/** Shown where the step's work is listed; default = the form's `form_name`. */
|
|
359
|
+
label?: string;
|
|
360
|
+
assign_to: AssignTarget[];
|
|
361
|
+
rule: CompletionRule;
|
|
362
|
+
}
|
|
363
|
+
/**
|
|
364
|
+
* Where one person asked on a step stands. `unassigned`: the target resolved to nobody, so it
|
|
365
|
+
* counts and can never decide. Work that no longer counts (cancelled, or from an earlier visit
|
|
366
|
+
* to the step) is left out by the caller.
|
|
367
|
+
*/
|
|
368
|
+
export type AskedState = 'waiting' | ApprovalDecision | 'unassigned';
|
|
369
|
+
/** What the people asked on a step add up to. */
|
|
370
|
+
export type StepOutcome = 'pending' | ApprovalDecision;
|
|
288
371
|
/** A form inside a workflow: adds its position in the linear order. */
|
|
289
372
|
export interface WorkflowForm extends FormDefinition {
|
|
290
373
|
order: number;
|
|
@@ -295,6 +378,8 @@ export interface WorkflowForm extends FormDefinition {
|
|
|
295
378
|
*/
|
|
296
379
|
kind?: 'form' | 'approval';
|
|
297
380
|
approval?: ApprovalConfig;
|
|
381
|
+
/** Who decides this approval step (spec 03 §4.1). Read by a server, not by `<baht-workflow>`. */
|
|
382
|
+
assignment?: Assignment;
|
|
298
383
|
/** Name of one of this form's `views` to render for this step (display only). */
|
|
299
384
|
view?: string;
|
|
300
385
|
/** Feature flag gating this whole step (spec 01 §12). */
|
|
@@ -491,7 +576,29 @@ export interface UploadedFile {
|
|
|
491
576
|
* descriptor being validated. A one-argument `(value) => …` still fits.
|
|
492
577
|
*/
|
|
493
578
|
export type CustomValidator = (value: unknown, data: Record<string, unknown>, field: FieldDescriptor) => string | null;
|
|
579
|
+
/**
|
|
580
|
+
* A field type an app adds (`registry.fieldTypes[type]`, spec 01 §5.1). The browser and the
|
|
581
|
+
* server are handed the same entry, so both check a value alike.
|
|
582
|
+
*/
|
|
583
|
+
export interface FieldTypeSpec {
|
|
584
|
+
/**
|
|
585
|
+
* The custom element that renders the control (browser only; the server ignores it). It is
|
|
586
|
+
* given what a built-in control is given, as properties: `field`, `value`, `disabled`,
|
|
587
|
+
* `readonly`, `required`, `showOptional`, `error`, `debounce`; and it tells a new value with a
|
|
588
|
+
* bubbling `baht-input` event whose `detail` is `{ value }`.
|
|
589
|
+
*/
|
|
590
|
+
tag?: string;
|
|
591
|
+
/**
|
|
592
|
+
* Is this a value of the type? Null when it is, else the message. Never called with an empty
|
|
593
|
+
* value (`required` owns emptiness). Without it any value passes.
|
|
594
|
+
*/
|
|
595
|
+
check?: (value: unknown, field: FieldDescriptor) => string | null;
|
|
596
|
+
/** The value as read-only text. Default: `String(value)`. */
|
|
597
|
+
display?: (value: unknown, field: FieldDescriptor) => string;
|
|
598
|
+
}
|
|
494
599
|
export interface Registry {
|
|
600
|
+
/** Field types of the app's own, by `type` name: see `FieldTypeSpec`. A built-in name is ignored. */
|
|
601
|
+
fieldTypes?: Record<string, FieldTypeSpec>;
|
|
495
602
|
formatters?: Record<string, (value: unknown) => unknown>;
|
|
496
603
|
/** `custom` validators by name: see `CustomValidator`. */
|
|
497
604
|
validators?: Record<string, CustomValidator>;
|
package/dist/validators.d.ts
CHANGED
|
@@ -1,39 +1,10 @@
|
|
|
1
|
-
import type { DerivedFieldState, FieldDescriptor,
|
|
1
|
+
import type { DerivedFieldState, FieldDescriptor, Registry, ValidationError } from './types.js';
|
|
2
2
|
/** Text with nothing visible in it: what `required` treats as empty. */
|
|
3
3
|
export declare function isBlank(text: string): boolean;
|
|
4
|
-
/** Star count of a rating field: `max` when it is a whole number 1–10, else 5. */
|
|
5
|
-
export declare function ratingMax(field: FieldDescriptor): number;
|
|
6
|
-
/** A range field's slider bounds: numeric `min`/`max`/`step` or 0 / 100 / 1. */
|
|
7
|
-
export declare function rangeBounds(field: FieldDescriptor): {
|
|
8
|
-
min: number;
|
|
9
|
-
max: number;
|
|
10
|
-
step: number;
|
|
11
|
-
};
|
|
12
|
-
/**
|
|
13
|
-
* Canonical tags value (spec 01 §4 — tags): trimmed, non-empty strings,
|
|
14
|
-
* de-duplicated case-insensitively (first spelling wins), in entry order.
|
|
15
|
-
* With `options`, a tag matching an option key case-insensitively takes the
|
|
16
|
-
* option's key spelling, so case-sensitive rules (`contains "urgent"`) match.
|
|
17
|
-
* Non-array input (or non-string entries) never reaches canonical data —
|
|
18
|
-
* they're dropped rather than thrown, same as a stray non-string slipping
|
|
19
|
-
* into a `multiselect` array would be filtered by option-key matching.
|
|
20
|
-
* Exported: @20baht/validator applies the identical normalisation to the
|
|
21
|
-
* canonical `data` it persists, so client and server agree byte-for-byte.
|
|
22
|
-
*/
|
|
23
|
-
export declare function normalizeTagsValue(value: unknown, options?: readonly Pick<FieldOption, 'key'>[]): string[];
|
|
24
|
-
/** lower-cased option key -> the option's own key (first one wins). */
|
|
25
|
-
export declare function optionKeyLookup(options: readonly Pick<FieldOption, 'key'>[] | undefined): Map<string, string>;
|
|
26
4
|
/**
|
|
27
5
|
* `rowStates` (repeaters only) are the rule-derived states of the row sub-fields,
|
|
28
6
|
* keyed `key[i].sub` (spec 02 §2a): a hidden one is skipped, a `required`
|
|
29
7
|
* override replaces the descriptor's.
|
|
30
8
|
*/
|
|
31
9
|
export declare function validateField(field: FieldDescriptor, value: unknown, registry?: Registry, data?: Record<string, unknown>, rowStates?: Record<string, DerivedFieldState>): ValidationError[];
|
|
32
|
-
|
|
33
|
-
export declare const isTimeOfDay: (value: unknown) => value is string;
|
|
34
|
-
/**
|
|
35
|
-
* The serializable ref an uploader returns (spec 01 §13): a name, a finite non-negative size, a
|
|
36
|
-
* link-safe url and an optional type. The one check core's `file` validation and the
|
|
37
|
-
* server-side validator share.
|
|
38
|
-
*/
|
|
39
|
-
export declare function isUploadedFile(v: unknown): v is UploadedFile;
|
|
10
|
+
export { isTimeOfDay, isUploadedFile, normalizeTagsValue, optionKeyLookup, rangeBounds, ratingMax, } from './type-checks.js';
|
package/dist/validators.js
CHANGED
|
@@ -1,20 +1,15 @@
|
|
|
1
|
+
import { builtInType } from './built-in-types.js';
|
|
1
2
|
import { defaultValue } from './defaults.js';
|
|
3
|
+
import { normalizeTagsValue, rangeBounds } from './type-checks.js';
|
|
4
|
+
import { fieldTypeSpec } from './field-types.js';
|
|
2
5
|
import { rowSubFields } from './keys.js';
|
|
3
6
|
import { compareValues } from './engine/conditions.js';
|
|
4
7
|
import { isUnsafePattern } from './pattern-safety.js';
|
|
5
|
-
import { dateModeOf, isDateDisabled, isoDaysOf, rangeInteriorDays } from './dates.js';
|
|
6
8
|
import { t } from './i18n.js';
|
|
7
|
-
import { isAllowedUrl
|
|
9
|
+
import { isAllowedUrl } from './urls.js';
|
|
8
10
|
const DEFAULT_URL_SCHEMES = ['http', 'https'];
|
|
9
11
|
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
10
12
|
const BLANK_RE = /^[\s\u00AD\u180E\u200B-\u200F\u2060-\u2064\uFEFF]*$/;
|
|
11
|
-
const DEFAULT_MAX_LENGTH = {
|
|
12
|
-
text: 1024,
|
|
13
|
-
email: 1024,
|
|
14
|
-
password: 1024,
|
|
15
|
-
textarea: 10_000,
|
|
16
|
-
markdown: 100_000,
|
|
17
|
-
};
|
|
18
13
|
const PATTERN_INPUT_CAP = 1024;
|
|
19
14
|
const PATTERN_INPUT_CEILING = 10_000;
|
|
20
15
|
const PATTERN_CACHE_LIMIT = 500;
|
|
@@ -37,7 +32,7 @@ function effectiveValidators(field) {
|
|
|
37
32
|
const has = (t) => list.some((v) => v.type === t);
|
|
38
33
|
if (field.required && !has('required'))
|
|
39
34
|
list.push({ type: 'required' });
|
|
40
|
-
const maxLength = field.max_length ??
|
|
35
|
+
const maxLength = field.max_length ?? builtInType(field.type)?.maxLength;
|
|
41
36
|
if (maxLength !== undefined && !has('maxLength'))
|
|
42
37
|
list.push({ type: 'maxLength', value: maxLength });
|
|
43
38
|
if (field.min_length !== undefined && !has('minLength'))
|
|
@@ -140,48 +135,6 @@ const CHECKERS = {
|
|
|
140
135
|
custom: checkCustom,
|
|
141
136
|
url: checkUrl,
|
|
142
137
|
};
|
|
143
|
-
function hasAtMostTwoDecimals(n) {
|
|
144
|
-
const cents = n * 100;
|
|
145
|
-
return Math.abs(cents - Math.round(cents)) <= 8 * Number.EPSILON * Math.max(1, Math.abs(cents));
|
|
146
|
-
}
|
|
147
|
-
export function ratingMax(field) {
|
|
148
|
-
const max = field.max;
|
|
149
|
-
return typeof max === 'number' && Number.isInteger(max) && max >= 1 && max <= 10 ? max : 5;
|
|
150
|
-
}
|
|
151
|
-
function ratingErrors(field, value) {
|
|
152
|
-
const max = ratingMax(field);
|
|
153
|
-
const ok = typeof value === 'number' && Number.isInteger(value) && value >= 1 && value <= max;
|
|
154
|
-
return ok ? [] : [{ key: field.key, message: t('ratingRange', { max }) }];
|
|
155
|
-
}
|
|
156
|
-
export function rangeBounds(field) {
|
|
157
|
-
const num = (v, fallback) => typeof v === 'number' && Number.isFinite(v) ? v : fallback;
|
|
158
|
-
const step = num(field.step, 1);
|
|
159
|
-
return { min: num(field.min, 0), max: num(field.max, 100), step: step > 0 ? step : 1 };
|
|
160
|
-
}
|
|
161
|
-
function rangeErrors(field, value) {
|
|
162
|
-
if (typeof value !== 'number' || !Number.isFinite(value)) {
|
|
163
|
-
return [{ key: field.key, message: t('pattern') }];
|
|
164
|
-
}
|
|
165
|
-
const { min, step } = rangeBounds(field);
|
|
166
|
-
const steps = (value - min) / step;
|
|
167
|
-
const onGrid = Math.abs(steps - Math.round(steps)) <= 1e-9 * Math.max(1, Math.abs(steps));
|
|
168
|
-
return onGrid ? [] : [{ key: field.key, message: t('stepOf', { step }) }];
|
|
169
|
-
}
|
|
170
|
-
function referenceErrors(field, value) {
|
|
171
|
-
return typeof value === 'string' ? [] : [{ key: field.key, message: t('pattern') }];
|
|
172
|
-
}
|
|
173
|
-
function numberErrors(field, value) {
|
|
174
|
-
if (typeof value !== 'number')
|
|
175
|
-
return [];
|
|
176
|
-
if (!Number.isFinite(value))
|
|
177
|
-
return [{ key: field.key, message: t('pattern') }];
|
|
178
|
-
if (field.type === 'currency' && !hasAtMostTwoDecimals(value)) {
|
|
179
|
-
return [{ key: field.key, message: t('decimals') }];
|
|
180
|
-
}
|
|
181
|
-
if (field.integer && !Number.isInteger(value))
|
|
182
|
-
return [{ key: field.key, message: t('integer') }];
|
|
183
|
-
return [];
|
|
184
|
-
}
|
|
185
138
|
const PATTERN_CACHE = new Map();
|
|
186
139
|
function compilePattern(source) {
|
|
187
140
|
let re = PATTERN_CACHE.get(source);
|
|
@@ -203,47 +156,6 @@ function compilePattern(source) {
|
|
|
203
156
|
}
|
|
204
157
|
return re;
|
|
205
158
|
}
|
|
206
|
-
export function normalizeTagsValue(value, options) {
|
|
207
|
-
if (!Array.isArray(value))
|
|
208
|
-
return [];
|
|
209
|
-
const keyFor = optionKeyLookup(options);
|
|
210
|
-
const seen = new Set();
|
|
211
|
-
const out = [];
|
|
212
|
-
for (const raw of value) {
|
|
213
|
-
if (typeof raw !== 'string')
|
|
214
|
-
continue;
|
|
215
|
-
const trimmed = raw.trim();
|
|
216
|
-
if (!trimmed)
|
|
217
|
-
continue;
|
|
218
|
-
const lower = trimmed.toLowerCase();
|
|
219
|
-
const tag = keyFor.get(lower) ?? trimmed;
|
|
220
|
-
if (seen.has(lower))
|
|
221
|
-
continue;
|
|
222
|
-
seen.add(lower);
|
|
223
|
-
out.push(tag);
|
|
224
|
-
}
|
|
225
|
-
return out;
|
|
226
|
-
}
|
|
227
|
-
export function optionKeyLookup(options) {
|
|
228
|
-
const map = new Map();
|
|
229
|
-
for (const o of options ?? []) {
|
|
230
|
-
const lower = o.key.toLowerCase();
|
|
231
|
-
if (!map.has(lower))
|
|
232
|
-
map.set(lower, o.key);
|
|
233
|
-
}
|
|
234
|
-
return map;
|
|
235
|
-
}
|
|
236
|
-
function tagsErrors(field, tags) {
|
|
237
|
-
const errors = [];
|
|
238
|
-
if (field.max_items !== undefined && tags.length > field.max_items) {
|
|
239
|
-
errors.push({ key: field.key, message: t('maxItems', { n: field.max_items }) });
|
|
240
|
-
}
|
|
241
|
-
const maxLen = field.max_length ?? 32;
|
|
242
|
-
if (tags.some((tag) => tag.length > maxLen)) {
|
|
243
|
-
errors.push({ key: field.key, message: t('tagTooLong', { n: maxLen }) });
|
|
244
|
-
}
|
|
245
|
-
return errors;
|
|
246
|
-
}
|
|
247
159
|
export function validateField(field, value, registry, data, rowStates) {
|
|
248
160
|
const errors = [];
|
|
249
161
|
const effectiveValue = field.type === 'tags' ? normalizeTagsValue(value) : value;
|
|
@@ -259,76 +171,18 @@ export function validateField(field, value, registry, data, rowStates) {
|
|
|
259
171
|
if (field.type === 'repeater') {
|
|
260
172
|
errors.push(...repeaterErrors(field, effectiveValue, registry, rowStates));
|
|
261
173
|
}
|
|
262
|
-
errors.push(...typeErrors(field, effectiveValue, empty));
|
|
174
|
+
errors.push(...typeErrors(field, effectiveValue, empty, registry));
|
|
263
175
|
return errors;
|
|
264
176
|
}
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
tags: { check: (f, v) => tagsErrors(f, v) },
|
|
270
|
-
date: { check: dateErrors, onValue: true },
|
|
271
|
-
time: { check: timeErrors, onValue: true },
|
|
272
|
-
rating: { check: ratingErrors, onValue: true },
|
|
273
|
-
range: { check: rangeErrors, onValue: true },
|
|
274
|
-
reference: { check: referenceErrors, onValue: true },
|
|
275
|
-
};
|
|
276
|
-
function typeErrors(field, value, empty) {
|
|
277
|
-
const rule = TYPE_CHECKS[field.type];
|
|
278
|
-
if (!rule || (rule.onValue && empty))
|
|
279
|
-
return [];
|
|
280
|
-
return rule.check(field, value);
|
|
281
|
-
}
|
|
282
|
-
function dateErrors(field, value) {
|
|
283
|
-
if (!field.disabled_dates?.length && !field.disabled_weekdays?.length)
|
|
284
|
-
return [];
|
|
285
|
-
const days = isoDaysOf(value);
|
|
286
|
-
if (dateModeOf(field) === 'range' && days.length === 2) {
|
|
287
|
-
days.push(...rangeInteriorDays(days[0], days[1]));
|
|
288
|
-
}
|
|
289
|
-
return days.some((d) => isDateDisabled(field, d))
|
|
290
|
-
? [{ key: field.key, message: t('dateDisabled') }]
|
|
291
|
-
: [];
|
|
292
|
-
}
|
|
293
|
-
export const isTimeOfDay = (value) => typeof value === 'string' && /^(?:[01]\d|2[0-3]):[0-5]\d$/.test(value);
|
|
294
|
-
function timeErrors(field, value) {
|
|
295
|
-
return isTimeOfDay(value) ? [] : [{ key: field.key, message: t('timeInvalid') }];
|
|
296
|
-
}
|
|
297
|
-
export function isUploadedFile(v) {
|
|
298
|
-
if (v === null || typeof v !== 'object')
|
|
299
|
-
return false;
|
|
300
|
-
const r = v;
|
|
301
|
-
return (typeof r.name === 'string' &&
|
|
302
|
-
typeof r.size === 'number' &&
|
|
303
|
-
Number.isFinite(r.size) &&
|
|
304
|
-
r.size >= 0 &&
|
|
305
|
-
typeof r.url === 'string' &&
|
|
306
|
-
isSafeUrl(r.url) &&
|
|
307
|
-
(r.type === undefined || typeof r.type === 'string'));
|
|
308
|
-
}
|
|
309
|
-
function acceptMatches(accept, name, type) {
|
|
310
|
-
return accept.split(',').some((raw) => {
|
|
311
|
-
const token = raw.trim().toLowerCase();
|
|
312
|
-
if (!token)
|
|
313
|
-
return false;
|
|
314
|
-
if (token.startsWith('.'))
|
|
315
|
-
return name.toLowerCase().endsWith(token);
|
|
316
|
-
if (token.endsWith('/*'))
|
|
317
|
-
return type.toLowerCase().startsWith(token.slice(0, -1));
|
|
318
|
-
return type.toLowerCase() === token;
|
|
319
|
-
});
|
|
320
|
-
}
|
|
321
|
-
function fileErrors(field, value) {
|
|
322
|
-
const errors = [];
|
|
323
|
-
for (const ref of (Array.isArray(value) ? value : [value]).filter(isUploadedFile)) {
|
|
324
|
-
if (field.max_size !== undefined && ref.size > field.max_size) {
|
|
325
|
-
errors.push({ key: field.key, message: t('fileTooLarge') });
|
|
326
|
-
}
|
|
327
|
-
if (field.accept && !acceptMatches(field.accept, ref.name, ref.type ?? '')) {
|
|
328
|
-
errors.push({ key: field.key, message: t('fileTypeNotAllowed') });
|
|
329
|
-
}
|
|
177
|
+
function typeErrors(field, value, empty, registry) {
|
|
178
|
+
const builtIn = builtInType(field.type);
|
|
179
|
+
if (builtIn) {
|
|
180
|
+
return builtIn.check && (builtIn.checkWhenEmpty || !empty) ? builtIn.check(field, value) : [];
|
|
330
181
|
}
|
|
331
|
-
|
|
182
|
+
const message = empty
|
|
183
|
+
? null
|
|
184
|
+
: (fieldTypeSpec(registry, field.type)?.check?.(value, field) ?? null);
|
|
185
|
+
return message === null ? [] : [{ key: field.key, message }];
|
|
332
186
|
}
|
|
333
187
|
function repeaterErrors(field, value, registry, rowStates) {
|
|
334
188
|
if (value !== null && value !== undefined && !Array.isArray(value)) {
|
|
@@ -370,3 +224,4 @@ function rowErrors(field, subs, row, i, registry, rowStates) {
|
|
|
370
224
|
}
|
|
371
225
|
return errors;
|
|
372
226
|
}
|
|
227
|
+
export { isTimeOfDay, isUploadedFile, normalizeTagsValue, optionKeyLookup, rangeBounds, ratingMax, } from './type-checks.js';
|