@sanity/validation 3.14.4 → 6.12.0-next.112

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