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

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.
Files changed (142) hide show
  1. package/lib/dts/src/index.d.ts +36 -13
  2. package/lib/index.js +1525 -1291
  3. package/lib/index.js.map +1 -1
  4. package/lib/index.mjs +1542 -0
  5. package/lib/index.mjs.map +1 -0
  6. package/package.json +24 -18
  7. package/src/index.ts +3 -1
  8. package/src/util/requestIdleCallback.ts +31 -0
  9. package/src/validateDocument.test.ts +0 -80
  10. package/src/validateDocument.ts +82 -43
  11. package/src/validators/slugValidator.ts +16 -2
  12. package/lib/dts/src/Rule.d.ts +0 -4
  13. package/lib/dts/src/Rule.d.ts.map +0 -1
  14. package/lib/dts/src/Rule.js +0 -336
  15. package/lib/dts/src/Rule.js.map +0 -1
  16. package/lib/dts/src/ValidationError.d.ts +0 -4
  17. package/lib/dts/src/ValidationError.d.ts.map +0 -1
  18. package/lib/dts/src/ValidationError.js +0 -18
  19. package/lib/dts/src/ValidationError.js.map +0 -1
  20. package/lib/dts/src/index.d.ts.map +0 -1
  21. package/lib/dts/src/index.js +0 -7
  22. package/lib/dts/src/index.js.map +0 -1
  23. package/lib/dts/src/inferFromSchema.d.ts +0 -4
  24. package/lib/dts/src/inferFromSchema.d.ts.map +0 -1
  25. package/lib/dts/src/inferFromSchema.js +0 -14
  26. package/lib/dts/src/inferFromSchema.js.map +0 -1
  27. package/lib/dts/src/inferFromSchemaType.d.ts +0 -5
  28. package/lib/dts/src/inferFromSchemaType.d.ts.map +0 -1
  29. package/lib/dts/src/inferFromSchemaType.js +0 -33
  30. package/lib/dts/src/inferFromSchemaType.js.map +0 -1
  31. package/lib/dts/src/util/convertToValidationMarker.d.ts +0 -6
  32. package/lib/dts/src/util/convertToValidationMarker.d.ts.map +0 -1
  33. package/lib/dts/src/util/convertToValidationMarker.js +0 -51
  34. package/lib/dts/src/util/convertToValidationMarker.js.map +0 -1
  35. package/lib/dts/src/util/deepEquals.d.ts +0 -6
  36. package/lib/dts/src/util/deepEquals.d.ts.map +0 -1
  37. package/lib/dts/src/util/deepEquals.js +0 -65
  38. package/lib/dts/src/util/deepEquals.js.map +0 -1
  39. package/lib/dts/src/util/escapeRegex.d.ts +0 -3
  40. package/lib/dts/src/util/escapeRegex.d.ts.map +0 -1
  41. package/lib/dts/src/util/escapeRegex.js +0 -6
  42. package/lib/dts/src/util/escapeRegex.js.map +0 -1
  43. package/lib/dts/src/util/normalizeValidationRules.d.ts +0 -6
  44. package/lib/dts/src/util/normalizeValidationRules.d.ts.map +0 -1
  45. package/lib/dts/src/util/normalizeValidationRules.js +0 -104
  46. package/lib/dts/src/util/normalizeValidationRules.js.map +0 -1
  47. package/lib/dts/src/util/normalizeValidationRules.test.d.ts +0 -2
  48. package/lib/dts/src/util/normalizeValidationRules.test.d.ts.map +0 -1
  49. package/lib/dts/src/util/normalizeValidationRules.test.js +0 -150
  50. package/lib/dts/src/util/normalizeValidationRules.test.js.map +0 -1
  51. package/lib/dts/src/util/pathToString.d.ts +0 -3
  52. package/lib/dts/src/util/pathToString.d.ts.map +0 -1
  53. package/lib/dts/src/util/pathToString.js +0 -18
  54. package/lib/dts/src/util/pathToString.js.map +0 -1
  55. package/lib/dts/src/util/typeString.d.ts +0 -2
  56. package/lib/dts/src/util/typeString.d.ts.map +0 -1
  57. package/lib/dts/src/util/typeString.js +0 -23
  58. package/lib/dts/src/util/typeString.js.map +0 -1
  59. package/lib/dts/src/util/typeString.test.d.ts +0 -2
  60. package/lib/dts/src/util/typeString.test.d.ts.map +0 -1
  61. package/lib/dts/src/util/typeString.test.js +0 -24
  62. package/lib/dts/src/util/typeString.test.js.map +0 -1
  63. package/lib/dts/src/validateDocument.d.ts +0 -25
  64. package/lib/dts/src/validateDocument.d.ts.map +0 -1
  65. package/lib/dts/src/validateDocument.js +0 -165
  66. package/lib/dts/src/validateDocument.js.map +0 -1
  67. package/lib/dts/src/validateDocument.test.d.ts +0 -2
  68. package/lib/dts/src/validateDocument.test.d.ts.map +0 -1
  69. package/lib/dts/src/validateDocument.test.js +0 -717
  70. package/lib/dts/src/validateDocument.test.js.map +0 -1
  71. package/lib/dts/src/validators/arrayValidator.d.ts +0 -4
  72. package/lib/dts/src/validators/arrayValidator.d.ts.map +0 -1
  73. package/lib/dts/src/validators/arrayValidator.js +0 -79
  74. package/lib/dts/src/validators/arrayValidator.js.map +0 -1
  75. package/lib/dts/src/validators/booleanValidator.d.ts +0 -4
  76. package/lib/dts/src/validators/booleanValidator.d.ts.map +0 -1
  77. package/lib/dts/src/validators/booleanValidator.js +0 -12
  78. package/lib/dts/src/validators/booleanValidator.js.map +0 -1
  79. package/lib/dts/src/validators/dateValidator.d.ts +0 -5
  80. package/lib/dts/src/validators/dateValidator.d.ts.map +0 -1
  81. package/lib/dts/src/validators/dateValidator.js +0 -83
  82. package/lib/dts/src/validators/dateValidator.js.map +0 -1
  83. package/lib/dts/src/validators/genericValidator.d.ts +0 -4
  84. package/lib/dts/src/validators/genericValidator.d.ts.map +0 -1
  85. package/lib/dts/src/validators/genericValidator.js +0 -93
  86. package/lib/dts/src/validators/genericValidator.js.map +0 -1
  87. package/lib/dts/src/validators/numberValidator.d.ts +0 -4
  88. package/lib/dts/src/validators/numberValidator.d.ts.map +0 -1
  89. package/lib/dts/src/validators/numberValidator.js +0 -47
  90. package/lib/dts/src/validators/numberValidator.js.map +0 -1
  91. package/lib/dts/src/validators/objectValidator.d.ts +0 -4
  92. package/lib/dts/src/validators/objectValidator.d.ts.map +0 -1
  93. package/lib/dts/src/validators/objectValidator.js +0 -48
  94. package/lib/dts/src/validators/objectValidator.js.map +0 -1
  95. package/lib/dts/src/validators/slugValidator.d.ts +0 -9
  96. package/lib/dts/src/validators/slugValidator.d.ts.map +0 -1
  97. package/lib/dts/src/validators/slugValidator.js +0 -83
  98. package/lib/dts/src/validators/slugValidator.js.map +0 -1
  99. package/lib/dts/src/validators/stringValidator.d.ts +0 -4
  100. package/lib/dts/src/validators/stringValidator.d.ts.map +0 -1
  101. package/lib/dts/src/validators/stringValidator.js +0 -94
  102. package/lib/dts/src/validators/stringValidator.js.map +0 -1
  103. package/lib/dts/test/array.test.d.ts +0 -2
  104. package/lib/dts/test/array.test.d.ts.map +0 -1
  105. package/lib/dts/test/array.test.js +0 -55
  106. package/lib/dts/test/array.test.js.map +0 -1
  107. package/lib/dts/test/children.test.d.ts +0 -2
  108. package/lib/dts/test/children.test.d.ts.map +0 -1
  109. package/lib/dts/test/children.test.js +0 -70
  110. package/lib/dts/test/children.test.js.map +0 -1
  111. package/lib/dts/test/createSchema.d.ts +0 -6
  112. package/lib/dts/test/createSchema.d.ts.map +0 -1
  113. package/lib/dts/test/createSchema.js +0 -19
  114. package/lib/dts/test/createSchema.js.map +0 -1
  115. package/lib/dts/test/generics.test.d.ts +0 -2
  116. package/lib/dts/test/generics.test.d.ts.map +0 -1
  117. package/lib/dts/test/generics.test.js +0 -60
  118. package/lib/dts/test/generics.test.js.map +0 -1
  119. package/lib/dts/test/infer.test.d.ts +0 -2
  120. package/lib/dts/test/infer.test.d.ts.map +0 -1
  121. package/lib/dts/test/infer.test.js +0 -244
  122. package/lib/dts/test/infer.test.js.map +0 -1
  123. package/lib/dts/test/mocks/mockSanityClient.d.ts +0 -6
  124. package/lib/dts/test/mocks/mockSanityClient.d.ts.map +0 -1
  125. package/lib/dts/test/mocks/mockSanityClient.js +0 -8
  126. package/lib/dts/test/mocks/mockSanityClient.js.map +0 -1
  127. package/lib/dts/test/nullExport.d.ts +0 -3
  128. package/lib/dts/test/nullExport.d.ts.map +0 -1
  129. package/lib/dts/test/nullExport.js +0 -4
  130. package/lib/dts/test/nullExport.js.map +0 -1
  131. package/lib/dts/test/numbers.test.d.ts +0 -2
  132. package/lib/dts/test/numbers.test.d.ts.map +0 -1
  133. package/lib/dts/test/numbers.test.js +0 -57
  134. package/lib/dts/test/numbers.test.js.map +0 -1
  135. package/lib/dts/test/strings.test.d.ts +0 -2
  136. package/lib/dts/test/strings.test.d.ts.map +0 -1
  137. package/lib/dts/test/strings.test.js +0 -100
  138. package/lib/dts/test/strings.test.js.map +0 -1
  139. package/lib/dts/tsconfig.lib.tsbuildinfo +0 -1
  140. package/lib/dts/tsconfig.tsbuildinfo +0 -1
  141. package/lib/index.cjs +0 -1341
  142. package/lib/index.cjs.map +0 -1
package/lib/index.cjs DELETED
@@ -1,1341 +0,0 @@
1
- 'use strict';
2
-
3
- var lodash = require('lodash');
4
- var types = require('@sanity/types');
5
- var formatDate = require('date-fns/format');
6
-
7
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
8
-
9
- var formatDate__default = /*#__PURE__*/_interopDefaultLegacy(formatDate);
10
-
11
- // Follows the same pattern as Rule and RuleClass. @see Rule
12
- const ValidationError = class ValidationError {
13
- message;
14
- paths;
15
- children;
16
- operation;
17
- constructor(message, options = {}) {
18
- this.message = message;
19
- this.paths = options.paths || [];
20
- this.children = options.children;
21
- this.operation = options.operation;
22
- }
23
- cloneWithMessage(msg) {
24
- return new ValidationError(msg, {
25
- paths: this.paths,
26
- children: this.children,
27
- operation: this.operation,
28
- });
29
- }
30
- };
31
-
32
- /* eslint-disable no-useless-escape */
33
- var escapeRegex = (string) => {
34
- // Escape ^$.*+-?=!:|\/()[]{},
35
- return string.replace(/[\^\$\.\*\+\-\?\=\!\:\|\\\/\(\)\[\]\{\}\,]/g, '\\$&');
36
- };
37
-
38
- function pathToString(path = []) {
39
- return path.reduce((target, segment, i) => {
40
- const segmentType = typeof segment;
41
- if (segmentType === 'number') {
42
- return `${target}[${segment}]`;
43
- }
44
- if (segmentType === 'string') {
45
- const separator = i === 0 ? '' : '.';
46
- return `${target}${separator}${segment}`;
47
- }
48
- if (types.isKeyedObject(segment)) {
49
- return `${target}[_key=="${segment._key}"]`;
50
- }
51
- throw new Error(`Unsupported path segment "${segment}"`);
52
- }, '');
53
- }
54
-
55
- function isNonNullable$1(t) {
56
- return t !== null || t !== undefined;
57
- }
58
- function convertToValidationMarker(validatorResult, level, context) {
59
- if (!context) {
60
- throw new Error('missing context');
61
- }
62
- if (validatorResult === true)
63
- return [];
64
- if (Array.isArray(validatorResult)) {
65
- return validatorResult
66
- .flatMap((child) => convertToValidationMarker(child, level, context))
67
- .filter(isNonNullable$1);
68
- }
69
- if (typeof validatorResult === 'string') {
70
- return convertToValidationMarker(new ValidationError(validatorResult), level, context);
71
- }
72
- if (!(validatorResult instanceof ValidationError)) {
73
- // in order to accept the `ValidationErrorLike`, it at least needs to have
74
- // a `message` in the object
75
- if (typeof validatorResult?.message !== 'string') {
76
- throw new Error(`${pathToString(context.path)}: Validator must return 'true' if valid or an error message as a string on errors`);
77
- }
78
- // this is the occurs when an object is returned that wasn't created with the
79
- // `ValidationErrorClass`. in this case, we want to convert it to a class
80
- return convertToValidationMarker(new ValidationError(validatorResult.message, validatorResult), level, context);
81
- }
82
- const results = [];
83
- // the validator result does not include any item-level relative paths,
84
- // then just return the top-level path with the validation result
85
- if (!validatorResult.paths?.length) {
86
- return [
87
- {
88
- level: level || 'error',
89
- item: validatorResult,
90
- path: context.path || [],
91
- },
92
- ];
93
- }
94
- // if the validator result did include item-level relative paths, then for
95
- // each item-level relative path, create a validation marker that concatenates
96
- // the relative path with the path from the validation context
97
- return results.concat(validatorResult.paths.map((path) => ({
98
- path: (context.path || []).concat(path),
99
- level: level || 'error',
100
- item: validatorResult,
101
- })));
102
- }
103
-
104
- // this file was adapted from a previous dependency `type-of-is`
105
- // https://github.com/stephenhandley/type-of-is/blob/7138a7e79f5af7c286bf8123f60843a91aaebf38/index.js
106
- const _toString = {}.toString;
107
- const builtIns = [Object, Function, Array, String, Boolean, Number, Date, RegExp, Error];
108
- function isBuiltIn(_constructor) {
109
- for (let i = 0; i < builtIns.length; i++) {
110
- if (builtIns[i] === _constructor)
111
- return true;
112
- }
113
- return false;
114
- }
115
- function typeString(obj) {
116
- // [object Blah] -> Blah
117
- const stringType = _toString.call(obj).slice(8, -1);
118
- if (obj === null || obj === undefined)
119
- return stringType.toLowerCase();
120
- // eslint-disable-next-line @typescript-eslint/ban-types
121
- const constructorType = obj.constructor;
122
- if (constructorType && !isBuiltIn(constructorType))
123
- return constructorType.name;
124
- return stringType;
125
- }
126
-
127
- /**
128
- * Modified version of fast-deep-equal (https://github.com/epoberezkin/fast-deep-equal)
129
- * MIT-licensed, copyright (c) 2017 Evgeny Poberezkin
130
- **/
131
- // NOTE: when converting to typescript, some of the checks were inlined (vs
132
- // having them in a variable) because the type predicate type narrowing only
133
- // works when type predicate is called inline in the condition that starts the
134
- // control flow branch.
135
- // see here: https://www.typescriptlang.org/docs/handbook/2/narrowing.html
136
- function deepEquals(a, b) {
137
- if (a === b) {
138
- return true;
139
- }
140
- if (Array.isArray(a) && Array.isArray(b)) {
141
- if (a.length != b.length)
142
- return false;
143
- for (let i = 0; i < a.length; i++) {
144
- if (!deepEquals(a[i], b[i])) {
145
- return false;
146
- }
147
- }
148
- return true;
149
- }
150
- if (Array.isArray(a) != Array.isArray(b)) {
151
- return false;
152
- }
153
- if (a && b && typeof a === 'object' && typeof b === 'object') {
154
- const keys = Object.keys(a);
155
- if (keys.length !== Object.keys(b).length) {
156
- return false;
157
- }
158
- if (a instanceof Date && b instanceof Date) {
159
- return a.getTime() === b.getTime();
160
- }
161
- if (a instanceof Date != b instanceof Date) {
162
- return false;
163
- }
164
- if (a instanceof RegExp && b instanceof RegExp) {
165
- return a.toString() == b.toString();
166
- }
167
- if (a instanceof RegExp != b instanceof RegExp) {
168
- return false;
169
- }
170
- for (let i = 0; i < keys.length; i++) {
171
- if (keys[i] === '_key') {
172
- continue;
173
- }
174
- if (!Object.prototype.hasOwnProperty.call(b, keys[i])) {
175
- return false;
176
- }
177
- }
178
- for (let i = 0; i < keys.length; i++) {
179
- const key = keys[i];
180
- if (key === '_key') {
181
- continue;
182
- }
183
- if (!deepEquals(a[key], b[key])) {
184
- return false;
185
- }
186
- }
187
- return true;
188
- }
189
- return false;
190
- }
191
-
192
- const SLOW_VALIDATOR_TIMEOUT = 5000;
193
- const formatValidationErrors = (options) => {
194
- let message;
195
- if (options.message) {
196
- message = options.message;
197
- }
198
- else if (options.results.length === 1) {
199
- message = options.results[0]?.item.message;
200
- }
201
- else {
202
- message = `[${options.results
203
- .map((err) => err.item.message)
204
- .join(` - ${options.operation} - `)}]`;
205
- }
206
- return new ValidationError(message, {
207
- children: options.results.length > 1 ? options.results : undefined,
208
- operation: options.operation,
209
- });
210
- };
211
- const genericValidators = {
212
- type: (expected, value, message) => {
213
- const actualType = typeString(value);
214
- if (actualType !== expected && actualType !== 'undefined') {
215
- return message || `Expected type "${expected}", got "${actualType}"`;
216
- }
217
- return true;
218
- },
219
- presence: (expected, value, message) => {
220
- if (value === undefined && expected === 'required') {
221
- return message || 'Value is required';
222
- }
223
- return true;
224
- },
225
- all: async (children, value, message, context) => {
226
- const resolved = await Promise.all(children.map((child) => child.validate(value, context)));
227
- const results = resolved.flat();
228
- if (!results.length)
229
- return true;
230
- return formatValidationErrors({
231
- message,
232
- results,
233
- operation: 'AND',
234
- });
235
- },
236
- either: async (children, value, message, context) => {
237
- const resolved = await Promise.all(children.map((child) => child.validate(value, context)));
238
- const results = resolved.flat();
239
- // Read: There is at least one rule that matched
240
- if (results.length < children.length)
241
- return true;
242
- return formatValidationErrors({
243
- message,
244
- results,
245
- operation: 'OR',
246
- });
247
- },
248
- valid: (allowedValues, actual, message) => {
249
- const valueType = typeof actual;
250
- if (valueType === 'undefined') {
251
- return true;
252
- }
253
- const value = (valueType === 'number' || valueType === 'string') && `${actual}`;
254
- const strValue = value && value.length > 30 ? `${value.slice(0, 30)}…` : value;
255
- const defaultMessage = value
256
- ? `Value "${strValue}" did not match any allowed values`
257
- : 'Value did not match any allowed values';
258
- return allowedValues.some((expected) => deepEquals(expected, actual))
259
- ? true
260
- : message || defaultMessage;
261
- },
262
- custom: async (fn, value, message, context) => {
263
- const slowTimer = setTimeout(() => {
264
- // eslint-disable-next-line no-console
265
- console.warn(`Custom validator at ${pathToString(context.path)} has taken more than ${SLOW_VALIDATOR_TIMEOUT}ms to respond`);
266
- }, SLOW_VALIDATOR_TIMEOUT);
267
- let result;
268
- try {
269
- result = await fn(value, context);
270
- }
271
- finally {
272
- clearTimeout(slowTimer);
273
- }
274
- if (typeof result === 'string')
275
- return message || result;
276
- return result;
277
- },
278
- };
279
-
280
- const booleanValidators = {
281
- ...genericValidators,
282
- presence: (flag, value, message) => {
283
- if (flag === 'required' && typeof value !== 'boolean') {
284
- return message || 'Required';
285
- }
286
- return true;
287
- },
288
- };
289
-
290
- const precisionRx = /(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/;
291
- const numberValidators = {
292
- ...genericValidators,
293
- integer: (_unused, value, message) => {
294
- if (!Number.isInteger(value)) {
295
- return message || 'Must be an integer';
296
- }
297
- return true;
298
- },
299
- precision: (limit, value, message) => {
300
- if (value === undefined)
301
- return true;
302
- const places = value.toString().match(precisionRx);
303
- const decimals = Math.max((places[1] ? places[1].length : 0) - (places[2] ? parseInt(places[2], 10) : 0), 0);
304
- if (decimals > limit) {
305
- return message || `Max precision is ${limit}`;
306
- }
307
- return true;
308
- },
309
- min: (minNum, value, message) => {
310
- if (value >= minNum) {
311
- return true;
312
- }
313
- return message || `Must be greater than or equal ${minNum}`;
314
- },
315
- max: (maxNum, value, message) => {
316
- if (value <= maxNum) {
317
- return true;
318
- }
319
- return message || `Must be less than or equal ${maxNum}`;
320
- },
321
- greaterThan: (num, value, message) => {
322
- if (value > num) {
323
- return true;
324
- }
325
- return message || `Must be greater than ${num}`;
326
- },
327
- lessThan: (maxNum, value, message) => {
328
- if (value < maxNum) {
329
- return true;
330
- }
331
- return message || `Must be less than ${maxNum}`;
332
- },
333
- };
334
-
335
- const DUMMY_ORIGIN = 'http://sanity';
336
- 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,}))$/;
337
- const isRelativeUrl = (url) => /^\.*\//.test(url);
338
- const stringValidators = {
339
- ...genericValidators,
340
- min: (minLength, value, message) => {
341
- if (!value || value.length >= minLength) {
342
- return true;
343
- }
344
- return message || `Must be at least ${minLength} characters long`;
345
- },
346
- max: (maxLength, value, message) => {
347
- if (!value || value.length <= maxLength) {
348
- return true;
349
- }
350
- return message || `Must be at most ${maxLength} characters long`;
351
- },
352
- length: (wantedLength, value, message) => {
353
- const strValue = value || '';
354
- if (strValue.length === wantedLength) {
355
- return true;
356
- }
357
- return message || `Must be exactly ${wantedLength} characters long`;
358
- },
359
- uri: (constraints, value, message) => {
360
- const strValue = value || '';
361
- const { options } = constraints;
362
- const { allowCredentials, relativeOnly } = options;
363
- const allowRelative = options.allowRelative || relativeOnly;
364
- let url;
365
- try {
366
- // WARNING: Safari checks for a given `base` param by looking at the length of arguments passed
367
- // to new URL(str, base), and will fail if invoked with new URL(strValue, undefined)
368
- url = allowRelative ? new URL(strValue, DUMMY_ORIGIN) : new URL(strValue);
369
- }
370
- catch (err) {
371
- return message || 'Not a valid URL';
372
- }
373
- if (relativeOnly && url.origin !== DUMMY_ORIGIN) {
374
- return message || 'Only relative URLs are allowed';
375
- }
376
- if (!allowRelative && url.origin === DUMMY_ORIGIN && isRelativeUrl(strValue)) {
377
- return message || 'Relative URLs are not allowed';
378
- }
379
- if (!allowCredentials && (url.username || url.password)) {
380
- return message || `Username/password not allowed`;
381
- }
382
- const urlScheme = url.protocol.replace(/:$/, '');
383
- const matchesAllowedScheme = options.scheme.some((scheme) => scheme.test(urlScheme));
384
- if (!matchesAllowedScheme) {
385
- return message || 'Does not match allowed protocols/schemes';
386
- }
387
- return true;
388
- },
389
- stringCasing: (casing, value, message) => {
390
- const strValue = value || '';
391
- if (casing === 'uppercase' && strValue !== strValue.toLocaleUpperCase()) {
392
- return message || `Must be all uppercase letters`;
393
- }
394
- if (casing === 'lowercase' && strValue !== strValue.toLocaleLowerCase()) {
395
- return message || `Must be all lowercase letters`;
396
- }
397
- return true;
398
- },
399
- presence: (flag, value, message) => {
400
- if (flag === 'required' && !value) {
401
- return message || 'Required';
402
- }
403
- return true;
404
- },
405
- regex: (options, value, message) => {
406
- const { pattern, name, invert } = options;
407
- const regName = name || `"${pattern.toString()}"`;
408
- const strValue = value || '';
409
- const matches = pattern.test(strValue);
410
- if ((!invert && !matches) || (invert && matches)) {
411
- const defaultMessage = invert
412
- ? `Should not match ${regName}-pattern`
413
- : `Does not match ${regName}-pattern`;
414
- return message || defaultMessage;
415
- }
416
- return true;
417
- },
418
- email: (_unused, value, message) => {
419
- const strValue = `${value || ''}`.trim();
420
- if (!strValue || emailRegex.test(strValue)) {
421
- return true;
422
- }
423
- return message || 'Must be a valid email address';
424
- },
425
- };
426
-
427
- const arrayValidators = {
428
- ...genericValidators,
429
- min: (minLength, value, message) => {
430
- if (!value || value.length >= minLength) {
431
- return true;
432
- }
433
- return message || `Must have at least ${minLength} items`;
434
- },
435
- max: (maxLength, value, message) => {
436
- if (!value || value.length <= maxLength) {
437
- return true;
438
- }
439
- return message || `Must have at most ${maxLength} items`;
440
- },
441
- length: (wantedLength, value, message) => {
442
- if (!value || value.length === wantedLength) {
443
- return true;
444
- }
445
- return message || `Must have exactly ${wantedLength} items`;
446
- },
447
- presence: (flag, value, message) => {
448
- if (flag === 'required' && !value) {
449
- return message || 'Required';
450
- }
451
- return true;
452
- },
453
- valid: (allowedValues, values, message) => {
454
- const valueType = typeof values;
455
- if (valueType === 'undefined') {
456
- return true;
457
- }
458
- const paths = [];
459
- for (let i = 0; i < values.length; i++) {
460
- const value = values[i];
461
- if (allowedValues.some((expected) => deepEquals(expected, value))) {
462
- continue;
463
- }
464
- const pathSegment = value && value._key ? { _key: value._key } : i;
465
- paths.push([pathSegment]);
466
- }
467
- return paths.length === 0
468
- ? true
469
- : new ValidationError(message || 'Value did not match any allowed values', { paths });
470
- },
471
- unique: (_unused, value, message) => {
472
- const dupeIndices = [];
473
- if (!value) {
474
- return true;
475
- }
476
- for (let x = 0; x < value.length; x++) {
477
- for (let y = x + 1; y < value.length; y++) {
478
- const itemA = value[x];
479
- const itemB = value[y];
480
- if (!deepEquals(itemA, itemB)) {
481
- continue;
482
- }
483
- if (dupeIndices.indexOf(x) === -1) {
484
- dupeIndices.push(x);
485
- }
486
- if (dupeIndices.indexOf(y) === -1) {
487
- dupeIndices.push(y);
488
- }
489
- }
490
- }
491
- const paths = dupeIndices.map((idx) => {
492
- const item = value[idx];
493
- const pathSegment = item && item._key ? { _key: item._key } : idx;
494
- return [pathSegment];
495
- });
496
- return dupeIndices.length > 0
497
- ? new ValidationError(message || `Can't be a duplicate`, { paths })
498
- : true;
499
- },
500
- };
501
-
502
- const metaKeys = ['_key', '_type', '_weak'];
503
- const objectValidators = {
504
- ...genericValidators,
505
- presence: (expected, value, message) => {
506
- if (expected !== 'required') {
507
- return true;
508
- }
509
- const keys = value && Object.keys(value).filter((key) => !metaKeys.includes(key));
510
- if (value === undefined || (keys && keys.length === 0)) {
511
- return message || 'Required';
512
- }
513
- return true;
514
- },
515
- reference: async (_unused, value, message, context) => {
516
- if (!value) {
517
- return true;
518
- }
519
- if (!types.isReference(value)) {
520
- return message || true;
521
- }
522
- const { type, getDocumentExists } = context;
523
- if (!type) {
524
- throw new Error(`\`type\` was not provided in validation context`);
525
- }
526
- if ('weak' in type && type.weak) {
527
- return true;
528
- }
529
- if (!getDocumentExists) {
530
- throw new Error(`\`getDocumentExists\` was not provided in validation context`);
531
- }
532
- const exists = await getDocumentExists({ id: value._ref });
533
- if (!exists) {
534
- return 'This reference must be published';
535
- }
536
- return true;
537
- },
538
- assetRequired: (flag, value, message) => {
539
- if (!value || !value.asset || !value.asset._ref) {
540
- const assetType = flag.assetType || 'Asset';
541
- return message || `${assetType} required`;
542
- }
543
- return true;
544
- },
545
- };
546
-
547
- function isRecord$1(obj) {
548
- return typeof obj === 'object' && obj !== null && !Array.isArray(obj);
549
- }
550
- 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)?)?)?)?$/;
551
- const getFormattedDate = (type = '', value, options) => {
552
- let format = 'yyyy-MM-dd';
553
- if (options && options.dateFormat) {
554
- format = options.dateFormat;
555
- }
556
- if (type === 'date') {
557
- // If the type is date only
558
- return formatDate__default["default"](new Date(value), format);
559
- }
560
- // If the type is datetime
561
- if (options && options.timeFormat) {
562
- format += ` ${options.timeFormat}`;
563
- }
564
- else {
565
- format += ' HH:mm';
566
- }
567
- return formatDate__default["default"](new Date(value), format);
568
- };
569
- function parseDate(date, throwOnError = false) {
570
- if (!date)
571
- return null;
572
- if (date === 'now')
573
- return new Date();
574
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
575
- const parsed = new Date(date);
576
- const isInvalid = isNaN(parsed.getTime());
577
- if (isInvalid && throwOnError) {
578
- throw new Error(`Unable to parse "${date}" to a date`);
579
- }
580
- return isInvalid ? null : parsed;
581
- }
582
- const dateValidators = {
583
- ...genericValidators,
584
- type: (_unused, value, message) => {
585
- const strVal = `${value}`;
586
- if (!strVal || isoDate.test(value)) {
587
- return true;
588
- }
589
- return message || 'Must be a valid ISO-8601 formatted date string';
590
- },
591
- min: (minDate, value, message, context) => {
592
- const dateVal = parseDate(value);
593
- if (!dateVal) {
594
- return true; // `type()` should catch parse errors
595
- }
596
- if (!value || dateVal >= parseDate(minDate, true)) {
597
- return true;
598
- }
599
- if (!context.type) {
600
- throw new Error(`\`type\` was not provided in validation context.`);
601
- }
602
- const dateTimeOptions = isRecord$1(context.type.options)
603
- ? context.type.options
604
- : {};
605
- const date = getFormattedDate(context.type.name, minDate, dateTimeOptions);
606
- return message || `Must be at or after ${date}`;
607
- },
608
- max: (maxDate, value, message, context) => {
609
- const dateVal = parseDate(value);
610
- if (!dateVal) {
611
- return true; // `type()` should catch parse errors
612
- }
613
- if (!value || dateVal <= parseDate(maxDate, true)) {
614
- return true;
615
- }
616
- if (!context.type) {
617
- throw new Error(`\`type\` was not provided in validation context.`);
618
- }
619
- const dateTimeOptions = isRecord$1(context.type.options)
620
- ? context.type.options
621
- : {};
622
- const date = getFormattedDate(context.type.name, maxDate, dateTimeOptions);
623
- return message || `Must be at or before ${date}`;
624
- },
625
- };
626
-
627
- const typeValidators = {
628
- Boolean: booleanValidators,
629
- Number: numberValidators,
630
- String: stringValidators,
631
- Array: arrayValidators,
632
- Object: objectValidators,
633
- Date: dateValidators,
634
- };
635
- const getBaseType = (type) => {
636
- return type && type.type ? getBaseType(type.type) : type;
637
- };
638
- const isFieldRef = (constraint) => {
639
- if (typeof constraint !== 'object' || !constraint)
640
- return false;
641
- return constraint.type === Rule.FIELD_REF;
642
- };
643
- const EMPTY_ARRAY = [];
644
- const FIELD_REF = Symbol('FIELD_REF');
645
- const ruleConstraintTypes$1 = [
646
- 'Array',
647
- 'Boolean',
648
- 'Date',
649
- 'Number',
650
- 'Object',
651
- 'String',
652
- ];
653
- // Note: `RuleClass` and `Rule` are split to fit the current `@sanity/types`
654
- // setup. Classes are a bit weird in the `@sanity/types` package because classes
655
- // create an actual javascript class while simultaneously creating a type
656
- // definition.
657
- //
658
- // This implicitly creates two types:
659
- // 1. the instance type — `Rule` and
660
- // 2. the static/class type - `RuleClass`
661
- //
662
- // The `RuleClass` type contains the static methods and the `Rule` instance
663
- // contains the instance methods.
664
- //
665
- // This package exports the RuleClass as a value without implicitly exporting
666
- // an instance definition. This should help reminder downstream users to import
667
- // from the `@sanity/types` package.
668
- const Rule = class Rule {
669
- static FIELD_REF = FIELD_REF;
670
- static array = (def) => new Rule(def).type('Array');
671
- static object = (def) => new Rule(def).type('Object');
672
- static string = (def) => new Rule(def).type('String');
673
- static number = (def) => new Rule(def).type('Number');
674
- static boolean = (def) => new Rule(def).type('Boolean');
675
- static dateTime = (def) => new Rule(def).type('Date');
676
- static valueOfField = (path) => ({
677
- type: FIELD_REF,
678
- path,
679
- });
680
- _type = undefined;
681
- _level = undefined;
682
- _required = undefined;
683
- _typeDef = undefined;
684
- _message = undefined;
685
- _rules = [];
686
- _fieldRules = undefined;
687
- constructor(typeDef) {
688
- this._typeDef = typeDef;
689
- this.reset();
690
- }
691
- _mergeRequired(next) {
692
- if (this._required === 'required' || next._required === 'required')
693
- return 'required';
694
- if (this._required === 'optional' || next._required === 'optional')
695
- return 'optional';
696
- return undefined;
697
- }
698
- // Alias to static method, since we often have access to an _instance_ of a rule but not the actual Rule class
699
- valueOfField = Rule.valueOfField.bind(Rule);
700
- error(message) {
701
- const rule = this.clone();
702
- rule._level = 'error';
703
- rule._message = message || undefined;
704
- return rule;
705
- }
706
- warning(message) {
707
- const rule = this.clone();
708
- rule._level = 'warning';
709
- rule._message = message || undefined;
710
- return rule;
711
- }
712
- info(message) {
713
- const rule = this.clone();
714
- rule._level = 'info';
715
- rule._message = message || undefined;
716
- return rule;
717
- }
718
- reset() {
719
- this._type = this._type || undefined;
720
- this._rules = (this._rules || []).filter((rule) => rule.flag === 'type');
721
- this._message = undefined;
722
- this._required = undefined;
723
- this._level = 'error';
724
- this._fieldRules = undefined;
725
- return this;
726
- }
727
- isRequired() {
728
- return this._required === 'required';
729
- }
730
- clone() {
731
- const rule = new Rule();
732
- rule._type = this._type;
733
- rule._message = this._message;
734
- rule._required = this._required;
735
- rule._rules = lodash.cloneDeep(this._rules);
736
- rule._level = this._level;
737
- rule._fieldRules = this._fieldRules;
738
- rule._typeDef = this._typeDef;
739
- return rule;
740
- }
741
- cloneWithRules(rules) {
742
- const rule = this.clone();
743
- const newRules = new Set();
744
- rules.forEach((curr) => {
745
- if (curr.flag === 'type') {
746
- rule._type = curr.constraint;
747
- }
748
- newRules.add(curr.flag);
749
- });
750
- rule._rules = rule._rules
751
- .filter((curr) => {
752
- const disallowDuplicate = ['type', 'uri', 'email'].includes(curr.flag);
753
- const isDuplicate = newRules.has(curr.flag);
754
- return !(disallowDuplicate && isDuplicate);
755
- })
756
- .concat(rules);
757
- return rule;
758
- }
759
- merge(rule) {
760
- if (this._type && rule._type && this._type !== rule._type) {
761
- throw new Error('merge() failed: conflicting types');
762
- }
763
- const newRule = this.cloneWithRules(rule._rules);
764
- newRule._type = this._type || rule._type;
765
- newRule._message = this._message || rule._message;
766
- newRule._required = this._mergeRequired(rule);
767
- newRule._level = this._level === 'error' ? rule._level : this._level;
768
- return newRule;
769
- }
770
- // Validation flag setters
771
- type(targetType) {
772
- const type = `${targetType.slice(0, 1).toUpperCase()}${targetType.slice(1)}`;
773
- if (!ruleConstraintTypes$1.includes(type)) {
774
- throw new Error(`Unknown type "${targetType}"`);
775
- }
776
- const rule = this.cloneWithRules([{ flag: 'type', constraint: type }]);
777
- rule._type = type;
778
- return rule;
779
- }
780
- all(children) {
781
- return this.cloneWithRules([{ flag: 'all', constraint: children }]);
782
- }
783
- either(children) {
784
- return this.cloneWithRules([{ flag: 'either', constraint: children }]);
785
- }
786
- // Shared rules
787
- optional() {
788
- const rule = this.cloneWithRules([{ flag: 'presence', constraint: 'optional' }]);
789
- rule._required = 'optional';
790
- return rule;
791
- }
792
- required() {
793
- const rule = this.cloneWithRules([{ flag: 'presence', constraint: 'required' }]);
794
- rule._required = 'required';
795
- return rule;
796
- }
797
- custom(fn) {
798
- return this.cloneWithRules([{ flag: 'custom', constraint: fn }]);
799
- }
800
- /**
801
- * @deprecated use `Rule.custom` instead
802
- */
803
- block(fn) {
804
- return this.cloneWithRules([{ flag: 'custom', constraint: fn }]);
805
- }
806
- min(len) {
807
- return this.cloneWithRules([{ flag: 'min', constraint: len }]);
808
- }
809
- max(len) {
810
- return this.cloneWithRules([{ flag: 'max', constraint: len }]);
811
- }
812
- length(len) {
813
- return this.cloneWithRules([{ flag: 'length', constraint: len }]);
814
- }
815
- valid(value) {
816
- const values = Array.isArray(value) ? value : [value];
817
- return this.cloneWithRules([{ flag: 'valid', constraint: values }]);
818
- }
819
- // Numbers only
820
- integer() {
821
- return this.cloneWithRules([{ flag: 'integer' }]);
822
- }
823
- precision(limit) {
824
- return this.cloneWithRules([{ flag: 'precision', constraint: limit }]);
825
- }
826
- positive() {
827
- return this.cloneWithRules([{ flag: 'min', constraint: 0 }]);
828
- }
829
- negative() {
830
- return this.cloneWithRules([{ flag: 'lessThan', constraint: 0 }]);
831
- }
832
- greaterThan(num) {
833
- return this.cloneWithRules([{ flag: 'greaterThan', constraint: num }]);
834
- }
835
- lessThan(num) {
836
- return this.cloneWithRules([{ flag: 'lessThan', constraint: num }]);
837
- }
838
- // String only
839
- uppercase() {
840
- return this.cloneWithRules([{ flag: 'stringCasing', constraint: 'uppercase' }]);
841
- }
842
- lowercase() {
843
- return this.cloneWithRules([{ flag: 'stringCasing', constraint: 'lowercase' }]);
844
- }
845
- regex(pattern, a, b) {
846
- const name = typeof a === 'string' ? a : a?.name ?? b?.name;
847
- const invert = typeof a === 'string' ? false : a?.invert ?? b?.invert;
848
- const constraint = {
849
- pattern,
850
- name,
851
- invert: invert || false,
852
- };
853
- return this.cloneWithRules([{ flag: 'regex', constraint }]);
854
- }
855
- email() {
856
- return this.cloneWithRules([{ flag: 'email' }]);
857
- }
858
- uri(opts) {
859
- const optsScheme = opts?.scheme || ['http', 'https'];
860
- const schemes = Array.isArray(optsScheme) ? optsScheme : [optsScheme];
861
- if (!schemes.length) {
862
- throw new Error('scheme must have at least 1 scheme specified');
863
- }
864
- const constraint = {
865
- options: {
866
- scheme: schemes.map((scheme) => {
867
- if (!(scheme instanceof RegExp) && typeof scheme !== 'string') {
868
- throw new Error('scheme must be a RegExp or a String');
869
- }
870
- return typeof scheme === 'string' ? new RegExp(`^${escapeRegex(scheme)}$`) : scheme;
871
- }),
872
- allowRelative: opts?.allowRelative || false,
873
- relativeOnly: opts?.relativeOnly || false,
874
- allowCredentials: opts?.allowCredentials || false,
875
- },
876
- };
877
- return this.cloneWithRules([{ flag: 'uri', constraint }]);
878
- }
879
- // Array only
880
- unique() {
881
- return this.cloneWithRules([{ flag: 'unique' }]);
882
- }
883
- // Objects only
884
- reference() {
885
- return this.cloneWithRules([{ flag: 'reference' }]);
886
- }
887
- fields(rules) {
888
- if (this._type !== 'Object') {
889
- throw new Error('fields() can only be called on an object type');
890
- }
891
- const rule = this.cloneWithRules([]);
892
- rule._fieldRules = rules;
893
- return rule;
894
- }
895
- assetRequired() {
896
- const base = getBaseType(this._typeDef);
897
- let assetType;
898
- if (base && ['image', 'file'].includes(base.name)) {
899
- assetType = base.name === 'image' ? 'Image' : 'File';
900
- }
901
- else {
902
- assetType = 'Asset';
903
- }
904
- return this.cloneWithRules([{ flag: 'assetRequired', constraint: { assetType } }]);
905
- }
906
- async validate(value, context) {
907
- if (!context) {
908
- throw new Error('missing context');
909
- }
910
- const valueIsEmpty = value === null || value === undefined;
911
- // Short-circuit on optional, empty fields
912
- if (valueIsEmpty && this._required === 'optional') {
913
- return EMPTY_ARRAY;
914
- }
915
- const rules =
916
- // Run only the _custom_ functions if the rule is not set to required or optional
917
- this._required === undefined && valueIsEmpty
918
- ? this._rules.filter((curr) => curr.flag === 'custom')
919
- : this._rules;
920
- const validators = (this._type && typeValidators[this._type]) || genericValidators;
921
- const results = await Promise.all(rules.map(async (curr) => {
922
- if (curr.flag === undefined) {
923
- throw new Error('Invalid rule, did not contain "flag"-property');
924
- }
925
- const validator = validators[curr.flag];
926
- if (!validator) {
927
- const forType = this._type ? `type "${this._type}"` : 'rule without declared type';
928
- throw new Error(`Validator for flag "${curr.flag}" not found for ${forType}`);
929
- }
930
- let specConstraint = 'constraint' in curr ? curr.constraint : null;
931
- if (isFieldRef(specConstraint)) {
932
- specConstraint = lodash.get(context.parent, specConstraint.path);
933
- }
934
- let result;
935
- try {
936
- result = await validator(specConstraint, value, this._message, context);
937
- }
938
- catch (err) {
939
- const errorFromException = new ValidationError(`${pathToString(context.path)}: Exception occurred while validating value: ${err.message}`);
940
- return convertToValidationMarker(errorFromException, 'error', context);
941
- }
942
- return convertToValidationMarker(result, this._level, context);
943
- }));
944
- return results.flat();
945
- }
946
- };
947
-
948
- // import getClient from '../getClient'
949
- const memoizedWarnOnArraySlug = lodash.memoize(warnOnArraySlug);
950
- function getDocumentIds(id) {
951
- const isDraft = id.indexOf('drafts.') === 0;
952
- return {
953
- published: isDraft ? id.slice('drafts.'.length) : id,
954
- draft: isDraft ? id : `drafts.${id}`,
955
- };
956
- }
957
- function serializePath(path) {
958
- return path.reduce((target, part, i) => {
959
- const isIndex = typeof part === 'number';
960
- const isKey = types.isKeyedObject(part);
961
- const separator = i === 0 ? '' : '.';
962
- const add = isIndex || isKey ? '[]' : `${separator}${part}`;
963
- return `${target}${add}`;
964
- }, '');
965
- }
966
- const defaultIsUnique = (slug, context) => {
967
- const { getClient, document, path, type } = context;
968
- const schemaOptions = type?.options;
969
- if (!document) {
970
- throw new Error(`\`document\` was not provided in validation context.`);
971
- }
972
- if (!path) {
973
- throw new Error(`\`path\` was not provided in validation context.`);
974
- }
975
- const disableArrayWarning = schemaOptions?.disableArrayWarning || false;
976
- const { published, draft } = getDocumentIds(document._id);
977
- const docType = document._type;
978
- const atPath = serializePath(path.concat('current'));
979
- if (!disableArrayWarning && atPath.includes('[]')) {
980
- memoizedWarnOnArraySlug(serializePath(path));
981
- }
982
- const constraints = [
983
- '_type == $docType',
984
- `!(_id in [$draft, $published])`,
985
- `${atPath} == $slug`,
986
- ].join(' && ');
987
- return getClient({ apiVersion: '2022-09-09' }).fetch(`!defined(*[${constraints}][0]._id)`, {
988
- docType,
989
- draft,
990
- published,
991
- slug,
992
- }, { tag: 'validation.slug-is-unique' });
993
- };
994
- function warnOnArraySlug(serializedPath) {
995
- /* eslint-disable no-console */
996
- console.warn([
997
- `Slug field at path ${serializedPath} is within an array and cannot be automatically checked for uniqueness`,
998
- `If you need to check for uniqueness, provide your own "isUnique" method`,
999
- `To disable this message, set \`disableArrayWarning: true\` on the slug \`options\` field`,
1000
- ].join('\n'));
1001
- /* eslint-enable no-console */
1002
- }
1003
- /**
1004
- * Validates slugs values by querying for uniqueness from the client.
1005
- *
1006
- * This is a custom rule implementation (e.g. `Rule.custom(slugValidator)`)
1007
- * that's populated in `inferFromSchemaType` when the type name is `slug`
1008
- */
1009
- const slugValidator = async (value, context) => {
1010
- if (!value) {
1011
- return true;
1012
- }
1013
- if (typeof value !== 'object') {
1014
- return 'Slug must be an object';
1015
- }
1016
- const slugValue = value.current;
1017
- if (!slugValue) {
1018
- return 'Slug must have a value';
1019
- }
1020
- const options = context?.type?.options;
1021
- const isUnique = options?.isUnique || defaultIsUnique;
1022
- const wasUnique = await isUnique(slugValue, { ...context, defaultIsUnique });
1023
- if (wasUnique) {
1024
- return true;
1025
- }
1026
- return 'Slug is already in use';
1027
- };
1028
-
1029
- const ruleConstraintTypes = {
1030
- array: true,
1031
- boolean: true,
1032
- date: true,
1033
- number: true,
1034
- object: true,
1035
- string: true,
1036
- };
1037
- const isRuleConstraint = (typeString) => typeString in ruleConstraintTypes;
1038
- function getTypeChain(type, visited) {
1039
- if (!type)
1040
- return [];
1041
- if (visited.has(type))
1042
- return [];
1043
- visited.add(type);
1044
- const next = type.type ? getTypeChain(type.type, visited) : [];
1045
- return [...next, type];
1046
- }
1047
- function baseRuleReducer(inputRule, type) {
1048
- let baseRule = inputRule;
1049
- if (isRuleConstraint(type.jsonType)) {
1050
- baseRule = baseRule.type(type.jsonType);
1051
- }
1052
- const typeOptionsList =
1053
- // if type.options is truthy
1054
- type?.options &&
1055
- // and type.options is an object (non-null from the previous)
1056
- typeof type.options === 'object' &&
1057
- // and if `list` is in options
1058
- 'list' in type.options &&
1059
- // then finally access the list
1060
- type.options.list;
1061
- if (Array.isArray(typeOptionsList)) {
1062
- baseRule = baseRule.valid(typeOptionsList.map((option) => extractValueFromListOption(option, type)));
1063
- }
1064
- if (type.name === 'datetime')
1065
- return baseRule.type('Date');
1066
- if (type.name === 'date')
1067
- return baseRule.type('Date');
1068
- if (type.name === 'url')
1069
- return baseRule.uri();
1070
- if (type.name === 'slug')
1071
- return baseRule.custom(slugValidator);
1072
- if (type.name === 'reference')
1073
- return baseRule.reference();
1074
- if (type.name === 'email')
1075
- return baseRule.email();
1076
- return baseRule;
1077
- }
1078
- function hasValueField(typeDef) {
1079
- if (!typeDef)
1080
- return false;
1081
- if (!('fields' in typeDef) && typeDef.type)
1082
- return hasValueField(typeDef.type);
1083
- if (!('fields' in typeDef))
1084
- return false;
1085
- if (!Array.isArray(typeDef.fields))
1086
- return false;
1087
- return typeDef.fields.some((field) => field.name === 'value');
1088
- }
1089
- function extractValueFromListOption(option, typeDef) {
1090
- // If you define a `list` option with object items, where the item has a `value` field,
1091
- // we don't want to treat that as the value but rather the surrounding object
1092
- // This differs from the case where you have a title/value pair setup for a string/number, for instance
1093
- if (typeDef.jsonType === 'object' && hasValueField(typeDef))
1094
- return option;
1095
- return option.value === undefined
1096
- ? option
1097
- : option.value;
1098
- }
1099
- /**
1100
- * Takes in `SchemaValidationValue` and returns an array of `Rule` instances.
1101
- */
1102
- function normalizeValidationRules(typeDef) {
1103
- if (!typeDef) {
1104
- return [];
1105
- }
1106
- const validation = typeDef.validation;
1107
- if (Array.isArray(validation)) {
1108
- return validation.flatMap((i) => normalizeValidationRules({
1109
- ...typeDef,
1110
- validation: i,
1111
- }));
1112
- }
1113
- if (validation instanceof Rule) {
1114
- return [validation];
1115
- }
1116
- const baseRule =
1117
- // using an object + Object.values to de-dupe the type chain by type name
1118
- Object.values(getTypeChain(typeDef, new Set()).reduce((acc, type) => {
1119
- acc[type.name] = type;
1120
- return acc;
1121
- }, {})).reduce(baseRuleReducer, new Rule(typeDef));
1122
- if (!validation) {
1123
- return [baseRule];
1124
- }
1125
- return normalizeValidationRules({
1126
- ...typeDef,
1127
- validation: validation(baseRule),
1128
- });
1129
- }
1130
-
1131
- const isRecord = (maybeRecord) => typeof maybeRecord === 'object' && maybeRecord !== null && !Array.isArray(maybeRecord);
1132
- const isNonNullable = (value) => value !== null && value !== undefined;
1133
- /**
1134
- * @internal
1135
- */
1136
- function resolveTypeForArrayItem(item, candidates) {
1137
- // if there is only one type available, assume that it's the correct one
1138
- if (candidates.length === 1)
1139
- return candidates[0];
1140
- const itemType = types.isTypedObject(item) && item._type;
1141
- const primitive = item === undefined || item === null || (!itemType && typeString(item).toLowerCase());
1142
- if (primitive && primitive !== 'object') {
1143
- return candidates.find((candidate) => candidate.jsonType === primitive);
1144
- }
1145
- return (candidates.find((candidate) => candidate.type?.name === itemType) ||
1146
- candidates.find((candidate) => candidate.name === itemType) ||
1147
- candidates.find((candidate) => candidate.name === 'object' && primitive === 'object'));
1148
- }
1149
- async function validateDocument(getClient, doc, schema, context) {
1150
- const documentType = schema.get(doc._type);
1151
- if (!documentType) {
1152
- console.warn('Schema type for object type "%s" not found, skipping validation', doc._type);
1153
- return [];
1154
- }
1155
- const client = getClient({ apiVersion: '2021-06-07' });
1156
- const validationOptions = {
1157
- client,
1158
- getClient,
1159
- schema,
1160
- parent: undefined,
1161
- value: doc,
1162
- path: [],
1163
- document: doc,
1164
- type: documentType,
1165
- getDocumentExists: context?.getDocumentExists,
1166
- };
1167
- // <TEMPORARY UGLY HACK TO PRINT DEPRECATION WARNINGS ON USE>
1168
- /* eslint-disable no-proto */
1169
- const wrappedClient = client;
1170
- validationOptions.client = [
1171
- ...Object.keys(client),
1172
- ...Object.keys(wrappedClient.__proto__),
1173
- ].reduce((acc, key) => {
1174
- const original = Object.hasOwnProperty.call(client, key)
1175
- ? wrappedClient[key]
1176
- : wrappedClient.__proto__[key];
1177
- return Object.defineProperty(acc, key, {
1178
- get() {
1179
- console.warn('`configContext.client` is deprecated and will be removed in the next release! Use `context.getClient({apiVersion: "2021-06-07"})` instead');
1180
- return original;
1181
- },
1182
- });
1183
- }, {});
1184
- /* eslint-enable no-proto */
1185
- // </TEMPORARY UGLY HACK TO PRINT DEPRECATION WARNINGS ON USE>
1186
- try {
1187
- return await validateItem(validationOptions);
1188
- }
1189
- catch (err) {
1190
- console.error(err);
1191
- return [
1192
- {
1193
- level: 'error',
1194
- path: [],
1195
- item: new ValidationError(err?.message),
1196
- },
1197
- ];
1198
- }
1199
- }
1200
- async function validateItem({ value, type, path = [], parent, ...restOfContext }) {
1201
- const rules = normalizeValidationRules(type);
1202
- // run validation for the current value
1203
- const selfChecks = rules.map((rule) => rule.validate(value, {
1204
- ...restOfContext,
1205
- parent,
1206
- path,
1207
- type,
1208
- }));
1209
- // run validation for nested values (conditionally)
1210
- let nestedChecks = [];
1211
- const selfIsRequired = rules.some((rule) => rule.isRequired());
1212
- const shouldRunNestedObjectValidation =
1213
- // run nested validation for objects
1214
- type?.jsonType === 'object' &&
1215
- // if the value is truthy
1216
- (!!value || // or
1217
- // (the value is null or undefined) and the top-level value is required
1218
- ((value === null || value === undefined) && selfIsRequired));
1219
- if (shouldRunNestedObjectValidation) {
1220
- const fieldTypes = type.fields.reduce((acc, field) => {
1221
- acc[field.name] = field.type;
1222
- return acc;
1223
- }, {});
1224
- // Validation for rules set at the object level with `Rule.fields({/* ... */})`
1225
- nestedChecks = nestedChecks.concat(rules
1226
- .map((rule) => rule._fieldRules)
1227
- .filter(isNonNullable)
1228
- .flatMap((fieldResults) => Object.entries(fieldResults))
1229
- .flatMap(([name, validation]) => {
1230
- const fieldType = fieldTypes[name];
1231
- return normalizeValidationRules({ ...fieldType, validation }).map((subRule) => {
1232
- const nestedValue = isRecord(value) ? value[name] : undefined;
1233
- return subRule.validate(nestedValue, {
1234
- ...restOfContext,
1235
- parent: value,
1236
- path: path.concat(name),
1237
- type: fieldType,
1238
- });
1239
- });
1240
- }));
1241
- // Validation from each field's schema `validation: Rule => {/* ... */}` function
1242
- nestedChecks = nestedChecks.concat(type.fields.map((field) => validateItem({
1243
- ...restOfContext,
1244
- parent: value,
1245
- value: isRecord(value) ? value[field.name] : undefined,
1246
- path: path.concat(field.name),
1247
- type: field.type,
1248
- })));
1249
- }
1250
- // note: unlike objects, arrays should not run nested validation for undefined
1251
- // values because we won't have a valid path to put a marker (i.e. missing the
1252
- // key or index in the path) and the downstream form builder won't have a
1253
- // valid target component
1254
- const shouldRunNestedValidationForArrays = type?.jsonType === 'array' && Array.isArray(value);
1255
- if (shouldRunNestedValidationForArrays) {
1256
- nestedChecks = nestedChecks.concat(value.map((item) => validateItem({
1257
- ...restOfContext,
1258
- parent: value,
1259
- value: item,
1260
- path: path.concat(types.isKeyedObject(item) ? { _key: item._key } : value.indexOf(item)),
1261
- type: resolveTypeForArrayItem(item, type.of),
1262
- })));
1263
- }
1264
- // markDefs also do no run nested validation if the parent object is undefined
1265
- // for a similar reason to arrays
1266
- const shouldRunNestedValidationForMarkDefs = types.isBlock(value) && value.markDefs.length && types.isBlockSchemaType(type);
1267
- if (shouldRunNestedValidationForMarkDefs) {
1268
- const [spanChildrenField] = type.fields;
1269
- const spanType = spanChildrenField.type.of.find(types.isSpanSchemaType);
1270
- const annotations = (spanType?.annotations || []).reduce((map, annotationType) => {
1271
- map.set(annotationType.name, annotationType);
1272
- return map;
1273
- }, new Map());
1274
- nestedChecks = nestedChecks.concat(value.markDefs.map((markDef) => validateItem({
1275
- ...restOfContext,
1276
- parent: value,
1277
- value: markDef,
1278
- path: path.concat(['markDefs', { _key: markDef._key }]),
1279
- type: annotations.get(markDef._type),
1280
- })));
1281
- }
1282
- const results = (await Promise.all([...selfChecks, ...nestedChecks])).flat();
1283
- // run `uniqBy` if `_fieldRules` are present because they can
1284
- // cause repeat markers
1285
- if (rules.some((rule) => rule._fieldRules)) {
1286
- return lodash.uniqBy(results, (rule) => JSON.stringify(rule));
1287
- }
1288
- return results;
1289
- }
1290
-
1291
- function traverse(typeDef, visited) {
1292
- if (visited.has(typeDef)) {
1293
- return;
1294
- }
1295
- visited.add(typeDef);
1296
- typeDef.validation = normalizeValidationRules(typeDef);
1297
- if ('fields' in typeDef) {
1298
- for (const field of typeDef.fields) {
1299
- traverse(field.type, visited);
1300
- }
1301
- }
1302
- if ('of' in typeDef) {
1303
- for (const candidate of typeDef.of) {
1304
- traverse(candidate, visited);
1305
- }
1306
- }
1307
- // eslint-disable-next-line no-warning-comments
1308
- // @ts-expect-error TODO (eventually): `annotations` does not exist on the SchemaType yet
1309
- if (typeDef.annotations) {
1310
- // eslint-disable-next-line no-warning-comments
1311
- // @ts-expect-error TODO (eventually): `annotations` does not exist on the SchemaType yet
1312
- for (const annotation of typeDef.annotations) {
1313
- traverse(annotation, visited);
1314
- }
1315
- }
1316
- }
1317
- function inferFromSchemaType(typeDef) {
1318
- traverse(typeDef, new Set());
1319
- return typeDef;
1320
- }
1321
-
1322
- // Note: Mutates schema. Refactor when @sanity/schema supports middlewares
1323
- function inferFromSchema(schema) {
1324
- const typeNames = schema.getTypeNames();
1325
- typeNames.forEach((typeName) => {
1326
- const schemaType = schema.get(typeName);
1327
- if (schemaType) {
1328
- inferFromSchemaType(schemaType);
1329
- }
1330
- });
1331
- return schema;
1332
- }
1333
-
1334
- var index = { Rule: Rule, validateDocument, inferFromSchema, inferFromSchemaType };
1335
-
1336
- exports.Rule = Rule;
1337
- exports["default"] = index;
1338
- exports.inferFromSchema = inferFromSchema;
1339
- exports.inferFromSchemaType = inferFromSchemaType;
1340
- exports.validateDocument = validateDocument;
1341
- //# sourceMappingURL=index.cjs.map