@remoteoss/json-schema-form 0.11.11-dev.20250220164730 → 1.0.0-alpha.1

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/dist/index.js DELETED
@@ -1,2114 +0,0 @@
1
-
2
- /*!
3
- Copyright (c) 2025 Remote Technology, Inc.
4
- NPM Package: @remoteoss/json-schema-form@0.11.11-dev.20250220164730
5
- Generated: Thu, 20 Feb 2025 16:47:52 GMT
6
-
7
- MIT License
8
-
9
- Copyright (c) 2023 Remote Technology, Inc.
10
-
11
- Permission is hereby granted, free of charge, to any person obtaining a copy
12
- of this software and associated documentation files (the "Software"), to deal
13
- in the Software without restriction, including without limitation the rights
14
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15
- copies of the Software, and to permit persons to whom the Software is
16
- furnished to do so, subject to the following conditions:
17
-
18
- The above copyright notice and this permission notice shall be included in all
19
- copies or substantial portions of the Software.
20
-
21
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27
- SOFTWARE.
28
-
29
- */
30
-
31
- // src/createHeadlessForm.js
32
- import get3 from "lodash/get";
33
- import isNil3 from "lodash/isNil";
34
- import omit3 from "lodash/omit";
35
- import omitBy2 from "lodash/omitBy";
36
- import pick2 from "lodash/pick";
37
- import size from "lodash/size";
38
-
39
- // src/calculateConditionalProperties.js
40
- import merge2 from "lodash/merge";
41
- import omit2 from "lodash/omit";
42
-
43
- // src/helpers.js
44
- import get2 from "lodash/get";
45
- import isNil from "lodash/isNil";
46
- import omit from "lodash/omit";
47
- import omitBy from "lodash/omitBy";
48
- import set from "lodash/set";
49
- import { lazy } from "yup";
50
-
51
- // src/utils.js
52
- function convertDiskSizeFromTo(from, to) {
53
- const units = ["bytes", "kb", "mb"];
54
- return function convert(value) {
55
- return value * Math.pow(1024, units.indexOf(from.toLowerCase())) / Math.pow(1024, units.indexOf(to.toLowerCase()));
56
- };
57
- }
58
- function hasProperty(object2, propertyName) {
59
- return Object.prototype.hasOwnProperty.call(object2, propertyName);
60
- }
61
-
62
- // src/internals/checkIfConditionMatches.js
63
- function checkIfConditionMatchesProperties(node, formValues, formFields, logic) {
64
- if (typeof node.if === "boolean") {
65
- return node.if;
66
- }
67
- if (node.if.anyOf) {
68
- return node.if.anyOf.some(
69
- (property) => checkIfConditionMatchesProperties({ if: property }, formValues, formFields, logic)
70
- );
71
- }
72
- return Object.keys(node.if.properties ?? {}).every((name) => {
73
- const currentProperty = node.if.properties[name];
74
- const value = formValues[name];
75
- const hasEmptyValue = typeof value === "undefined" || // NOTE: This is a "Remote API" dependency, as empty fields are sent as "null".
76
- value === null;
77
- const hasIfExplicit = node.if.required?.includes(name);
78
- if (hasEmptyValue && !hasIfExplicit) {
79
- return true;
80
- }
81
- if (hasProperty(currentProperty, "const")) {
82
- return compareFormValueWithSchemaValue(value, currentProperty.const);
83
- }
84
- if (currentProperty.contains?.pattern) {
85
- const formValue = value || [];
86
- if (Array.isArray(formValue)) {
87
- const pattern = new RegExp(currentProperty.contains.pattern);
88
- return (value || []).some((item) => pattern.test(item));
89
- }
90
- }
91
- if (currentProperty.enum) {
92
- return currentProperty.enum.includes(value);
93
- }
94
- if (currentProperty.properties) {
95
- return checkIfConditionMatchesProperties(
96
- { if: currentProperty },
97
- formValues[name],
98
- getField(name, formFields).fields,
99
- logic
100
- );
101
- }
102
- const field = getField(name, formFields);
103
- return validateFieldSchema(
104
- {
105
- ...field,
106
- ...currentProperty,
107
- required: true
108
- },
109
- value
110
- );
111
- });
112
- }
113
- function checkIfMatchesValidationsAndComputedValues(node, formValues, logic, parentID) {
114
- const validationsMatch = Object.entries(node.if.validations ?? {}).every(([name, property]) => {
115
- const currentValue = logic.getScope(parentID).applyValidationRuleInCondition(name, formValues);
116
- if (Object.hasOwn(property, "const") && currentValue === property.const)
117
- return true;
118
- return false;
119
- });
120
- const computedValuesMatch = Object.entries(node.if.computedValues ?? {}).every(
121
- ([name, property]) => {
122
- const currentValue = logic.getScope(parentID).applyComputedValueRuleInCondition(name, formValues);
123
- if (Object.hasOwn(property, "const") && currentValue === property.const)
124
- return true;
125
- return false;
126
- }
127
- );
128
- return computedValuesMatch && validationsMatch;
129
- }
130
-
131
- // src/internals/helpers.js
132
- import merge from "lodash/fp/merge";
133
- import get from "lodash/get";
134
- import isEmpty from "lodash/isEmpty";
135
- import isFunction from "lodash/isFunction";
136
- function pickXKey(node, key) {
137
- const deprecatedKeys = ["presentation", "errorMessage"];
138
- return get(node, `x-jsf-${key}`, deprecatedKeys.includes(key) ? node?.[key] : void 0);
139
- }
140
- function getFieldDescription(node, customProperties = {}) {
141
- const nodeDescription = node?.description ? {
142
- description: node.description
143
- } : {};
144
- const customDescription = customProperties?.description ? {
145
- description: isFunction(customProperties.description) ? customProperties.description(node?.description, {
146
- ...node,
147
- ...customProperties
148
- }) : customProperties.description
149
- } : {};
150
- const nodePresentation = pickXKey(node, "presentation");
151
- const presentation = !isEmpty(nodePresentation) && {
152
- presentation: { ...nodePresentation, ...customDescription }
153
- };
154
- return merge(nodeDescription, { ...customDescription, ...presentation });
155
- }
156
-
157
- // src/internals/fields.js
158
- var jsonTypes = {
159
- STRING: "string",
160
- NUMBER: "number",
161
- INTEGER: "integer",
162
- OBJECT: "object",
163
- ARRAY: "array",
164
- BOOLEAN: "boolean",
165
- NULL: "null"
166
- };
167
- var supportedTypes = {
168
- TEXT: "text",
169
- NUMBER: "number",
170
- SELECT: "select",
171
- FILE: "file",
172
- RADIO: "radio",
173
- GROUP_ARRAY: "group-array",
174
- EMAIL: "email",
175
- DATE: "date",
176
- CHECKBOX: "checkbox",
177
- FIELDSET: "fieldset"
178
- };
179
- var jsonTypeToInputType = {
180
- [jsonTypes.STRING]: ({ oneOf, format }) => {
181
- if (format === "email")
182
- return supportedTypes.EMAIL;
183
- if (format === "date")
184
- return supportedTypes.DATE;
185
- if (format === "data-url")
186
- return supportedTypes.FILE;
187
- if (oneOf)
188
- return supportedTypes.RADIO;
189
- return supportedTypes.TEXT;
190
- },
191
- [jsonTypes.NUMBER]: () => supportedTypes.NUMBER,
192
- [jsonTypes.INTEGER]: () => supportedTypes.NUMBER,
193
- [jsonTypes.OBJECT]: () => supportedTypes.FIELDSET,
194
- [jsonTypes.ARRAY]: ({ items }) => {
195
- if (items.properties)
196
- return supportedTypes.GROUP_ARRAY;
197
- return supportedTypes.SELECT;
198
- },
199
- [jsonTypes.BOOLEAN]: () => supportedTypes.CHECKBOX
200
- };
201
- function getInputType(fieldProperties, strictInputType, name) {
202
- const presentation = pickXKey(fieldProperties, "presentation") ?? {};
203
- const presentationInputType = presentation?.inputType;
204
- if (presentationInputType) {
205
- return presentationInputType;
206
- }
207
- if (strictInputType) {
208
- throw Error(`Strict error: Missing inputType to field "${name || fieldProperties.title}".
209
- You can fix the json schema or skip this error by calling createHeadlessForm(schema, { strictInputType: false })`);
210
- }
211
- if (!fieldProperties.type) {
212
- if (fieldProperties.items?.properties) {
213
- return supportedTypes.GROUP_ARRAY;
214
- }
215
- if (fieldProperties.properties) {
216
- return supportedTypes.SELECT;
217
- }
218
- return jsonTypeToInputType[jsonTypes.STRING](fieldProperties);
219
- }
220
- return jsonTypeToInputType[fieldProperties.type]?.(fieldProperties);
221
- }
222
- function _composeFieldFile({ name, label, description, accept, required = true, ...attrs }) {
223
- return {
224
- type: supportedTypes.FILE,
225
- name,
226
- label,
227
- description,
228
- required,
229
- accept,
230
- ...attrs
231
- };
232
- }
233
- function _composeFieldText({ name, label, description, required = true, ...attrs }) {
234
- return {
235
- type: supportedTypes.TEXT,
236
- name,
237
- label,
238
- description,
239
- required,
240
- ...attrs
241
- };
242
- }
243
- function _composeFieldEmail({ name, label, required = true, ...attrs }) {
244
- return {
245
- type: supportedTypes.EMAIL,
246
- name,
247
- label,
248
- required,
249
- ...attrs
250
- };
251
- }
252
- function _composeFieldNumber({
253
- name,
254
- label,
255
- percentage = false,
256
- required = true,
257
- minimum,
258
- maximum,
259
- ...attrs
260
- }) {
261
- let minValue = minimum;
262
- let maxValue = maximum;
263
- if (percentage) {
264
- minValue = minValue ?? 0;
265
- maxValue = maxValue ?? 100;
266
- }
267
- return {
268
- type: supportedTypes.NUMBER,
269
- name,
270
- label,
271
- percentage,
272
- required,
273
- minimum: minValue,
274
- maximum: maxValue,
275
- ...attrs
276
- };
277
- }
278
- function _composeFieldDate({ name, label, required = true, ...attrs }) {
279
- return {
280
- type: supportedTypes.DATE,
281
- name,
282
- label,
283
- required,
284
- ...attrs
285
- };
286
- }
287
- function _composeFieldRadio({ name, label, options, required = true, ...attrs }) {
288
- return {
289
- type: supportedTypes.RADIO,
290
- name,
291
- label,
292
- options,
293
- required,
294
- ...attrs
295
- };
296
- }
297
- function _composeFieldSelect({ name, label, options, required = true, ...attrs }) {
298
- return {
299
- type: supportedTypes.SELECT,
300
- name,
301
- label,
302
- options,
303
- required,
304
- ...attrs
305
- };
306
- }
307
- function _composeNthFieldGroup({ name, label, required, nthFieldGroup, ...attrs }) {
308
- return [
309
- {
310
- ...nthFieldGroup,
311
- type: supportedTypes.GROUP_ARRAY,
312
- name,
313
- label,
314
- required,
315
- ...attrs
316
- }
317
- ];
318
- }
319
- function _composeFieldCheckbox({
320
- required = true,
321
- name,
322
- label,
323
- description,
324
- default: defaultValue,
325
- checkboxValue,
326
- ...attrs
327
- }) {
328
- return {
329
- type: supportedTypes.CHECKBOX,
330
- required,
331
- name,
332
- label,
333
- description,
334
- checkboxValue,
335
- ...defaultValue && { default: defaultValue },
336
- ...attrs
337
- };
338
- }
339
- function _composeFieldset({ name, label, fields, variant, ...attrs }) {
340
- return {
341
- type: supportedTypes.FIELDSET,
342
- name,
343
- label,
344
- fields,
345
- variant,
346
- ...attrs
347
- };
348
- }
349
- var _composeFieldArbitraryClosure = (inputType) => (attrs) => ({
350
- type: inputType,
351
- ...attrs
352
- });
353
- var inputTypeMap = {
354
- text: _composeFieldText,
355
- select: _composeFieldSelect,
356
- radio: _composeFieldRadio,
357
- date: _composeFieldDate,
358
- number: _composeFieldNumber,
359
- "group-array": _composeNthFieldGroup,
360
- fieldset: _composeFieldset,
361
- file: _composeFieldFile,
362
- email: _composeFieldEmail,
363
- checkbox: _composeFieldCheckbox
364
- };
365
- function _composeFieldCustomClosure(defaultComposeFn) {
366
- return ({ fieldCustomization, ...attrs }) => {
367
- const { description, ...restFieldCustomization } = fieldCustomization;
368
- const fieldDescription = getFieldDescription(attrs, fieldCustomization);
369
- const { nthFieldGroup, ...restAttrs } = attrs;
370
- const commonAttrs = {
371
- ...restAttrs,
372
- ...restFieldCustomization,
373
- ...fieldDescription
374
- };
375
- if (attrs.inputType === supportedTypes.GROUP_ARRAY) {
376
- return [
377
- {
378
- ...nthFieldGroup,
379
- ...commonAttrs
380
- }
381
- ];
382
- }
383
- return {
384
- ...defaultComposeFn(attrs),
385
- ...commonAttrs
386
- };
387
- };
388
- }
389
-
390
- // src/jsonLogic.js
391
- import jsonLogic from "json-logic-js";
392
-
393
- // src/yupSchema.js
394
- import flow from "lodash/flow";
395
- import noop from "lodash/noop";
396
- import { randexp } from "randexp";
397
- import { string, number, boolean, object, array, mixed } from "yup";
398
- var DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
399
- var baseString = string().trim();
400
- var todayDateHint = (/* @__PURE__ */ new Date()).toISOString().substring(0, 10);
401
- var convertBytesToKB = convertDiskSizeFromTo("Bytes", "KB");
402
- var convertKbBytesToMB = convertDiskSizeFromTo("KB", "MB");
403
- var validateOnlyStrings = string().trim().nullable().test(
404
- "is-string",
405
- "${path} must be a `string` type, but the final value was: `${value}`.",
406
- (value, context) => {
407
- if (context.originalValue !== null && context.originalValue !== void 0) {
408
- return typeof context.originalValue === "string";
409
- }
410
- return true;
411
- }
412
- );
413
- var compareDates = (d1, d2) => {
414
- let date1 = new Date(d1).getTime();
415
- let date2 = new Date(d2).getTime();
416
- if (date1 < date2) {
417
- return "LESSER";
418
- } else if (date1 > date2) {
419
- return "GREATER";
420
- } else {
421
- return "EQUAL";
422
- }
423
- };
424
- var validateMinDate = (value, minDate) => {
425
- const compare = compareDates(value, minDate);
426
- return compare === "GREATER" || compare === "EQUAL" ? true : false;
427
- };
428
- var validateMaxDate = (value, minDate) => {
429
- const compare = compareDates(value, minDate);
430
- return compare === "LESSER" || compare === "EQUAL" ? true : false;
431
- };
432
- var validateRadioOrSelectOptions = (value, options) => {
433
- if (value === void 0)
434
- return true;
435
- const exactMatch = options.some((option) => option.value === value);
436
- if (exactMatch)
437
- return true;
438
- const patternMatch = options.some((option) => option.pattern?.test(value));
439
- return !!patternMatch;
440
- };
441
- var yupSchemas = {
442
- text: validateOnlyStrings,
443
- radioOrSelectString: (options) => {
444
- return string().nullable().transform((value) => {
445
- if (value === "") {
446
- return void 0;
447
- }
448
- if (options?.some((option) => option.value === null)) {
449
- return value;
450
- }
451
- return value === null ? void 0 : value;
452
- }).test(
453
- "matchesOptionOrPattern",
454
- ({ value }) => `The option ${JSON.stringify(value)} is not valid.`,
455
- (castValue, { originalValue }) => {
456
- if (castValue !== void 0 && typeof originalValue !== "string") {
457
- return false;
458
- }
459
- return validateRadioOrSelectOptions(castValue, options);
460
- }
461
- );
462
- },
463
- date: ({ minDate, maxDate }) => {
464
- let dateString = string().nullable().transform((value) => {
465
- if (value === "") {
466
- return void 0;
467
- }
468
- return value === null ? void 0 : value;
469
- }).trim().matches(
470
- /(?:\d){4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-9]|3[0-1])/,
471
- `Must be a valid date in ${DEFAULT_DATE_FORMAT.toLocaleLowerCase()} format. e.g. ${todayDateHint}`
472
- );
473
- if (minDate) {
474
- dateString = dateString.test(
475
- "minDate",
476
- `The date must be ${minDate} or after.`,
477
- (value) => validateMinDate(value, minDate)
478
- );
479
- }
480
- if (maxDate) {
481
- dateString = dateString.test(
482
- "maxDate",
483
- `The date must be ${maxDate} or before.`,
484
- (value) => validateMaxDate(value, maxDate)
485
- );
486
- }
487
- return dateString;
488
- },
489
- radioOrSelectNumber: (options) => mixed().typeError("The value must be a number").transform((value) => {
490
- if (options?.some((option) => option.value === null)) {
491
- return value;
492
- }
493
- return value === null ? void 0 : value;
494
- }).test(
495
- "matchesOptionOrPattern",
496
- ({ value }) => {
497
- return `The option ${JSON.stringify(value)} is not valid.`;
498
- },
499
- (value) => {
500
- if (value !== void 0 && typeof value !== "number")
501
- return false;
502
- return validateRadioOrSelectOptions(value, options);
503
- }
504
- ).nullable(),
505
- radioOrSelectBoolean: (options) => {
506
- return boolean().nullable().transform((value) => {
507
- if (options?.some((option) => option.value === null)) {
508
- return value;
509
- }
510
- return value === null ? void 0 : value;
511
- }).test(
512
- "matchesOptionOrPattern",
513
- ({ originalValue }) => {
514
- return `The option ${JSON.stringify(originalValue)} is not valid.`;
515
- },
516
- (castValue, { originalValue }) => {
517
- if (typeof originalValue !== "boolean" && castValue !== void 0)
518
- return false;
519
- return validateRadioOrSelectOptions(castValue, options);
520
- }
521
- );
522
- },
523
- number: number().typeError("The value must be a number").nullable(),
524
- file: array().nullable(),
525
- email: string().trim().email("Please enter a valid email address").nullable(),
526
- fieldset: object().nullable(),
527
- checkbox: string().trim().nullable(),
528
- checkboxBool: boolean().typeError('The value must be a boolean, but received "${value}"').nullable(),
529
- multiple: {
530
- select: array().nullable(),
531
- "group-array": array().nullable()
532
- },
533
- null: mixed().typeError("The value must be null").test(
534
- "matchesNullValue",
535
- ({ value }) => `The value ${JSON.stringify(value)} is not valid.`,
536
- (value) => value === void 0 || value === null
537
- )
538
- };
539
- var yupSchemasToJsonTypes = {
540
- string: yupSchemas.text,
541
- number: yupSchemas.number,
542
- integer: yupSchemas.number,
543
- object: yupSchemas.fieldset,
544
- array: yupSchemas.multiple.select,
545
- boolean: yupSchemas.checkboxBool,
546
- null: yupSchemas.null
547
- };
548
- function getRequiredErrorMessage(inputType, { inlineError, configError }) {
549
- if (inlineError)
550
- return inlineError;
551
- if (configError)
552
- return configError;
553
- if (inputType === supportedTypes.CHECKBOX)
554
- return "Please acknowledge this field";
555
- return "Required field";
556
- }
557
- var getJsonTypeInArray = (jsonType) => {
558
- return Array.isArray(jsonType) ? jsonType.find((val) => val !== "null") : jsonType;
559
- };
560
- var getOptions = (field) => {
561
- const allValues = field.options?.map((option) => ({
562
- value: option.value,
563
- pattern: option.pattern ? new RegExp(option.pattern) : null
564
- }));
565
- const isOptionalWithNull = Array.isArray(field.jsonType) && // @TODO should also check the "oneOf" directly looking for "null"
566
- // option but we don't have direct access at this point.
567
- // Otherwise the JSON Schema validator will fail as explained in PR#18
568
- field.jsonType.includes("null");
569
- return isOptionalWithNull ? [...allValues, { option: null }] : allValues;
570
- };
571
- var getYupSchema = ({ inputType, ...field }) => {
572
- const jsonType = getJsonTypeInArray(field.jsonType);
573
- const hasOptions = field.options?.length > 0;
574
- const generateOptionSchema = (type) => {
575
- const optionValues = getOptions(field);
576
- switch (type) {
577
- case "number":
578
- return yupSchemas.radioOrSelectNumber(optionValues);
579
- case "boolean":
580
- return yupSchemas.radioOrSelectBoolean(optionValues);
581
- default:
582
- return yupSchemas.radioOrSelectString(optionValues);
583
- }
584
- };
585
- if (hasOptions) {
586
- if (Array.isArray(field.jsonType)) {
587
- return field.jsonType.includes("number") ? generateOptionSchema("number") : generateOptionSchema("string");
588
- }
589
- return generateOptionSchema(field.jsonType);
590
- }
591
- if (field.format === "date") {
592
- return yupSchemas.date({ minDate: field.minDate, maxDate: field.maxDate });
593
- }
594
- return yupSchemas[inputType] || yupSchemasToJsonTypes[jsonType];
595
- };
596
- function buildYupSchema(field, config, logic) {
597
- const { inputType, jsonType: jsonTypeValue, errorMessage = {}, ...propertyFields } = field;
598
- const isCheckboxBoolean = typeof propertyFields.checkboxValue === "boolean";
599
- let baseSchema;
600
- const errorMessageFromConfig = config?.inputTypes?.[inputType]?.errorMessage || {};
601
- const jsonType = getJsonTypeInArray(field.jsonType);
602
- if (propertyFields.multiple) {
603
- baseSchema = yupSchemas.multiple[inputType] || yupSchemasToJsonTypes.array;
604
- } else if (isCheckboxBoolean) {
605
- baseSchema = yupSchemas.checkboxBool;
606
- } else {
607
- baseSchema = getYupSchema(field);
608
- }
609
- if (!baseSchema) {
610
- return noop;
611
- }
612
- const randomPlaceholder = propertyFields.pattern && randexp(propertyFields.pattern);
613
- const requiredMessage = getRequiredErrorMessage(inputType, {
614
- inlineError: errorMessage.required,
615
- configError: errorMessageFromConfig.required
616
- });
617
- function withRequired(yupSchema) {
618
- if (isCheckboxBoolean) {
619
- return yupSchema.oneOf([true], requiredMessage).required(requiredMessage);
620
- }
621
- return yupSchema.required(requiredMessage);
622
- }
623
- function withInteger(yupSchema) {
624
- return yupSchema.integer(
625
- (message) => errorMessage.integer ?? errorMessageFromConfig.integer ?? `Must not contain decimal points. E.g. ${Math.floor(message.value)} instead of ${message.value}`
626
- );
627
- }
628
- function withMin(yupSchema) {
629
- return yupSchema.min(
630
- propertyFields.minimum,
631
- (message) => errorMessage.minimum ?? errorMessageFromConfig.minimum ?? `Must be greater or equal to ${message.min}`
632
- );
633
- }
634
- function withMinLength(yupSchema) {
635
- return yupSchema.min(
636
- propertyFields.minLength,
637
- (message) => errorMessage.minLength ?? errorMessageFromConfig.minLength ?? `Please insert at least ${message.min} characters`
638
- );
639
- }
640
- function withMax(yupSchema) {
641
- return yupSchema.max(
642
- propertyFields.maximum,
643
- (message) => errorMessage.maximum ?? errorMessageFromConfig.maximum ?? `Must be smaller or equal to ${message.max}`
644
- );
645
- }
646
- function withMaxLength(yupSchema) {
647
- return yupSchema.max(
648
- propertyFields.maxLength,
649
- (message) => errorMessage.maxLength ?? errorMessageFromConfig.maxLength ?? `Please insert up to ${message.max} characters`
650
- );
651
- }
652
- function withMatches(yupSchema) {
653
- return yupSchema.matches(
654
- propertyFields.pattern,
655
- () => errorMessage.pattern ?? errorMessageFromConfig.pattern ?? `Must have a valid format. E.g. ${randomPlaceholder}`
656
- );
657
- }
658
- function isValidFileInput(files) {
659
- return files === void 0 || files === null || files.every(
660
- (file) => file instanceof File || Object.prototype.hasOwnProperty.call(file, "name")
661
- );
662
- }
663
- function withFile(yupSchema) {
664
- return yupSchema.test("isValidFile", "Not a valid file.", isValidFileInput);
665
- }
666
- function withMaxFileSize(yupSchema) {
667
- return yupSchema.test(
668
- "isValidFileSize",
669
- errorMessage.maxFileSize ?? errorMessageFromConfig.maxFileSize ?? `File size too large. The limit is ${convertKbBytesToMB(propertyFields.maxFileSize)} MB.`,
670
- (files) => isValidFileInput(files) && !files?.some((file) => convertBytesToKB(file.size) > propertyFields.maxFileSize)
671
- );
672
- }
673
- function withFileFormat(yupSchema) {
674
- return yupSchema.test(
675
- "isSupportedFormat",
676
- errorMessage.accept ?? errorMessageFromConfig.accept ?? `Unsupported file format. The acceptable formats are ${propertyFields.accept}.`,
677
- (files) => isValidFileInput(files) && files?.length > 0 ? files.some((file) => {
678
- const fileType = file.name.split(".").pop();
679
- return propertyFields.accept.includes(fileType.toLowerCase());
680
- }) : true
681
- );
682
- }
683
- function withConst(yupSchema) {
684
- return yupSchema.test(
685
- "isConst",
686
- errorMessage.const ?? errorMessageFromConfig.const ?? `The only accepted value is ${propertyFields.const}.`,
687
- (value) => propertyFields.required === false && value === void 0 || value === null || value === propertyFields.const
688
- );
689
- }
690
- function withBaseSchema() {
691
- const customErrorMsg = errorMessage.type || errorMessageFromConfig.type;
692
- if (customErrorMsg) {
693
- return baseSchema.typeError(customErrorMsg);
694
- }
695
- return baseSchema;
696
- }
697
- function buildFieldSetSchema(innerFields) {
698
- const fieldSetShape = {};
699
- innerFields.forEach((fieldSetfield) => {
700
- if (fieldSetfield.fields) {
701
- fieldSetShape[fieldSetfield.name] = object().shape(
702
- buildFieldSetSchema(fieldSetfield.fields)
703
- );
704
- } else {
705
- fieldSetShape[fieldSetfield.name] = buildYupSchema(
706
- {
707
- ...fieldSetfield,
708
- inputType: fieldSetfield.type
709
- },
710
- config
711
- )();
712
- }
713
- });
714
- return fieldSetShape;
715
- }
716
- function buildGroupArraySchema() {
717
- return object().shape(
718
- propertyFields.nthFieldGroup.fields().reduce(
719
- (schema, groupArrayField) => ({
720
- ...schema,
721
- [groupArrayField.name]: buildYupSchema(groupArrayField, config)()
722
- }),
723
- {}
724
- )
725
- );
726
- }
727
- const validators = [withBaseSchema];
728
- if (inputType === supportedTypes.GROUP_ARRAY) {
729
- validators[0] = () => withBaseSchema().of(buildGroupArraySchema());
730
- } else if (inputType === supportedTypes.FIELDSET) {
731
- validators[0] = () => withBaseSchema().shape(buildFieldSetSchema(propertyFields.fields));
732
- }
733
- if (propertyFields.required) {
734
- validators.push(withRequired);
735
- }
736
- if (inputType === supportedTypes.FILE) {
737
- validators.push(withFile);
738
- }
739
- if (jsonType === "integer") {
740
- validators.push(withInteger);
741
- }
742
- if (typeof propertyFields.minimum !== "undefined") {
743
- validators.push(withMin);
744
- }
745
- if (typeof propertyFields.minLength !== "undefined") {
746
- validators.push(withMinLength);
747
- }
748
- if (propertyFields.maximum !== void 0) {
749
- validators.push(withMax);
750
- }
751
- if (propertyFields.maxLength) {
752
- validators.push(withMaxLength);
753
- }
754
- if (propertyFields.pattern) {
755
- validators.push(withMatches);
756
- }
757
- if (propertyFields.maxFileSize) {
758
- validators.push(withMaxFileSize);
759
- }
760
- if (propertyFields.accept) {
761
- validators.push(withFileFormat);
762
- }
763
- if (typeof propertyFields.const !== "undefined") {
764
- validators.push(withConst);
765
- }
766
- if (propertyFields.jsonLogicValidations) {
767
- propertyFields.jsonLogicValidations.forEach(
768
- (id) => validators.push(yupSchemaWithCustomJSONLogic({ field, id, logic, config }))
769
- );
770
- }
771
- return flow(validators);
772
- }
773
- function getNoSortEdges(fields = []) {
774
- return fields.reduce((list, field) => {
775
- if (field.noSortEdges) {
776
- list.push(field.name);
777
- }
778
- return list;
779
- }, []);
780
- }
781
- function getSchema(fields = [], config) {
782
- const newSchema = {};
783
- fields.forEach((field) => {
784
- if (field.schema) {
785
- if (field.name) {
786
- if (field.inputType === supportedTypes.FIELDSET) {
787
- const fieldsetSchema = buildYupSchema(field, config)();
788
- newSchema[field.name] = fieldsetSchema;
789
- } else {
790
- newSchema[field.name] = field.schema;
791
- }
792
- } else {
793
- Object.assign(newSchema, getSchema(field.fields, config));
794
- }
795
- }
796
- });
797
- return newSchema;
798
- }
799
- function buildCompleteYupSchema(fields, config) {
800
- return object().shape(getSchema(fields, config), getNoSortEdges(fields));
801
- }
802
-
803
- // src/jsonLogic.js
804
- function createValidationChecker(schema) {
805
- const scopes = /* @__PURE__ */ new Map();
806
- function createScopes(jsonSchema, key = "root") {
807
- const sampleEmptyObject = buildSampleEmptyObject(schema);
808
- scopes.set(key, createValidationsScope(jsonSchema));
809
- Object.entries(jsonSchema?.properties ?? {}).filter(([, property]) => property.type === "object" || property.type === "array").forEach(([key2, property]) => {
810
- if (property.type === "array") {
811
- createScopes(property.items, `${key2}[]`);
812
- } else {
813
- createScopes(property, key2);
814
- }
815
- });
816
- validateInlineRules(jsonSchema, sampleEmptyObject);
817
- }
818
- createScopes(schema);
819
- return {
820
- scopes,
821
- getScope(name = "root") {
822
- return scopes.get(name);
823
- }
824
- };
825
- }
826
- function createValidationsScope(schema) {
827
- const validationMap = /* @__PURE__ */ new Map();
828
- const computedValuesMap = /* @__PURE__ */ new Map();
829
- const logic = schema?.["x-jsf-logic"] ?? {
830
- validations: {},
831
- computedValues: {}
832
- };
833
- const validations = Object.entries(logic.validations ?? {});
834
- const computedValues = Object.entries(logic.computedValues ?? {});
835
- const sampleEmptyObject = buildSampleEmptyObject(schema);
836
- validations.forEach(([id, validation]) => {
837
- if (!validation.rule) {
838
- throw Error(`[json-schema-form] json-logic error: Validation "${id}" has missing rule.`);
839
- }
840
- checkRuleIntegrity(validation.rule, id, sampleEmptyObject);
841
- validationMap.set(id, validation);
842
- });
843
- computedValues.forEach(([id, computedValue]) => {
844
- if (!computedValue.rule) {
845
- throw Error(`[json-schema-form] json-logic error: Computed value "${id}" has missing rule.`);
846
- }
847
- checkRuleIntegrity(computedValue.rule, id, sampleEmptyObject);
848
- computedValuesMap.set(id, computedValue);
849
- });
850
- function validate(rule, values) {
851
- return jsonLogic.apply(
852
- rule,
853
- replaceUndefinedValuesWithNulls({ ...sampleEmptyObject, ...values })
854
- );
855
- }
856
- return {
857
- validationMap,
858
- computedValuesMap,
859
- validate,
860
- applyValidationRuleInCondition(id, values) {
861
- const validation = validationMap.get(id);
862
- return validate(validation.rule, values);
863
- },
864
- applyComputedValueInField(id, values, fieldName) {
865
- const validation = computedValuesMap.get(id);
866
- if (validation === void 0) {
867
- throw Error(
868
- `[json-schema-form] json-logic error: Computed value "${id}" doesn't exist in field "${fieldName}".`
869
- );
870
- }
871
- return validate(validation.rule, values);
872
- },
873
- applyComputedValueRuleInCondition(id, values) {
874
- const validation = computedValuesMap.get(id);
875
- return validate(validation.rule, values);
876
- }
877
- };
878
- }
879
- function replaceUndefinedValuesWithNulls(values = {}) {
880
- return Object.entries(values).reduce((prev, [key, value]) => {
881
- return { ...prev, [key]: value === void 0 || value === null ? NaN : value };
882
- }, {});
883
- }
884
- function yupSchemaWithCustomJSONLogic({ field, logic, config, id }) {
885
- const { parentID = "root" } = config;
886
- const validation = logic.getScope(parentID).validationMap.get(id);
887
- if (validation === void 0) {
888
- throw Error(
889
- `[json-schema-form] json-logic error: "${field.name}" required validation "${id}" doesn't exist.`
890
- );
891
- }
892
- return (yupSchema) => yupSchema.test(
893
- `${field.name}-validation-${id}`,
894
- validation?.errorMessage ?? "This field is invalid.",
895
- (value, { parent }) => {
896
- if (value === void 0 && !field.required)
897
- return true;
898
- return jsonLogic.apply(validation.rule, parent);
899
- }
900
- );
901
- }
902
- var HANDLEBARS_REGEX = /\{\{([^{}]+)\}\}/g;
903
- function replaceHandlebarsTemplates({
904
- value: toReplace,
905
- logic,
906
- formValues,
907
- parentID,
908
- name: fieldName
909
- }) {
910
- if (typeof toReplace === "string") {
911
- return toReplace.replace(HANDLEBARS_REGEX, (match, key) => {
912
- return logic.getScope(parentID).applyComputedValueInField(key.trim(), formValues, fieldName);
913
- });
914
- } else if (typeof toReplace === "object") {
915
- const { value, ...rules } = toReplace;
916
- if (Object.keys(rules).length > 1 && !value) {
917
- throw Error("Cannot define multiple rules without a template string with key `value`.");
918
- }
919
- const computedTemplateValue = Object.entries(rules).reduce((prev, [key, rule]) => {
920
- const computedValue = logic.getScope(parentID).validate(rule, formValues);
921
- return prev.replaceAll(`{{${key}}}`, computedValue);
922
- }, value);
923
- return computedTemplateValue.replace(/\{\{([^{}]+)\}\}/g, (match, key) => {
924
- return logic.getScope(parentID).applyComputedValueInField(key.trim(), formValues, fieldName);
925
- });
926
- }
927
- return toReplace;
928
- }
929
- function calculateComputedAttributes(fieldParams, { parentID = "root" } = {}) {
930
- return ({ logic, isRequired, config, formValues }) => {
931
- const { name, computedAttributes } = fieldParams;
932
- const attributes = Object.fromEntries(
933
- Object.entries(computedAttributes).map(handleComputedAttribute(logic, formValues, parentID, name)).filter(([, value]) => value !== null)
934
- );
935
- return {
936
- ...attributes,
937
- schema: buildYupSchema(
938
- { ...fieldParams, ...attributes, required: isRequired },
939
- config,
940
- logic
941
- )
942
- };
943
- };
944
- }
945
- function handleComputedAttribute(logic, formValues, parentID, name) {
946
- return ([key, value]) => {
947
- switch (key) {
948
- case "description":
949
- return [key, replaceHandlebarsTemplates({ value, logic, formValues, parentID, name })];
950
- case "title":
951
- return ["label", replaceHandlebarsTemplates({ value, logic, formValues, parentID, name })];
952
- case "x-jsf-errorMessage":
953
- return [
954
- "errorMessage",
955
- handleNestedObjectForComputedValues(value, formValues, parentID, logic, name)
956
- ];
957
- case "x-jsf-presentation": {
958
- if (value.statement) {
959
- return [
960
- "statement",
961
- handleNestedObjectForComputedValues(value.statement, formValues, parentID, logic, name)
962
- ];
963
- }
964
- return [
965
- key,
966
- handleNestedObjectForComputedValues(value.statement, formValues, parentID, logic, name)
967
- ];
968
- }
969
- case "const":
970
- default: {
971
- if (typeof value === "object" && value.rule) {
972
- return [key, logic.getScope(parentID).validate(value.rule, formValues)];
973
- }
974
- return [key, logic.getScope(parentID).applyComputedValueInField(value, formValues, name)];
975
- }
976
- }
977
- };
978
- }
979
- function handleNestedObjectForComputedValues(values, formValues, parentID, logic, name) {
980
- return Object.fromEntries(
981
- Object.entries(values).map(([key, value]) => {
982
- return [key, replaceHandlebarsTemplates({ value, logic, formValues, parentID, name })];
983
- })
984
- );
985
- }
986
- function buildSampleEmptyObject(schema = {}) {
987
- const sample = {};
988
- if (typeof schema !== "object" || !schema.properties) {
989
- return schema;
990
- }
991
- for (const key in schema.properties) {
992
- if (schema.properties[key].type === "object") {
993
- sample[key] = buildSampleEmptyObject(schema.properties[key]);
994
- } else if (schema.properties[key].type === "array") {
995
- const itemSchema = schema.properties[key].items;
996
- sample[key] = buildSampleEmptyObject(itemSchema);
997
- } else {
998
- sample[key] = true;
999
- }
1000
- }
1001
- return sample;
1002
- }
1003
- function validateInlineRules(jsonSchema, sampleEmptyObject) {
1004
- const properties = (jsonSchema?.properties || jsonSchema?.items?.properties) ?? {};
1005
- Object.entries(properties).filter(([, property]) => property["x-jsf-logic-computedAttrs"] !== void 0).forEach(([fieldName, property]) => {
1006
- Object.entries(property["x-jsf-logic-computedAttrs"]).filter(([, value]) => typeof value === "object").forEach(([key, item]) => {
1007
- Object.values(item).forEach((rule) => {
1008
- checkRuleIntegrity(
1009
- rule,
1010
- fieldName,
1011
- sampleEmptyObject,
1012
- (item2) => `[json-schema-form] json-logic error: fieldName "${item2.var}" doesn't exist in field "${fieldName}.x-jsf-logic-computedAttrs.${key}".`
1013
- );
1014
- });
1015
- });
1016
- });
1017
- }
1018
- function checkRuleIntegrity(rule, id, data, errorMessage = (item) => `[json-schema-form] json-logic error: rule "${id}" has no variable "${item.var}".`) {
1019
- Object.entries(rule ?? {}).map(([operator, subRule]) => {
1020
- if (!Array.isArray(subRule) && subRule !== null && subRule !== void 0)
1021
- return;
1022
- throwIfUnknownOperator(operator, subRule, id);
1023
- subRule.map((item) => {
1024
- const isVar = item !== null && typeof item === "object" && Object.hasOwn(item, "var");
1025
- if (isVar) {
1026
- const exists = jsonLogic.apply({ var: removeIndicesFromPath(item.var) }, data);
1027
- if (exists === null) {
1028
- throw Error(errorMessage(item));
1029
- }
1030
- } else {
1031
- checkRuleIntegrity(item, id, data);
1032
- }
1033
- });
1034
- });
1035
- }
1036
- function throwIfUnknownOperator(operator, subRule, id) {
1037
- try {
1038
- jsonLogic.apply({ [operator]: subRule });
1039
- } catch (e) {
1040
- if (e.message === `Unrecognized operation ${operator}`) {
1041
- throw Error(
1042
- `[json-schema-form] json-logic error: in "${id}" rule there is an unknown operator "${operator}".`
1043
- );
1044
- }
1045
- }
1046
- }
1047
- var regexToGetIndices = /\.\d+\./g;
1048
- function removeIndicesFromPath(path) {
1049
- const intermediatePath = path.replace(regexToGetIndices, ".");
1050
- return intermediatePath.replace(/\.\d+$/, "");
1051
- }
1052
- function processJSONLogicNode({
1053
- node,
1054
- formFields,
1055
- formValues,
1056
- accRequired,
1057
- parentID,
1058
- logic
1059
- }) {
1060
- const requiredFields = new Set(accRequired);
1061
- if (node.allOf) {
1062
- node.allOf.map(
1063
- (allOfNode) => processJSONLogicNode({ node: allOfNode, formValues, formFields, logic, parentID })
1064
- ).forEach(({ required: allOfItemRequired }) => {
1065
- allOfItemRequired.forEach(requiredFields.add, requiredFields);
1066
- });
1067
- }
1068
- if (node.if) {
1069
- const matchesPropertyCondition = checkIfConditionMatchesProperties(
1070
- node,
1071
- formValues,
1072
- formFields,
1073
- logic
1074
- );
1075
- const matchesValidationsAndComputedValues = matchesPropertyCondition && checkIfMatchesValidationsAndComputedValues(node, formValues, logic, parentID);
1076
- const isConditionMatch = matchesPropertyCondition && matchesValidationsAndComputedValues;
1077
- let nextNode;
1078
- if (isConditionMatch && node.then) {
1079
- nextNode = node.then;
1080
- }
1081
- if (!isConditionMatch && node.else) {
1082
- nextNode = node.else;
1083
- }
1084
- if (nextNode) {
1085
- const { required: branchRequired } = processNode({
1086
- node: nextNode,
1087
- formValues,
1088
- formFields,
1089
- accRequired,
1090
- logic,
1091
- parentID
1092
- });
1093
- branchRequired.forEach((field) => requiredFields.add(field));
1094
- }
1095
- }
1096
- return { required: requiredFields };
1097
- }
1098
-
1099
- // src/helpers.js
1100
- var dynamicInternalJsfAttrs = [
1101
- "isVisible",
1102
- // Driven from conditionals state
1103
- "fields",
1104
- // driven from group-array
1105
- "getComputedAttributes",
1106
- // From json-logic
1107
- "computedAttributes",
1108
- // From json-logic
1109
- "calculateConditionalProperties",
1110
- // driven from conditionals
1111
- "calculateCustomValidationProperties",
1112
- // To be deprecated in favor of json-logic
1113
- "scopedJsonSchema",
1114
- // The respective JSON Schema
1115
- // HOTFIX/TODO Internal customizations, check test conditions.test.js for more info.
1116
- "Component",
1117
- "calculateDynamicProperties",
1118
- "visibilityCondition"
1119
- ];
1120
- var dynamicInternalJsfAttrsObj = Object.fromEntries(
1121
- dynamicInternalJsfAttrs.map((k) => [k, true])
1122
- );
1123
- function removeConditionalStaleAttributes(field, conditionalAttrs, rootAttrs) {
1124
- Object.keys(field).forEach((key) => {
1125
- if (conditionalAttrs[key] === void 0 && rootAttrs[key] === void 0 && // Don't remove attrs that were declared in the root field.
1126
- dynamicInternalJsfAttrsObj[key] === void 0) {
1127
- field[key] = void 0;
1128
- }
1129
- });
1130
- }
1131
- function hasType(type, typeName) {
1132
- return Array.isArray(type) ? type.includes(typeName) : type === typeName;
1133
- }
1134
- function getField(fieldName, fields) {
1135
- return fields.find(({ name }) => name === fieldName);
1136
- }
1137
- function validateFieldSchema(field, value, logic) {
1138
- const validator = buildYupSchema(field, {}, logic);
1139
- return validator().isValidSync(value);
1140
- }
1141
- function compareFormValueWithSchemaValue(formValue, schemaValue) {
1142
- const currentPropertyValue = typeof schemaValue === "number" ? schemaValue : schemaValue || void 0;
1143
- return String(formValue) === String(currentPropertyValue);
1144
- }
1145
- function isFieldFilled(fieldValue) {
1146
- return Array.isArray(fieldValue) ? fieldValue.length > 0 : !!fieldValue;
1147
- }
1148
- function findFirstAnyOfMatch(nodes, formValues) {
1149
- return nodes.find(
1150
- ({ required }) => required?.some((fieldName) => isFieldFilled(formValues[fieldName]))
1151
- ) || nodes[0];
1152
- }
1153
- function getPrefillSubFieldValues(field, defaultValues, parentFieldKeyPath) {
1154
- let initialValue = defaultValues ?? {};
1155
- let fieldKeyPath = field.name;
1156
- if (parentFieldKeyPath) {
1157
- fieldKeyPath = fieldKeyPath ? `${parentFieldKeyPath}.${fieldKeyPath}` : parentFieldKeyPath;
1158
- }
1159
- const subFields = field.fields;
1160
- if (Array.isArray(subFields)) {
1161
- const subFieldValues = {};
1162
- subFields.forEach((subField) => {
1163
- Object.assign(
1164
- subFieldValues,
1165
- getPrefillSubFieldValues(subField, initialValue[field.name], fieldKeyPath)
1166
- );
1167
- });
1168
- if (field.inputType === supportedTypes.FIELDSET && field.valueGroupingDisabled) {
1169
- Object.assign(initialValue, subFieldValues);
1170
- } else {
1171
- initialValue[field.name] = subFieldValues;
1172
- }
1173
- } else {
1174
- if (typeof initialValue !== "object") {
1175
- console.warn(
1176
- `Field "${parentFieldKeyPath}"'s value is "${initialValue}", but should be type object.`
1177
- );
1178
- initialValue = getPrefillValues([field], {
1179
- // TODO nested fieldsets are not handled
1180
- });
1181
- } else {
1182
- initialValue = getPrefillValues([field], initialValue);
1183
- }
1184
- }
1185
- return initialValue;
1186
- }
1187
- function getPrefillValues(fields, initialValues = {}) {
1188
- fields.forEach((field) => {
1189
- const fieldName = field.name;
1190
- switch (field.type) {
1191
- case supportedTypes.GROUP_ARRAY: {
1192
- initialValues[fieldName] = initialValues[fieldName]?.map(
1193
- (subFieldValues) => getPrefillValues(field.fields(), subFieldValues)
1194
- );
1195
- break;
1196
- }
1197
- case supportedTypes.FIELDSET: {
1198
- const subFieldValues = getPrefillSubFieldValues(field, initialValues);
1199
- Object.assign(initialValues, subFieldValues);
1200
- break;
1201
- }
1202
- default: {
1203
- if (!initialValues[fieldName]) {
1204
- initialValues[fieldName] = field.default;
1205
- }
1206
- break;
1207
- }
1208
- }
1209
- });
1210
- return initialValues;
1211
- }
1212
- function updateField(field, requiredFields, node, formValues, logic, config) {
1213
- if (!field) {
1214
- return;
1215
- }
1216
- const fieldIsRequired = requiredFields.has(field.name);
1217
- if (node.properties && hasProperty(node.properties, field.name)) {
1218
- field.isVisible = !!node.properties[field.name];
1219
- }
1220
- if (fieldIsRequired) {
1221
- field.isVisible = true;
1222
- }
1223
- const updateAttributes = (fieldAttrs) => {
1224
- Object.entries(fieldAttrs).forEach(([key, value]) => {
1225
- field[key] = value;
1226
- if (key === "schema" && typeof value === "function") {
1227
- field[key] = value();
1228
- }
1229
- if (key === "value") {
1230
- const readOnlyPropertyWasUpdated = typeof fieldAttrs.readOnly !== "undefined";
1231
- const isReadonlyByDefault = field.readOnly;
1232
- const isReadonly = readOnlyPropertyWasUpdated ? fieldAttrs.readOnly : isReadonlyByDefault;
1233
- if (!isReadonly && (value === null || field.inputType === "checkbox")) {
1234
- field.value = void 0;
1235
- }
1236
- }
1237
- });
1238
- };
1239
- if (field.getComputedAttributes) {
1240
- const newAttributes = field.getComputedAttributes({
1241
- field,
1242
- isRequired: fieldIsRequired,
1243
- node,
1244
- formValues,
1245
- config,
1246
- logic
1247
- });
1248
- updateAttributes(newAttributes);
1249
- }
1250
- if (field.calculateConditionalProperties) {
1251
- const { rootFieldAttrs, newAttributes } = field.calculateConditionalProperties({
1252
- isRequired: fieldIsRequired,
1253
- conditionBranch: node,
1254
- formValues
1255
- });
1256
- updateAttributes(newAttributes);
1257
- removeConditionalStaleAttributes(field, newAttributes, rootFieldAttrs);
1258
- }
1259
- if (field.calculateCustomValidationProperties) {
1260
- const newAttributes = field.calculateCustomValidationProperties(
1261
- fieldIsRequired,
1262
- node,
1263
- formValues
1264
- );
1265
- updateAttributes(newAttributes);
1266
- }
1267
- }
1268
- function processNode({
1269
- node,
1270
- formValues,
1271
- formFields,
1272
- accRequired = /* @__PURE__ */ new Set(),
1273
- parentID = "root",
1274
- logic
1275
- }) {
1276
- const requiredFields = new Set(accRequired);
1277
- Object.keys(node.properties ?? []).forEach((fieldName) => {
1278
- const field = getField(fieldName, formFields);
1279
- updateField(field, requiredFields, node, formValues, logic, { parentID });
1280
- });
1281
- node.required?.forEach((fieldName) => {
1282
- requiredFields.add(fieldName);
1283
- updateField(getField(fieldName, formFields), requiredFields, node, formValues, logic, {
1284
- parentID
1285
- });
1286
- });
1287
- if (node.if !== void 0) {
1288
- const matchesCondition = checkIfConditionMatchesProperties(node, formValues, formFields, logic);
1289
- if (matchesCondition && node.then) {
1290
- const { required: branchRequired } = processNode({
1291
- node: node.then,
1292
- formValues,
1293
- formFields,
1294
- accRequired: requiredFields,
1295
- parentID,
1296
- logic
1297
- });
1298
- branchRequired.forEach((field) => requiredFields.add(field));
1299
- } else if (node.else) {
1300
- const { required: branchRequired } = processNode({
1301
- node: node.else,
1302
- formValues,
1303
- formFields,
1304
- accRequired: requiredFields,
1305
- parentID,
1306
- logic
1307
- });
1308
- branchRequired.forEach((field) => requiredFields.add(field));
1309
- }
1310
- }
1311
- if (node.anyOf) {
1312
- const firstMatchOfAnyOf = findFirstAnyOfMatch(node.anyOf, formValues);
1313
- firstMatchOfAnyOf.required?.forEach((fieldName) => {
1314
- requiredFields.add(fieldName);
1315
- });
1316
- node.anyOf.forEach(({ required = [] }) => {
1317
- required.forEach((fieldName) => {
1318
- const field = getField(fieldName, formFields);
1319
- updateField(field, requiredFields, node, formValues, logic, { parentID });
1320
- });
1321
- });
1322
- }
1323
- if (node.allOf) {
1324
- node.allOf.map(
1325
- (allOfNode) => processNode({
1326
- node: allOfNode,
1327
- formValues,
1328
- formFields,
1329
- accRequired: requiredFields,
1330
- parentID,
1331
- logic
1332
- })
1333
- ).forEach(({ required: allOfItemRequired }) => {
1334
- allOfItemRequired.forEach(requiredFields.add, requiredFields);
1335
- });
1336
- }
1337
- if (node.properties) {
1338
- Object.entries(node.properties).forEach(([name, nestedNode]) => {
1339
- const inputType = getInputType(nestedNode);
1340
- if (inputType === supportedTypes.FIELDSET) {
1341
- processNode({
1342
- node: nestedNode,
1343
- formValues: formValues[name] || {},
1344
- formFields: getField(name, formFields).fields,
1345
- parentID: name,
1346
- logic
1347
- });
1348
- }
1349
- });
1350
- }
1351
- if (node["x-jsf-logic"]) {
1352
- const { required: requiredFromLogic } = processJSONLogicNode({
1353
- node: node["x-jsf-logic"],
1354
- formValues,
1355
- formFields,
1356
- accRequired: requiredFields,
1357
- parentID,
1358
- logic
1359
- });
1360
- requiredFromLogic.forEach((field) => requiredFields.add(field));
1361
- }
1362
- return {
1363
- required: requiredFields
1364
- };
1365
- }
1366
- function clearValuesIfNotVisible(fields, formValues) {
1367
- fields.forEach(({ isVisible = true, name, inputType, fields: nestedFields }) => {
1368
- if (!isVisible) {
1369
- formValues[name] = null;
1370
- }
1371
- if (inputType === supportedTypes.FIELDSET && nestedFields && formValues[name]) {
1372
- clearValuesIfNotVisible(nestedFields, formValues[name]);
1373
- }
1374
- });
1375
- }
1376
- function updateFieldsProperties(fields, formValues, jsonSchema, logic) {
1377
- if (!jsonSchema?.properties) {
1378
- return;
1379
- }
1380
- processNode({ node: jsonSchema, formValues, formFields: fields, logic });
1381
- clearValuesIfNotVisible(fields, formValues);
1382
- }
1383
- var notNullOption = (opt) => opt.const !== null;
1384
- function flatPresentation(item) {
1385
- return Object.entries(item).reduce((newItem, [key, value]) => {
1386
- if (key === "x-jsf-presentation") {
1387
- return {
1388
- ...newItem,
1389
- ...value
1390
- };
1391
- }
1392
- return {
1393
- ...newItem,
1394
- [key]: value
1395
- };
1396
- }, {});
1397
- }
1398
- function getFieldOptions(node, presentation) {
1399
- function convertToOptions(nodeOptions) {
1400
- return nodeOptions.filter(notNullOption).map(({ title, const: cons, ...item }) => ({
1401
- label: title,
1402
- value: cons,
1403
- ...flatPresentation(item)
1404
- }));
1405
- }
1406
- if (presentation.options) {
1407
- return presentation.options;
1408
- }
1409
- if (node.oneOf || presentation.inputType === "radio") {
1410
- return convertToOptions(node.oneOf || []);
1411
- }
1412
- if (node.items?.anyOf) {
1413
- return convertToOptions(node.items.anyOf);
1414
- }
1415
- return null;
1416
- }
1417
- function extractParametersFromNode(schemaNode) {
1418
- if (!schemaNode) {
1419
- return {};
1420
- }
1421
- const presentation = pickXKey(schemaNode, "presentation") ?? {};
1422
- const errorMessage = pickXKey(schemaNode, "errorMessage") ?? {};
1423
- const jsonLogicValidations = schemaNode["x-jsf-logic-validations"];
1424
- const computedAttributes = schemaNode["x-jsf-logic-computedAttrs"];
1425
- const decoratedComputedAttributes = getDecoratedComputedAttributes(computedAttributes);
1426
- const node = omit(schemaNode, ["x-jsf-presentation", "presentation"]);
1427
- const description = presentation?.description || node.description;
1428
- const statementDescription = presentation.statement?.description;
1429
- const value = typeof node.const !== "undefined" && typeof node.default !== "undefined" && node.const === node.default ? { forcedValue: node.const } : {};
1430
- return omitBy(
1431
- {
1432
- const: node.const,
1433
- ...value,
1434
- label: node.title,
1435
- readOnly: node.readOnly,
1436
- ...node.deprecated && {
1437
- deprecated: {
1438
- description: presentation.deprecated?.description
1439
- // @TODO/@IDEA These might be useful down the road :thinking:
1440
- // version: presentation.deprecated.version, // e.g. "1.1"
1441
- // replacement: presentation.deprecated.replacement, // e.g. ['contract_duration_type']
1442
- }
1443
- },
1444
- pattern: node.pattern,
1445
- options: getFieldOptions(node, presentation),
1446
- items: node.items,
1447
- maxLength: node.maxLength,
1448
- minLength: node.minLength,
1449
- minimum: node.minimum,
1450
- maximum: node.maximum,
1451
- maxFileSize: node.maxFileSize,
1452
- // @deprecated in favor of presentation.maxFileSize
1453
- default: node.default,
1454
- format: node.format,
1455
- // Checkboxes conditions
1456
- // — For checkboxes that only accept one value (string)
1457
- ...presentation?.inputType === "checkbox" && { checkboxValue: node.const },
1458
- // - For checkboxes with boolean value
1459
- ...presentation?.inputType === "checkbox" && node.type === "boolean" && {
1460
- // true is what describes this checkbox as a boolean, regardless if its required or not
1461
- checkboxValue: true
1462
- },
1463
- ...hasType(node.type, "array") && {
1464
- multiple: true
1465
- },
1466
- // Handle [name].presentation
1467
- ...presentation,
1468
- jsonLogicValidations,
1469
- computedAttributes: decoratedComputedAttributes,
1470
- description,
1471
- extra: presentation.extra,
1472
- statement: presentation.statement && {
1473
- ...presentation.statement,
1474
- description: statementDescription
1475
- },
1476
- // Support scoped conditions (fieldsets)
1477
- if: node.if,
1478
- then: node.then,
1479
- else: node.else,
1480
- anyOf: node.anyOf,
1481
- allOf: node.allOf,
1482
- errorMessage
1483
- },
1484
- isNil
1485
- );
1486
- }
1487
- function yupToFormErrors(yupError) {
1488
- if (!yupError) {
1489
- return yupError;
1490
- }
1491
- const errors = {};
1492
- if (yupError.inner) {
1493
- if (yupError.inner.length === 0) {
1494
- return set(errors, yupError.path, yupError.message);
1495
- }
1496
- yupError.inner.forEach((err) => {
1497
- if (!get2(errors, err.path)) {
1498
- set(errors, err.path, err.message);
1499
- }
1500
- });
1501
- }
1502
- return errors;
1503
- }
1504
- var handleValuesChange = (fields, jsonSchema, config, logic) => (values) => {
1505
- updateFieldsProperties(fields, values, jsonSchema, logic);
1506
- const lazySchema = lazy(() => buildCompleteYupSchema(fields, config));
1507
- let errors;
1508
- try {
1509
- lazySchema.validateSync(values, {
1510
- abortEarly: false
1511
- });
1512
- } catch (err) {
1513
- if (err.name === "ValidationError") {
1514
- errors = err;
1515
- } else {
1516
- console.warn(`Warning: An unhandled error was caught during validationSchema`, err);
1517
- }
1518
- }
1519
- return {
1520
- yupError: errors,
1521
- formErrors: yupToFormErrors(errors)
1522
- };
1523
- };
1524
- function getDecoratedComputedAttributes(computedAttributes) {
1525
- const isEqualConstAndDefault = computedAttributes?.const === computedAttributes?.default;
1526
- return {
1527
- ...computedAttributes ?? {},
1528
- ...computedAttributes?.const && computedAttributes?.default && isEqualConstAndDefault ? { forcedValue: computedAttributes.const } : {}
1529
- };
1530
- }
1531
-
1532
- // src/calculateConditionalProperties.js
1533
- function isFieldRequired(node, field) {
1534
- return (
1535
- // Check base root required
1536
- field.scopedJsonSchema?.required?.includes(field.name) || // Check conditional required
1537
- node?.required?.includes(field.name)
1538
- );
1539
- }
1540
- function rebuildFieldset(fields, property) {
1541
- if (property?.properties) {
1542
- return fields.map((field) => {
1543
- const propertyConditionals = property.properties[field.name];
1544
- if (!propertyConditionals) {
1545
- return field;
1546
- }
1547
- const newFieldParams = extractParametersFromNode(propertyConditionals);
1548
- if (field.fields) {
1549
- return {
1550
- ...field,
1551
- ...newFieldParams,
1552
- fields: rebuildFieldset(field.fields, propertyConditionals)
1553
- };
1554
- }
1555
- return {
1556
- ...field,
1557
- ...newFieldParams,
1558
- required: isFieldRequired(property, field)
1559
- };
1560
- });
1561
- }
1562
- return fields.map((field) => ({
1563
- ...field,
1564
- required: isFieldRequired(property, field)
1565
- }));
1566
- }
1567
- function calculateConditionalProperties({ fieldParams, customProperties, logic, config }) {
1568
- return ({ isRequired, conditionBranch, formValues }) => {
1569
- const conditionalProperty = conditionBranch?.properties?.[fieldParams.name];
1570
- if (conditionalProperty) {
1571
- const presentation = pickXKey(conditionalProperty, "presentation") ?? {};
1572
- const fieldDescription = getFieldDescription(conditionalProperty, customProperties);
1573
- const newFieldParams = extractParametersFromNode({
1574
- ...conditionalProperty,
1575
- ...fieldDescription
1576
- });
1577
- let fieldSetFields;
1578
- if (fieldParams.inputType === supportedTypes.FIELDSET) {
1579
- fieldSetFields = rebuildFieldset(fieldParams.fields, conditionalProperty);
1580
- newFieldParams.fields = fieldSetFields;
1581
- }
1582
- const { computedAttributes, ...restNewFieldParams } = newFieldParams;
1583
- const calculatedComputedAttributes = computedAttributes ? calculateComputedAttributes(newFieldParams, config)({ logic, formValues }) : {};
1584
- const jsonLogicValidations = [
1585
- ...fieldParams.jsonLogicValidations ?? [],
1586
- ...restNewFieldParams.jsonLogicValidations ?? []
1587
- ];
1588
- const base = {
1589
- isVisible: true,
1590
- required: isRequired,
1591
- ...presentation?.inputType && { type: presentation.inputType },
1592
- ...calculatedComputedAttributes,
1593
- ...calculatedComputedAttributes.value ? { value: calculatedComputedAttributes.value } : { value: void 0 },
1594
- schema: buildYupSchema(
1595
- {
1596
- ...fieldParams,
1597
- ...restNewFieldParams,
1598
- ...calculatedComputedAttributes,
1599
- jsonLogicValidations,
1600
- // If there are inner fields (case of fieldset) they need to be updated based on the condition
1601
- fields: fieldSetFields,
1602
- required: isRequired
1603
- },
1604
- config,
1605
- logic
1606
- )
1607
- };
1608
- return {
1609
- rootFieldAttrs: fieldParams,
1610
- newAttributes: omit2(merge2(base, presentation, newFieldParams), ["inputType"])
1611
- };
1612
- }
1613
- const isVisible = isRequired;
1614
- return {
1615
- rootFieldAttrs: fieldParams,
1616
- newAttributes: {
1617
- isVisible,
1618
- required: isRequired,
1619
- schema: buildYupSchema({
1620
- ...fieldParams,
1621
- ...extractParametersFromNode(conditionBranch),
1622
- required: isRequired
1623
- })
1624
- }
1625
- };
1626
- };
1627
- }
1628
-
1629
- // src/calculateCustomValidationProperties.js
1630
- import inRange from "lodash/inRange";
1631
- import isFunction2 from "lodash/isFunction";
1632
- import isNil2 from "lodash/isNil";
1633
- import isObject from "lodash/isObject";
1634
- import mapValues from "lodash/mapValues";
1635
- import pick from "lodash/pick";
1636
- var SUPPORTED_CUSTOM_VALIDATION_FIELD_PARAMS = ["minimum", "maximum"];
1637
- var isCustomValidationAllowed = (fieldParams) => (customValidation, customValidationKey) => {
1638
- if (isNil2(customValidation)) {
1639
- return false;
1640
- }
1641
- const { minimum, maximum } = fieldParams;
1642
- const isAllowed = inRange(
1643
- customValidation,
1644
- minimum ?? -Infinity,
1645
- maximum ? maximum + 1 : Infinity
1646
- );
1647
- if (!isAllowed) {
1648
- const errorMessage = `Custom validation for ${fieldParams.name} is not allowed because ${customValidationKey}:${customValidation} is less strict than the original range: ${minimum} to ${maximum}`;
1649
- if (true) {
1650
- throw new Error(errorMessage);
1651
- } else {
1652
- console.warn(errorMessage);
1653
- }
1654
- }
1655
- return isAllowed;
1656
- };
1657
- function calculateCustomValidationProperties(fieldParams, customProperties) {
1658
- return (isRequired, conditionBranch, formValues) => {
1659
- const params = { ...fieldParams, ...conditionBranch?.properties?.[fieldParams.name] };
1660
- const presentation = pickXKey(params, "presentation") ?? {};
1661
- const supportedParams = pick(customProperties, SUPPORTED_CUSTOM_VALIDATION_FIELD_PARAMS);
1662
- const checkIfAllowed = isCustomValidationAllowed(params);
1663
- const customErrorMessages = [];
1664
- const fieldParamsWithNewValidation = mapValues(
1665
- supportedParams,
1666
- (customValidationValue, customValidationKey) => {
1667
- const originalValidation = params[customValidationKey];
1668
- const customValidation = isFunction2(customValidationValue) ? customValidationValue(formValues, params) : customValidationValue;
1669
- if (isObject(customValidation)) {
1670
- if (checkIfAllowed(customValidation[customValidationKey], customValidationKey)) {
1671
- customErrorMessages.push(pickXKey(customValidation, "errorMessage"));
1672
- return customValidation[customValidationKey];
1673
- }
1674
- return originalValidation;
1675
- }
1676
- return checkIfAllowed(customValidation, customValidationKey) ? customValidation : originalValidation;
1677
- }
1678
- );
1679
- const errorMessage = Object.assign({ ...params.errorMessage }, ...customErrorMessages);
1680
- return {
1681
- ...params,
1682
- ...fieldParamsWithNewValidation,
1683
- type: presentation?.inputType || params.inputType,
1684
- errorMessage,
1685
- required: isRequired,
1686
- schema: buildYupSchema({
1687
- ...params,
1688
- ...fieldParamsWithNewValidation,
1689
- errorMessage,
1690
- required: isRequired
1691
- })
1692
- };
1693
- };
1694
- }
1695
-
1696
- // src/createHeadlessForm.js
1697
- function sortByOrderOrPosition(a, b, order) {
1698
- if (order) {
1699
- return order.indexOf(a.name) - order.indexOf(b.name);
1700
- }
1701
- return a.position - b.position;
1702
- }
1703
- function removeInvalidAttributes(fields) {
1704
- return omit3(fields, ["items", "maxFileSize", "isDynamic"]);
1705
- }
1706
- function buildFieldParameters(name, fieldProperties, required = [], config = {}, logic) {
1707
- const { position } = pickXKey(fieldProperties, "presentation") ?? {};
1708
- let fields;
1709
- const inputType = getInputType(fieldProperties, config.strictInputType, name);
1710
- if (inputType === supportedTypes.FIELDSET) {
1711
- fields = getFieldsFromJSONSchema(
1712
- fieldProperties,
1713
- {
1714
- customProperties: get3(config, `customProperties.${name}.customProperties`, {}),
1715
- parentID: name
1716
- },
1717
- logic
1718
- );
1719
- }
1720
- const result = {
1721
- name,
1722
- inputType,
1723
- jsonType: fieldProperties.type,
1724
- type: inputType,
1725
- // @deprecated in favor of inputType,
1726
- required: required?.includes(name) ?? false,
1727
- fields,
1728
- position,
1729
- ...extractParametersFromNode(fieldProperties)
1730
- };
1731
- return omitBy2(result, isNil3);
1732
- }
1733
- function convertJSONSchemaPropertiesToFieldParameters({ properties, required, "x-jsf-order": order }, config = {}) {
1734
- const sortFields = (a, b) => sortByOrderOrPosition(a, b, order);
1735
- return Object.entries(properties).filter(([, value]) => typeof value === "object").map(([key, value]) => buildFieldParameters(key, value, required, config)).sort(sortFields).map(({ position, ...fieldParams }) => fieldParams);
1736
- }
1737
- function applyFieldsDependencies(fieldsParameters, node) {
1738
- if (node?.then) {
1739
- fieldsParameters.filter(
1740
- ({ name }) => node.then?.properties?.[name] || node.then?.required?.includes(name) || node.else?.properties?.[name] || node.else?.required?.includes(name)
1741
- ).forEach((property) => {
1742
- property.isDynamic = true;
1743
- });
1744
- applyFieldsDependencies(fieldsParameters, node.then);
1745
- }
1746
- if (node?.anyOf) {
1747
- fieldsParameters.filter(({ name }) => node.anyOf.some(({ required }) => required?.includes(name))).forEach((property) => {
1748
- property.isDynamic = true;
1749
- });
1750
- applyFieldsDependencies(fieldsParameters, node.then);
1751
- }
1752
- if (node?.allOf) {
1753
- node.allOf.forEach((condition) => {
1754
- applyFieldsDependencies(fieldsParameters, condition);
1755
- });
1756
- }
1757
- if (node?.["x-jsf-logic"]) {
1758
- applyFieldsDependencies(fieldsParameters, node["x-jsf-logic"]);
1759
- }
1760
- }
1761
- function getCustomPropertiesForField(fieldParams, config) {
1762
- return config?.customProperties?.[fieldParams.name];
1763
- }
1764
- function getComposeFunctionForField(fieldParams, hasCustomizations) {
1765
- const composeFn = inputTypeMap[fieldParams.inputType] || _composeFieldArbitraryClosure(fieldParams.inputType);
1766
- if (hasCustomizations) {
1767
- return _composeFieldCustomClosure(composeFn);
1768
- }
1769
- return composeFn;
1770
- }
1771
- function buildField(fieldParams, config, scopedJsonSchema, logic) {
1772
- const customProperties = getCustomPropertiesForField(fieldParams, config);
1773
- const composeFn = getComposeFunctionForField(fieldParams, !!customProperties);
1774
- const yupSchema = buildYupSchema(fieldParams, config, logic);
1775
- const calculateConditionalFieldsClosure = fieldParams.isDynamic && calculateConditionalProperties({ fieldParams, customProperties, logic, config });
1776
- const calculateCustomValidationPropertiesClosure = calculateCustomValidationProperties(
1777
- fieldParams,
1778
- customProperties
1779
- );
1780
- const getComputedAttributes = Object.keys(fieldParams.computedAttributes).length > 0 && calculateComputedAttributes(fieldParams, config);
1781
- const hasCustomValidations = !!customProperties && size(pick2(customProperties, SUPPORTED_CUSTOM_VALIDATION_FIELD_PARAMS)) > 0;
1782
- const finalFieldParams = {
1783
- // invalid attribute cleanup
1784
- ...removeInvalidAttributes(fieldParams),
1785
- // calculateConditionalProperties function if needed
1786
- ...!!calculateConditionalFieldsClosure && {
1787
- calculateConditionalProperties: calculateConditionalFieldsClosure
1788
- },
1789
- // calculateCustomValidationProperties function if needed
1790
- ...hasCustomValidations && {
1791
- calculateCustomValidationProperties: calculateCustomValidationPropertiesClosure
1792
- },
1793
- ...getComputedAttributes && { getComputedAttributes },
1794
- // field customization properties
1795
- ...customProperties && { fieldCustomization: customProperties },
1796
- // base schema
1797
- schema: yupSchema(),
1798
- scopedJsonSchema
1799
- };
1800
- return composeFn(finalFieldParams);
1801
- }
1802
- function getFieldsFromJSONSchema(scopedJsonSchema, config, logic) {
1803
- if (!scopedJsonSchema) {
1804
- return [];
1805
- }
1806
- const fieldParamsList = convertJSONSchemaPropertiesToFieldParameters(scopedJsonSchema, config);
1807
- applyFieldsDependencies(fieldParamsList, scopedJsonSchema);
1808
- const fields = [];
1809
- fieldParamsList.forEach((fieldParams) => {
1810
- if (fieldParams.inputType === "group-array") {
1811
- const groupArrayItems = convertJSONSchemaPropertiesToFieldParameters(fieldParams.items);
1812
- const groupArrayFields = groupArrayItems.map((groupArrayItem) => {
1813
- groupArrayItem.nameKey = groupArrayItem.name;
1814
- const customProperties = null;
1815
- const composeFn = getComposeFunctionForField(groupArrayItem, !!customProperties);
1816
- return composeFn(groupArrayItem);
1817
- });
1818
- fieldParams.nameKey = fieldParams.name;
1819
- fieldParams.nthFieldGroup = {
1820
- name: fieldParams.name,
1821
- label: fieldParams.label,
1822
- description: fieldParams.description,
1823
- fields: () => groupArrayFields,
1824
- addFieldText: fieldParams.addFieldText
1825
- };
1826
- buildField(fieldParams, config, scopedJsonSchema, logic).forEach((groupField) => {
1827
- fields.push(groupField);
1828
- });
1829
- } else {
1830
- fields.push(buildField(fieldParams, config, scopedJsonSchema, logic));
1831
- }
1832
- });
1833
- return fields;
1834
- }
1835
- function createHeadlessForm(jsonSchema, customConfig = {}) {
1836
- const config = {
1837
- strictInputType: true,
1838
- ...customConfig
1839
- };
1840
- try {
1841
- const logic = createValidationChecker(jsonSchema);
1842
- const fields = getFieldsFromJSONSchema(jsonSchema, config, logic);
1843
- const handleValidation = handleValuesChange(fields, jsonSchema, config, logic);
1844
- updateFieldsProperties(
1845
- fields,
1846
- getPrefillValues(fields, config.initialValues),
1847
- jsonSchema,
1848
- logic
1849
- );
1850
- return {
1851
- fields,
1852
- handleValidation,
1853
- isError: false
1854
- };
1855
- } catch (error) {
1856
- console.error("JSON Schema invalid!", error);
1857
- return {
1858
- fields: [],
1859
- isError: true,
1860
- error
1861
- };
1862
- }
1863
- }
1864
-
1865
- // src/modify.js
1866
- import difference from "lodash/difference";
1867
- import get4 from "lodash/get";
1868
- import intersection from "lodash/intersection";
1869
- import merge3 from "lodash/merge";
1870
- import mergeWith from "lodash/mergeWith";
1871
- import set2 from "lodash/set";
1872
- var WARNING_TYPES = {
1873
- FIELD_TO_CHANGE_NOT_FOUND: "FIELD_TO_CHANGE_NOT_FOUND",
1874
- ORDER_MISSING_FIELDS: "ORDER_MISSING_FIELDS",
1875
- FIELD_TO_CREATE_EXISTS: "FIELD_TO_CREATE_EXISTS",
1876
- PICK_MISSED_FIELD: "PICK_MISSED_FIELD"
1877
- };
1878
- function shortToFullPath(path) {
1879
- return path.replace(".", ".properties.");
1880
- }
1881
- function mergeReplaceArray(_, newVal) {
1882
- return Array.isArray(newVal) ? newVal : void 0;
1883
- }
1884
- function standardizeAttrs(attrs) {
1885
- const { errorMessage, presentation, properties, ...rest } = attrs;
1886
- return {
1887
- ...rest,
1888
- ...presentation ? { "x-jsf-presentation": presentation } : {},
1889
- ...errorMessage ? { "x-jsf-errorMessage": errorMessage } : {}
1890
- };
1891
- }
1892
- function isConditionalReferencingAnyPickedField(condition, fieldsToPick) {
1893
- const { if: ifCondition, then: thenCondition, else: elseCondition } = condition;
1894
- const inIf = intersection(ifCondition.required, fieldsToPick);
1895
- if (inIf.length > 0) {
1896
- return true;
1897
- }
1898
- const inThen = intersection(thenCondition.required, fieldsToPick) || intersection(Object.keys(thenCondition.properties), fieldsToPick);
1899
- if (inThen.length > 0) {
1900
- return true;
1901
- }
1902
- const inElse = intersection(elseCondition.required, fieldsToPick) || intersection(Object.keys(elseCondition.properties), fieldsToPick);
1903
- if (inElse.length > 0) {
1904
- return true;
1905
- }
1906
- return false;
1907
- }
1908
- function rewriteFields(schema, fieldsConfig) {
1909
- if (!fieldsConfig)
1910
- return { warnings: null };
1911
- const warnings = [];
1912
- const fieldsToModify = Object.entries(fieldsConfig);
1913
- fieldsToModify.forEach(([shortPath, mutation]) => {
1914
- const fieldPath = shortToFullPath(shortPath);
1915
- if (!get4(schema.properties, fieldPath)) {
1916
- warnings.push({
1917
- type: WARNING_TYPES.FIELD_TO_CHANGE_NOT_FOUND,
1918
- message: `Changing field "${shortPath}" was ignored because it does not exist.`
1919
- });
1920
- return;
1921
- }
1922
- const fieldAttrs = get4(schema.properties, fieldPath);
1923
- const fieldChanges = typeof mutation === "function" ? mutation(fieldAttrs) : mutation;
1924
- mergeWith(
1925
- get4(schema.properties, fieldPath),
1926
- {
1927
- ...fieldAttrs,
1928
- ...standardizeAttrs(fieldChanges)
1929
- },
1930
- mergeReplaceArray
1931
- );
1932
- if (fieldChanges.properties) {
1933
- const result = rewriteFields(get4(schema.properties, fieldPath), fieldChanges.properties);
1934
- warnings.push(result.warnings);
1935
- }
1936
- });
1937
- return { warnings: warnings.flat() };
1938
- }
1939
- function rewriteAllFields(schema, configCallback, context) {
1940
- if (!configCallback)
1941
- return null;
1942
- const parentName = context?.parent;
1943
- Object.entries(schema.properties).forEach(([fieldName, fieldAttrs]) => {
1944
- const fullName = parentName ? `${parentName}.${fieldName}` : fieldName;
1945
- mergeWith(
1946
- get4(schema.properties, fieldName),
1947
- {
1948
- ...fieldAttrs,
1949
- ...standardizeAttrs(configCallback(fullName, fieldAttrs))
1950
- },
1951
- mergeReplaceArray
1952
- );
1953
- if (fieldAttrs.properties) {
1954
- rewriteAllFields(fieldAttrs, configCallback, {
1955
- parent: fieldName
1956
- });
1957
- }
1958
- });
1959
- }
1960
- function reorderFields(schema, configOrder) {
1961
- if (!configOrder)
1962
- return { warnings: null };
1963
- const warnings = [];
1964
- const originalOrder = schema["x-jsf-order"] || [];
1965
- const orderConfig = typeof configOrder === "function" ? configOrder(originalOrder) : configOrder;
1966
- const remaining = difference(originalOrder, orderConfig);
1967
- if (remaining.length > 0) {
1968
- warnings.push({
1969
- type: WARNING_TYPES.ORDER_MISSING_FIELDS,
1970
- message: `Some fields got forgotten in the new order. They were automatically appended: ${remaining.join(
1971
- ", "
1972
- )}`
1973
- });
1974
- }
1975
- schema["x-jsf-order"] = [...orderConfig, ...remaining];
1976
- return { warnings };
1977
- }
1978
- function createFields(schema, fieldsConfig) {
1979
- if (!fieldsConfig)
1980
- return { warnings: null };
1981
- const warnings = [];
1982
- const fieldsToCreate = Object.entries(fieldsConfig);
1983
- fieldsToCreate.forEach(([shortPath, fieldAttrs]) => {
1984
- const fieldPath = shortToFullPath(shortPath);
1985
- if (fieldAttrs.properties) {
1986
- const result = createFields(get4(schema.properties, fieldPath), fieldAttrs.properties);
1987
- warnings.push(result.warnings);
1988
- }
1989
- const fieldInSchema = get4(schema.properties, fieldPath);
1990
- if (fieldInSchema) {
1991
- warnings.push({
1992
- type: WARNING_TYPES.FIELD_TO_CREATE_EXISTS,
1993
- message: `Creating field "${shortPath}" was ignored because it already exists.`
1994
- });
1995
- return;
1996
- }
1997
- const fieldInObjectPath = set2({}, fieldPath, standardizeAttrs(fieldAttrs));
1998
- merge3(schema.properties, fieldInObjectPath);
1999
- });
2000
- return { warnings: warnings.flat() };
2001
- }
2002
- function pickFields(originalSchema, fieldsToPick) {
2003
- if (!fieldsToPick) {
2004
- return { schema: originalSchema, warnings: null };
2005
- }
2006
- const newSchema = {
2007
- properties: {}
2008
- };
2009
- Object.entries(originalSchema).forEach(([attrKey, attrValue]) => {
2010
- switch (attrKey) {
2011
- case "properties":
2012
- fieldsToPick.forEach((fieldPath) => {
2013
- set2(newSchema.properties, fieldPath, attrValue[fieldPath]);
2014
- });
2015
- break;
2016
- case "x-jsf-order":
2017
- case "required":
2018
- newSchema[attrKey] = attrValue.filter((fieldName) => fieldsToPick.includes(fieldName));
2019
- break;
2020
- case "allOf": {
2021
- const newAllOf = originalSchema.allOf.filter(
2022
- (condition) => isConditionalReferencingAnyPickedField(condition, fieldsToPick)
2023
- );
2024
- newSchema[attrKey] = newAllOf;
2025
- break;
2026
- }
2027
- default:
2028
- newSchema[attrKey] = attrValue;
2029
- }
2030
- });
2031
- let missingFields = {};
2032
- newSchema.allOf?.forEach((condition) => {
2033
- const { if: ifCondition, then: thenCondition, else: elseCondition } = condition;
2034
- const index = originalSchema.allOf.indexOf(condition);
2035
- missingFields = {
2036
- ...missingFields,
2037
- ...findMissingFields(ifCondition, {
2038
- fields: fieldsToPick,
2039
- path: `allOf[${index}].if`
2040
- }),
2041
- ...findMissingFields(thenCondition, {
2042
- fields: fieldsToPick,
2043
- path: `allOf[${index}].then`
2044
- }),
2045
- ...findMissingFields(elseCondition, {
2046
- fields: fieldsToPick,
2047
- path: `allOf[${index}].else`
2048
- })
2049
- };
2050
- });
2051
- const warnings = [];
2052
- if (Object.keys(missingFields).length > 0) {
2053
- Object.entries(missingFields).forEach(([fieldName]) => {
2054
- set2(newSchema.properties, fieldName, originalSchema.properties[fieldName]);
2055
- });
2056
- warnings.push({
2057
- type: WARNING_TYPES.PICK_MISSED_FIELD,
2058
- message: `The picked fields are in conditionals that refeer other fields. They added automatically: ${Object.keys(
2059
- missingFields
2060
- ).map((name) => `"${name}"`).join(", ")}. Check "meta" for more details.`,
2061
- meta: missingFields
2062
- });
2063
- }
2064
- return { schema: newSchema, warnings };
2065
- }
2066
- function findMissingFields(conditional, { fields, path }) {
2067
- if (!conditional) {
2068
- return null;
2069
- }
2070
- let missingFields = {};
2071
- conditional.required?.forEach((fieldName) => {
2072
- if (!fields.includes(fieldName)) {
2073
- missingFields[fieldName] = {
2074
- path
2075
- };
2076
- }
2077
- });
2078
- Object.entries(conditional.properties || []).forEach(([fieldName]) => {
2079
- if (!fields.includes(fieldName)) {
2080
- missingFields[fieldName] = { path };
2081
- }
2082
- });
2083
- return missingFields;
2084
- }
2085
- function modify(originalSchema, config) {
2086
- const schema = JSON.parse(JSON.stringify(originalSchema));
2087
- const resultRewrite = rewriteFields(schema, config.fields);
2088
- rewriteAllFields(schema, config.allFields);
2089
- const resultCreate = createFields(schema, config.create);
2090
- const resultPick = pickFields(schema, config.pick);
2091
- const finalSchema = resultPick.schema;
2092
- const resultReorder = reorderFields(finalSchema, config.orderRoot);
2093
- if (!config.muteLogging) {
2094
- console.warn(
2095
- "json-schema-form modify(): We highly recommend you to handle/report the returned `warnings` as they highlight possible bugs in your modifications. To mute this log, pass `muteLogging: true` to the config."
2096
- );
2097
- }
2098
- const warnings = [
2099
- resultRewrite.warnings,
2100
- resultCreate.warnings,
2101
- resultPick.warnings,
2102
- resultReorder.warnings
2103
- ].flat().filter(Boolean);
2104
- return {
2105
- schema: finalSchema,
2106
- warnings
2107
- };
2108
- }
2109
- export {
2110
- buildCompleteYupSchema,
2111
- createHeadlessForm,
2112
- modify,
2113
- pickXKey
2114
- };