@sanity/validation 3.0.0-dev-preview.21 → 3.0.0-dev-preview.22

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,39 +1,25 @@
1
1
  'use strict';
2
2
 
3
3
  const _excluded = ["value", "type", "path", "parent"];
4
-
5
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; }
6
-
7
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; }
8
-
9
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; }
10
-
11
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; }
12
-
13
8
  function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
14
-
15
9
  Object.defineProperty(exports, '__esModule', {
16
10
  value: true
17
11
  });
18
-
19
12
  var lodash = require('lodash');
20
-
21
13
  var types = require('@sanity/types');
22
-
23
14
  var formatDate = require('date-fns/format');
24
-
25
15
  var rxjs = require('rxjs');
26
-
27
16
  var operators = require('rxjs/operators');
28
-
29
17
  function _interopDefaultLegacy(e) {
30
18
  return e && typeof e === 'object' && 'default' in e ? e : {
31
19
  'default': e
32
20
  };
33
21
  }
34
-
35
22
  var formatDate__default = /*#__PURE__*/_interopDefaultLegacy(formatDate);
36
-
37
23
  const ValidationError = class ValidationError2 {
38
24
  constructor(message) {
39
25
  let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
@@ -42,7 +28,6 @@ const ValidationError = class ValidationError2 {
42
28
  this.children = options.children;
43
29
  this.operation = options.operation;
44
30
  }
45
-
46
31
  cloneWithMessage(msg) {
47
32
  return new ValidationError2(msg, {
48
33
  paths: this.paths,
@@ -50,66 +35,49 @@ const ValidationError = class ValidationError2 {
50
35
  operation: this.operation
51
36
  });
52
37
  }
53
-
54
38
  };
55
-
56
39
  var escapeRegex = string => {
57
40
  return string.replace(/[\^\$\.\*\+\-\?\=\!\:\|\\\/\(\)\[\]\{\}\,]/g, "\\$&");
58
41
  };
59
-
60
42
  function pathToString() {
61
43
  let path = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
62
44
  return path.reduce((target, segment, i) => {
63
45
  const segmentType = typeof segment;
64
-
65
46
  if (segmentType === "number") {
66
47
  return "".concat(target, "[").concat(segment, "]");
67
48
  }
68
-
69
49
  if (segmentType === "string") {
70
50
  const separator = i === 0 ? "" : ".";
71
51
  return "".concat(target).concat(separator).concat(segment);
72
52
  }
73
-
74
53
  if (types.isKeyedObject(segment)) {
75
54
  return "".concat(target, "[_key==\"").concat(segment._key, "\"]");
76
55
  }
77
-
78
56
  throw new Error("Unsupported path segment \"".concat(segment, "\""));
79
57
  }, "");
80
58
  }
81
-
82
59
  function isNonNullable$1(t) {
83
60
  return t !== null || t !== void 0;
84
61
  }
85
-
86
62
  function convertToValidationMarker(validatorResult, level, context) {
87
63
  var _a;
88
-
89
64
  if (!context) {
90
65
  throw new Error("missing context");
91
66
  }
92
-
93
67
  if (validatorResult === true) return [];
94
-
95
68
  if (Array.isArray(validatorResult)) {
96
69
  return validatorResult.flatMap(child => convertToValidationMarker(child, level, context)).filter(isNonNullable$1);
97
70
  }
98
-
99
71
  if (typeof validatorResult === "string") {
100
72
  return convertToValidationMarker(new ValidationError(validatorResult), level, context);
101
73
  }
102
-
103
74
  if (!(validatorResult instanceof ValidationError)) {
104
75
  if (typeof (validatorResult == null ? void 0 : validatorResult.message) !== "string") {
105
76
  throw new Error("".concat(pathToString(context.path), ": Validator must return 'true' if valid or an error message as a string on errors"));
106
77
  }
107
-
108
78
  return convertToValidationMarker(new ValidationError(validatorResult.message, validatorResult), level, context);
109
79
  }
110
-
111
80
  const results = [];
112
-
113
81
  if (!((_a = validatorResult.paths) == null ? void 0 : _a.length)) {
114
82
  return [{
115
83
  level: level || "error",
@@ -117,113 +85,85 @@ function convertToValidationMarker(validatorResult, level, context) {
117
85
  path: context.path || []
118
86
  }];
119
87
  }
120
-
121
88
  return results.concat(validatorResult.paths.map(path => ({
122
89
  path: (context.path || []).concat(path),
123
90
  level: level || "error",
124
91
  item: validatorResult
125
92
  })));
126
93
  }
127
-
128
94
  const _toString = {}.toString;
129
95
  const builtIns = [Object, Function, Array, String, Boolean, Number, Date, RegExp, Error];
130
-
131
96
  function isBuiltIn(_constructor) {
132
97
  for (let i = 0; i < builtIns.length; i++) {
133
98
  if (builtIns[i] === _constructor) return true;
134
99
  }
135
-
136
100
  return false;
137
101
  }
138
-
139
102
  function typeString(obj) {
140
103
  const stringType = _toString.call(obj).slice(8, -1);
141
-
142
104
  if (obj === null || obj === void 0) return stringType.toLowerCase();
143
105
  const constructorType = obj.constructor;
144
106
  if (constructorType && !isBuiltIn(constructorType)) return constructorType.name;
145
107
  return stringType;
146
108
  }
147
-
148
109
  function deepEquals(a, b) {
149
110
  if (a === b) {
150
111
  return true;
151
112
  }
152
-
153
113
  if (Array.isArray(a) && Array.isArray(b)) {
154
114
  if (a.length != b.length) return false;
155
-
156
115
  for (let i = 0; i < a.length; i++) {
157
116
  if (!deepEquals(a[i], b[i])) {
158
117
  return false;
159
118
  }
160
119
  }
161
-
162
120
  return true;
163
121
  }
164
-
165
122
  if (Array.isArray(a) != Array.isArray(b)) {
166
123
  return false;
167
124
  }
168
-
169
125
  if (a && b && typeof a === "object" && typeof b === "object") {
170
126
  const keys = Object.keys(a);
171
-
172
127
  if (keys.length !== Object.keys(b).length) {
173
128
  return false;
174
129
  }
175
-
176
130
  if (a instanceof Date && b instanceof Date) {
177
131
  return a.getTime() === b.getTime();
178
132
  }
179
-
180
133
  if (a instanceof Date != b instanceof Date) {
181
134
  return false;
182
135
  }
183
-
184
136
  if (a instanceof RegExp && b instanceof RegExp) {
185
137
  return a.toString() == b.toString();
186
138
  }
187
-
188
139
  if (a instanceof RegExp != b instanceof RegExp) {
189
140
  return false;
190
141
  }
191
-
192
142
  for (let i = 0; i < keys.length; i++) {
193
143
  if (keys[i] === "_key") {
194
144
  continue;
195
145
  }
196
-
197
146
  if (!Object.prototype.hasOwnProperty.call(b, keys[i])) {
198
147
  return false;
199
148
  }
200
149
  }
201
-
202
150
  for (let i = 0; i < keys.length; i++) {
203
151
  const key = keys[i];
204
-
205
152
  if (key === "_key") {
206
153
  continue;
207
154
  }
208
-
209
155
  if (!deepEquals(a[key], b[key])) {
210
156
  return false;
211
157
  }
212
158
  }
213
-
214
159
  return true;
215
160
  }
216
-
217
161
  return false;
218
162
  }
219
-
220
163
  const SLOW_VALIDATOR_TIMEOUT = 5e3;
221
-
222
164
  const formatValidationErrors = options => {
223
165
  var _a;
224
-
225
166
  let message;
226
-
227
167
  if (options.message) {
228
168
  message = options.message;
229
169
  } else if (options.results.length === 1) {
@@ -231,28 +171,23 @@ const formatValidationErrors = options => {
231
171
  } else {
232
172
  message = "[".concat(options.results.map(err => err.item.message).join(" - ".concat(options.operation, " - ")), "]");
233
173
  }
234
-
235
174
  return new ValidationError(message, {
236
175
  children: options.results.length > 1 ? options.results : void 0,
237
176
  operation: options.operation
238
177
  });
239
178
  };
240
-
241
179
  const genericValidators = {
242
180
  type: (expected, value, message) => {
243
181
  const actualType = typeString(value);
244
-
245
182
  if (actualType !== expected && actualType !== "undefined") {
246
183
  return message || "Expected type \"".concat(expected, "\", got \"").concat(actualType, "\"");
247
184
  }
248
-
249
185
  return true;
250
186
  },
251
187
  presence: (expected, value, message) => {
252
188
  if (value === void 0 && expected === "required") {
253
189
  return message || "Value is required";
254
190
  }
255
-
256
191
  return true;
257
192
  },
258
193
  all: async (children, value, message, context) => {
@@ -277,11 +212,9 @@ const genericValidators = {
277
212
  },
278
213
  valid: (allowedValues, actual, message) => {
279
214
  const valueType = typeof actual;
280
-
281
215
  if (valueType === "undefined") {
282
216
  return true;
283
217
  }
284
-
285
218
  const value = (valueType === "number" || valueType === "string") && "".concat(actual);
286
219
  const strValue = value && value.length > 30 ? "".concat(value.slice(0, 30), "\u2026") : value;
287
220
  const defaultMessage = value ? "Value \"".concat(strValue, "\" did not match any allowed values") : "Value did not match any allowed values";
@@ -292,106 +225,86 @@ const genericValidators = {
292
225
  console.warn("Custom validator at ".concat(pathToString(context.path), " has taken more than ").concat(SLOW_VALIDATOR_TIMEOUT, "ms to respond"));
293
226
  }, SLOW_VALIDATOR_TIMEOUT);
294
227
  let result;
295
-
296
228
  try {
297
229
  result = await fn(value, context);
298
230
  } finally {
299
231
  clearTimeout(slowTimer);
300
232
  }
301
-
302
233
  if (typeof result === "string") return message || result;
303
234
  return result;
304
235
  }
305
236
  };
306
-
307
237
  const booleanValidators = _objectSpread(_objectSpread({}, genericValidators), {}, {
308
238
  presence: (flag, value, message) => {
309
239
  if (flag === "required" && typeof value !== "boolean") {
310
240
  return message || "Required";
311
241
  }
312
-
313
242
  return true;
314
243
  }
315
244
  });
316
-
317
245
  const precisionRx = /(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/;
318
-
319
246
  const numberValidators = _objectSpread(_objectSpread({}, genericValidators), {}, {
320
247
  integer: (_unused, value, message) => {
321
248
  if (!Number.isInteger(value)) {
322
249
  return message || "Must be an integer";
323
250
  }
324
-
325
251
  return true;
326
252
  },
327
253
  precision: (limit, value, message) => {
328
254
  if (value === void 0) return true;
329
255
  const places = value.toString().match(precisionRx);
330
256
  const decimals = Math.max((places[1] ? places[1].length : 0) - (places[2] ? parseInt(places[2], 10) : 0), 0);
331
-
332
257
  if (decimals > limit) {
333
258
  return message || "Max precision is ".concat(limit);
334
259
  }
335
-
336
260
  return true;
337
261
  },
338
262
  min: (minNum, value, message) => {
339
263
  if (value >= minNum) {
340
264
  return true;
341
265
  }
342
-
343
266
  return message || "Must be greater than or equal ".concat(minNum);
344
267
  },
345
268
  max: (maxNum, value, message) => {
346
269
  if (value <= maxNum) {
347
270
  return true;
348
271
  }
349
-
350
272
  return message || "Must be less than or equal ".concat(maxNum);
351
273
  },
352
274
  greaterThan: (num, value, message) => {
353
275
  if (value > num) {
354
276
  return true;
355
277
  }
356
-
357
278
  return message || "Must be greater than ".concat(num);
358
279
  },
359
280
  lessThan: (maxNum, value, message) => {
360
281
  if (value < maxNum) {
361
282
  return true;
362
283
  }
363
-
364
284
  return message || "Must be less than ".concat(maxNum);
365
285
  }
366
286
  });
367
-
368
287
  const DUMMY_ORIGIN = "http://sanity";
369
288
  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,}))$/;
370
-
371
289
  const isRelativeUrl = url => /^\.*\//.test(url);
372
-
373
290
  const stringValidators = _objectSpread(_objectSpread({}, genericValidators), {}, {
374
291
  min: (minLength, value, message) => {
375
292
  if (!value || value.length >= minLength) {
376
293
  return true;
377
294
  }
378
-
379
295
  return message || "Must be at least ".concat(minLength, " characters long");
380
296
  },
381
297
  max: (maxLength, value, message) => {
382
298
  if (!value || value.length <= maxLength) {
383
299
  return true;
384
300
  }
385
-
386
301
  return message || "Must be at most ".concat(maxLength, " characters long");
387
302
  },
388
303
  length: (wantedLength, value, message) => {
389
304
  const strValue = value || "";
390
-
391
305
  if (strValue.length === wantedLength) {
392
306
  return true;
393
307
  }
394
-
395
308
  return message || "Must be exactly ".concat(wantedLength, " characters long");
396
309
  },
397
310
  uri: (constraints, value, message) => {
@@ -405,52 +318,41 @@ const stringValidators = _objectSpread(_objectSpread({}, genericValidators), {},
405
318
  } = options;
406
319
  const allowRelative = options.allowRelative || relativeOnly;
407
320
  let url;
408
-
409
321
  try {
410
322
  url = allowRelative ? new URL(strValue, DUMMY_ORIGIN) : new URL(strValue);
411
323
  } catch (err) {
412
324
  return message || "Not a valid URL";
413
325
  }
414
-
415
326
  if (relativeOnly && url.origin !== DUMMY_ORIGIN) {
416
327
  return message || "Only relative URLs are allowed";
417
328
  }
418
-
419
329
  if (!allowRelative && url.origin === DUMMY_ORIGIN && isRelativeUrl(strValue)) {
420
330
  return message || "Relative URLs are not allowed";
421
331
  }
422
-
423
332
  if (!allowCredentials && (url.username || url.password)) {
424
333
  return message || "Username/password not allowed";
425
334
  }
426
-
427
335
  const urlScheme = url.protocol.replace(/:$/, "");
428
336
  const matchesAllowedScheme = options.scheme.some(scheme => scheme.test(urlScheme));
429
-
430
337
  if (!matchesAllowedScheme) {
431
338
  return message || "Does not match allowed protocols/schemes";
432
339
  }
433
-
434
340
  return true;
435
341
  },
436
342
  stringCasing: (casing, value, message) => {
437
343
  const strValue = value || "";
438
-
439
344
  if (casing === "uppercase" && strValue !== strValue.toLocaleUpperCase()) {
440
345
  return message || "Must be all uppercase letters";
441
346
  }
442
-
443
347
  if (casing === "lowercase" && strValue !== strValue.toLocaleLowerCase()) {
444
348
  return message || "Must be all lowercase letters";
445
349
  }
446
-
447
350
  return true;
448
351
  },
449
352
  presence: (flag, value, message) => {
450
353
  if (flag === "required" && !value) {
451
354
  return message || "Required";
452
355
  }
453
-
454
356
  return true;
455
357
  },
456
358
  regex: (options, value, message) => {
@@ -462,106 +364,85 @@ const stringValidators = _objectSpread(_objectSpread({}, genericValidators), {},
462
364
  const regName = name || "\"".concat(pattern.toString(), "\"");
463
365
  const strValue = value || "";
464
366
  const matches = pattern.test(strValue);
465
-
466
367
  if (!invert && !matches || invert && matches) {
467
368
  const defaultMessage = invert ? "Should not match ".concat(regName, "-pattern") : "Does not match ".concat(regName, "-pattern");
468
369
  return message || defaultMessage;
469
370
  }
470
-
471
371
  return true;
472
372
  },
473
373
  email: (_unused, value, message) => {
474
374
  const strValue = "".concat(value || "").trim();
475
-
476
375
  if (!strValue || emailRegex.test(strValue)) {
477
376
  return true;
478
377
  }
479
-
480
378
  return message || "Must be a valid email address";
481
379
  }
482
380
  });
483
-
484
381
  const arrayValidators = _objectSpread(_objectSpread({}, genericValidators), {}, {
485
382
  min: (minLength, value, message) => {
486
383
  if (!value || value.length >= minLength) {
487
384
  return true;
488
385
  }
489
-
490
386
  return message || "Must have at least ".concat(minLength, " items");
491
387
  },
492
388
  max: (maxLength, value, message) => {
493
389
  if (!value || value.length <= maxLength) {
494
390
  return true;
495
391
  }
496
-
497
392
  return message || "Must have at most ".concat(maxLength, " items");
498
393
  },
499
394
  length: (wantedLength, value, message) => {
500
395
  if (!value || value.length === wantedLength) {
501
396
  return true;
502
397
  }
503
-
504
398
  return message || "Must have exactly ".concat(wantedLength, " items");
505
399
  },
506
400
  presence: (flag, value, message) => {
507
401
  if (flag === "required" && !value) {
508
402
  return message || "Required";
509
403
  }
510
-
511
404
  return true;
512
405
  },
513
406
  valid: (allowedValues, values, message) => {
514
407
  const valueType = typeof values;
515
-
516
408
  if (valueType === "undefined") {
517
409
  return true;
518
410
  }
519
-
520
411
  const paths = [];
521
-
522
412
  for (let i = 0; i < values.length; i++) {
523
413
  const value = values[i];
524
-
525
414
  if (allowedValues.some(expected => deepEquals(expected, value))) {
526
415
  continue;
527
416
  }
528
-
529
417
  const pathSegment = value && value._key ? {
530
418
  _key: value._key
531
419
  } : i;
532
420
  paths.push([pathSegment]);
533
421
  }
534
-
535
422
  return paths.length === 0 ? true : new ValidationError(message || "Value did not match any allowed values", {
536
423
  paths
537
424
  });
538
425
  },
539
426
  unique: (_unused, value, message) => {
540
427
  const dupeIndices = [];
541
-
542
428
  if (!value) {
543
429
  return true;
544
430
  }
545
-
546
431
  for (let x = 0; x < value.length; x++) {
547
432
  for (let y = x + 1; y < value.length; y++) {
548
433
  const itemA = value[x];
549
434
  const itemB = value[y];
550
-
551
435
  if (!deepEquals(itemA, itemB)) {
552
436
  continue;
553
437
  }
554
-
555
438
  if (dupeIndices.indexOf(x) === -1) {
556
439
  dupeIndices.push(x);
557
440
  }
558
-
559
441
  if (dupeIndices.indexOf(y) === -1) {
560
442
  dupeIndices.push(y);
561
443
  }
562
444
  }
563
445
  }
564
-
565
446
  const paths = dupeIndices.map(idx => {
566
447
  const item = value[idx];
567
448
  const pathSegment = item && item._key ? {
@@ -574,57 +455,44 @@ const arrayValidators = _objectSpread(_objectSpread({}, genericValidators), {},
574
455
  }) : true;
575
456
  }
576
457
  });
577
-
578
458
  const metaKeys = ["_key", "_type", "_weak"];
579
-
580
459
  const objectValidators = _objectSpread(_objectSpread({}, genericValidators), {}, {
581
460
  presence: (expected, value, message) => {
582
461
  if (expected !== "required") {
583
462
  return true;
584
463
  }
585
-
586
464
  const keys = value && Object.keys(value).filter(key => !metaKeys.includes(key));
587
-
588
465
  if (value === void 0 || keys && keys.length === 0) {
589
466
  return message || "Required";
590
467
  }
591
-
592
468
  return true;
593
469
  },
594
470
  reference: async (_unused, value, message, context) => {
595
471
  if (!value) {
596
472
  return true;
597
473
  }
598
-
599
474
  if (!types.isReference(value)) {
600
475
  return message || true;
601
476
  }
602
-
603
477
  const {
604
478
  type,
605
479
  getDocumentExists
606
480
  } = context;
607
-
608
481
  if (!type) {
609
482
  throw new Error("`type` was not provided in validation context");
610
483
  }
611
-
612
484
  if ("weak" in type && type.weak) {
613
485
  return true;
614
486
  }
615
-
616
487
  if (!getDocumentExists) {
617
488
  throw new Error("`getDocumentExists` was not provided in validation context");
618
489
  }
619
-
620
490
  const exists = await getDocumentExists({
621
491
  id: value._ref
622
492
  });
623
-
624
493
  if (!exists) {
625
494
  return "This reference must be published";
626
495
  }
627
-
628
496
  return true;
629
497
  },
630
498
  assetRequired: (flag, value, message) => {
@@ -632,106 +500,82 @@ const objectValidators = _objectSpread(_objectSpread({}, genericValidators), {},
632
500
  const assetType = flag.assetType || "Asset";
633
501
  return message || "".concat(assetType, " required");
634
502
  }
635
-
636
503
  return true;
637
504
  }
638
505
  });
639
-
640
506
  function isRecord$1(obj) {
641
507
  return typeof obj === "object" && obj !== null && !Array.isArray(obj);
642
508
  }
643
-
644
509
  const isoDate = /^(?:[-+]\d{2})?(?:\d{4}(?!\d{2}\b))(?:(-?)(?:(?:0[1-9]|1[0-2])(?:\1(?:[12]\d|0[1-9]|3[01]))?|W(?:[0-4]\d|5[0-2])(?:-?[1-7])?|(?:00[1-9]|0[1-9]\d|[12]\d{2}|3(?:[0-5]\d|6[1-6])))(?![T]$|[T][\d]+Z$)(?:[T\s](?:(?:(?:[01]\d|2[0-3])(?:(:?)[0-5]\d)?|24:?00)(?:[.,]\d+(?!:))?)(?:\2[0-5]\d(?:[.,]\d+)?)?(?:[Z]|(?:[+-])(?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?)?$/;
645
-
646
510
  const getFormattedDate = function () {
647
511
  let type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "";
648
512
  let value = arguments.length > 1 ? arguments[1] : undefined;
649
513
  let options = arguments.length > 2 ? arguments[2] : undefined;
650
514
  let format = "yyyy-MM-dd";
651
-
652
515
  if (options && options.dateFormat) {
653
516
  format = options.dateFormat;
654
517
  }
655
-
656
518
  if (type === "date") {
657
519
  return formatDate__default["default"](new Date(value), format);
658
520
  }
659
-
660
521
  if (options && options.timeFormat) {
661
522
  format += " ".concat(options.timeFormat);
662
523
  } else {
663
524
  format += " HH:mm";
664
525
  }
665
-
666
526
  return formatDate__default["default"](new Date(value), format);
667
527
  };
668
-
669
528
  function parseDate(date) {
670
529
  let throwOnError = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
671
530
  if (!date) return null;
672
531
  if (date === "now") return new Date();
673
532
  const parsed = new Date(date);
674
533
  const isInvalid = isNaN(parsed.getTime());
675
-
676
534
  if (isInvalid && throwOnError) {
677
535
  throw new Error("Unable to parse \"".concat(date, "\" to a date"));
678
536
  }
679
-
680
537
  return isInvalid ? null : parsed;
681
538
  }
682
-
683
539
  const dateValidators = _objectSpread(_objectSpread({}, genericValidators), {}, {
684
540
  type: (_unused, value, message) => {
685
541
  const strVal = "".concat(value);
686
-
687
542
  if (!strVal || isoDate.test(value)) {
688
543
  return true;
689
544
  }
690
-
691
545
  return message || "Must be a valid ISO-8601 formatted date string";
692
546
  },
693
547
  min: (minDate, value, message, context) => {
694
548
  const dateVal = parseDate(value);
695
-
696
549
  if (!dateVal) {
697
550
  return true;
698
551
  }
699
-
700
552
  if (!value || dateVal >= parseDate(minDate, true)) {
701
553
  return true;
702
554
  }
703
-
704
555
  if (!context.type) {
705
556
  throw new Error("`type` was not provided in validation context.");
706
557
  }
707
-
708
558
  const dateTimeOptions = isRecord$1(context.type.options) ? context.type.options : {};
709
559
  const date = getFormattedDate(context.type.name, minDate, dateTimeOptions);
710
560
  return message || "Must be at or after ".concat(date);
711
561
  },
712
562
  max: (maxDate, value, message, context) => {
713
563
  const dateVal = parseDate(value);
714
-
715
564
  if (!dateVal) {
716
565
  return true;
717
566
  }
718
-
719
567
  if (!value || dateVal <= parseDate(maxDate, true)) {
720
568
  return true;
721
569
  }
722
-
723
570
  if (!context.type) {
724
571
  throw new Error("`type` was not provided in validation context.");
725
572
  }
726
-
727
573
  const dateTimeOptions = isRecord$1(context.type.options) ? context.type.options : {};
728
574
  const date = getFormattedDate(context.type.name, maxDate, dateTimeOptions);
729
575
  return message || "Must be at or before ".concat(date);
730
576
  }
731
577
  });
732
-
733
578
  var _a;
734
-
735
579
  const typeValidators = {
736
580
  Boolean: booleanValidators,
737
581
  Number: numberValidators,
@@ -740,16 +584,13 @@ const typeValidators = {
740
584
  Object: objectValidators,
741
585
  Date: dateValidators
742
586
  };
743
-
744
587
  const getBaseType = type => {
745
588
  return type && type.type ? getBaseType(type.type) : type;
746
589
  };
747
-
748
590
  const isFieldRef = constraint => {
749
591
  if (typeof constraint !== "object" || !constraint) return false;
750
592
  return constraint.type === Rule.FIELD_REF;
751
593
  };
752
-
753
594
  const EMPTY_ARRAY = [];
754
595
  const FIELD_REF = Symbol("FIELD_REF");
755
596
  const ruleConstraintTypes$1 = ["Array", "Boolean", "Date", "Number", "Object", "String"];
@@ -766,34 +607,29 @@ const Rule = (_a = class {
766
607
  this._typeDef = typeDef;
767
608
  this.reset();
768
609
  }
769
-
770
610
  _mergeRequired(next) {
771
611
  if (this._required === "required" || next._required === "required") return "required";
772
612
  if (this._required === "optional" || next._required === "optional") return "optional";
773
613
  return void 0;
774
614
  }
775
-
776
615
  error(message) {
777
616
  const rule = this.clone();
778
617
  rule._level = "error";
779
618
  rule._message = message || void 0;
780
619
  return rule;
781
620
  }
782
-
783
621
  warning(message) {
784
622
  const rule = this.clone();
785
623
  rule._level = "warning";
786
624
  rule._message = message || void 0;
787
625
  return rule;
788
626
  }
789
-
790
627
  info(message) {
791
628
  const rule = this.clone();
792
629
  rule._level = "info";
793
630
  rule._message = message || void 0;
794
631
  return rule;
795
632
  }
796
-
797
633
  reset() {
798
634
  this._type = this._type || void 0;
799
635
  this._rules = (this._rules || []).filter(rule => rule.flag === "type");
@@ -803,11 +639,9 @@ const Rule = (_a = class {
803
639
  this._fieldRules = void 0;
804
640
  return this;
805
641
  }
806
-
807
642
  isRequired() {
808
643
  return this._required === "required";
809
644
  }
810
-
811
645
  clone() {
812
646
  const rule = new _a();
813
647
  rule._type = this._type;
@@ -819,7 +653,6 @@ const Rule = (_a = class {
819
653
  rule._typeDef = this._typeDef;
820
654
  return rule;
821
655
  }
822
-
823
656
  cloneWithRules(rules) {
824
657
  const rule = this.clone();
825
658
  const newRules = /* @__PURE__ */new Set();
@@ -827,7 +660,6 @@ const Rule = (_a = class {
827
660
  if (curr.flag === "type") {
828
661
  rule._type = curr.constraint;
829
662
  }
830
-
831
663
  newRules.add(curr.flag);
832
664
  });
833
665
  rule._rules = rule._rules.filter(curr => {
@@ -837,12 +669,10 @@ const Rule = (_a = class {
837
669
  }).concat(rules);
838
670
  return rule;
839
671
  }
840
-
841
672
  merge(rule) {
842
673
  if (this._type && rule._type && this._type !== rule._type) {
843
674
  throw new Error("merge() failed: conflicting types");
844
675
  }
845
-
846
676
  const newRule = this.cloneWithRules(rule._rules);
847
677
  newRule._type = this._type || rule._type;
848
678
  newRule._message = this._message || rule._message;
@@ -850,14 +680,11 @@ const Rule = (_a = class {
850
680
  newRule._level = this._level === "error" ? rule._level : this._level;
851
681
  return newRule;
852
682
  }
853
-
854
683
  type(targetType) {
855
684
  const type = "".concat(targetType.slice(0, 1).toUpperCase()).concat(targetType.slice(1));
856
-
857
685
  if (!ruleConstraintTypes$1.includes(type)) {
858
686
  throw new Error("Unknown type \"".concat(targetType, "\""));
859
687
  }
860
-
861
688
  const rule = this.cloneWithRules([{
862
689
  flag: "type",
863
690
  constraint: type
@@ -865,21 +692,18 @@ const Rule = (_a = class {
865
692
  rule._type = type;
866
693
  return rule;
867
694
  }
868
-
869
695
  all(children) {
870
696
  return this.cloneWithRules([{
871
697
  flag: "all",
872
698
  constraint: children
873
699
  }]);
874
700
  }
875
-
876
701
  either(children) {
877
702
  return this.cloneWithRules([{
878
703
  flag: "either",
879
704
  constraint: children
880
705
  }]);
881
706
  }
882
-
883
707
  optional() {
884
708
  const rule = this.cloneWithRules([{
885
709
  flag: "presence",
@@ -888,7 +712,6 @@ const Rule = (_a = class {
888
712
  rule._required = "optional";
889
713
  return rule;
890
714
  }
891
-
892
715
  required() {
893
716
  const rule = this.cloneWithRules([{
894
717
  flag: "presence",
@@ -897,42 +720,36 @@ const Rule = (_a = class {
897
720
  rule._required = "required";
898
721
  return rule;
899
722
  }
900
-
901
723
  custom(fn) {
902
724
  return this.cloneWithRules([{
903
725
  flag: "custom",
904
726
  constraint: fn
905
727
  }]);
906
728
  }
907
-
908
729
  block(fn) {
909
730
  return this.cloneWithRules([{
910
731
  flag: "custom",
911
732
  constraint: fn
912
733
  }]);
913
734
  }
914
-
915
735
  min(len) {
916
736
  return this.cloneWithRules([{
917
737
  flag: "min",
918
738
  constraint: len
919
739
  }]);
920
740
  }
921
-
922
741
  max(len) {
923
742
  return this.cloneWithRules([{
924
743
  flag: "max",
925
744
  constraint: len
926
745
  }]);
927
746
  }
928
-
929
747
  length(len) {
930
748
  return this.cloneWithRules([{
931
749
  flag: "length",
932
750
  constraint: len
933
751
  }]);
934
752
  }
935
-
936
753
  valid(value) {
937
754
  const values = Array.isArray(value) ? value : [value];
938
755
  return this.cloneWithRules([{
@@ -940,65 +757,55 @@ const Rule = (_a = class {
940
757
  constraint: values
941
758
  }]);
942
759
  }
943
-
944
760
  integer() {
945
761
  return this.cloneWithRules([{
946
762
  flag: "integer"
947
763
  }]);
948
764
  }
949
-
950
765
  precision(limit) {
951
766
  return this.cloneWithRules([{
952
767
  flag: "precision",
953
768
  constraint: limit
954
769
  }]);
955
770
  }
956
-
957
771
  positive() {
958
772
  return this.cloneWithRules([{
959
773
  flag: "min",
960
774
  constraint: 0
961
775
  }]);
962
776
  }
963
-
964
777
  negative() {
965
778
  return this.cloneWithRules([{
966
779
  flag: "lessThan",
967
780
  constraint: 0
968
781
  }]);
969
782
  }
970
-
971
783
  greaterThan(num) {
972
784
  return this.cloneWithRules([{
973
785
  flag: "greaterThan",
974
786
  constraint: num
975
787
  }]);
976
788
  }
977
-
978
789
  lessThan(num) {
979
790
  return this.cloneWithRules([{
980
791
  flag: "lessThan",
981
792
  constraint: num
982
793
  }]);
983
794
  }
984
-
985
795
  uppercase() {
986
796
  return this.cloneWithRules([{
987
797
  flag: "stringCasing",
988
798
  constraint: "uppercase"
989
799
  }]);
990
800
  }
991
-
992
801
  lowercase() {
993
802
  return this.cloneWithRules([{
994
803
  flag: "stringCasing",
995
804
  constraint: "lowercase"
996
805
  }]);
997
806
  }
998
-
999
807
  regex(pattern, a, b) {
1000
808
  var _a2, _b;
1001
-
1002
809
  const name = typeof a === "string" ? a : (_a2 = a == null ? void 0 : a.name) != null ? _a2 : b == null ? void 0 : b.name;
1003
810
  const invert = typeof a === "string" ? false : (_b = a == null ? void 0 : a.invert) != null ? _b : b == null ? void 0 : b.invert;
1004
811
  const constraint = {
@@ -1011,28 +818,23 @@ const Rule = (_a = class {
1011
818
  constraint
1012
819
  }]);
1013
820
  }
1014
-
1015
821
  email() {
1016
822
  return this.cloneWithRules([{
1017
823
  flag: "email"
1018
824
  }]);
1019
825
  }
1020
-
1021
826
  uri(opts) {
1022
827
  const optsScheme = (opts == null ? void 0 : opts.scheme) || ["http", "https"];
1023
828
  const schemes = Array.isArray(optsScheme) ? optsScheme : [optsScheme];
1024
-
1025
829
  if (!schemes.length) {
1026
830
  throw new Error("scheme must have at least 1 scheme specified");
1027
831
  }
1028
-
1029
832
  const constraint = {
1030
833
  options: {
1031
834
  scheme: schemes.map(scheme => {
1032
835
  if (!(scheme instanceof RegExp) && typeof scheme !== "string") {
1033
836
  throw new Error("scheme must be a RegExp or a String");
1034
837
  }
1035
-
1036
838
  return typeof scheme === "string" ? new RegExp("^".concat(escapeRegex(scheme), "$")) : scheme;
1037
839
  }),
1038
840
  allowRelative: (opts == null ? void 0 : opts.allowRelative) || false,
@@ -1045,39 +847,32 @@ const Rule = (_a = class {
1045
847
  constraint
1046
848
  }]);
1047
849
  }
1048
-
1049
850
  unique() {
1050
851
  return this.cloneWithRules([{
1051
852
  flag: "unique"
1052
853
  }]);
1053
854
  }
1054
-
1055
855
  reference() {
1056
856
  return this.cloneWithRules([{
1057
857
  flag: "reference"
1058
858
  }]);
1059
859
  }
1060
-
1061
860
  fields(rules) {
1062
861
  if (this._type !== "Object") {
1063
862
  throw new Error("fields() can only be called on an object type");
1064
863
  }
1065
-
1066
864
  const rule = this.cloneWithRules([]);
1067
865
  rule._fieldRules = rules;
1068
866
  return rule;
1069
867
  }
1070
-
1071
868
  assetRequired() {
1072
869
  const base = getBaseType(this._typeDef);
1073
870
  let assetType;
1074
-
1075
871
  if (base && ["image", "file"].includes(base.name)) {
1076
872
  assetType = base.name === "image" ? "Image" : "File";
1077
873
  } else {
1078
874
  assetType = "Asset";
1079
875
  }
1080
-
1081
876
  return this.cloneWithRules([{
1082
877
  flag: "assetRequired",
1083
878
  constraint: {
@@ -1085,80 +880,62 @@ const Rule = (_a = class {
1085
880
  }
1086
881
  }]);
1087
882
  }
1088
-
1089
883
  async validate(value, context) {
1090
884
  if (!context) {
1091
885
  throw new Error("missing context");
1092
886
  }
1093
-
1094
887
  const valueIsEmpty = value === null || value === void 0;
1095
-
1096
888
  if (valueIsEmpty && this._required === "optional") {
1097
889
  return EMPTY_ARRAY;
1098
890
  }
1099
-
1100
891
  const rules = this._required === void 0 && valueIsEmpty ? this._rules.filter(curr => curr.flag === "custom") : this._rules;
1101
892
  const validators = this._type && typeValidators[this._type] || genericValidators;
1102
893
  const results = await Promise.all(rules.map(async curr => {
1103
894
  if (curr.flag === void 0) {
1104
895
  throw new Error('Invalid rule, did not contain "flag"-property');
1105
896
  }
1106
-
1107
897
  const validator = validators[curr.flag];
1108
-
1109
898
  if (!validator) {
1110
899
  const forType = this._type ? "type \"".concat(this._type, "\"") : "rule without declared type";
1111
900
  throw new Error("Validator for flag \"".concat(curr.flag, "\" not found for ").concat(forType));
1112
901
  }
1113
-
1114
902
  let specConstraint = "constraint" in curr ? curr.constraint : null;
1115
-
1116
903
  if (isFieldRef(specConstraint)) {
1117
904
  specConstraint = lodash.get(context.parent, specConstraint.path);
1118
905
  }
1119
-
1120
906
  let result;
1121
-
1122
907
  try {
1123
908
  result = await validator(specConstraint, value, this._message, context);
1124
909
  } catch (err) {
1125
910
  const errorFromException = new ValidationError("".concat(pathToString(context.path), ": Exception occurred while validating value: ").concat(err.message));
1126
911
  return convertToValidationMarker(errorFromException, "error", context);
1127
912
  }
1128
-
1129
913
  return convertToValidationMarker(result, this._level, context);
1130
914
  }));
1131
915
  return results.flat();
1132
916
  }
1133
-
1134
917
  }, _a.FIELD_REF = FIELD_REF, _a.array = def => new _a(def).type("Array"), _a.object = def => new _a(def).type("Object"), _a.string = def => new _a(def).type("String"), _a.number = def => new _a(def).type("Number"), _a.boolean = def => new _a(def).type("Boolean"), _a.dateTime = def => new _a(def).type("Date"), _a.valueOfField = path => ({
1135
918
  type: FIELD_REF,
1136
919
  path
1137
920
  }), _a);
1138
-
1139
921
  const requestIdleCallbackShim = function requestIdleCallbackShim2(callback, options) {
1140
922
  const start = Date.now();
1141
923
  return window.setTimeout(() => {
1142
924
  callback({
1143
925
  didTimeout: false,
1144
-
1145
926
  timeRemaining() {
1146
927
  return Math.max(0, Date.now() - start);
1147
928
  }
1148
-
1149
929
  });
1150
930
  }, 0);
1151
931
  };
1152
-
1153
932
  const cancelIdleCallbackShim = function cancelIdleCallbackShim2(handle) {
1154
933
  return window.clearTimeout(handle);
1155
934
  };
1156
-
1157
935
  const win = typeof window === "undefined" ? void 0 : window;
1158
936
  const requestIdleCallback = (win == null ? void 0 : win.requestIdleCallback) || requestIdleCallbackShim;
1159
937
  const cancelIdleCallback = (win == null ? void 0 : win.cancelIdleCallback) || cancelIdleCallbackShim;
1160
938
  const memoizedWarnOnArraySlug = lodash.memoize(warnOnArraySlug);
1161
-
1162
939
  function getDocumentIds(id) {
1163
940
  const isDraft = id.indexOf("drafts.") === 0;
1164
941
  return {
@@ -1166,7 +943,6 @@ function getDocumentIds(id) {
1166
943
  draft: isDraft ? id : "drafts.".concat(id)
1167
944
  };
1168
945
  }
1169
-
1170
946
  function serializePath(path) {
1171
947
  return path.reduce((target, part, i) => {
1172
948
  const isIndex = typeof part === "number";
@@ -1176,7 +952,6 @@ function serializePath(path) {
1176
952
  return "".concat(target).concat(add);
1177
953
  }, "");
1178
954
  }
1179
-
1180
955
  const defaultIsUnique = (slug, context) => {
1181
956
  const {
1182
957
  getClient,
@@ -1185,15 +960,12 @@ const defaultIsUnique = (slug, context) => {
1185
960
  type
1186
961
  } = context;
1187
962
  const schemaOptions = type == null ? void 0 : type.options;
1188
-
1189
963
  if (!document) {
1190
964
  throw new Error("`document` was not provided in validation context.");
1191
965
  }
1192
-
1193
966
  if (!path) {
1194
967
  throw new Error("`path` was not provided in validation context.");
1195
968
  }
1196
-
1197
969
  const disableArrayWarning = (schemaOptions == null ? void 0 : schemaOptions.disableArrayWarning) || false;
1198
970
  const {
1199
971
  published,
@@ -1201,11 +973,9 @@ const defaultIsUnique = (slug, context) => {
1201
973
  } = getDocumentIds(document._id);
1202
974
  const docType = document._type;
1203
975
  const atPath = serializePath(path.concat("current"));
1204
-
1205
976
  if (!disableArrayWarning && atPath.includes("[]")) {
1206
977
  memoizedWarnOnArraySlug(serializePath(path));
1207
978
  }
1208
-
1209
979
  const constraints = ["_type == $docType", "!(_id in [$draft, $published])", "".concat(atPath, " == $slug")].join(" && ");
1210
980
  return getClient({
1211
981
  apiVersion: "2022-09-09"
@@ -1218,46 +988,34 @@ const defaultIsUnique = (slug, context) => {
1218
988
  tag: "validation.slug-is-unique"
1219
989
  });
1220
990
  };
1221
-
1222
991
  function warnOnArraySlug(serializedPath) {
1223
992
  console.warn(["Slug field at path ".concat(serializedPath, " is within an array and cannot be automatically checked for uniqueness"), "If you need to check for uniqueness, provide your own \"isUnique\" method", "To disable this message, set `disableArrayWarning: true` on the slug `options` field"].join("\n"));
1224
993
  }
1225
-
1226
994
  const slugValidator = async (value, context) => {
1227
995
  var _a;
1228
-
1229
996
  if (!value) {
1230
997
  return true;
1231
998
  }
1232
-
1233
999
  if (typeof value !== "object") {
1234
1000
  return "Slug must be an object";
1235
1001
  }
1236
-
1237
1002
  const slugValue = value.current;
1238
-
1239
1003
  if (!slugValue) {
1240
1004
  return "Slug must have a value";
1241
1005
  }
1242
-
1243
1006
  const options = (_a = context == null ? void 0 : context.type) == null ? void 0 : _a.options;
1244
1007
  const isUnique = (options == null ? void 0 : options.isUnique) || defaultIsUnique;
1245
-
1246
1008
  const slugContext = _objectSpread(_objectSpread({}, context), {}, {
1247
1009
  parent: context.parent,
1248
1010
  type: context.type,
1249
1011
  defaultIsUnique
1250
1012
  });
1251
-
1252
1013
  const wasUnique = await isUnique(slugValue, slugContext);
1253
-
1254
1014
  if (wasUnique) {
1255
1015
  return true;
1256
1016
  }
1257
-
1258
1017
  return "Slug is already in use";
1259
1018
  };
1260
-
1261
1019
  const ruleConstraintTypes = {
1262
1020
  array: true,
1263
1021
  boolean: true,
@@ -1266,9 +1024,7 @@ const ruleConstraintTypes = {
1266
1024
  object: true,
1267
1025
  string: true
1268
1026
  };
1269
-
1270
1027
  const isRuleConstraint = typeString => typeString in ruleConstraintTypes;
1271
-
1272
1028
  function getTypeChain(type, visited) {
1273
1029
  if (!type) return [];
1274
1030
  if (visited.has(type)) return [];
@@ -1276,20 +1032,15 @@ function getTypeChain(type, visited) {
1276
1032
  const next = type.type ? getTypeChain(type.type, visited) : [];
1277
1033
  return [...next, type];
1278
1034
  }
1279
-
1280
1035
  function baseRuleReducer(inputRule, type) {
1281
1036
  let baseRule = inputRule;
1282
-
1283
1037
  if (isRuleConstraint(type.jsonType)) {
1284
1038
  baseRule = baseRule.type(type.jsonType);
1285
1039
  }
1286
-
1287
1040
  const typeOptionsList = (type == null ? void 0 : type.options) && typeof type.options === "object" && "list" in type.options && type.options.list;
1288
-
1289
1041
  if (Array.isArray(typeOptionsList)) {
1290
1042
  baseRule = baseRule.valid(typeOptionsList.map(option => extractValueFromListOption(option, type)));
1291
1043
  }
1292
-
1293
1044
  if (type.name === "datetime") return baseRule.type("Date");
1294
1045
  if (type.name === "date") return baseRule.type("Date");
1295
1046
  if (type.name === "url") return baseRule.uri();
@@ -1298,7 +1049,6 @@ function baseRuleReducer(inputRule, type) {
1298
1049
  if (type.name === "email") return baseRule.email();
1299
1050
  return baseRule;
1300
1051
  }
1301
-
1302
1052
  function hasValueField(typeDef) {
1303
1053
  if (!typeDef) return false;
1304
1054
  if (!("fields" in typeDef) && typeDef.type) return hasValueField(typeDef.type);
@@ -1306,79 +1056,58 @@ function hasValueField(typeDef) {
1306
1056
  if (!Array.isArray(typeDef.fields)) return false;
1307
1057
  return typeDef.fields.some(field => field.name === "value");
1308
1058
  }
1309
-
1310
1059
  function extractValueFromListOption(option, typeDef) {
1311
1060
  if (typeDef.jsonType === "object" && hasValueField(typeDef)) return option;
1312
1061
  return option.value === void 0 ? option : option.value;
1313
1062
  }
1314
-
1315
1063
  function normalizeValidationRules(typeDef) {
1316
1064
  if (!typeDef) {
1317
1065
  return [];
1318
1066
  }
1319
-
1320
1067
  const validation = typeDef.validation;
1321
-
1322
1068
  if (Array.isArray(validation)) {
1323
1069
  return validation.flatMap(i => normalizeValidationRules(_objectSpread(_objectSpread({}, typeDef), {}, {
1324
1070
  validation: i
1325
1071
  })));
1326
1072
  }
1327
-
1328
1073
  if (validation instanceof Rule) {
1329
1074
  return [validation];
1330
1075
  }
1331
-
1332
1076
  const baseRule = Object.values(getTypeChain(typeDef, /* @__PURE__ */new Set()).reduce((acc, type) => {
1333
1077
  acc[type.name] = type;
1334
1078
  return acc;
1335
1079
  }, {})).reduce(baseRuleReducer, new Rule(typeDef));
1336
-
1337
1080
  if (!validation) {
1338
1081
  return [baseRule];
1339
1082
  }
1340
-
1341
1083
  return normalizeValidationRules(_objectSpread(_objectSpread({}, typeDef), {}, {
1342
1084
  validation: validation(baseRule)
1343
1085
  }));
1344
1086
  }
1345
-
1346
1087
  const isRecord = maybeRecord => typeof maybeRecord === "object" && maybeRecord !== null && !Array.isArray(maybeRecord);
1347
-
1348
1088
  const isNonNullable = value => value !== null && value !== void 0;
1349
-
1350
1089
  function resolveTypeForArrayItem(item, candidates) {
1351
1090
  if (candidates.length === 1) return candidates[0];
1352
-
1353
1091
  const itemType = types.isTypedObject(item) && item._type;
1354
-
1355
1092
  const primitive = item === void 0 || item === null || !itemType && typeString(item).toLowerCase();
1356
-
1357
1093
  if (primitive && primitive !== "object") {
1358
1094
  return candidates.find(candidate => candidate.jsonType === primitive);
1359
1095
  }
1360
-
1361
1096
  return candidates.find(candidate => {
1362
1097
  var _a;
1363
-
1364
1098
  return ((_a = candidate.type) == null ? void 0 : _a.name) === itemType;
1365
1099
  }) || candidates.find(candidate => candidate.name === itemType) || candidates.find(candidate => candidate.name === "object" && primitive === "object");
1366
1100
  }
1367
-
1368
1101
  const EMPTY_MARKERS = [];
1369
-
1370
1102
  async function validateDocument(getClient, doc, schema, context) {
1371
1103
  return validateDocumentObservable(getClient, doc, schema, context).toPromise();
1372
1104
  }
1373
-
1374
1105
  function validateDocumentObservable(getClient, doc, schema, context) {
1375
1106
  const documentType = schema.get(doc._type);
1376
-
1377
1107
  if (!documentType) {
1378
1108
  console.warn('Schema type for object type "%s" not found, skipping validation', doc._type);
1379
1109
  return rxjs.of(EMPTY_MARKERS);
1380
1110
  }
1381
-
1382
1111
  const client = getClient({
1383
1112
  apiVersion: "2021-06-07"
1384
1113
  });
@@ -1401,7 +1130,6 @@ function validateDocumentObservable(getClient, doc, schema, context) {
1401
1130
  console.warn('`configContext.client` is deprecated and will be removed in the next release! Use `context.getClient({apiVersion: "2021-06-07"})` instead');
1402
1131
  return original;
1403
1132
  }
1404
-
1405
1133
  });
1406
1134
  }, {});
1407
1135
  return validateItemObservable(validationOptions).pipe(operators.catchError(err => {
@@ -1414,16 +1142,14 @@ function validateDocumentObservable(getClient, doc, schema, context) {
1414
1142
  }]);
1415
1143
  }));
1416
1144
  }
1417
-
1418
1145
  function validateItemObservable(_ref) {
1419
1146
  let {
1420
- value,
1421
- type,
1422
- path = [],
1423
- parent
1424
- } = _ref,
1425
- restOfContext = _objectWithoutProperties(_ref, _excluded);
1426
-
1147
+ value,
1148
+ type,
1149
+ path = [],
1150
+ parent
1151
+ } = _ref,
1152
+ restOfContext = _objectWithoutProperties(_ref, _excluded);
1427
1153
  const rules = normalizeValidationRules(type);
1428
1154
  const selfChecks = rules.map(rule => rxjs.defer(() => rule.validate(value, _objectSpread(_objectSpread({}, restOfContext), {}, {
1429
1155
  parent,
@@ -1433,7 +1159,6 @@ function validateItemObservable(_ref) {
1433
1159
  let nestedChecks = [];
1434
1160
  const selfIsRequired = rules.some(rule => rule.isRequired());
1435
1161
  const shouldRunNestedObjectValidation = (type == null ? void 0 : type.jsonType) === "object" && (!!value || (value === null || value === void 0) && selfIsRequired);
1436
-
1437
1162
  if (shouldRunNestedObjectValidation) {
1438
1163
  const fieldTypes = type.fields.reduce((acc, field) => {
1439
1164
  acc[field.name] = field.type;
@@ -1460,22 +1185,18 @@ function validateItemObservable(_ref) {
1460
1185
  type: field.type
1461
1186
  }))));
1462
1187
  }
1463
-
1464
1188
  const shouldRunNestedValidationForArrays = (type == null ? void 0 : type.jsonType) === "array" && Array.isArray(value);
1465
-
1466
1189
  if (shouldRunNestedValidationForArrays) {
1467
- nestedChecks = nestedChecks.concat(value.map(item => validateItemObservable(_objectSpread(_objectSpread({}, restOfContext), {}, {
1190
+ nestedChecks = nestedChecks.concat(value.map((item, index) => validateItemObservable(_objectSpread(_objectSpread({}, restOfContext), {}, {
1468
1191
  parent: value,
1469
1192
  value: item,
1470
1193
  path: path.concat(types.isKeyedObject(item) ? {
1471
1194
  _key: item._key
1472
- } : value.indexOf(item)),
1195
+ } : index),
1473
1196
  type: resolveTypeForArrayItem(item, type.of)
1474
1197
  }))));
1475
1198
  }
1476
-
1477
1199
  const shouldRunNestedValidationForMarkDefs = types.isBlock(value) && value.markDefs.length && types.isBlockSchemaType(type);
1478
-
1479
1200
  if (shouldRunNestedValidationForMarkDefs) {
1480
1201
  const [spanChildrenField] = type.fields;
1481
1202
  const spanType = spanChildrenField.type.of.find(types.isSpanSchemaType);
@@ -1492,16 +1213,13 @@ function validateItemObservable(_ref) {
1492
1213
  type: annotations.get(markDef._type)
1493
1214
  }))));
1494
1215
  }
1495
-
1496
1216
  return rxjs.defer(() => rxjs.merge([...selfChecks, ...nestedChecks])).pipe(operators.mergeMap(validateNode => rxjs.concat(idle(), validateNode), 40), operators.mergeAll(), operators.toArray(), operators.map(lodash.flatten), operators.map(results => {
1497
1217
  if (rules.some(rule => rule._fieldRules)) {
1498
1218
  return lodash.uniqBy(results, rule => JSON.stringify(rule));
1499
1219
  }
1500
-
1501
1220
  return results;
1502
1221
  }));
1503
1222
  }
1504
-
1505
1223
  function idle(timeout) {
1506
1224
  return new rxjs.Observable(observer => {
1507
1225
  const handle = requestIdleCallback(() => {
@@ -1512,51 +1230,42 @@ function idle(timeout) {
1512
1230
  return () => cancelIdleCallback(handle);
1513
1231
  });
1514
1232
  }
1515
-
1516
1233
  function traverse(typeDef, visited) {
1517
1234
  if (visited.has(typeDef)) {
1518
1235
  return;
1519
1236
  }
1520
-
1521
1237
  visited.add(typeDef);
1522
1238
  typeDef.validation = normalizeValidationRules(typeDef);
1523
-
1524
1239
  if ("fields" in typeDef) {
1525
1240
  for (const field of typeDef.fields) {
1526
1241
  traverse(field.type, visited);
1527
1242
  }
1528
1243
  }
1529
-
1530
1244
  if ("of" in typeDef) {
1531
1245
  for (const candidate of typeDef.of) {
1532
1246
  traverse(candidate, visited);
1533
1247
  }
1534
1248
  }
1535
-
1536
1249
  if (typeDef.annotations) {
1537
1250
  for (const annotation of typeDef.annotations) {
1538
1251
  traverse(annotation, visited);
1539
1252
  }
1540
1253
  }
1541
1254
  }
1542
-
1543
1255
  function inferFromSchemaType(typeDef) {
1544
1256
  traverse(typeDef, /* @__PURE__ */new Set());
1545
1257
  return typeDef;
1546
1258
  }
1547
-
1548
1259
  function inferFromSchema(schema) {
1549
1260
  const typeNames = schema.getTypeNames();
1550
1261
  typeNames.forEach(typeName => {
1551
1262
  const schemaType = schema.get(typeName);
1552
-
1553
1263
  if (schemaType) {
1554
1264
  inferFromSchemaType(schemaType);
1555
1265
  }
1556
1266
  });
1557
1267
  return schema;
1558
1268
  }
1559
-
1560
1269
  exports.Rule = Rule;
1561
1270
  exports.inferFromSchema = inferFromSchema;
1562
1271
  exports.inferFromSchemaType = inferFromSchemaType;