@rjsf/utils 5.0.0-beta.17 → 5.0.0-beta.19

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.
@@ -1,8 +1,8 @@
1
1
  (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('lodash-es/isEqualWith'), require('lodash-es/get'), require('lodash-es/isEmpty'), require('jsonpointer'), require('lodash-es/omit'), require('lodash-es/set'), require('json-schema-merge-allof'), require('lodash-es/union'), require('lodash-es/cloneDeep'), require('react'), require('react-is'), require('lodash-es/isString')) :
3
- typeof define === 'function' && define.amd ? define(['exports', 'lodash-es/isEqualWith', 'lodash-es/get', 'lodash-es/isEmpty', 'jsonpointer', 'lodash-es/omit', 'lodash-es/set', 'json-schema-merge-allof', 'lodash-es/union', 'lodash-es/cloneDeep', 'react', 'react-is', 'lodash-es/isString'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["@rjsf/utils"] = {}, global.isEqualWith, global.get, global.isEmpty, global.jsonpointer, global.omit, global.set, global.mergeAllOf, global.union, global.cloneDeep, global.React, global.ReactIs, global.isString));
5
- })(this, (function (exports, isEqualWith, get, isEmpty, jsonpointer, omit, set, mergeAllOf, union, cloneDeep, React, ReactIs, isString) { 'use strict';
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('lodash-es/isEqualWith'), require('lodash-es/get'), require('lodash-es/isEmpty'), require('jsonpointer'), require('lodash-es/omit'), require('lodash-es/has'), require('lodash-es/isObject'), require('lodash-es/isString'), require('lodash-es/reduce'), require('lodash-es/times'), require('lodash-es/set'), require('json-schema-merge-allof'), require('lodash-es/union'), require('lodash-es/cloneDeep'), require('react'), require('react-is')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', 'lodash-es/isEqualWith', 'lodash-es/get', 'lodash-es/isEmpty', 'jsonpointer', 'lodash-es/omit', 'lodash-es/has', 'lodash-es/isObject', 'lodash-es/isString', 'lodash-es/reduce', 'lodash-es/times', 'lodash-es/set', 'json-schema-merge-allof', 'lodash-es/union', 'lodash-es/cloneDeep', 'react', 'react-is'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["@rjsf/utils"] = {}, global.isEqualWith, global.get, global.isEmpty, global.jsonpointer, global.omit, global.has, global.isObject$1, global.isString, global.reduce, global.times, global.set, global.mergeAllOf, global.union, global.cloneDeep, global.React, global.ReactIs));
5
+ })(this, (function (exports, isEqualWith, get, isEmpty, jsonpointer, omit, has, isObject$1, isString, reduce, times, set, mergeAllOf, union, cloneDeep, React, ReactIs) { 'use strict';
6
6
 
7
7
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
8
8
 
@@ -11,13 +11,17 @@
11
11
  var isEmpty__default = /*#__PURE__*/_interopDefaultLegacy(isEmpty);
12
12
  var jsonpointer__default = /*#__PURE__*/_interopDefaultLegacy(jsonpointer);
13
13
  var omit__default = /*#__PURE__*/_interopDefaultLegacy(omit);
14
+ var has__default = /*#__PURE__*/_interopDefaultLegacy(has);
15
+ var isObject__default = /*#__PURE__*/_interopDefaultLegacy(isObject$1);
16
+ var isString__default = /*#__PURE__*/_interopDefaultLegacy(isString);
17
+ var reduce__default = /*#__PURE__*/_interopDefaultLegacy(reduce);
18
+ var times__default = /*#__PURE__*/_interopDefaultLegacy(times);
14
19
  var set__default = /*#__PURE__*/_interopDefaultLegacy(set);
15
20
  var mergeAllOf__default = /*#__PURE__*/_interopDefaultLegacy(mergeAllOf);
16
21
  var union__default = /*#__PURE__*/_interopDefaultLegacy(union);
17
22
  var cloneDeep__default = /*#__PURE__*/_interopDefaultLegacy(cloneDeep);
18
23
  var React__default = /*#__PURE__*/_interopDefaultLegacy(React);
19
24
  var ReactIs__default = /*#__PURE__*/_interopDefaultLegacy(ReactIs);
20
- var isString__default = /*#__PURE__*/_interopDefaultLegacy(isString);
21
25
 
22
26
  /** Determines whether a `thing` is an object for the purposes of RSJF. In this case, `thing` is an object if it has
23
27
  * the type `object` but is NOT null, an array or a File.
@@ -298,12 +302,14 @@
298
302
  }
299
303
 
300
304
  /** Given the `formData` and list of `options`, attempts to find the index of the option that best matches the data.
305
+ * Deprecated, use `getFirstMatchingOption()` instead.
301
306
  *
302
307
  * @param validator - An implementation of the `ValidatorType` interface that will be used when necessary
303
308
  * @param formData - The current formData, if any, used to figure out a match
304
309
  * @param options - The list of options to find a matching options from
305
310
  * @param rootSchema - The root schema, used to primarily to look up `$ref`s
306
311
  * @returns - The index of the matched option or 0 if none is available
312
+ * @deprecated
307
313
  */
308
314
  function getMatchingOption(validator, formData, options, rootSchema) {
309
315
  // For performance, skip validating subschemas if formData is undefined. We just
@@ -359,6 +365,19 @@
359
365
  return 0;
360
366
  }
361
367
 
368
+ /** Given the `formData` and list of `options`, attempts to find the index of the first option that matches the data.
369
+ * Always returns the first option if there is nothing that matches.
370
+ *
371
+ * @param validator - An implementation of the `ValidatorType` interface that will be used when necessary
372
+ * @param formData - The current formData, if any, used to figure out a match
373
+ * @param options - The list of options to find a matching options from
374
+ * @param rootSchema - The root schema, used to primarily to look up `$ref`s
375
+ * @returns - The index of the first matched option or 0 if none is available
376
+ */
377
+ function getFirstMatchingOption(validator, formData, options, rootSchema) {
378
+ return getMatchingOption(validator, formData, options, rootSchema);
379
+ }
380
+
362
381
  /** Given a specific `value` attempts to guess the type of a schema element. In the case where we have to implicitly
363
382
  * create a schema, it is useful to know what type to use based on the data we are defining.
364
383
  *
@@ -410,6 +429,12 @@
410
429
  if (!type && (schema.properties || schema.additionalProperties)) {
411
430
  return "object";
412
431
  }
432
+ if (!type && Array.isArray(schema.oneOf) && schema.oneOf.length) {
433
+ return getSchemaType(schema.oneOf[0]);
434
+ }
435
+ if (!type && Array.isArray(schema.anyOf) && schema.anyOf.length) {
436
+ return getSchemaType(schema.anyOf[0]);
437
+ }
413
438
  if (Array.isArray(type) && type.length === 2 && type.includes("null")) {
414
439
  type = type.find(function (type) {
415
440
  return type !== "null";
@@ -418,99 +443,6 @@
418
443
  return type;
419
444
  }
420
445
 
421
- /** Detects whether the given `schema` contains fixed items. This is the case when `schema.items` is a non-empty array
422
- * that only contains objects.
423
- *
424
- * @param schema - The schema in which to check for fixed items
425
- * @returns - True if there are fixed items in the schema, false otherwise
426
- */
427
- function isFixedItems(schema) {
428
- return Array.isArray(schema.items) && schema.items.length > 0 && schema.items.every(function (item) {
429
- return isObject(item);
430
- });
431
- }
432
-
433
- /** Merges the `defaults` object of type `T` into the `formData` of type `T`
434
- *
435
- * When merging defaults and form data, we want to merge in this specific way:
436
- * - objects are deeply merged
437
- * - arrays are merged in such a way that:
438
- * - when the array is set in form data, only array entries set in form data
439
- * are deeply merged; additional entries from the defaults are ignored
440
- * - when the array is not set in form data, the default is copied over
441
- * - scalars are overwritten/set by form data
442
- *
443
- * @param defaults - The defaults to merge
444
- * @param formData - The form data into which the defaults will be merged
445
- * @returns - The resulting merged form data with defaults
446
- */
447
- function mergeDefaultsWithFormData(defaults, formData) {
448
- if (Array.isArray(formData)) {
449
- var defaultsArray = Array.isArray(defaults) ? defaults : [];
450
- var mapped = formData.map(function (value, idx) {
451
- if (defaultsArray[idx]) {
452
- return mergeDefaultsWithFormData(defaultsArray[idx], value);
453
- }
454
- return value;
455
- });
456
- return mapped;
457
- }
458
- if (isObject(formData)) {
459
- var acc = Object.assign({}, defaults); // Prevent mutation of source object.
460
- return Object.keys(formData).reduce(function (acc, key) {
461
- acc[key] = mergeDefaultsWithFormData(defaults ? get__default["default"](defaults, key) : {}, get__default["default"](formData, key));
462
- return acc;
463
- }, acc);
464
- }
465
- return formData;
466
- }
467
-
468
- /** Recursively merge deeply nested objects.
469
- *
470
- * @param obj1 - The first object to merge
471
- * @param obj2 - The second object to merge
472
- * @param [concatArrays=false] - Optional flag that, when true, will cause arrays to be concatenated. Use
473
- * "preventDuplicates" to merge arrays in a manner that prevents any duplicate entries from being merged.
474
- * NOTE: Uses shallow comparison for the duplicate checking.
475
- * @returns - A new object that is the merge of the two given objects
476
- */
477
- function mergeObjects(obj1, obj2, concatArrays) {
478
- if (concatArrays === void 0) {
479
- concatArrays = false;
480
- }
481
- return Object.keys(obj2).reduce(function (acc, key) {
482
- var left = obj1 ? obj1[key] : {},
483
- right = obj2[key];
484
- if (obj1 && key in obj1 && isObject(right)) {
485
- acc[key] = mergeObjects(left, right, concatArrays);
486
- } else if (concatArrays && Array.isArray(left) && Array.isArray(right)) {
487
- var toMerge = right;
488
- if (concatArrays === "preventDuplicates") {
489
- toMerge = right.reduce(function (result, value) {
490
- if (!left.includes(value)) {
491
- result.push(value);
492
- }
493
- return result;
494
- }, []);
495
- }
496
- acc[key] = left.concat(toMerge);
497
- } else {
498
- acc[key] = right;
499
- }
500
- return acc;
501
- }, Object.assign({}, obj1)); // Prevent mutation of source object.
502
- }
503
-
504
- /** This function checks if the given `schema` matches a single constant value. This happens when either the schema has
505
- * an `enum` array with a single value or there is a `const` defined.
506
- *
507
- * @param schema - The schema for a field
508
- * @returns - True if the `schema` has a single constant value, false otherwise
509
- */
510
- function isConstant(schema) {
511
- return Array.isArray(schema["enum"]) && schema["enum"].length === 1 || CONST_KEY in schema;
512
- }
513
-
514
446
  /** Recursively merge deeply nested schemas. The difference between `mergeSchemas` and `mergeObjects` is that
515
447
  * `mergeSchemas` only concats arrays for values under the 'required' keyword, and when it does, it doesn't include
516
448
  * duplicate values.
@@ -547,7 +479,7 @@
547
479
  * @param validator - An implementation of the `ValidatorType<T, S>` interface that is used to detect valid schema conditions
548
480
  * @param schema - The schema for which resolving a condition is desired
549
481
  * @param rootSchema - The root schema that will be forwarded to all the APIs
550
- * @param formData - The current formData to assist retrieving a schema
482
+ * @param [formData] - The current formData to assist retrieving a schema
551
483
  * @returns - A schema with the appropriate condition resolved
552
484
  */
553
485
  function resolveCondition(validator, schema, rootSchema, formData) {
@@ -635,6 +567,10 @@
635
567
  }, rootSchema, formData);
636
568
  } else if ("type" in schema.additionalProperties) {
637
569
  additionalProperties = _extends({}, schema.additionalProperties);
570
+ } else if (ANY_OF_KEY in schema.additionalProperties || ONE_OF_KEY in schema.additionalProperties) {
571
+ additionalProperties = _extends({
572
+ type: "object"
573
+ }, schema.additionalProperties);
638
574
  } else {
639
575
  additionalProperties = {
640
576
  type: guessType(get__default["default"](formData, [key]))
@@ -706,9 +642,9 @@
706
642
  remainingSchema = _objectWithoutPropertiesLoose(schema, _excluded4);
707
643
  var resolvedSchema = remainingSchema;
708
644
  if (Array.isArray(resolvedSchema.oneOf)) {
709
- resolvedSchema = resolvedSchema.oneOf[getMatchingOption(validator, formData, resolvedSchema.oneOf, rootSchema)];
645
+ resolvedSchema = resolvedSchema.oneOf[getFirstMatchingOption(validator, formData, resolvedSchema.oneOf, rootSchema)];
710
646
  } else if (Array.isArray(resolvedSchema.anyOf)) {
711
- resolvedSchema = resolvedSchema.anyOf[getMatchingOption(validator, formData, resolvedSchema.anyOf, rootSchema)];
647
+ resolvedSchema = resolvedSchema.anyOf[getFirstMatchingOption(validator, formData, resolvedSchema.anyOf, rootSchema)];
712
648
  }
713
649
  return processDependencies(validator, dependencies, resolvedSchema, rootSchema, formData);
714
650
  }
@@ -829,6 +765,242 @@
829
765
  return mergeSchemas(schema, retrieveSchema(validator, dependentSchema, rootSchema, formData));
830
766
  }
831
767
 
768
+ /** A junk option used to determine when the getFirstMatchingOption call really matches an option rather than returning
769
+ * the first item
770
+ */
771
+ var JUNK_OPTION = {
772
+ type: "object",
773
+ properties: {
774
+ __not_really_there__: {
775
+ type: "number"
776
+ }
777
+ }
778
+ };
779
+ /** Recursive function that calculates the score of a `formData` against the given `schema`. The computation is fairly
780
+ * simple. Initially the total score is 0. When `schema.properties` object exists, then all the `key/value` pairs within
781
+ * the object are processed as follows after obtaining the formValue from `formData` using the `key`:
782
+ * - If the `value` contains a `$ref`, `calculateIndexScore()` is called recursively with the formValue and the new
783
+ * schema that is the result of the ref in the schema being resolved and that sub-schema's resulting score is added to
784
+ * the total.
785
+ * - If the `value` contains a `oneOf` and there is a formValue, then score based on the index returned from calling
786
+ * `getClosestMatchingOption()` of that oneOf.
787
+ * - If the type of the `value` is 'object', `calculateIndexScore()` is called recursively with the formValue and the
788
+ * `value` itself as the sub-schema, and the score is added to the total.
789
+ * - If the type of the `value` matches the guessed-type of the `formValue`, the score is incremented by 1, UNLESS the
790
+ * value has a `default` or `const`. In those case, if the `default` or `const` and the `formValue` match, the score
791
+ * is incremented by another 1 otherwise it is decremented by 1.
792
+ *
793
+ * @param validator - An implementation of the `ValidatorType` interface that will be used when necessary
794
+ * @param rootSchema - The root JSON schema of the entire form
795
+ * @param schema - The schema for which the score is being calculated
796
+ * @param formData - The form data associated with the schema, used to calculate the score
797
+ * @returns - The score a schema against the formData
798
+ */
799
+ function calculateIndexScore(validator, rootSchema, schema, formData) {
800
+ if (formData === void 0) {
801
+ formData = {};
802
+ }
803
+ var totalScore = 0;
804
+ if (schema) {
805
+ if (isObject__default["default"](schema.properties)) {
806
+ totalScore += reduce__default["default"](schema.properties, function (score, value, key) {
807
+ var formValue = get__default["default"](formData, key);
808
+ if (typeof value === "boolean") {
809
+ return score;
810
+ }
811
+ if (has__default["default"](value, REF_KEY)) {
812
+ var newSchema = retrieveSchema(validator, value, rootSchema, formValue);
813
+ return score + calculateIndexScore(validator, rootSchema, newSchema, formValue || {});
814
+ }
815
+ if (has__default["default"](value, ONE_OF_KEY) && formValue) {
816
+ return score + getClosestMatchingOption(validator, rootSchema, formValue, get__default["default"](value, ONE_OF_KEY));
817
+ }
818
+ if (value.type === "object") {
819
+ return score + calculateIndexScore(validator, rootSchema, value, formValue || {});
820
+ }
821
+ if (value.type === guessType(formValue)) {
822
+ // If the types match, then we bump the score by one
823
+ var newScore = score + 1;
824
+ if (value["default"]) {
825
+ // If the schema contains a readonly default value score the value that matches the default higher and
826
+ // any non-matching value lower
827
+ newScore += formValue === value["default"] ? 1 : -1;
828
+ } else if (value["const"]) {
829
+ // If the schema contains a const value score the value that matches the default higher and
830
+ // any non-matching value lower
831
+ newScore += formValue === value["const"] ? 1 : -1;
832
+ }
833
+ // TODO eventually, deal with enums/arrays
834
+ return newScore;
835
+ }
836
+ return score;
837
+ }, 0);
838
+ } else if (isString__default["default"](schema.type) && schema.type === guessType(formData)) {
839
+ totalScore += 1;
840
+ }
841
+ }
842
+ return totalScore;
843
+ }
844
+ /** Determines which of the given `options` provided most closely matches the `formData`. Using
845
+ * `getFirstMatchingOption()` to match two schemas that differ only by the readOnly, default or const value of a field
846
+ * based on the `formData` and returns 0 when there is no match. Rather than passing in all the `options` at once to
847
+ * this utility, instead an array of valid option indexes is created by iterating over the list of options, call
848
+ * `getFirstMatchingOptions` with a list of one junk option and one good option, seeing if the good option is considered
849
+ * matched.
850
+ *
851
+ * Once the list of valid indexes is created, if there is only one valid index, just return it. Otherwise, if there are
852
+ * no valid indexes, then fill the valid indexes array with the indexes of all the options. Next, the index of the
853
+ * option with the highest score is determined by iterating over the list of valid options, calling
854
+ * `calculateIndexScore()` on each, comparing it against the current best score, and returning the index of the one that
855
+ * eventually has the best score.
856
+ *
857
+ * @param validator - An implementation of the `ValidatorType` interface that will be used when necessary
858
+ * @param rootSchema - The root JSON schema of the entire form
859
+ * @param formData - The form data associated with the schema
860
+ * @param options - The list of options that can be selected from
861
+ * @param [selectedOption=-1] - The index of the currently selected option, defaulted to -1 if not specified
862
+ * @returns - The index of the option that is the closest match to the `formData` or the `selectedOption` if no match
863
+ */
864
+ function getClosestMatchingOption(validator, rootSchema, formData, options, selectedOption) {
865
+ if (selectedOption === void 0) {
866
+ selectedOption = -1;
867
+ }
868
+ // Reduce the array of options down to a list of the indexes that are considered matching options
869
+ var allValidIndexes = options.reduce(function (validList, option, index) {
870
+ var testOptions = [JUNK_OPTION, option];
871
+ var match = getFirstMatchingOption(validator, formData, testOptions, rootSchema);
872
+ // The match is the real option, so add its index to list of valid indexes
873
+ if (match === 1) {
874
+ validList.push(index);
875
+ }
876
+ return validList;
877
+ }, []);
878
+ // There is only one valid index, so return it!
879
+ if (allValidIndexes.length === 1) {
880
+ return allValidIndexes[0];
881
+ }
882
+ if (!allValidIndexes.length) {
883
+ // No indexes were valid, so we'll score all the options, add all the indexes
884
+ times__default["default"](options.length, function (i) {
885
+ return allValidIndexes.push(i);
886
+ });
887
+ }
888
+ // Score all the options in the list of valid indexes and return the index with the best score
889
+ var _allValidIndexes$redu = allValidIndexes.reduce(function (scoreData, index) {
890
+ var bestScore = scoreData.bestScore;
891
+ var option = options[index];
892
+ if (has__default["default"](option, REF_KEY)) {
893
+ option = retrieveSchema(validator, option, rootSchema, formData);
894
+ }
895
+ var score = calculateIndexScore(validator, rootSchema, option, formData);
896
+ if (score > bestScore) {
897
+ return {
898
+ bestIndex: index,
899
+ bestScore: score
900
+ };
901
+ }
902
+ return scoreData;
903
+ }, {
904
+ bestIndex: selectedOption,
905
+ bestScore: 0
906
+ }),
907
+ bestIndex = _allValidIndexes$redu.bestIndex;
908
+ return bestIndex;
909
+ }
910
+
911
+ /** Detects whether the given `schema` contains fixed items. This is the case when `schema.items` is a non-empty array
912
+ * that only contains objects.
913
+ *
914
+ * @param schema - The schema in which to check for fixed items
915
+ * @returns - True if there are fixed items in the schema, false otherwise
916
+ */
917
+ function isFixedItems(schema) {
918
+ return Array.isArray(schema.items) && schema.items.length > 0 && schema.items.every(function (item) {
919
+ return isObject(item);
920
+ });
921
+ }
922
+
923
+ /** Merges the `defaults` object of type `T` into the `formData` of type `T`
924
+ *
925
+ * When merging defaults and form data, we want to merge in this specific way:
926
+ * - objects are deeply merged
927
+ * - arrays are merged in such a way that:
928
+ * - when the array is set in form data, only array entries set in form data
929
+ * are deeply merged; additional entries from the defaults are ignored
930
+ * - when the array is not set in form data, the default is copied over
931
+ * - scalars are overwritten/set by form data
932
+ *
933
+ * @param [defaults] - The defaults to merge
934
+ * @param [formData] - The form data into which the defaults will be merged
935
+ * @returns - The resulting merged form data with defaults
936
+ */
937
+ function mergeDefaultsWithFormData(defaults, formData) {
938
+ if (Array.isArray(formData)) {
939
+ var defaultsArray = Array.isArray(defaults) ? defaults : [];
940
+ var mapped = formData.map(function (value, idx) {
941
+ if (defaultsArray[idx]) {
942
+ return mergeDefaultsWithFormData(defaultsArray[idx], value);
943
+ }
944
+ return value;
945
+ });
946
+ return mapped;
947
+ }
948
+ if (isObject(formData)) {
949
+ var acc = Object.assign({}, defaults); // Prevent mutation of source object.
950
+ return Object.keys(formData).reduce(function (acc, key) {
951
+ acc[key] = mergeDefaultsWithFormData(defaults ? get__default["default"](defaults, key) : {}, get__default["default"](formData, key));
952
+ return acc;
953
+ }, acc);
954
+ }
955
+ return formData;
956
+ }
957
+
958
+ /** Recursively merge deeply nested objects.
959
+ *
960
+ * @param obj1 - The first object to merge
961
+ * @param obj2 - The second object to merge
962
+ * @param [concatArrays=false] - Optional flag that, when true, will cause arrays to be concatenated. Use
963
+ * "preventDuplicates" to merge arrays in a manner that prevents any duplicate entries from being merged.
964
+ * NOTE: Uses shallow comparison for the duplicate checking.
965
+ * @returns - A new object that is the merge of the two given objects
966
+ */
967
+ function mergeObjects(obj1, obj2, concatArrays) {
968
+ if (concatArrays === void 0) {
969
+ concatArrays = false;
970
+ }
971
+ return Object.keys(obj2).reduce(function (acc, key) {
972
+ var left = obj1 ? obj1[key] : {},
973
+ right = obj2[key];
974
+ if (obj1 && key in obj1 && isObject(right)) {
975
+ acc[key] = mergeObjects(left, right, concatArrays);
976
+ } else if (concatArrays && Array.isArray(left) && Array.isArray(right)) {
977
+ var toMerge = right;
978
+ if (concatArrays === "preventDuplicates") {
979
+ toMerge = right.reduce(function (result, value) {
980
+ if (!left.includes(value)) {
981
+ result.push(value);
982
+ }
983
+ return result;
984
+ }, []);
985
+ }
986
+ acc[key] = left.concat(toMerge);
987
+ } else {
988
+ acc[key] = right;
989
+ }
990
+ return acc;
991
+ }, Object.assign({}, obj1)); // Prevent mutation of source object.
992
+ }
993
+
994
+ /** This function checks if the given `schema` matches a single constant value. This happens when either the schema has
995
+ * an `enum` array with a single value or there is a `const` defined.
996
+ *
997
+ * @param schema - The schema for a field
998
+ * @returns - True if the `schema` has a single constant value, false otherwise
999
+ */
1000
+ function isConstant(schema) {
1001
+ return Array.isArray(schema["enum"]) && schema["enum"].length === 1 || CONST_KEY in schema;
1002
+ }
1003
+
832
1004
  /** Checks to see if the `schema` combination represents a select
833
1005
  *
834
1006
  * @param validator - An implementation of the `ValidatorType` interface that will be used when necessary
@@ -954,9 +1126,9 @@
954
1126
  return computeDefaults(validator, itemSchema, Array.isArray(parentDefaults) ? parentDefaults[idx] : undefined, rootSchema, formData, includeUndefinedValues);
955
1127
  });
956
1128
  } else if (ONE_OF_KEY in schema) {
957
- schema = schema.oneOf[getMatchingOption(validator, isEmpty__default["default"](formData) ? undefined : formData, schema.oneOf, rootSchema)];
1129
+ schema = schema.oneOf[getClosestMatchingOption(validator, rootSchema, isEmpty__default["default"](formData) ? undefined : formData, schema.oneOf, 0)];
958
1130
  } else if (ANY_OF_KEY in schema) {
959
- schema = schema.anyOf[getMatchingOption(validator, isEmpty__default["default"](formData) ? undefined : formData, schema.anyOf, rootSchema)];
1131
+ schema = schema.anyOf[getClosestMatchingOption(validator, rootSchema, isEmpty__default["default"](formData) ? undefined : formData, schema.anyOf, 0)];
960
1132
  }
961
1133
  // Not defaults defined for this node, fallback to generic typed ones.
962
1134
  if (typeof defaults === "undefined") {
@@ -1148,6 +1320,169 @@
1148
1320
  };
1149
1321
  }
1150
1322
 
1323
+ var NO_VALUE = /*#__PURE__*/Symbol("no Value");
1324
+ /** Sanitize the `data` associated with the `oldSchema` so it is considered appropriate for the `newSchema`. If the new
1325
+ * schema does not contain any properties, then `undefined` is returned to clear all the form data. Due to the nature
1326
+ * of schemas, this sanitization happens recursively for nested objects of data. Also, any properties in the old schema
1327
+ * that are non-existent in the new schema are set to `undefined`. The data sanitization process has the following flow:
1328
+ *
1329
+ * - If the new schema is an object that contains a `properties` object then:
1330
+ * - Create a `removeOldSchemaData` object, setting each key in the `oldSchema.properties` having `data` to undefined
1331
+ * - Create an empty `nestedData` object for use in the key filtering below:
1332
+ * - Iterate over each key in the `newSchema.properties` as follows:
1333
+ * - Get the `formValue` of the key from the `data`
1334
+ * - Get the `oldKeySchema` and `newKeyedSchema` for the key, defaulting to `{}` when it doesn't exist
1335
+ * - Retrieve the schema for any refs within each `oldKeySchema` and/or `newKeySchema`
1336
+ * - Get the types of the old and new keyed schemas and if the old doesn't exist or the old & new are the same then:
1337
+ * - If `removeOldSchemaData` has an entry for the key, delete it since the new schema has the same property
1338
+ * - If type of the key in the new schema is `object`:
1339
+ * - Store the value from the recursive `sanitizeDataForNewSchema` call in `nestedData[key]`
1340
+ * - Otherwise, check for default or const values:
1341
+ * - Get the old and new `default` values from the schema and check:
1342
+ * - If the new `default` value does not match the form value:
1343
+ * - If the old `default` value DOES match the form value, then:
1344
+ * - Replace `removeOldSchemaData[key]` with the new `default`
1345
+ * - Otherwise, if the new schema is `readOnly` then replace `removeOldSchemaData[key]` with undefined
1346
+ * - Get the old and new `const` values from the schema and check:
1347
+ * - If the new `const` value does not match the form value:
1348
+ * - If the old `const` value DOES match the form value, then:
1349
+ * - Replace `removeOldSchemaData[key]` with the new `const`
1350
+ * - Otherwise, replace `removeOldSchemaData[key]` with undefined
1351
+ * - Once all keys have been processed, return an object built as follows:
1352
+ * - `{ ...removeOldSchemaData, ...nestedData, ...pick(data, keysToKeep) }`
1353
+ * - If the new and old schema types are array and the `data` is an array then:
1354
+ * - If the type of the old and new schema `items` are a non-array objects:
1355
+ * - Retrieve the schema for any refs within each `oldKeySchema.items` and/or `newKeySchema.items`
1356
+ * - If the `type`s of both items are the same (or the old does not have a type):
1357
+ * - If the type is "object", then:
1358
+ * - For each element in the `data` recursively sanitize the data, stopping at `maxItems` if specified
1359
+ * - Otherwise, just return the `data` removing any values after `maxItems` if it is set
1360
+ * - If the type of the old and new schema `items` are booleans of the same value, return `data` as is
1361
+ * - Otherwise return `undefined`
1362
+ *
1363
+ * @param validator - An implementation of the `ValidatorType` interface that will be used when necessary
1364
+ * @param rootSchema - The root JSON schema of the entire form
1365
+ * @param [newSchema] - The new schema for which the data is being sanitized
1366
+ * @param [oldSchema] - The old schema from which the data originated
1367
+ * @param [data={}] - The form data associated with the schema, defaulting to an empty object when undefined
1368
+ * @returns - The new form data, with all the fields uniquely associated with the old schema set
1369
+ * to `undefined`. Will return `undefined` if the new schema is not an object containing properties.
1370
+ */
1371
+ function sanitizeDataForNewSchema(validator, rootSchema, newSchema, oldSchema, data) {
1372
+ if (data === void 0) {
1373
+ data = {};
1374
+ }
1375
+ // By default, we will clear the form data
1376
+ var newFormData;
1377
+ // If the new schema is of type object and that object contains a list of properties
1378
+ if (has__default["default"](newSchema, PROPERTIES_KEY)) {
1379
+ // Create an object containing root-level keys in the old schema, setting each key to undefined to remove the data
1380
+ var removeOldSchemaData = {};
1381
+ if (has__default["default"](oldSchema, PROPERTIES_KEY)) {
1382
+ var properties = get__default["default"](oldSchema, PROPERTIES_KEY, {});
1383
+ Object.keys(properties).forEach(function (key) {
1384
+ if (has__default["default"](data, key)) {
1385
+ removeOldSchemaData[key] = undefined;
1386
+ }
1387
+ });
1388
+ }
1389
+ var keys = Object.keys(get__default["default"](newSchema, PROPERTIES_KEY, {}));
1390
+ // Create a place to store nested data that will be a side-effect of the filter
1391
+ var nestedData = {};
1392
+ keys.forEach(function (key) {
1393
+ var formValue = get__default["default"](data, key);
1394
+ var oldKeyedSchema = get__default["default"](oldSchema, [PROPERTIES_KEY, key], {});
1395
+ var newKeyedSchema = get__default["default"](newSchema, [PROPERTIES_KEY, key], {});
1396
+ // Resolve the refs if they exist
1397
+ if (has__default["default"](oldKeyedSchema, REF_KEY)) {
1398
+ oldKeyedSchema = retrieveSchema(validator, oldKeyedSchema, rootSchema, formValue);
1399
+ }
1400
+ if (has__default["default"](newKeyedSchema, REF_KEY)) {
1401
+ newKeyedSchema = retrieveSchema(validator, newKeyedSchema, rootSchema, formValue);
1402
+ }
1403
+ // Now get types and see if they are the same
1404
+ var oldSchemaTypeForKey = get__default["default"](oldKeyedSchema, "type");
1405
+ var newSchemaTypeForKey = get__default["default"](newKeyedSchema, "type");
1406
+ // Check if the old option has the same key with the same type
1407
+ if (!oldSchemaTypeForKey || oldSchemaTypeForKey === newSchemaTypeForKey) {
1408
+ if (has__default["default"](removeOldSchemaData, key)) {
1409
+ // SIDE-EFFECT: remove the undefined value for a key that has the same type between the old and new schemas
1410
+ delete removeOldSchemaData[key];
1411
+ }
1412
+ // If it is an object, we'll recurse and store the resulting sanitized data for the key
1413
+ if (newSchemaTypeForKey === "object" || newSchemaTypeForKey === "array" && Array.isArray(formValue)) {
1414
+ // SIDE-EFFECT: process the new schema type of object recursively to save iterations
1415
+ var itemData = sanitizeDataForNewSchema(validator, rootSchema, newKeyedSchema, oldKeyedSchema, formValue);
1416
+ if (itemData !== undefined || newSchemaTypeForKey === "array") {
1417
+ // only put undefined values for the array type and not the object type
1418
+ nestedData[key] = itemData;
1419
+ }
1420
+ } else {
1421
+ // Ok, the non-object types match, let's make sure that a default or a const of a different value is replaced
1422
+ // with the new default or const. This allows the case where two schemas differ that only by the default/const
1423
+ // value to be properly selected
1424
+ var newOptionDefault = get__default["default"](newKeyedSchema, "default", NO_VALUE);
1425
+ var oldOptionDefault = get__default["default"](oldKeyedSchema, "default", NO_VALUE);
1426
+ if (newOptionDefault !== NO_VALUE && newOptionDefault !== formValue) {
1427
+ if (oldOptionDefault === formValue) {
1428
+ // If the old default matches the formValue, we'll update the new value to match the new default
1429
+ removeOldSchemaData[key] = newOptionDefault;
1430
+ } else if (get__default["default"](newKeyedSchema, "readOnly") === true) {
1431
+ // If the new schema has the default set to read-only, treat it like a const and remove the value
1432
+ removeOldSchemaData[key] = undefined;
1433
+ }
1434
+ }
1435
+ var newOptionConst = get__default["default"](newKeyedSchema, "const", NO_VALUE);
1436
+ var oldOptionConst = get__default["default"](oldKeyedSchema, "const", NO_VALUE);
1437
+ if (newOptionConst !== NO_VALUE && newOptionConst !== formValue) {
1438
+ // Since this is a const, if the old value matches, replace the value with the new const otherwise clear it
1439
+ removeOldSchemaData[key] = oldOptionConst === formValue ? newOptionConst : undefined;
1440
+ }
1441
+ }
1442
+ }
1443
+ });
1444
+ newFormData = _extends({}, data, removeOldSchemaData, nestedData);
1445
+ // First apply removing the old schema data, then apply the nested data, then apply the old data keys to keep
1446
+ } else if (get__default["default"](oldSchema, "type") === "array" && get__default["default"](newSchema, "type") === "array" && Array.isArray(data)) {
1447
+ var oldSchemaItems = get__default["default"](oldSchema, "items");
1448
+ var newSchemaItems = get__default["default"](newSchema, "items");
1449
+ // If any of the array types `items` are arrays (remember arrays are objects) then we'll just drop the data
1450
+ // Eventually, we may want to deal with when either of the `items` are arrays since those tuple validations
1451
+ if (typeof oldSchemaItems === "object" && typeof newSchemaItems === "object" && !Array.isArray(oldSchemaItems) && !Array.isArray(newSchemaItems)) {
1452
+ if (has__default["default"](oldSchemaItems, REF_KEY)) {
1453
+ oldSchemaItems = retrieveSchema(validator, oldSchemaItems, rootSchema, data);
1454
+ }
1455
+ if (has__default["default"](newSchemaItems, REF_KEY)) {
1456
+ newSchemaItems = retrieveSchema(validator, newSchemaItems, rootSchema, data);
1457
+ }
1458
+ // Now get types and see if they are the same
1459
+ var oldSchemaType = get__default["default"](oldSchemaItems, "type");
1460
+ var newSchemaType = get__default["default"](newSchemaItems, "type");
1461
+ // Check if the old option has the same key with the same type
1462
+ if (!oldSchemaType || oldSchemaType === newSchemaType) {
1463
+ var maxItems = get__default["default"](newSchema, "maxItems", -1);
1464
+ if (newSchemaType === "object") {
1465
+ newFormData = data.reduce(function (newValue, aValue) {
1466
+ var itemValue = sanitizeDataForNewSchema(validator, rootSchema, newSchemaItems, oldSchemaItems, aValue);
1467
+ if (itemValue !== undefined && (maxItems < 0 || newValue.length < maxItems)) {
1468
+ newValue.push(itemValue);
1469
+ }
1470
+ return newValue;
1471
+ }, []);
1472
+ } else {
1473
+ newFormData = maxItems > 0 && data.length > maxItems ? data.slice(0, maxItems) : data;
1474
+ }
1475
+ }
1476
+ } else if (typeof oldSchemaItems === "boolean" && typeof newSchemaItems === "boolean" && oldSchemaItems === newSchemaItems) {
1477
+ // If they are both booleans and have the same value just return the data as is otherwise fall-thru to undefined
1478
+ newFormData = data;
1479
+ }
1480
+ // Also probably want to deal with `prefixItems` as tuples with the latest 2020 draft
1481
+ }
1482
+
1483
+ return newFormData;
1484
+ }
1485
+
1151
1486
  /** Generates an `IdSchema` object for the `schema`, recursively
1152
1487
  *
1153
1488
  * @param validator - An implementation of the `ValidatorType` interface that will be used when necessary
@@ -1209,6 +1544,16 @@
1209
1544
  return toPathSchema(validator, _schema, name, rootSchema, formData);
1210
1545
  }
1211
1546
  var pathSchema = (_pathSchema = {}, _pathSchema[NAME_KEY] = name.replace(/^\./, ""), _pathSchema);
1547
+ if (ONE_OF_KEY in schema) {
1548
+ var index = getClosestMatchingOption(validator, rootSchema, formData, schema.oneOf, 0);
1549
+ var _schema2 = schema.oneOf[index];
1550
+ return toPathSchema(validator, _schema2, name, rootSchema, formData);
1551
+ }
1552
+ if (ANY_OF_KEY in schema) {
1553
+ var _index = getClosestMatchingOption(validator, rootSchema, formData, schema.anyOf, 0);
1554
+ var _schema3 = schema.anyOf[_index];
1555
+ return toPathSchema(validator, _schema3, name, rootSchema, formData);
1556
+ }
1212
1557
  if (ADDITIONAL_PROPERTIES_KEY in schema && schema[ADDITIONAL_PROPERTIES_KEY] !== false) {
1213
1558
  set__default["default"](pathSchema, RJSF_ADDITONAL_PROPERTIES_FLAG, true);
1214
1559
  }
@@ -1293,11 +1638,37 @@
1293
1638
  _proto.getDisplayLabel = function getDisplayLabel$1(schema, uiSchema) {
1294
1639
  return getDisplayLabel(this.validator, schema, uiSchema, this.rootSchema);
1295
1640
  }
1641
+ /** Determines which of the given `options` provided most closely matches the `formData`.
1642
+ * Returns the index of the option that is valid and is the closest match, or 0 if there is no match.
1643
+ *
1644
+ * The closest match is determined using the number of matching properties, and more heavily favors options with
1645
+ * matching readOnly, default, or const values.
1646
+ *
1647
+ * @param formData - The form data associated with the schema
1648
+ * @param options - The list of options that can be selected from
1649
+ * @param [selectedOption] - The index of the currently selected option, defaulted to -1 if not specified
1650
+ * @returns - The index of the option that is the closest match to the `formData` or the `selectedOption` if no match
1651
+ */;
1652
+ _proto.getClosestMatchingOption = function getClosestMatchingOption$1(formData, options, selectedOption) {
1653
+ return getClosestMatchingOption(this.validator, this.rootSchema, formData, options, selectedOption);
1654
+ }
1655
+ /** Given the `formData` and list of `options`, attempts to find the index of the first option that matches the data.
1656
+ * Always returns the first option if there is nothing that matches.
1657
+ *
1658
+ * @param formData - The current formData, if any, used to figure out a match
1659
+ * @param options - The list of options to find a matching options from
1660
+ * @returns - The firstindex of the matched option or 0 if none is available
1661
+ */;
1662
+ _proto.getFirstMatchingOption = function getFirstMatchingOption$1(formData, options) {
1663
+ return getFirstMatchingOption(this.validator, formData, options, this.rootSchema);
1664
+ }
1296
1665
  /** Given the `formData` and list of `options`, attempts to find the index of the option that best matches the data.
1666
+ * Deprecated, use `getFirstMatchingOption()` instead.
1297
1667
  *
1298
1668
  * @param formData - The current formData, if any, onto which to provide any missing defaults
1299
1669
  * @param options - The list of options to find a matching options from
1300
1670
  * @returns - The index of the matched option or 0 if none is available
1671
+ * @deprecated
1301
1672
  */;
1302
1673
  _proto.getMatchingOption = function getMatchingOption$1(formData, options) {
1303
1674
  return getMatchingOption(this.validator, formData, options, this.rootSchema);
@@ -1350,6 +1721,20 @@
1350
1721
  _proto.retrieveSchema = function retrieveSchema$1(schema, rawFormData) {
1351
1722
  return retrieveSchema(this.validator, schema, this.rootSchema, rawFormData);
1352
1723
  }
1724
+ /** Sanitize the `data` associated with the `oldSchema` so it is considered appropriate for the `newSchema`. If the
1725
+ * new schema does not contain any properties, then `undefined` is returned to clear all the form data. Due to the
1726
+ * nature of schemas, this sanitization happens recursively for nested objects of data. Also, any properties in the
1727
+ * old schemas that are non-existent in the new schema are set to `undefined`.
1728
+ *
1729
+ * @param [newSchema] - The new schema for which the data is being sanitized
1730
+ * @param [oldSchema] - The old schema from which the data originated
1731
+ * @param [data={}] - The form data associated with the schema, defaulting to an empty object when undefined
1732
+ * @returns - The new form data, with all the fields uniquely associated with the old schema set
1733
+ * to `undefined`. Will return `undefined` if the new schema is not an object containing properties.
1734
+ */;
1735
+ _proto.sanitizeDataForNewSchema = function sanitizeDataForNewSchema$1(newSchema, oldSchema, data) {
1736
+ return sanitizeDataForNewSchema(this.validator, this.rootSchema, newSchema, oldSchema, data);
1737
+ }
1353
1738
  /** Generates an `IdSchema` object for the `schema`, recursively
1354
1739
  *
1355
1740
  * @param schema - The schema for which the display label flag is desired
@@ -2240,8 +2625,10 @@
2240
2625
  exports.errorId = errorId;
2241
2626
  exports.examplesId = examplesId;
2242
2627
  exports.findSchemaDefinition = findSchemaDefinition;
2628
+ exports.getClosestMatchingOption = getClosestMatchingOption;
2243
2629
  exports.getDefaultFormState = getDefaultFormState;
2244
2630
  exports.getDisplayLabel = getDisplayLabel;
2631
+ exports.getFirstMatchingOption = getFirstMatchingOption;
2245
2632
  exports.getInputProps = getInputProps;
2246
2633
  exports.getMatchingOption = getMatchingOption;
2247
2634
  exports.getSchemaType = getSchemaType;
@@ -2272,6 +2659,7 @@
2272
2659
  exports.processSelectValue = processSelectValue;
2273
2660
  exports.rangeSpec = rangeSpec;
2274
2661
  exports.retrieveSchema = retrieveSchema;
2662
+ exports.sanitizeDataForNewSchema = sanitizeDataForNewSchema;
2275
2663
  exports.schemaRequiresTrueValue = schemaRequiresTrueValue;
2276
2664
  exports.shouldRender = shouldRender;
2277
2665
  exports.titleId = titleId;