@sanity/validation 3.1.3 → 3.1.5-canary.14

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/lib/index.js CHANGED
@@ -1,13 +1,5 @@
1
1
  'use strict';
2
2
 
3
- const _excluded = ["value", "type", "path", "parent"];
4
- function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
5
- function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
6
- function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
7
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
8
- function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
9
- function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
10
- function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
11
3
  Object.defineProperty(exports, '__esModule', {
12
4
  value: true
13
5
  });
@@ -245,16 +237,18 @@ const genericValidators = {
245
237
  return result;
246
238
  }
247
239
  };
248
- const booleanValidators = _objectSpread(_objectSpread({}, genericValidators), {}, {
240
+ const booleanValidators = {
241
+ ...genericValidators,
249
242
  presence: (flag, value, message) => {
250
243
  if (flag === "required" && typeof value !== "boolean") {
251
244
  return message || "Required";
252
245
  }
253
246
  return true;
254
247
  }
255
- });
248
+ };
256
249
  const precisionRx = /(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/;
257
- const numberValidators = _objectSpread(_objectSpread({}, genericValidators), {}, {
250
+ const numberValidators = {
251
+ ...genericValidators,
258
252
  integer: (_unused, value, message) => {
259
253
  if (!Number.isInteger(value)) {
260
254
  return message || "Must be an integer";
@@ -294,11 +288,12 @@ const numberValidators = _objectSpread(_objectSpread({}, genericValidators), {},
294
288
  }
295
289
  return message || "Must be less than ".concat(maxNum);
296
290
  }
297
- });
291
+ };
298
292
  const DUMMY_ORIGIN = "http://sanity";
299
293
  const emailRegex = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
300
294
  const isRelativeUrl = url => /^\.*\//.test(url);
301
- const stringValidators = _objectSpread(_objectSpread({}, genericValidators), {}, {
295
+ const stringValidators = {
296
+ ...genericValidators,
302
297
  min: (minLength, value, message) => {
303
298
  if (!value || value.length >= minLength) {
304
299
  return true;
@@ -388,8 +383,9 @@ const stringValidators = _objectSpread(_objectSpread({}, genericValidators), {},
388
383
  }
389
384
  return message || "Must be a valid email address";
390
385
  }
391
- });
392
- const arrayValidators = _objectSpread(_objectSpread({}, genericValidators), {}, {
386
+ };
387
+ const arrayValidators = {
388
+ ...genericValidators,
393
389
  min: (minLength, value, message) => {
394
390
  if (!value || value.length >= minLength) {
395
391
  return true;
@@ -465,9 +461,10 @@ const arrayValidators = _objectSpread(_objectSpread({}, genericValidators), {},
465
461
  paths
466
462
  }) : true;
467
463
  }
468
- });
464
+ };
469
465
  const metaKeys = ["_key", "_type", "_weak"];
470
- const objectValidators = _objectSpread(_objectSpread({}, genericValidators), {}, {
466
+ const objectValidators = {
467
+ ...genericValidators,
471
468
  presence: (expected, value, message) => {
472
469
  if (expected !== "required") {
473
470
  return true;
@@ -513,7 +510,7 @@ const objectValidators = _objectSpread(_objectSpread({}, genericValidators), {},
513
510
  }
514
511
  return true;
515
512
  }
516
- });
513
+ };
517
514
  function isRecord$1(obj) {
518
515
  return typeof obj === "object" && obj !== null && !Array.isArray(obj);
519
516
  }
@@ -547,7 +544,8 @@ function parseDate(date) {
547
544
  }
548
545
  return isInvalid ? null : parsed;
549
546
  }
550
- const dateValidators = _objectSpread(_objectSpread({}, genericValidators), {}, {
547
+ const dateValidators = {
548
+ ...genericValidators,
551
549
  type: (_unused, value, message) => {
552
550
  const strVal = "".concat(value);
553
551
  if (!strVal || isoDate.test(value)) {
@@ -585,7 +583,7 @@ const dateValidators = _objectSpread(_objectSpread({}, genericValidators), {}, {
585
583
  const date = getFormattedDate(context.type.name, maxDate, dateTimeOptions);
586
584
  return message || "Must be at or before ".concat(date);
587
585
  }
588
- });
586
+ };
589
587
  var _a;
590
588
  const typeValidators = {
591
589
  Boolean: booleanValidators,
@@ -614,6 +612,7 @@ const Rule = (_a = class {
614
612
  this._message = void 0;
615
613
  this._rules = [];
616
614
  this._fieldRules = void 0;
615
+ // Alias to static method, since we often have access to an _instance_ of a rule but not the actual Rule class
617
616
  this.valueOfField = _a.valueOfField.bind(_a);
618
617
  this._typeDef = typeDef;
619
618
  this.reset();
@@ -691,6 +690,7 @@ const Rule = (_a = class {
691
690
  newRule._level = this._level === "error" ? rule._level : this._level;
692
691
  return newRule;
693
692
  }
693
+ // Validation flag setters
694
694
  type(targetType) {
695
695
  const type = "".concat(targetType.slice(0, 1).toUpperCase()).concat(targetType.slice(1));
696
696
  if (!ruleConstraintTypes$1.includes(type)) {
@@ -715,6 +715,7 @@ const Rule = (_a = class {
715
715
  constraint: children
716
716
  }]);
717
717
  }
718
+ // Shared rules
718
719
  optional() {
719
720
  const rule = this.cloneWithRules([{
720
721
  flag: "presence",
@@ -762,6 +763,7 @@ const Rule = (_a = class {
762
763
  constraint: values
763
764
  }]);
764
765
  }
766
+ // Numbers only
765
767
  integer() {
766
768
  return this.cloneWithRules([{
767
769
  flag: "integer"
@@ -797,6 +799,7 @@ const Rule = (_a = class {
797
799
  constraint: num
798
800
  }]);
799
801
  }
802
+ // String only
800
803
  uppercase() {
801
804
  return this.cloneWithRules([{
802
805
  flag: "stringCasing",
@@ -852,11 +855,13 @@ const Rule = (_a = class {
852
855
  constraint
853
856
  }]);
854
857
  }
858
+ // Array only
855
859
  unique() {
856
860
  return this.cloneWithRules([{
857
861
  flag: "unique"
858
862
  }]);
859
863
  }
864
+ // Objects only
860
865
  reference() {
861
866
  return this.cloneWithRules([{
862
867
  flag: "reference"
@@ -893,7 +898,9 @@ const Rule = (_a = class {
893
898
  if (valueIsEmpty && this._required === "optional") {
894
899
  return EMPTY_ARRAY;
895
900
  }
896
- const rules = this._required === void 0 && valueIsEmpty ? this._rules.filter(curr => curr.flag === "custom") : this._rules;
901
+ const rules =
902
+ // Run only the _custom_ functions if the rule is not set to required or optional
903
+ this._required === void 0 && valueIsEmpty ? this._rules.filter(curr => curr.flag === "custom") : this._rules;
897
904
  const validators = this._type && typeValidators[this._type] || genericValidators;
898
905
  const results = await Promise.all(rules.map(async curr => {
899
906
  if (curr.flag === void 0) {
@@ -1010,11 +1017,12 @@ const slugValidator = async (value, context) => {
1010
1017
  }
1011
1018
  const options = (_a = context == null ? void 0 : context.type) == null ? void 0 : _a.options;
1012
1019
  const isUnique = (options == null ? void 0 : options.isUnique) || defaultIsUnique;
1013
- const slugContext = _objectSpread(_objectSpread({}, context), {}, {
1020
+ const slugContext = {
1021
+ ...context,
1014
1022
  parent: context.parent,
1015
1023
  type: context.type,
1016
1024
  defaultIsUnique
1017
- });
1025
+ };
1018
1026
  const wasUnique = await isUnique(slugValue, slugContext);
1019
1027
  if (wasUnique) {
1020
1028
  return true;
@@ -1042,7 +1050,15 @@ function baseRuleReducer(inputRule, type) {
1042
1050
  if (isRuleConstraint(type.jsonType)) {
1043
1051
  baseRule = baseRule.type(type.jsonType);
1044
1052
  }
1045
- const typeOptionsList = (type == null ? void 0 : type.options) && typeof type.options === "object" && "list" in type.options && type.options.list;
1053
+ const typeOptionsList =
1054
+ // if type.options is truthy
1055
+ (type == null ? void 0 : type.options) &&
1056
+ // and type.options is an object (non-null from the previous)
1057
+ typeof type.options === "object" &&
1058
+ // and if `list` is in options
1059
+ "list" in type.options &&
1060
+ // then finally access the list
1061
+ type.options.list;
1046
1062
  if (Array.isArray(typeOptionsList)) {
1047
1063
  baseRule = baseRule.valid(typeOptionsList.map(option => extractValueFromListOption(option, type)));
1048
1064
  }
@@ -1071,23 +1087,27 @@ function normalizeValidationRules(typeDef) {
1071
1087
  }
1072
1088
  const validation = typeDef.validation;
1073
1089
  if (Array.isArray(validation)) {
1074
- return validation.flatMap(i => normalizeValidationRules(_objectSpread(_objectSpread({}, typeDef), {}, {
1090
+ return validation.flatMap(i => normalizeValidationRules({
1091
+ ...typeDef,
1075
1092
  validation: i
1076
- })));
1093
+ }));
1077
1094
  }
1078
1095
  if (validation instanceof Rule) {
1079
1096
  return [validation];
1080
1097
  }
1081
- const baseRule = Object.values(getTypeChain(typeDef, /* @__PURE__ */new Set()).reduce((acc, type) => {
1098
+ const baseRule =
1099
+ // using an object + Object.values to de-dupe the type chain by type name
1100
+ Object.values(getTypeChain(typeDef, /* @__PURE__ */new Set()).reduce((acc, type) => {
1082
1101
  acc[type.name] = type;
1083
1102
  return acc;
1084
1103
  }, {})).reduce(baseRuleReducer, new Rule(typeDef));
1085
1104
  if (!validation) {
1086
1105
  return [baseRule];
1087
1106
  }
1088
- return normalizeValidationRules(_objectSpread(_objectSpread({}, typeDef), {}, {
1107
+ return normalizeValidationRules({
1108
+ ...typeDef,
1089
1109
  validation: validation(baseRule)
1090
- }));
1110
+ });
1091
1111
  }
1092
1112
  const isRecord = maybeRecord => typeof maybeRecord === "object" && maybeRecord !== null && !Array.isArray(maybeRecord);
1093
1113
  const isNonNullable = value => value !== null && value !== void 0;
@@ -1149,22 +1169,25 @@ function validateDocumentObservable(getClient, doc, schema, context) {
1149
1169
  }
1150
1170
  function validateItemObservable(_ref) {
1151
1171
  let {
1152
- value,
1153
- type,
1154
- path = [],
1155
- parent
1156
- } = _ref,
1157
- restOfContext = _objectWithoutProperties(_ref, _excluded);
1172
+ value,
1173
+ type,
1174
+ path = [],
1175
+ parent,
1176
+ ...restOfContext
1177
+ } = _ref;
1158
1178
  var _a;
1159
1179
  const rules = normalizeValidationRules(type);
1160
- const selfChecks = rules.map(rule => rxjs.defer(() => rule.validate(value, _objectSpread(_objectSpread({}, restOfContext), {}, {
1180
+ const selfChecks = rules.map(rule => rxjs.defer(() => rule.validate(value, {
1181
+ ...restOfContext,
1161
1182
  parent,
1162
1183
  path,
1163
1184
  type
1164
- }))));
1185
+ })));
1165
1186
  let nestedChecks = [];
1166
1187
  const selfIsRequired = rules.some(rule => rule.isRequired());
1167
- const shouldRunNestedObjectValidation = (type == null ? void 0 : type.jsonType) === "object" && (!!value || (value === null || value === void 0) && selfIsRequired);
1188
+ const shouldRunNestedObjectValidation =
1189
+ // run nested validation for objects
1190
+ (type == null ? void 0 : type.jsonType) === "object" && (!!value || (value === null || value === void 0) && selfIsRequired);
1168
1191
  if (shouldRunNestedObjectValidation) {
1169
1192
  const fieldTypes = type.fields.reduce((acc, field) => {
1170
1193
  acc[field.name] = field.type;
@@ -1173,34 +1196,38 @@ function validateItemObservable(_ref) {
1173
1196
  nestedChecks = nestedChecks.concat(rules.map(rule => rule._fieldRules).filter(isNonNullable).flatMap(fieldResults => Object.entries(fieldResults)).flatMap(_ref2 => {
1174
1197
  let [name, validation] = _ref2;
1175
1198
  const fieldType = fieldTypes[name];
1176
- return normalizeValidationRules(_objectSpread(_objectSpread({}, fieldType), {}, {
1199
+ return normalizeValidationRules({
1200
+ ...fieldType,
1177
1201
  validation
1178
- })).map(subRule => {
1202
+ }).map(subRule => {
1179
1203
  const nestedValue = isRecord(value) ? value[name] : void 0;
1180
- return rxjs.defer(() => subRule.validate(nestedValue, _objectSpread(_objectSpread({}, restOfContext), {}, {
1204
+ return rxjs.defer(() => subRule.validate(nestedValue, {
1205
+ ...restOfContext,
1181
1206
  parent: value,
1182
1207
  path: path.concat(name),
1183
1208
  type: fieldType
1184
- })));
1209
+ }));
1185
1210
  });
1186
1211
  }));
1187
- nestedChecks = nestedChecks.concat(type.fields.map(field => validateItemObservable(_objectSpread(_objectSpread({}, restOfContext), {}, {
1212
+ nestedChecks = nestedChecks.concat(type.fields.map(field => validateItemObservable({
1213
+ ...restOfContext,
1188
1214
  parent: value,
1189
1215
  value: isRecord(value) ? value[field.name] : void 0,
1190
1216
  path: path.concat(field.name),
1191
1217
  type: field.type
1192
- }))));
1218
+ })));
1193
1219
  }
1194
1220
  const shouldRunNestedValidationForArrays = (type == null ? void 0 : type.jsonType) === "array" && Array.isArray(value);
1195
1221
  if (shouldRunNestedValidationForArrays) {
1196
- nestedChecks = nestedChecks.concat(value.map((item, index) => validateItemObservable(_objectSpread(_objectSpread({}, restOfContext), {}, {
1222
+ nestedChecks = nestedChecks.concat(value.map((item, index) => validateItemObservable({
1223
+ ...restOfContext,
1197
1224
  parent: value,
1198
1225
  value: item,
1199
1226
  path: path.concat(types.isKeyedObject(item) ? {
1200
1227
  _key: item._key
1201
1228
  } : index),
1202
1229
  type: resolveTypeForArrayItem(item, type.of)
1203
- }))));
1230
+ })));
1204
1231
  }
1205
1232
  const shouldRunNestedValidationForMarkDefs = types.isPortableTextTextBlock(value) && ((_a = value.markDefs) == null ? void 0 : _a.length) && types.isBlockSchemaType(type);
1206
1233
  if (shouldRunNestedValidationForMarkDefs) {
@@ -1210,14 +1237,15 @@ function validateItemObservable(_ref) {
1210
1237
  acc.set(annotationType.name, annotationType);
1211
1238
  return acc;
1212
1239
  }, /* @__PURE__ */new Map());
1213
- nestedChecks = nestedChecks.concat((value.markDefs || []).map(markDef => validateItemObservable(_objectSpread(_objectSpread({}, restOfContext), {}, {
1240
+ nestedChecks = nestedChecks.concat((value.markDefs || []).map(markDef => validateItemObservable({
1241
+ ...restOfContext,
1214
1242
  parent: value,
1215
1243
  value: markDef,
1216
1244
  path: path.concat(["markDefs", {
1217
1245
  _key: markDef._key
1218
1246
  }]),
1219
1247
  type: annotations.get(markDef._type)
1220
- }))));
1248
+ })));
1221
1249
  }
1222
1250
  return rxjs.defer(() => rxjs.merge([...selfChecks, ...nestedChecks])).pipe(operators.mergeMap(validateNode => rxjs.concat(idle(), validateNode), 40), operators.mergeAll(), operators.toArray(), operators.map(flatten__default.default), operators.map(results => {
1223
1251
  if (rules.some(rule => rule._fieldRules)) {