-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathvalidator.ts
More file actions
1127 lines (1045 loc) · 37.9 KB
/
validator.ts
File metadata and controls
1127 lines (1045 loc) · 37.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type {
FormanSchemaField,
FormanValidationResult,
FormanSchemaExtendedNested,
FormanSchemaExtendedOptions,
FormanSchemaOption,
FormanSchemaOptionGroup,
FormanValidationOptions,
FormanSchemaNested,
FormanSchemaFieldState,
FormanSchemaPathExtendedOptions,
FormanSchemaDirectoryOption,
FormanSchemaSelectOptionsStore,
} from './types';
import {
containsIMLExpression,
isObject,
buildRestoreStructure,
isPrimitiveIMLExpression,
normalizeFormanFieldType,
isVisualType,
isReferenceType,
isEditableType,
IML_FILTER_OPERATORS,
findValueInSelectOptions,
pathToString,
stringToPath,
} from './utils';
import { udttypeExpand } from './composites/udttype';
import { udtspecExpand } from './composites/udtspec';
/**
* Context for schema validation operations
*/
export interface ValidationContext {
/** Current domain */
domain: string;
/** Domain roots */
roots: Record<string, DomainRoot>;
/** Tail of parameters in nested selects, required to resolve RPC payloads */
tail: {
/** Name of the parameter */
name: string;
/** Value of the parameter */
value: unknown;
}[];
/** Path of parameters in nested collections (string for field name, number for array index) */
path: (string | number)[];
/** Unknown fields are not allowed when strict is true */
strict: boolean;
/** Validate nested fields */
validateNestedFields(fields: FormanSchemaField[], context: ValidationContext): Promise<void>;
/** Remote resource resolver
* @param path The remote resource path
* @param context The validation context
* @param localData Optional local data to merge with data of the context in which the resolver is called
*/
resolveRemote(path: string, context: ValidationContext, localData?: Record<string, unknown>): Promise<unknown>;
}
/**
* Domain root configuration
*/
export interface DomainRoot {
/** Validate fields in the root of the domain
* @param fields The fields to validate
* @param tail The tail of parameters in nested selects, required to resolve RPC payloads
* @returns The validation result
*/
validateFields: (fields: FormanSchemaField[], context: ValidationContext) => Promise<FormanValidationResult>;
/** Fields seen by the validator (for strict mode) */
seenFields: Set<string>;
/** States of fields used to restore UI components */
fieldStates: Array<{
/** Path of the field (string for field name, number for array index) */
path: (string | number)[];
/** State of the field */
state: Omit<FormanSchemaFieldState, 'nested' | 'items'>;
}>;
}
/**
* Checks if a field is a select-like type with placeholder.nested
*/
function hasPlaceholderNested(field: FormanSchemaField): boolean {
if (!isObject<FormanSchemaExtendedOptions>(field.options)) return false;
const placeholder = field.options.placeholder;
return isObject<{ nested?: FormanSchemaNested }>(placeholder) && placeholder.nested != null;
}
/**
* Extracts the nested definition from `field.nested` or `field.options.nested`.
*/
function extractNestedFromField(
field: FormanSchemaField,
): FormanSchemaNested | FormanSchemaExtendedNested | undefined {
if (field.nested) return field.nested;
if (isObject<FormanSchemaExtendedOptions>(field.options) && field.options.nested) return field.options.nested;
return undefined;
}
/**
* Maps Forman Schema types to JS values.
*/
const FORMAN_TYPE_MAP: Readonly<Record<string, string | undefined>> = {
account: 'number',
hook: 'number',
device: 'number',
keychain: 'number',
datastore: 'number',
aiagent: 'string',
udt: 'number',
array: 'array',
collection: 'object',
text: 'string',
number: 'number',
boolean: 'boolean',
checkbox: 'boolean',
date: 'string',
json: 'string',
buffer: 'string',
cert: 'string',
color: 'string',
email: 'string',
filename: 'string',
file: 'string',
filter: 'array',
folder: 'string',
hidden: undefined,
integer: 'number',
uinteger: 'number',
password: 'string',
path: 'string',
pkey: 'string',
port: 'number',
select: undefined,
udttype: 'string',
udtspec: 'array',
time: 'string',
timestamp: 'string',
timezone: 'string',
upload: 'array',
url: 'string',
uuid: 'string',
any: undefined,
} as const;
/**
* Validates a Forman domains against schemas
* @param domains The domains to validate
* @param options The validation options
* @returns The validation result
*/
export async function validateFormanWithDomainsInternal(
domains: Record<
string,
{
values: Record<string, unknown>;
schema?: FormanSchemaField[];
restoreExtras?: Record<string, Record<string, unknown>>;
}
>,
options?: FormanValidationOptions,
): Promise<FormanValidationResult> {
const errors: FormanValidationResult['errors'] = [];
const roots = Object.keys(domains).reduce(
(acc, domain) => {
acc[domain] = {
seenFields: new Set(),
fieldStates: [],
validateFields: (fields: FormanSchemaField[], context: ValidationContext) => {
return validateFormanValue(
domains[domain]!.values,
{
name: domain,
type: 'collection',
spec: fields,
},
{
...context,
path: [],
domain,
},
);
},
};
return acc;
},
{} as Record<string, DomainRoot>,
);
for (const domain of Object.keys(domains)) {
if (!domains[domain]) continue;
const result = await validateFormanValue(
domains[domain].values,
{
name: domain,
type: 'collection',
spec: domains[domain].schema || [],
},
{
roots,
domain,
path: [],
tail: [],
strict: options?.strict === true,
validateNestedFields: () => {
throw new Error('Cannot validate nested fields without parent field.');
},
resolveRemote: async (path, context, localData) => {
if (!options?.resolveRemote) {
throw new Error('Remote resource not supported when resolver is not provided.');
}
const data = context.tail.reduce(
(acc, curr) => {
acc[curr.name] = curr.value;
return acc;
},
{} as Record<string, unknown>,
);
return await options.resolveRemote(path, {
...data,
...localData,
});
},
},
);
errors.push(...result.errors);
// Append the additional restore data, if provided.
// Extras only apply when states are enabled, because they contribute field-level state (labels, modes, etc.).
const restoreExtras = options?.states && domains[domain]?.restoreExtras;
if (restoreExtras) {
// To reduce compute, prepare all field states of the domain into a searchable map first
const fieldStateMap = new Map<string, DomainRoot['fieldStates'][number]['state']>(
roots[domain]!.fieldStates.map(({ path, state }) => {
return [pathToString(path), state];
}),
);
// For each field from the extra map...
for (const [fieldPath, extra] of Object.entries(restoreExtras)) {
const state = fieldStateMap.get(fieldPath);
if (state) {
// If the state has existed, add the extra value.
state.extra = extra;
} else {
// Else we need to create a new state just with the extra value.
roots[domain]!.fieldStates.push({
path: stringToPath(fieldPath),
state: { extra },
});
}
}
}
}
return {
valid: errors.length === 0,
errors,
states:
errors.length === 0 && options?.states
? buildRestoreStructure(
Object.keys(domains)
.map(domain => roots[domain]!.fieldStates.map(state => ({ domain, ...state })))
.flat(),
)
: undefined,
};
}
/**
* Validates a Forman value against a schema
* @param value The value to validate
* @param field The schema to validate against
* @param context The context for the validation
* @returns The validation result
*/
async function validateFormanValue(
value: unknown,
field: FormanSchemaField,
context: ValidationContext,
): Promise<FormanValidationResult> {
if (isVisualType(field.type)) {
return {
valid: true,
errors: [],
};
}
// Normalize field type (handle prefixed types)
const normalizedField = normalizeFormanFieldType(field);
if (normalizedField.required && (value == null || value === '')) {
return {
valid: false,
errors: [
{
domain: context.domain,
path: context.path.join('.'),
message: 'Field is mandatory.',
},
],
};
}
if (value == null || value === '') {
// When a select field has placeholder.nested, null/'' means "no selection" and we need to validate the nested fields
if (normalizedField.type === 'select' && hasPlaceholderNested(normalizedField)) {
return handleSelectType(value, normalizedField, context);
}
return {
valid: true,
errors: [],
};
}
const expectedType = FORMAN_TYPE_MAP[normalizedField.type];
let actualType: string = typeof value;
if (actualType === 'object' && Array.isArray(value)) actualType = 'array';
if (expectedType && expectedType !== actualType && !isPrimitiveIMLExpression(value)) {
return {
valid: false,
errors: [
{
domain: context.domain,
path: context.path.join('.'),
message: `Expected type '${expectedType}', got type '${actualType}'.`,
},
],
};
}
if (containsIMLExpression(value)) {
if (normalizedField.mappable === false) {
return {
valid: false,
errors: [
{
domain: context.domain,
path: context.path.join('.'),
message: 'Value contains prohibited IML expression.',
},
],
};
}
if (isEditableType(normalizedField.type)) {
context.roots[context.domain]!.fieldStates.push({
path: [...context.path],
state: { mode: 'edit' },
});
}
const nested = extractNestedFromField(normalizedField);
if (nested) {
return handleNestedFields(nested, value, normalizedField, context);
}
return {
valid: true,
errors: [],
};
}
if (normalizedField.type === 'udttype') {
return validateFormanValue(value, udttypeExpand({ ...normalizedField }), context);
}
if (normalizedField.type === 'udtspec') {
return validateFormanValue(value, udtspecExpand({ ...normalizedField }), context);
}
switch (normalizedField.type) {
case 'collection':
return handleCollectionType(value as Record<string, unknown>, normalizedField, context);
case 'array':
return handleArrayType(value as unknown[], normalizedField, context);
case 'select':
case 'account':
case 'hook':
case 'device':
case 'keychain':
case 'datastore':
case 'aiagent':
case 'udt':
case 'scenario':
return handleSelectType(value, normalizedField, context);
case 'file':
case 'folder':
return handlePathType(value, normalizedField, context);
case 'filter':
return handleFilterType(value, normalizedField, context);
default:
return handlePrimitiveType(value, normalizedField, context);
}
}
/**
* Handles collection type validation
* @param field The field to convert
* @param object The object to validate
* @param schema The schema to validate against
* @returns The validation result
*/
async function handleCollectionType(
value: Record<string, unknown>,
field: FormanSchemaField,
context: ValidationContext,
): Promise<FormanValidationResult> {
const errors: FormanValidationResult['errors'] = [];
const seen = context.path.length === 0 ? context.roots[context.domain]!.seenFields : new Set<string>();
const path = context.path;
if (Array.isArray(field.spec)) {
const spec = field.spec.slice();
while (spec.length > 0) {
let subField = spec.shift();
if (!subField) continue;
if (typeof subField === 'string') {
try {
const resolved = (await context.resolveRemote(subField, context)) as FormanSchemaField;
if (Array.isArray(resolved)) {
spec.unshift(...resolved);
continue;
} else {
subField = resolved;
}
} catch (error) {
return {
valid: false,
errors: [
...errors,
{
domain: context.domain,
path: context.path.join('.'),
message: `Failed to resolve remote resource ${subField}: ${error}`,
},
],
};
}
}
if (isVisualType(subField.type)) {
continue;
}
if (!subField.name) {
errors.push({
domain: context.domain,
path: context.path.join('.'),
message: 'Object contains field with unknown name.',
});
continue;
}
if (context.strict && !seen.has(subField.name)) seen.add(subField.name);
const result = await validateFormanValue(value[subField.name], subField, {
...context,
path: [...path, subField.name],
validateNestedFields: async (fields: FormanSchemaField[], context: ValidationContext) => {
for (const subField of fields) {
if (isVisualType(subField.type)) {
continue;
}
if (!subField.name) {
errors.push({
domain: context.domain,
path: context.path.join('.'),
message: 'Object contains field with unknown name.',
});
continue;
}
if (context.strict && !seen.has(subField.name)) seen.add(subField.name);
const result = await validateFormanValue(value[subField.name], subField, {
...context,
path: [...path, subField.name],
});
errors.push(...result.errors);
}
},
});
errors.push(...result.errors);
}
}
if (context.strict) {
for (const key of Object.keys(value)) {
if (!seen.has(key)) {
seen.add(key); // To avoid duplicate detection when nested fields are specified by another domain
errors.push({
domain: context.domain,
path: context.path.join('.'),
message: `Unknown field '${key}'.`,
});
}
}
}
return {
valid: errors.length === 0,
errors,
};
}
/**
* Handles array type validation
* @param field The field to convert
* @param value The value to validate
* @param path The path to the value
* @returns The validation result
*/
async function handleArrayType(
value: unknown[],
field: FormanSchemaField,
context: ValidationContext,
): Promise<FormanValidationResult> {
const errors: FormanValidationResult['errors'] = [];
if (field.spec) {
for (const [index, item] of value.entries()) {
const result = await validateFormanValue(
item,
Array.isArray(field.spec)
? { name: index.toString(), type: 'collection', spec: field.spec }
: Object.assign({}, field.spec, { name: index.toString() }),
{ ...context, path: [...context.path, index] },
);
errors.push(...result.errors);
}
}
// Add validation if present
if (field.validate) {
if (field.validate.minItems !== undefined && value.length < field.validate.minItems) {
errors.push({
domain: context.domain,
path: context.path.join('.'),
message: `Array has less than ${field.validate.minItems} items.`,
});
}
if (field.validate.maxItems !== undefined && value.length > field.validate.maxItems) {
errors.push({
domain: context.domain,
path: context.path.join('.'),
message: `Array has more than ${field.validate.maxItems} items.`,
});
}
}
return {
valid: errors.length === 0,
errors,
};
}
/**
* Handles filter type validation
* @param value Value to validate
* @param field Forman Field Definition
* @param context The context for the validation
* @returns Validation result
*/
async function handleFilterType(value: unknown, field: FormanSchemaField, context: ValidationContext) {
const operandOptions = isObject<FormanSchemaExtendedOptions>(field.options) ? field.options.store : field.options;
const operandSpec = {
name: 'a',
type: 'any',
required: true,
} as FormanSchemaField;
if (Array.isArray(operandOptions)) {
// Options are defined as array, turn the spec into a select instead.
operandSpec.type = 'select';
operandSpec.options = operandOptions;
}
const operatorOptions = isObject<FormanSchemaExtendedOptions>(field.options) ? field.options.operators : undefined;
const operatorSpec: FormanSchemaField = {
name: 'o',
type: 'any',
required: true,
};
if (Array.isArray(operatorOptions)) {
operatorSpec.type = 'select';
operatorSpec.grouped = true;
operatorSpec.options = operatorOptions;
} else {
operatorSpec.type = 'text';
operatorSpec.validate = {
enum: IML_FILTER_OPERATORS,
};
}
// The filter is technically just an array or arrays, or an array. Craft the inline definition and pass to array validator instead.
const filterEntry: FormanSchemaField = {
type: 'collection',
spec: [
operandSpec,
operatorSpec,
{
name: 'b',
type: 'any',
},
],
};
const inlineSchema: FormanSchemaField = ['and', 'or'].includes(field.logic ?? 'default')
? {
name: field.name,
type: 'array',
spec: filterEntry,
}
: {
name: field.name,
type: 'array',
spec: {
type: 'array',
spec: filterEntry,
},
};
return handleArrayType(value as unknown[], inlineSchema, context);
}
/**
* Handles file and folder path type validation
* @param value The value to validate
* @param field The field to convert
* @param context The context for the conversion
* @returns The validation result
*/
async function handlePathType(value: unknown, field: FormanSchemaField, context: ValidationContext) {
const errors: FormanValidationResult['errors'] = [];
if (typeof value !== 'string') {
return {
valid: false,
errors: [
...errors,
{
domain: context.domain,
path: context.path.join('.'),
message: `Expected type 'string' for path, got type '${typeof value}'.`,
},
],
};
}
let showRoot = true;
let ids = false;
let singleLevel = false;
let options: string | FormanSchemaPathExtendedOptions | FormanSchemaDirectoryOption[];
if (isObject<FormanSchemaPathExtendedOptions>(field.options)) {
if (field.options.showRoot !== undefined) showRoot = field.options.showRoot;
if (field.options.ids !== undefined) ids = field.options.ids;
if (field.options.singleLevel !== undefined) singleLevel = field.options.singleLevel;
options = field.options.store;
} else {
options = field.options as string | FormanSchemaDirectoryOption[];
}
// If single level AND either (not showing root and value contains slashes) OR (showing root and there's more than the root slash), it's invalid
if (singleLevel && ((!showRoot && value.includes('/')) || (showRoot && value.lastIndexOf('/') > 0))) {
return {
valid: false,
errors: [
...errors,
{
domain: context.domain,
path: context.path.join('.'),
message: `Single level path cannot contain slashes.`,
},
],
};
}
let nested = field.nested
? field.nested
: isObject<FormanSchemaPathExtendedOptions>(field.options)
? field.options.nested
: undefined;
// In order to validate the full path, we need to go level-by-level in the nesting. That's the only way we get also the labels correctly.
const levels = value.split('/');
// This way we start with an empty path always
if (levels[0] !== '') levels.unshift('');
// Special case: root folder is valid for folder type
if (showRoot && value === '/' && field.type === 'folder') {
return {
valid: true,
errors: [],
};
}
// Now there have to be at least two levels (root + one entry)
if (levels.length < 2) {
return {
valid: false,
errors: [
...errors,
{
domain: context.domain,
path: context.path.join('.'),
message: `Invalid path "${value}" encountered.`,
},
],
};
}
const selectedPath: FormanSchemaDirectoryOption[] = [];
let levelOptions: FormanSchemaDirectoryOption[] = [];
for (let levelIndex = 0; levelIndex < levels.length - 1; ++levelIndex) {
const isLastLevel = levelIndex === levels.length - 2;
const levelSelectedValue = levels[levelIndex + 1];
const selectedPathValue = selectedPath.map(({ value }) => value).join('/');
if (!levelSelectedValue) {
return {
valid: false,
errors: [
...errors,
{
domain: context.domain,
path: context.path.join('.'),
message: `Invalid selected value of "${value}" encountered.`,
},
],
};
}
if (typeof options === 'string') {
try {
levelOptions = (await context.resolveRemote(options, context, {
[field.name!]: (showRoot && !selectedPathValue.startsWith('/') ? '/' : '') + selectedPathValue,
})) as FormanSchemaDirectoryOption[];
} catch (error) {
return {
valid: false,
errors: [
...errors,
{
domain: context.domain,
path: context.path.join('.'),
message: `Failed to resolve remote resource ${options}: ${error}`,
},
],
};
}
} else if (isLastLevel) {
levelOptions = options;
}
const selectableOptions = levelOptions.flatMap(candidate => {
// In the last level, filter only files or folders, based on the field type
if (
isLastLevel &&
((field.type === 'file' && !candidate.file) || (field.type === 'folder' && candidate.file))
) {
return [];
}
// In non-last levels, filter out files, as we accept only folders there
if (!isLastLevel && candidate.file) {
return [];
}
return candidate;
});
const selectedOption = selectableOptions.find(candidate => candidate.value === levelSelectedValue);
if (!selectedOption) {
return {
valid: false,
errors: [
...errors,
{
domain: context.domain,
path: context.path.join('.'),
message: `Path '${levelSelectedValue}' not found in options.`,
},
],
};
}
selectedPath.push(selectedOption);
}
if (ids) {
/** Add state of the field to the domain root */
context.roots[context.domain]!.fieldStates.push({
path: context.path,
state: {
mode: 'chose',
path: selectedPath.map(({ label, value }) => (label ?? value) as string),
},
});
}
if (nested) {
const result = await handleNestedFields(nested, value, field, context);
errors.push(...result.errors);
}
return {
valid: errors.length === 0,
errors,
};
}
/**
* Handles select type validation
* @param field The field to convert
* @param result The prepared JSON Schema field
* @param context The context for the conversion
* @returns The converted JSON Schema field
*/
async function handleSelectType(
value: unknown,
field: FormanSchemaField,
context: ValidationContext,
): Promise<FormanValidationResult> {
const errors: FormanValidationResult['errors'] = [];
let optionsOrGroups = isObject<FormanSchemaExtendedOptions>(field.options) ? field.options.store : field.options;
let nested = extractNestedFromField(field);
if (typeof optionsOrGroups === 'string') {
try {
const resolved = await context.resolveRemote(optionsOrGroups, context);
if (resolved == null || typeof resolved !== 'object') {
return {
valid: false,
errors: [
...errors,
{
domain: context.domain,
path: context.path.join('.'),
message: `Remote resource ${optionsOrGroups} returned no data.`,
},
],
};
}
optionsOrGroups = (Array.isArray(resolved) ? resolved : [resolved]) as
| FormanSchemaOption[]
| FormanSchemaOptionGroup[];
} catch (error) {
return {
valid: false,
errors: [
...errors,
{
domain: context.domain,
path: context.path.join('.'),
message: `Failed to resolve remote resource ${optionsOrGroups}: ${error}`,
},
],
};
}
}
if (field.multiple) {
if (!Array.isArray(value)) {
return {
valid: false,
errors: [
...errors,
{
domain: context.domain,
path: context.path.join('.'),
message: `Value is not an array.`,
},
],
};
}
for (const singleValue of value) {
const found = findValueInSelectOptions(
field,
singleValue,
optionsOrGroups as FormanSchemaSelectOptionsStore,
);
if (!found) {
errors.push({
domain: context.domain,
path: context.path.join('.'),
message: `Value '${singleValue}' not found in options.`,
});
}
}
// Add validation if present
if (field.validate) {
if (field.validate.minItems !== undefined && value.length < field.validate.minItems) {
errors.push({
domain: context.domain,
path: context.path.join('.'),
message: `Selected less than ${field.validate.minItems} items.`,
});
}
if (field.validate.maxItems !== undefined && value.length > field.validate.maxItems) {
errors.push({
domain: context.domain,
path: context.path.join('.'),
message: `Selected more than ${field.validate.maxItems} items.`,
});
}
}
} else if ((value == null || value === '') && hasPlaceholderNested(field)) {
// Null/empty value with placeholder.nested: treat as valid "no selection" and use placeholder's nested
const placeholder = (field.options as FormanSchemaExtendedOptions).placeholder as {
label: string;
nested?: FormanSchemaNested;
};
if (placeholder.label) {
context.roots[context.domain]!.fieldStates.push({
path: context.path,
state: {
mode: 'chose',
label: placeholder.label,
},
});
}
if (placeholder.nested) nested = placeholder.nested;
} else {
const item = findValueInSelectOptions(field, value, optionsOrGroups as FormanSchemaSelectOptionsStore);
if (!item) {
return {
valid: false,
errors: [
...errors,
{
domain: context.domain,
path: context.path.join('.'),
message: `Value '${value}' not found in options.`,
},
],
};
}
if (item.label) {
/** Add state of the field to the domain root */
context.roots[context.domain]!.fieldStates.push({
path: context.path,
state: {
mode: isReferenceType(field.type) ? undefined : 'chose',
label: item.label,
},
});
}
if (item.nested) nested = item.nested;
}
if (nested) {
const result = await handleNestedFields(nested, value, field, context);
errors.push(...result.errors);
}
return {
valid: errors.length === 0,
errors,
};
}
/**
* Handles nested fields validation
* @param nested The nested fields
* @param value The value to validate
* @param field The field to validate
* @param context The context for the validation
* @returns The validation result
*/
async function handleNestedFields(
nested: FormanSchemaNested | FormanSchemaExtendedNested,
value: unknown,
field: FormanSchemaField,
context: ValidationContext,
): Promise<FormanValidationResult> {
const errors: FormanValidationResult['errors'] = [];
let store = isObject<FormanSchemaExtendedNested>(nested) ? nested.store : nested;
const domain = isObject<FormanSchemaExtendedNested>(nested) && nested.domain ? nested.domain : undefined;
context = {
...context,
tail: field.name ? [...context.tail, { name: field.name, value }] : context.tail,
};
if (typeof store === 'string') {
store = [store];
}
if (Array.isArray(store) && store.some(item => typeof item === 'string')) {
const resolvedStore: FormanSchemaField[] = [];
for (const item of store) {