@sanity/validation 6.25.0-next.30 → 6.25.0-next.63

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { E as LocaleSource, S as ValidationMarkerCode, T as ValidationScheduling, d as evaluateDocumentInternal, f as evaluateDocumentObservable, g as validateDocumentObservable, h as validateDocumentInternal, n as ValidateDocumentInternalOptions, p as resolveTypeForArrayItem, r as ValidateDocumentObservableOptions, s as ValidateItemOptions, w as ValidationContext, y as validateItem } from "./validateDocument-Clpbuo5v.js";
1
+ import { E as LocaleSource, S as ValidationMarkerCode, T as ValidationScheduling, d as evaluateDocumentInternal, f as evaluateDocumentObservable, g as validateDocumentObservable, h as validateDocumentInternal, n as ValidateDocumentInternalOptions, p as resolveTypeForArrayItem, r as ValidateDocumentObservableOptions, s as ValidateItemOptions, w as ValidationContext, y as validateItem } from "./validateDocument-aLaCENLs.js";
2
2
  import { Path, Rule as Rule$1, RuleClass, Schema, SchemaType, SchemaValidationValue, ValidationContext as ValidationContext$1, ValidationError, ValidationMarker } from "@sanity/types";
3
3
  import { accepts } from "@sanity/util/accepts";
4
4
  export declare function getFallbackLocaleSource(): LocaleSource;
package/lib/_internal.js CHANGED
@@ -1,4 +1,4 @@
1
- import { _ as pathToString, a as validateDocumentInternal, d as compileValidationRules, f as normalizeValidationRules, g as convertToValidationMarker, h as typeString, l as validateItem, m as getTypeChain, n as evaluateDocumentObservable, o as validateDocumentObservable, p as Rule, r as resolveTypeForArrayItem, t as evaluateDocumentInternal, v as getFallbackLocaleSource, y as validationLocaleStrings } from "./validateDocument-NMKSm_Yr.js";
1
+ import { _ as pathToString, a as validateDocumentInternal, d as compileValidationRules, f as normalizeValidationRules, g as convertToValidationMarker, h as typeString, l as validateItem, m as getTypeChain, n as evaluateDocumentObservable, o as validateDocumentObservable, p as Rule, r as resolveTypeForArrayItem, t as evaluateDocumentInternal, v as getFallbackLocaleSource, y as validationLocaleStrings } from "./validateDocument-ChZQiqHl.js";
2
2
  import { accepts } from "@sanity/util/accepts";
3
3
  function inferFromSchemaType(typeDef) {
4
4
  return traverse(typeDef, /* @__PURE__ */ new Set()), typeDef;
package/lib/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { C as validationMarkerCodes, D as ValidationLocaleSource, S as ValidationMarkerCode, _ as validateDocumentWithWorkspace, a as ValidateDocumentWorkspaceOptions, b as BuiltInValidationMarkerCode, c as ValidationClient, i as ValidateDocumentOptions, l as ValidationSchema, m as validateDocument, o as ValidateDocumentsOptions, t as DocumentValidationResult, u as ValidationSource, v as validateDocuments, x as DocumentValidationMarker } from "./validateDocument-Clpbuo5v.js";
1
+ import { C as validationMarkerCodes, D as ValidationLocaleSource, S as ValidationMarkerCode, _ as validateDocumentWithWorkspace, a as ValidateDocumentWorkspaceOptions, b as BuiltInValidationMarkerCode, c as ValidationClient, i as ValidateDocumentOptions, l as ValidationSchema, m as validateDocument, o as ValidateDocumentsOptions, t as DocumentValidationResult, u as ValidationSource, v as validateDocuments, x as DocumentValidationMarker } from "./validateDocument-aLaCENLs.js";
2
2
  import { SanityDocument } from "@sanity/types";
3
3
  type DocumentCheck = (options: {
4
4
  id: string;
package/lib/index.js CHANGED
@@ -1 +1 @@
1
- export { i as validateDocument, s as validateDocumentWithWorkspace, c as validateDocuments, b as validationMarkerCodes, u as withReleaseReferences } from "./validateDocument-NMKSm_Yr.js";
1
+ export { i as validateDocument, s as validateDocumentWithWorkspace, c as validateDocuments, b as validationMarkerCodes, u as withReleaseReferences } from "./validateDocument-ChZQiqHl.js";
@@ -410,10 +410,7 @@ const SLOW_VALIDATOR_TIMEOUT = 5e3, formatValidationErrors = (options) => {
410
410
  unique: (_unused, value, message, { i18n }) => {
411
411
  let dupeIndices = [];
412
412
  if (!value) return !0;
413
- for (let x = 0; x < value.length; x++) for (let y = x + 1; y < value.length; y++) {
414
- let itemA = value[x], itemB = value[y];
415
- deepEqualsIgnoreKey(itemA, itemB) && (dupeIndices.indexOf(x) === -1 && dupeIndices.push(x), dupeIndices.indexOf(y) === -1 && dupeIndices.push(y));
416
- }
413
+ for (let x = 0; x < value.length; x++) for (let y = x + 1; y < value.length; y++) deepEqualsIgnoreKey(value[x], value[y]) && (dupeIndices.indexOf(x) === -1 && dupeIndices.push(x), dupeIndices.indexOf(y) === -1 && dupeIndices.push(y));
417
414
  let paths = dupeIndices.map((idx) => {
418
415
  let item = value[idx];
419
416
  return [item && item._key ? { _key: item._key } : idx];
@@ -1678,4 +1675,4 @@ function toDocumentValidationMarker(marker) {
1678
1675
  }
1679
1676
  export { pathToString as _, validateDocumentInternal as a, validationMarkerCodes as b, validateDocuments as c, compileValidationRules as d, normalizeValidationRules as f, convertToValidationMarker as g, typeString as h, validateDocument as i, validateItem as l, getTypeChain as m, evaluateDocumentObservable as n, validateDocumentObservable as o, Rule as p, resolveTypeForArrayItem as r, validateDocumentWithWorkspace as s, evaluateDocumentInternal as t, withReleaseReferences as u, getFallbackLocaleSource as v, validationLocaleStrings as y };
1680
1677
 
1681
- //# sourceMappingURL=validateDocument-NMKSm_Yr.js.map
1678
+ //# sourceMappingURL=validateDocument-ChZQiqHl.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"validateDocument-NMKSm_Yr.js","names":["isRecord","DEFAULT_API_VERSION","BaseRule","RuleClass","isEqual","RuleClass","isEqual"],"sources":["../src/codes.ts","../src/clientUnavailable.ts","../src/i18n/resources.ts","../src/i18n/fallback.ts","../src/resolveConditionalProperty.ts","../src/util/pathToString.ts","../src/util/convertToValidationMarker.ts","../src/util/localizeMessage.ts","../src/util/deepEqualsIgnoreKey.ts","../src/util/typeString.ts","../src/validators/genericValidator.ts","../src/validators/arrayValidator.ts","../src/validators/booleanValidator.ts","../src/util/getTypeChain.ts","../src/validators/dateValidator.ts","../src/validators/numberValidator.ts","../src/validators/objectValidator.ts","../src/validators/slugValidator.ts","../src/validators/stringValidator.ts","../src/Rule.ts","../src/util/createBatchedGetDocumentExists.ts","../src/util/createBatchedGetDocumentType.ts","../src/validators/assetAcceptValidator.ts","../src/util/normalizeValidationRules.ts","../src/util/requestIdleCallback.ts","../src/util/pace.ts","../src/util/withReleaseReferences.ts","../src/validators/unknownFieldsValidator.ts","../src/validateDocument.ts"],"sourcesContent":["import {type ValidationMarker as BaseValidationMarker} from '@sanity/types'\n\n/** Machine-readable codes emitted by built-in document validation. @beta */\nexport const validationMarkerCodes = {\n arrayDuplicateItem: 'array.duplicate-item',\n arrayExactLength: 'array.exact-length',\n arrayMaximumLength: 'array.maximum-length',\n arrayMinimumLength: 'array.minimum-length',\n assetNotAccepted: 'asset.not-accepted',\n assetRequired: 'asset.required',\n custom: 'custom',\n dateInvalidFormat: 'date.invalid-format',\n dateMaximum: 'date.maximum',\n dateMinimum: 'date.minimum',\n documentUnknownType: 'document.unknown-type',\n mediaCustom: 'media.custom',\n mediaInvalidReference: 'media.invalid-reference',\n mediaNotFound: 'media.not-found',\n numberGreaterThan: 'number.greater-than',\n numberInteger: 'number.integer',\n numberLessThan: 'number.less-than',\n numberMaximum: 'number.maximum',\n numberMinimum: 'number.minimum',\n numberPrecision: 'number.precision',\n objectUnknownField: 'object.unknown-field',\n referenceInvalid: 'reference.invalid',\n referenceNotPublished: 'reference.not-published',\n referenceTargetTypeMismatch: 'reference.target-type-mismatch',\n ruleAllFailed: 'rule.all-failed',\n ruleEitherFailed: 'rule.either-failed',\n slugInvalidType: 'slug.invalid-type',\n slugMissingCurrent: 'slug.missing-current',\n slugNotUnique: 'slug.not-unique',\n stringEmail: 'string.email',\n stringExactLength: 'string.exact-length',\n stringLowercase: 'string.lowercase',\n stringMaximumLength: 'string.maximum-length',\n stringMinimumLength: 'string.minimum-length',\n stringRegexMatch: 'string.regex-match',\n stringRegexMismatch: 'string.regex-mismatch',\n stringUppercase: 'string.uppercase',\n stringUrlCredentialsNotAllowed: 'string.url.credentials-not-allowed',\n stringUrlInvalid: 'string.url.invalid',\n stringUrlNotAbsolute: 'string.url.not-absolute',\n stringUrlNotRelative: 'string.url.not-relative',\n stringUrlSchemeNotAllowed: 'string.url.scheme-not-allowed',\n validationException: 'validation.exception',\n validationFailed: 'validation.failed',\n valueNotAllowed: 'value.not-allowed',\n valueRequired: 'value.required',\n valueTypeMismatch: 'value.type-mismatch',\n} as const\n\n/** A code emitted by a built-in validator. @beta */\nexport type BuiltInValidationMarkerCode =\n (typeof validationMarkerCodes)[keyof typeof validationMarkerCodes]\n\n/**\n * A built-in validation code or an application-defined custom code.\n * Custom validators should namespace their codes, for example `custom.seo-title`.\n * @beta\n */\nexport type ValidationMarkerCode = BuiltInValidationMarkerCode | (string & {})\n\n/** A validation marker emitted by `validateDocument`, which always has a code. @beta */\nexport type DocumentValidationMarker = Omit<BaseValidationMarker, 'code'> & {\n code: ValidationMarkerCode\n}\n","export class ClientUnavailableError extends Error {\n override name = 'ClientUnavailableError'\n\n constructor() {\n super('A Sanity client is required to run this validation check')\n }\n}\n","export const validationLocaleStrings = {\n 'array.exact-length': 'Must have exactly {{wantedLength}} items',\n 'array.exact-length_blocks': 'Must have exactly {{wantedLength}} blocks',\n 'array.item-duplicate': \"Can't be a duplicate\",\n 'array.maximum-length': 'Must have at most {{maxLength}} items',\n 'array.maximum-length_blocks': 'Must have at most {{maxLength}} blocks',\n 'array.minimum-length': 'Must have at least {{minLength}} items',\n 'array.minimum-length_blocks': 'Must have at least {{minLength}} blocks',\n 'date.invalid-format': 'Must be a valid ISO-8601 formatted date string',\n 'date.maximum': 'Must be at or before {{maxDate}}',\n 'date.minimum': 'Must be at or after {{minDate}}',\n 'generic.incorrect-type': 'Expected type \"{{expectedType}}\", got \"{{actualType}}\"',\n 'generic.not-allowed': 'Value did not match any allowed values',\n 'generic.not-allowed_hint': 'Value \"{{hint}}\" did not match any allowed values',\n 'generic.required': 'Required',\n 'number.greater-than': 'Must be greater than {{threshold}}',\n 'number.less-than': 'Must be less than {{threshold}}',\n 'number.maximum': 'Must be lower than or equal to {{maxNumber}}',\n 'number.maximum-precision': 'Max precision is {{limit}}',\n 'number.minimum': 'Must be greater than or equal to {{minNumber}}',\n 'number.non-integer': 'Must be an integer',\n 'object.asset-not-accepted': 'File type \"{{mimeType}}\" is not accepted',\n 'object.asset-not-accepted_file': 'File type \"{{mimeType}}\" is not accepted',\n 'object.asset-not-accepted_image': 'Image type \"{{mimeType}}\" is not accepted',\n 'object.asset-required': 'Asset is required',\n 'object.asset-required_file': 'File is required',\n 'object.asset-required_image': 'Image is required',\n 'object.media-not-found': 'The asset could not be found in the Media Library',\n 'object.not-media-library-asset': 'Must be a reference to a Media Library asset',\n 'object.not-reference': 'Must be a reference to a document',\n 'object.reference-not-published': 'Referenced document must be published',\n 'object.reference-target-type-mismatch':\n 'Referenced document has type \"{{actualType}}\"; expected one of: {{allowedTypes}}',\n 'slug.missing-current': 'Slug must have a value',\n 'slug.not-object': 'Slug must be an object',\n 'slug.not-unique': 'Slug is already in use',\n 'string.email': 'Must be a valid email address',\n 'string.exact-length': 'Must be exactly {{wantedLength}} characters long',\n 'string.lowercase': 'Must be all lowercase characters',\n 'string.maximum-length': 'Must be at most {{maxLength}} characters long',\n 'string.minimum-length': 'Must be at least {{minLength}} characters long',\n 'string.regex-does-not-match': 'Does not match \"{{name}}\"-pattern',\n 'string.regex-match': 'Should not match \"{{name}}\"-pattern',\n 'string.uppercase': 'Must be all uppercase characters',\n 'string.url.disallowed-scheme': 'Does not match allowed protocols/schemes',\n 'string.url.includes-credentials': 'Username/password not allowed',\n 'string.url.invalid': 'Not a valid URL',\n 'string.url.not-absolute': 'Relative URLs are not allowed',\n 'string.url.not-relative': 'Only relative URLs are allowed',\n} as const\n","import {createInstance} from 'i18next'\n\nimport {validationLocaleStrings} from './resources'\nimport {type LocaleSource} from './types'\n\nlet fallbackLocaleSource: LocaleSource | undefined\n\nexport function getFallbackLocaleSource(): LocaleSource {\n if (fallbackLocaleSource) return fallbackLocaleSource\n\n const i18n = createInstance({\n defaultNS: 'validation',\n fallbackLng: 'en-US',\n initAsync: false,\n interpolation: {escapeValue: false},\n lng: 'en-US',\n ns: ['validation'],\n resources: {'en-US': {validation: validationLocaleStrings}},\n supportedLngs: ['en-US'],\n })\n void i18n.init()\n\n fallbackLocaleSource = {\n currentLocale: {id: 'en-US'},\n loadNamespaces: (namespaces) => i18n.loadNamespaces(namespaces),\n t: i18n.t,\n }\n return fallbackLocaleSource\n}\n","import {type ConditionalProperty, type CurrentUser, type Path} from '@sanity/types'\n\ninterface ConditionalPropertyCallbackContext {\n parent?: unknown\n document?: Record<string, unknown>\n currentUser: Omit<CurrentUser, 'role'> | null\n value: unknown\n path: Path\n}\n\nexport function resolveConditionalProperty(\n property: ConditionalProperty,\n context: ConditionalPropertyCallbackContext,\n) {\n const {currentUser, document, parent, value, path} = context\n\n if (typeof property === 'boolean' || property === undefined) return Boolean(property)\n\n // oxlint-disable-next-line no-unnecessary-boolean-literal-compare -- runtime callbacks may return non-booleans\n return property({document: document as never, parent, value, currentUser, path}) === true\n}\n","import {isKeyedObject, type Path} from '@sanity/types'\n\nexport function pathToString(path: Path | undefined = []): string {\n return path.reduce<string>((target, segment, i) => {\n const segmentType = typeof segment\n if (segmentType === 'number') {\n return `${target}[${segment}]`\n }\n\n if (segmentType === 'string') {\n const separator = i === 0 ? '' : '.'\n return `${target}${separator}${segment}`\n }\n\n if (isKeyedObject(segment)) {\n return `${target}[_key==\"${segment._key}\"]`\n }\n\n throw new Error(`Unsupported path segment \"${segment}\"`)\n }, '')\n}\n","/* oxlint-disable typescript/no-deprecated -- marker compatibility requires legacy fields */\nimport {type Path, type ValidationError, type ValidationMarker} from '@sanity/types'\n\nimport {type ValidationMarkerCode, validationMarkerCodes} from '../codes'\nimport {type ValidationContext} from '../types'\nimport {pathToString} from '../util/pathToString'\n\nexport function convertToValidationMarker(\n validatorResult: true | true[] | string | string[] | ValidationError | ValidationError[],\n level: 'error' | 'warning' | 'info' | undefined,\n context: ValidationContext,\n fallback: {code: ValidationMarkerCode; details?: Record<string, unknown>} = {\n code: validationMarkerCodes.validationFailed,\n },\n): ValidationMarker[] {\n if (!context) {\n throw new Error('missing context')\n }\n\n if (validatorResult === true) return []\n\n if (Array.isArray(validatorResult)) {\n return validatorResult.flatMap((child) =>\n convertToValidationMarker(child, level, context, fallback),\n )\n }\n\n if (typeof validatorResult === 'string') {\n return convertToValidationMarker({message: validatorResult}, level, context, fallback)\n }\n\n if (typeof validatorResult.message !== 'string') {\n // in order to accept the `ValidationError`, it at least needs to have a\n // `message` in the object\n throw new Error(\n `${pathToString(\n context.path,\n )}: Validator must return 'true' if valid or an error message as a string on errors`,\n )\n }\n\n const {message, __internal_metadata} = validatorResult\n const code = validatorResult.code || fallback.code\n const details = validatorResult.details || fallback.details\n\n const normalizedPaths: Path[] = []\n if (validatorResult.path) {\n normalizedPaths.push(validatorResult.path)\n }\n\n // legacy support for `paths`\n for (const path of validatorResult.paths || []) {\n normalizedPaths.push(path)\n }\n\n // the validator result does not include any item-level relative paths,\n // then just return the top-level path with the validation result\n if (!normalizedPaths.length) {\n return [\n {\n code,\n ...(details && {details}),\n level: level || 'error',\n item: {message},\n message,\n path: context.path || [],\n __internal_metadata,\n },\n ]\n }\n\n // if the validator result did include item-level relative paths, then for\n // each item-level relative path, create a validation marker that concatenates\n // the relative path with the path from the validation context\n return normalizedPaths.map((path) => ({\n code,\n ...(details && {details}),\n path: (context.path || []).concat(path),\n level: level || 'error',\n item: {message},\n message,\n __internal_metadata,\n }))\n}\n","import {type CustomValidatorResult, type LocalizedValidationMessages} from '@sanity/types'\nimport isPlainObject from 'lodash-es/isPlainObject.js'\n\nimport {type LocaleSource} from '../i18n/types'\n\n/**\n * Extracts the correct localized validation message based on given locale source\n *\n * @param message - Localized messages to extract string from\n * @param i18n - Locale source, holding the current locale\n * @returns The localized string, or a fallback \"Unknown error\" if not found\n * @internal\n */\nexport function localizeMessage(message: LocalizedValidationMessages, i18n: LocaleSource): string {\n const {currentLocale} = i18n\n const locale = currentLocale.id\n\n // Obviously, try direct match first (`no-NB`)\n if (message[locale]) {\n return message[locale]\n }\n\n // In the case of composed languages (`en-US`, `no-NB` etc), fall back to base language (`en`)\n if (locale.includes('-')) {\n const language = locale.split('-', 1)[0]\n if (message[language]) {\n return message[language]\n }\n }\n\n // Try english as last resort\n return (\n message['en-US'] || message['en-GB'] || message.en || 'Unknown validation error (not localized)'\n )\n}\n\n/**\n * Check if passed message/result is a localized message object\n *\n * @param message - Message to check\n * @returns True if message is a localized message object, false otherwise\n * @internal\n */\nexport function isLocalizedMessages(\n message: CustomValidatorResult | undefined,\n): message is LocalizedValidationMessages {\n return (\n message !== true &&\n typeof message !== 'undefined' &&\n typeof message !== 'string' &&\n isPlainObject(message) &&\n !('message' in message)\n )\n}\n","/**\n * Modified version of fast-deep-equal (https://github.com/epoberezkin/fast-deep-equal)\n * MIT-licensed, copyright (c) 2017 Evgeny Poberezkin\n **/\n\n// NOTE: when converting to typescript, some of the checks were inlined (vs\n// having them in a variable) because the type predicate type narrowing only\n// works when type predicate is called inline in the condition that starts the\n// control flow branch.\n// see here: https://www.typescriptlang.org/docs/handbook/2/narrowing.html\nexport function deepEqualsIgnoreKey(a: unknown, b: unknown): boolean {\n if (a === b) {\n return true\n }\n\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length != b.length) return false\n for (let i = 0; i < a.length; i++) {\n if (!deepEqualsIgnoreKey(a[i], b[i])) {\n return false\n }\n }\n return true\n }\n\n if (Array.isArray(a) != Array.isArray(b)) {\n return false\n }\n\n if (a && b && typeof a === 'object' && typeof b === 'object') {\n const keys = Object.keys(a).filter((key) => key !== '_key')\n if (keys.length !== Object.keys(b).filter((key) => key !== '_key').length) {\n return false\n }\n\n if (a instanceof Date && b instanceof Date) {\n return a.getTime() === b.getTime()\n }\n\n if (a instanceof Date != b instanceof Date) {\n return false\n }\n\n if (a instanceof RegExp && b instanceof RegExp) {\n return a.toString() == b.toString()\n }\n\n if (a instanceof RegExp != b instanceof RegExp) {\n return false\n }\n\n for (let i = 0; i < keys.length; i++) {\n if (!Object.prototype.hasOwnProperty.call(b, keys[i])) {\n return false\n }\n }\n\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i] as keyof typeof a\n if (!deepEqualsIgnoreKey(a[key], b[key])) {\n return false\n }\n }\n\n return true\n }\n\n return false\n}\n","// this file was adapted from a previous dependency `type-of-is`\n// https://github.com/stephenhandley/type-of-is/blob/7138a7e79f5af7c286bf8123f60843a91aaebf38/index.js\nconst _toString = {}.toString\n\nconst builtIns = [Object, Function, Array, String, Boolean, Number, Date, RegExp, Error]\n\nfunction isBuiltIn(_constructor: unknown) {\n for (let i = 0; i < builtIns.length; i++) {\n if (builtIns[i] === _constructor) return true\n }\n return false\n}\n\nexport function typeString(obj: unknown): string {\n // [object Blah] -> Blah\n const stringType = _toString.call(obj).slice(8, -1)\n if (obj === null || obj === undefined) return stringType.toLowerCase()\n\n const constructorType = (obj as object).constructor\n if (constructorType && !isBuiltIn(constructorType)) return constructorType.name\n return stringType\n}\n","/* oxlint-disable typescript/no-deprecated -- marker compatibility requires the legacy item field */\nimport {type ValidationError, type ValidationMarker, type Validators} from '@sanity/types'\n\nimport {validationMarkerCodes} from '../codes'\nimport {type LocaleSource} from '../i18n/types'\nimport {deepEqualsIgnoreKey} from '../util/deepEqualsIgnoreKey'\nimport {isLocalizedMessages, localizeMessage} from '../util/localizeMessage'\nimport {pathToString} from '../util/pathToString'\nimport {typeString} from '../util/typeString'\n\nexport const SLOW_VALIDATOR_TIMEOUT = 5000\n\nconst formatValidationErrors = (options: {\n message: string | undefined\n results: ValidationMarker[]\n operation: 'conjunction' | 'disjunction'\n i18n: LocaleSource\n}): ValidationError => {\n const message =\n options.message ||\n (options.results.length === 1\n ? options.results[0]?.message\n : // Intentionally hard-coded to use locale conjunction/disjunctions\n options.i18n.t('{{messages, list}}', {\n messages: options.results.map((err) => err.message || err.item?.message),\n formatParams: {messages: {style: 'long', type: options.operation}},\n }))\n\n return {\n code:\n options.operation === 'conjunction'\n ? validationMarkerCodes.ruleAllFailed\n : validationMarkerCodes.ruleEitherFailed,\n details: {\n causes: options.results.map(({code, details, item, message: causeMessage, path}) => ({\n code: code || validationMarkerCodes.validationFailed,\n details,\n message: causeMessage || item?.message,\n path,\n })),\n },\n message: message || 'Validation failed',\n }\n}\n\nexport const genericValidators: Validators = {\n type: (expectedType, value, message, {i18n}) => {\n const actualType = typeString(value)\n if (actualType !== expectedType && actualType !== 'undefined') {\n return {\n code: validationMarkerCodes.valueTypeMismatch,\n details: {actualType, expectedType},\n message: message || i18n.t('validation:generic.incorrect-type', {actualType, expectedType}),\n }\n }\n\n return true\n },\n\n presence: (expected, value, message, {i18n}) => {\n if (value === undefined && expected === 'required') {\n return {\n code: validationMarkerCodes.valueRequired,\n message: message || i18n.t('validation:generic.required'),\n }\n }\n\n return true\n },\n\n all: async (children, value, message, context) => {\n const resolved = await Promise.all(children.map((child) => child.validate(value, context)))\n const results = resolved.flat()\n\n if (results.length === 0) {\n return true\n }\n\n return formatValidationErrors({\n message,\n results,\n operation: 'conjunction',\n i18n: context.i18n,\n })\n },\n\n either: async (children, value, message, context) => {\n const resolved = await Promise.all(children.map((child) => child.validate(value, context)))\n const results = resolved.flat()\n\n // if one of the results is an empty array then at least one rule match\n if (resolved.find((result) => !result.length)) {\n return true\n }\n\n return formatValidationErrors({\n message,\n results,\n operation: 'disjunction',\n i18n: context.i18n,\n })\n },\n\n valid: (allowedValues, actual, message, {i18n}) => {\n const valueType = typeof actual\n if (valueType === 'undefined') {\n return true\n }\n\n const value = (valueType === 'number' || valueType === 'string') && `${actual}`\n const strValue = value && value.length > 30 ? `${value.slice(0, 30)}…` : value\n\n if (allowedValues.some((expected) => deepEqualsIgnoreKey(expected, actual))) {\n return true\n }\n\n return {\n code: validationMarkerCodes.valueNotAllowed,\n details: {allowedValuesCount: allowedValues.length},\n message:\n message ||\n i18n.t(\n 'validation:generic.not-allowed',\n value ? {context: 'hint', replace: {hint: strValue}} : {},\n ),\n }\n },\n\n custom: async (fn, value, message, context) => {\n const slowTimer = setTimeout(() => {\n // only show this warning in the studio\n if (context.environment !== 'studio') return\n\n console.warn(\n `Custom validator at ${pathToString(\n context.path,\n )} has taken more than ${SLOW_VALIDATOR_TIMEOUT}ms to respond`,\n )\n }, SLOW_VALIDATOR_TIMEOUT)\n\n let result\n try {\n result = await fn(value, context)\n } finally {\n clearTimeout(slowTimer)\n }\n\n if (isLocalizedMessages(result)) {\n return localizeMessage(result, context.i18n)\n }\n\n if (typeof result === 'string') {\n return message || result\n }\n\n return result\n },\n}\n","import {\n isArrayOfBlocksSchemaType,\n type Path,\n type PathSegment,\n type Validators,\n} from '@sanity/types'\n\nimport {validationMarkerCodes} from '../codes'\nimport {deepEqualsIgnoreKey} from '../util/deepEqualsIgnoreKey'\nimport {genericValidators} from './genericValidator'\n\nexport const arrayValidators: Validators = {\n ...genericValidators,\n\n min: (minLength, value, message, {i18n, type}) => {\n if (!value || value.length >= minLength) {\n return true\n }\n\n const context = isArrayOfBlocksSchemaType(type) ? 'blocks' : undefined\n return {\n code: validationMarkerCodes.arrayMinimumLength,\n details: {actualLength: value.length, minimumLength: minLength},\n message: message || i18n.t('validation:array.minimum-length', {minLength, context}),\n }\n },\n\n max: (maxLength, value, message, {i18n, type}) => {\n if (!value || value.length <= maxLength) {\n return true\n }\n\n const context = isArrayOfBlocksSchemaType(type) ? 'blocks' : undefined\n return {\n code: validationMarkerCodes.arrayMaximumLength,\n details: {actualLength: value.length, maximumLength: maxLength},\n message: message || i18n.t('validation:array.maximum-length', {maxLength, context}),\n }\n },\n\n length: (wantedLength, value, message, {i18n, type}) => {\n if (!value || value.length === wantedLength) {\n return true\n }\n\n const context = isArrayOfBlocksSchemaType(type) ? 'blocks' : undefined\n return {\n code: validationMarkerCodes.arrayExactLength,\n details: {actualLength: value.length, expectedLength: wantedLength},\n message: message || i18n.t('validation:array.exact-length', {wantedLength, context}),\n }\n },\n\n presence: (flag, value, message, {i18n}) => {\n if (flag === 'required' && !value) {\n return {\n code: validationMarkerCodes.valueRequired,\n message: message || i18n.t('validation:generic.required', {context: 'array'}),\n }\n }\n\n return true\n },\n\n valid: (allowedValues, values, message, {i18n}) => {\n const valueType = typeof values\n if (valueType === 'undefined') {\n return true\n }\n\n const paths: Path[] = []\n for (let i = 0; i < values.length; i++) {\n const value = values[i]\n if (allowedValues.some((expected) => deepEqualsIgnoreKey(expected, value))) {\n continue\n }\n\n const pathSegment: PathSegment = value && value._key ? {_key: value._key} : i\n paths.push([pathSegment])\n }\n\n // we emit the same message for each path we find in this array\n const sharedMessage = message || i18n.t('validation:generic.not-allowed')\n\n return paths.map((path) => ({\n code: validationMarkerCodes.valueNotAllowed,\n details: {allowedValuesCount: allowedValues.length},\n message: sharedMessage,\n path,\n }))\n },\n\n unique: (_unused, value, message, {i18n}) => {\n const dupeIndices = []\n if (!value) {\n return true\n }\n\n for (let x = 0; x < value.length; x++) {\n for (let y = x + 1; y < value.length; y++) {\n const itemA = value[x]\n const itemB = value[y]\n\n if (!deepEqualsIgnoreKey(itemA, itemB)) {\n continue\n }\n\n if (dupeIndices.indexOf(x) === -1) {\n dupeIndices.push(x)\n }\n\n if (dupeIndices.indexOf(y) === -1) {\n dupeIndices.push(y)\n }\n }\n }\n\n const paths = dupeIndices.map((idx) => {\n const item = value[idx]\n const pathSegment = item && item._key ? {_key: item._key} : idx\n return [pathSegment]\n })\n\n // we emit the same message for each path we find in this array\n const sharedMessage = message || i18n.t('validation:array.item-duplicate')\n\n return paths.map((path) => ({\n code: validationMarkerCodes.arrayDuplicateItem,\n message: sharedMessage,\n path,\n }))\n },\n}\n","import {type Validators} from '@sanity/types'\n\nimport {validationMarkerCodes} from '../codes'\nimport {genericValidators} from './genericValidator'\n\nexport const booleanValidators: Validators = {\n ...genericValidators,\n\n presence: (flag, value, message, {i18n}) => {\n if (flag === 'required' && typeof value !== 'boolean') {\n return {\n code: validationMarkerCodes.valueRequired,\n message: message || i18n.t('validation:generic.required', {context: 'boolean'}),\n }\n }\n\n return true\n },\n}\n","import {type SchemaType} from '@sanity/types'\n\nexport function getTypeChain(\n type: SchemaType | undefined,\n visited: Set<SchemaType> = new Set(),\n): SchemaType[] {\n if (!type) return []\n if (visited.has(type)) return []\n\n visited.add(type)\n\n const next = type.type ? getTypeChain(type.type, visited) : []\n return [...next, type]\n}\n","import {type SchemaType, type Validators} from '@sanity/types'\nimport * as legacyDateFormat from '@sanity/util/legacyDateFormat'\n\nimport {validationMarkerCodes} from '../codes'\nimport {getTypeChain} from '../util/getTypeChain'\nimport {genericValidators} from './genericValidator'\n\nfunction isRecord(obj: unknown): obj is Record<string, unknown> {\n return typeof obj === 'object' && obj !== null && !Array.isArray(obj)\n}\n\nconst isoDate =\n /^(?:[-+]\\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)?)?)?)?$/\n\n// TODO (eventually): move these to schema type package\ninterface DateTimeOptions {\n // @todo accept object representing `Intl.DateTimeFormatOptions`? how do we localize?\n dateFormat?: string\n timeFormat?: string\n}\n\nconst getFormattedDate = (type: SchemaType, value: Date, options?: DateTimeOptions) => {\n const dateOnly = getTypeChain(type).some((candidate) => candidate.name === 'date')\n const dateFormat = options?.dateFormat || legacyDateFormat.DEFAULT_DATE_FORMAT\n const timeFormat = options?.timeFormat || legacyDateFormat.DEFAULT_TIME_FORMAT\n\n // adding the time information in the date only case causes timezone information to be kept\n // instead of it being assumed to be UTC. This was a problem because midnight UTC is the previous\n // day in many other timezones resulting in the date displayed to be the previous day.\n return legacyDateFormat.format(value, dateOnly ? dateFormat : `${dateFormat} ${timeFormat}`, {\n useUTC: dateOnly,\n })\n}\n\nfunction parseDate(date: unknown): Date | null\nfunction parseDate(date: unknown, throwOnError: true): Date\nfunction parseDate(date: unknown, throwOnError = false): Date | null {\n if (!date) return null\n if (date === 'now') return new Date()\n\n // oxlint-disable-next-line no-explicit-any\n const parsed = new Date(date as any)\n const isInvalid = isNaN(parsed.getTime())\n if (isInvalid && throwOnError) {\n throw new Error(`Unable to parse \"${date}\" to a date`)\n }\n\n return isInvalid ? null : parsed\n}\n\nexport const dateValidators: Validators = {\n ...genericValidators,\n\n type: (_unused, value, message, {i18n}) => {\n if (typeof value === 'undefined' || isoDate.test(`${value}`)) {\n return true\n }\n\n return {\n code: validationMarkerCodes.dateInvalidFormat,\n details: {actualValue: value},\n message: message || i18n.t('validation:date.invalid-format'),\n }\n },\n\n min: (minDate, value, message, {type, i18n}) => {\n const dateVal = parseDate(value)\n const minDateVal = parseDate(minDate, true)\n\n if (!dateVal) {\n return true // `type()` should catch parse errors\n }\n\n if (!value || dateVal >= minDateVal) {\n return true\n }\n\n if (!type) {\n throw new Error(`\\`type\\` was not provided in validation context.`)\n }\n\n const dateTimeOptions: DateTimeOptions = isRecord(type.options)\n ? (type.options as DateTimeOptions)\n : {}\n\n return {\n code: validationMarkerCodes.dateMinimum,\n details: {actualValue: value, minimum: minDate},\n message:\n message ||\n // Note that the `minDate` passed here is _formatted_, while the raw value provided to the\n // validator is available as `providedMinDate`. This because the formatted date is likely\n // what the developer wants to present to the user\n i18n.t('validation:date.minimum', {\n minDate: getFormattedDate(type, minDateVal, dateTimeOptions),\n providedMinDate: minDate,\n }),\n }\n },\n\n max: (maxDate, value, message, {type, i18n}) => {\n const dateVal = parseDate(value)\n const maxDateVal = parseDate(maxDate, true)\n\n if (!dateVal) {\n return true // `type()` should catch parse errors\n }\n\n if (!value || dateVal <= maxDateVal) {\n return true\n }\n\n if (!type) {\n throw new Error(`\\`type\\` was not provided in validation context.`)\n }\n\n const dateTimeOptions: DateTimeOptions = isRecord(type.options)\n ? (type.options as DateTimeOptions)\n : {}\n\n return {\n code: validationMarkerCodes.dateMaximum,\n details: {actualValue: value, maximum: maxDate},\n message:\n message ||\n // Note that the `maxDate` passed here is _formatted_, while the raw value provided to the\n // validator is available as `providedMaxDate`. This because the formatted date is likely\n // what the developer wants to present to the user\n i18n.t('validation:date.maximum', {\n maxDate: getFormattedDate(type, maxDateVal, dateTimeOptions),\n providedMaxDate: maxDate,\n }),\n }\n },\n}\n","import {type Validators} from '@sanity/types'\n\nimport {validationMarkerCodes} from '../codes'\nimport {genericValidators} from './genericValidator'\n\nconst precisionRx = /(?:\\.(\\d+))?(?:[eE]([+-]?\\d+))?$/\n\nexport const numberValidators: Validators = {\n ...genericValidators,\n\n integer: (_unused, value, message, {i18n}) => {\n if (!Number.isInteger(value)) {\n return {\n code: validationMarkerCodes.numberInteger,\n details: {actualValue: value},\n message: message || i18n.t('validation:number.non-integer'),\n }\n }\n\n return true\n },\n\n precision: (limit, value, message, {i18n}) => {\n if (value === undefined) return true\n\n const places = value.toString().match(precisionRx)\n const decimals = Math.max(\n (places[1] ? places[1].length : 0) - (places[2] ? parseInt(places[2], 10) : 0),\n 0,\n )\n\n if (decimals > limit) {\n return {\n code: validationMarkerCodes.numberPrecision,\n details: {actualPrecision: decimals, maximumPrecision: limit},\n message: message || i18n.t('validation:number.maximum-precision', {limit}),\n }\n }\n\n return true\n },\n\n min: (minNumber, value, message, {i18n}) => {\n if (value >= minNumber) {\n return true\n }\n\n return {\n code: validationMarkerCodes.numberMinimum,\n details: {actualValue: value, minimum: minNumber},\n message: message || i18n.t('validation:number.minimum', {minNumber}),\n }\n },\n\n max: (maxNumber, value, message, {i18n}) => {\n if (value <= maxNumber) {\n return true\n }\n\n return {\n code: validationMarkerCodes.numberMaximum,\n details: {actualValue: value, maximum: maxNumber},\n message: message || i18n.t('validation:number.maximum', {maxNumber}),\n }\n },\n\n greaterThan: (threshold, value, message, {i18n}) => {\n if (value > threshold) {\n return true\n }\n\n return {\n code: validationMarkerCodes.numberGreaterThan,\n details: {actualValue: value, threshold},\n message: message || i18n.t('validation:number.greater-than', {threshold}),\n }\n },\n\n lessThan: (threshold, value, message, {i18n}) => {\n if (value < threshold) {\n return true\n }\n\n return {\n code: validationMarkerCodes.numberLessThan,\n details: {actualValue: value, threshold},\n message: message || i18n.t('validation:number.less-than', {threshold}),\n }\n },\n}\n","import {type DocumentId, getPublishedId} from '@sanity/id-utils'\nimport {\n type CustomValidatorResult,\n isReference,\n isReferenceSchemaType,\n type Validators,\n} from '@sanity/types'\n\nimport {validationMarkerCodes} from '../codes'\nimport {type InternalValidationContext} from '../types'\nimport {isLocalizedMessages, localizeMessage} from '../util/localizeMessage'\nimport {pathToString} from '../util/pathToString'\nimport {typeString} from '../util/typeString'\nimport {genericValidators, SLOW_VALIDATOR_TIMEOUT} from './genericValidator'\n\nconst metaKeys = ['_key', '_type', '_weak']\n\ninterface MediaLibraryAsset {\n currentVersion: Record<string, unknown>\n [key: string]: unknown\n}\n\nexport const objectValidators: Validators = {\n ...genericValidators,\n\n presence: (expected, value, message, {i18n}) => {\n if (expected !== 'required') {\n return true\n }\n\n const keys = value && Object.keys(value).filter((key) => !metaKeys.includes(key))\n\n if (value === undefined || (keys && keys.length === 0)) {\n return {\n code: validationMarkerCodes.valueRequired,\n message: message || i18n.t('validation:generic.required', {context: 'object'}),\n }\n }\n\n return true\n },\n\n reference: async (_unused, value: unknown, message, context) => {\n if (!value) {\n return true\n }\n\n const {type, document, getDocumentExists, i18n} = context\n\n if (!isReference(value)) {\n return {\n code: validationMarkerCodes.referenceInvalid,\n details: {actualType: typeString(value)},\n message: message || i18n.t('validation:object.not-reference'),\n }\n }\n\n if (!type) {\n throw new Error(`\\`type\\` was not provided in validation context`)\n }\n\n const getDocumentType = (context as InternalValidationContext).__internal?.getDocumentType\n const weak = 'weak' in type && type.weak\n if (weak && !getDocumentType) {\n return true\n }\n\n if (!getDocumentExists) {\n throw new Error(`\\`getDocumentExists\\` was not provided in validation context`)\n }\n\n const selfReference = document?._id && value._ref === getPublishedId(document._id as DocumentId)\n // A self-reference needs no lookup, even if the document is not published yet.\n const exists =\n selfReference || (await getDocumentExists({id: value._ref, signal: context.signal}))\n if (!exists && !weak) {\n return {\n code: validationMarkerCodes.referenceNotPublished,\n details: {referenceId: value._ref},\n message: i18n.t('validation:object.reference-not-published', {documentId: value._ref}),\n }\n }\n\n if (exists && getDocumentType && isReferenceSchemaType(type)) {\n const actualType = selfReference ? document?._type : await getDocumentType(value._ref)\n if (!actualType) {\n throw new Error(`Could not read the type of referenced document \"${value._ref}\"`)\n }\n const allowedTypes = type.to.map((target) => target.name)\n if (!allowedTypes.includes(actualType)) {\n return {\n code: validationMarkerCodes.referenceTargetTypeMismatch,\n details: {referenceId: value._ref, actualType, allowedTypes},\n message: i18n.t('validation:object.reference-target-type-mismatch', {\n actualType,\n allowedTypes: allowedTypes.join(', '),\n }),\n }\n }\n }\n\n return true\n },\n\n assetRequired: (flag, value, message, {i18n}) => {\n if (!value || !value.asset || !value.asset._ref) {\n return {\n __internal_metadata: {\n name: 'assetRequired',\n },\n code: validationMarkerCodes.assetRequired,\n details: {assetType: flag.assetType},\n message:\n message || i18n.t('validation:object.asset-required', {context: flag.assetType || ''}),\n }\n }\n\n return true\n },\n\n media: async (fn, value, message, context) => {\n const slowTimer = setTimeout(() => {\n // only show this warning in the studio\n if (context.environment !== 'studio') return\n\n console.warn(\n `Media validator at ${pathToString(\n context.path,\n )} has taken more than ${SLOW_VALIDATOR_TIMEOUT}ms to respond`,\n )\n }, SLOW_VALIDATOR_TIMEOUT)\n\n // If no value is provided, we assume the validation passes. This should be handled by the 'isRequired' validator.\n if (!value) {\n return true\n }\n\n // If the value is not an object or does not have a media reference, we return an error message.\n // It should not be allowed to use regular dataset assets with this validator.\n if (!value || !value.media || !value.media._ref) {\n return {\n code: validationMarkerCodes.mediaInvalidReference,\n message: context.i18n.t('validation:object.not-media-library-asset'),\n }\n }\n\n let result: CustomValidatorResult = true\n\n try {\n const [type, libraryId, documentId] = value.media._ref.split(':', 3)\n // TODO: replace this with stable resource config when available\n const resourceConfig = {resource: {type, id: libraryId}}\n const asset = await context\n .getClient({apiVersion: '2025-02-19'})\n .withConfig(resourceConfig)\n .fetch<MediaLibraryAsset | null>(\n `*[_id == $id] { ..., 'currentVersion': @.currentVersion-> { ... } }[0]`,\n {\n id: documentId,\n },\n {signal: context.signal},\n )\n if (!asset) {\n console.warn(\n `${context.i18n.t('validation:object.media-not-found')}\\nAsset ID: ${value.media._ref}`,\n )\n return {\n code: validationMarkerCodes.mediaNotFound,\n details: {referenceId: value.media._ref},\n message: context.i18n.t('validation:object.media-not-found'),\n }\n }\n\n result = await fn(\n {\n media: {\n asset: asset as unknown as Parameters<typeof fn>[0]['media']['asset'],\n },\n value,\n },\n context,\n )\n } catch (err) {\n const error = new Error(\n `Media validator at ${pathToString(\n context.path,\n )} failed with an error: ${err instanceof Error ? err.message : String(err)}`,\n {cause: err},\n )\n throw error\n } finally {\n clearTimeout(slowTimer)\n }\n\n const validationErrorMetadata = {\n __internal_metadata: {\n name: 'media',\n },\n }\n\n // Valid, no errors\n if (result === true) {\n return result\n }\n\n // Ensure we always return ValidationMarker with metadata\n return Array.isArray(result)\n ? result\n : [result].map((res) => {\n if (typeof res === 'string') {\n return {...validationErrorMetadata, message: message || res}\n }\n if (isLocalizedMessages(res)) {\n return {\n ...validationErrorMetadata,\n message: message || localizeMessage(res, context.i18n),\n }\n }\n return {...validationErrorMetadata, ...res, message: message || res.message}\n })\n },\n}\n","import {type DocumentId, getPublishedId} from '@sanity/id-utils'\nimport {\n type CustomValidator,\n isKeyedObject,\n isSlug,\n type Path,\n type SlugIsUniqueValidator,\n type SlugParent,\n type SlugSchemaType,\n type SlugValidationContext,\n} from '@sanity/types'\nimport memoize from 'lodash-es/memoize.js'\n\nimport {validationMarkerCodes} from '../codes'\nimport {typeString} from '../util/typeString'\n\nconst DEFAULT_API_VERSION = '2025-02-19'\n\nconst memoizedWarnOnArraySlug = memoize(warnOnArraySlug)\n\nexport function hasCustomSlugUniqueness(\n options: unknown,\n): options is {isUnique: SlugIsUniqueValidator} {\n return (\n typeof options === 'object' &&\n options !== null &&\n 'isUnique' in options &&\n typeof options.isUnique === 'function'\n )\n}\n\nfunction serializePath(path: Path): string {\n return path.reduce<string>((target, part, i) => {\n const isIndex = typeof part === 'number'\n const isKey = isKeyedObject(part)\n const separator = i === 0 ? '' : '.'\n const add = isIndex || isKey ? '[]' : `${separator}${part}`\n return `${target}${add}`\n }, '')\n}\n\nconst defaultIsUnique: SlugIsUniqueValidator = (slug, context) => {\n const {getClient, document, path, type} = context\n const schemaOptions = type?.options\n\n if (!document) {\n throw new Error(`\\`document\\` was not provided in validation context.`)\n }\n if (!path) {\n throw new Error(`\\`path\\` was not provided in validation context.`)\n }\n\n const disableArrayWarning = schemaOptions?.disableArrayWarning || false\n const docType = document._type\n const atPath = serializePath(path.concat('current'))\n\n if (!disableArrayWarning && atPath.includes('[]') && context.environment === 'studio') {\n memoizedWarnOnArraySlug(serializePath(path))\n }\n\n const constraints = [\n '_type == $docType',\n `!sanity::versionOf($published)`,\n `${atPath} == $slug`,\n ].join(' && ')\n\n return getClient({apiVersion: DEFAULT_API_VERSION})\n .withConfig({perspective: 'raw'})\n .fetch<boolean>(\n `!defined(*[${constraints}][0]._id)`,\n {\n docType,\n published: getPublishedId(document._id as DocumentId),\n slug,\n },\n {signal: context.signal, tag: 'validation.slug-is-unique'},\n )\n}\n\nfunction warnOnArraySlug(serializedPath: string) {\n console.warn(\n [\n `Slug field at path ${serializedPath} is within an array and cannot be automatically checked for uniqueness`,\n `If you need to check for uniqueness, provide your own \"isUnique\" method`,\n `To disable this message, set \\`disableArrayWarning: true\\` on the slug \\`options\\` field`,\n ].join('\\n'),\n )\n}\n\nexport const slugStructureValidator: CustomValidator = (value, context) => {\n if (!value) {\n return true\n }\n\n const {i18n} = context\n\n if (typeof value !== 'object' || Array.isArray(value)) {\n return {\n code: validationMarkerCodes.slugInvalidType,\n details: {actualType: typeString(value)},\n message: i18n.t('validation:slug.not-object'),\n }\n }\n\n if (!isSlug(value) || value.current.trim().length === 0) {\n return {\n code: validationMarkerCodes.slugMissingCurrent,\n message: i18n.t('validation:slug.missing-current'),\n }\n }\n\n return true\n}\n\nasync function validateSlugUniqueness(\n value: unknown,\n context: Parameters<CustomValidator>[1],\n isUnique: SlugIsUniqueValidator,\n) {\n if (!isSlug(value) || value.current.trim().length === 0) {\n return true\n }\n\n const {i18n} = context\n const slugContext: SlugValidationContext = {\n ...context,\n parent: context.parent as SlugParent,\n type: context.type as SlugSchemaType,\n defaultIsUnique,\n }\n\n const wasUnique = await isUnique(value.current, slugContext)\n if (wasUnique) {\n return true\n }\n\n return {\n code: validationMarkerCodes.slugNotUnique,\n details: {slug: value.current},\n message: i18n.t('validation:slug.not-unique', {slug: value.current}),\n }\n}\n\nexport const slugUniquenessValidator: CustomValidator = (value, context) => {\n const options = context.type?.options\n const isUnique = hasCustomSlugUniqueness(options) ? options.isUnique : defaultIsUnique\n return validateSlugUniqueness(value, context, isUnique)\n}\n","import {type Validators} from '@sanity/types'\n\nimport {validationMarkerCodes} from '../codes'\nimport {genericValidators} from './genericValidator'\n\nconst DUMMY_ORIGIN = 'http://sanity'\nconst isRelativeUrl = (url: string) => /^\\.*\\//.test(url)\n\n// WHATWG \"special\" schemes, whose hosts are domains rather than opaque strings\nconst SPECIAL_SCHEMES = new Set(['http:', 'https:', 'ws:', 'wss:', 'ftp:', 'file:'])\n// WHATWG \"forbidden domain code point\"\nconst FORBIDDEN_DOMAIN_CODE_POINT = /[\\p{Cc} #/:<>?@[\\\\\\]^|%]/u\n\n// Node follows the spec and fails to parse a domain that percent-decodes to a forbidden code point,\n// but Chrome keeps `%20` in `hostname` and accepts it, so check the decoded host ourselves\nfunction hasInvalidDomain(url: URL): boolean {\n if (!SPECIAL_SCHEMES.has(url.protocol) || url.hostname.startsWith('[')) return false\n try {\n return FORBIDDEN_DOMAIN_CODE_POINT.test(decodeURIComponent(url.hostname))\n } catch {\n return true\n }\n}\nconst emailRegex =\n /^(([^<>()[\\]\\\\.,;:\\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,}))$/\n\nexport const stringValidators: Validators = {\n ...genericValidators,\n\n min: (minLength, value, message, {i18n}) => {\n if (!value || value.length >= minLength) {\n return true\n }\n\n return {\n code: validationMarkerCodes.stringMinimumLength,\n details: {actualLength: value.length, minimumLength: minLength},\n message: message || i18n.t('validation:string.minimum-length', {minLength}),\n }\n },\n\n max: (maxLength, value, message, {i18n}) => {\n if (!value || value.length <= maxLength) {\n return true\n }\n\n return {\n code: validationMarkerCodes.stringMaximumLength,\n details: {actualLength: value.length, maximumLength: maxLength},\n message: message || i18n.t('validation:string.maximum-length', {maxLength}),\n }\n },\n\n length: (wantedLength, value, message, {i18n}) => {\n const strValue = value || ''\n if (strValue.length === wantedLength) {\n return true\n }\n\n return {\n code: validationMarkerCodes.stringExactLength,\n details: {actualLength: strValue.length, expectedLength: wantedLength},\n message: message || i18n.t('validation:string.exact-length', {wantedLength}),\n }\n },\n\n uri: (constraints, value, message, {i18n}) => {\n const strValue = value || ''\n if (!strValue) {\n return true // `presence()` should catch empty values\n }\n\n const {options} = constraints\n const {allowCredentials, relativeOnly} = options\n const allowRelative = options.allowRelative || relativeOnly\n\n const invalidUrl = {\n code: validationMarkerCodes.stringUrlInvalid,\n message: message || i18n.t('validation:string.url.invalid'),\n }\n\n let url\n try {\n // WARNING: Safari checks for a given `base` param by looking at the length of arguments passed\n // to new URL(str, base), and will fail if invoked with new URL(strValue, undefined)\n url = allowRelative ? new URL(strValue, DUMMY_ORIGIN) : new URL(strValue)\n } catch {\n return invalidUrl\n }\n\n if (hasInvalidDomain(url)) {\n return invalidUrl\n }\n\n if (relativeOnly && url.origin !== DUMMY_ORIGIN) {\n return {\n code: validationMarkerCodes.stringUrlNotRelative,\n message: message || i18n.t('validation:string.url.not-relative'),\n }\n }\n\n if (!allowRelative && url.origin === DUMMY_ORIGIN && isRelativeUrl(strValue)) {\n return {\n code: validationMarkerCodes.stringUrlNotAbsolute,\n message: message || i18n.t('validation:string.url.not-absolute'),\n }\n }\n\n if (!allowCredentials && (url.username || url.password)) {\n return {\n code: validationMarkerCodes.stringUrlCredentialsNotAllowed,\n message: message || i18n.t('validation:string.url.includes-credentials'),\n }\n }\n\n const urlScheme = url.protocol.replace(/:$/, '')\n const isRelative = isRelativeUrl(strValue)\n const matchesAllowedScheme =\n isRelative || options.scheme.some((scheme) => scheme.test(urlScheme))\n if (!matchesAllowedScheme) {\n return {\n code: validationMarkerCodes.stringUrlSchemeNotAllowed,\n details: {scheme: urlScheme},\n message: message || i18n.t('validation:string.url.disallowed-scheme', {scheme: urlScheme}),\n }\n }\n\n return true\n },\n\n stringCasing: (casing, value, message, {i18n}) => {\n const strValue = value || ''\n if (casing === 'uppercase' && strValue !== strValue.toLocaleUpperCase()) {\n return {\n code: validationMarkerCodes.stringUppercase,\n message: message || i18n.t('validation:string.uppercase'),\n }\n }\n\n if (casing === 'lowercase' && strValue !== strValue.toLocaleLowerCase()) {\n return {\n code: validationMarkerCodes.stringLowercase,\n message: message || i18n.t('validation:string.lowercase'),\n }\n }\n\n return true\n },\n\n presence: (flag, value, message, {i18n}) => {\n if (flag === 'required' && !value) {\n return {\n code: validationMarkerCodes.valueRequired,\n message: message || i18n.t('validation:generic.required', {context: 'string'}),\n }\n }\n\n return true\n },\n\n regex: (options, value, message, {i18n}) => {\n const {pattern, name, invert} = options\n const regName = name || `${pattern.toString()}`\n const strValue = value || ''\n // Regexes with global or sticky flags are stateful (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/lastIndex).\n // This resets the state stored from the previous check\n pattern.lastIndex = 0\n const matches = pattern.test(strValue)\n if ((!invert && !matches) || (invert && matches)) {\n return {\n code: invert\n ? validationMarkerCodes.stringRegexMatch\n : validationMarkerCodes.stringRegexMismatch,\n details: {invert, name: regName, pattern: pattern.source},\n message:\n message ||\n (invert\n ? i18n.t('validation:string.regex-match', {name: regName})\n : i18n.t('validation:string.regex-does-not-match', {name: regName})),\n }\n }\n\n return true\n },\n\n email: (_unused, value, message, {i18n}) => {\n const strValue = `${value || ''}`.trim()\n if (!strValue || emailRegex.test(strValue)) {\n return true\n }\n\n return {\n code: validationMarkerCodes.stringEmail,\n message: message || i18n.t('validation:string.email'),\n }\n },\n}\n","/* oxlint-disable typescript/no-deprecated -- this is the concrete implementation of the legacy Rule internals */\nimport {Rule as BaseRule} from '@sanity/schema'\nimport {isInternalValidator} from '@sanity/schema/_internal'\nimport {\n type CustomValidator,\n type Rule as IRule,\n type RuleClass,\n type SchemaType,\n type ValidationMarker,\n type Validator,\n} from '@sanity/types'\nimport get from 'lodash-es/get.js'\n\nimport {ClientUnavailableError} from './clientUnavailable'\nimport {validationMarkerCodes} from './codes'\nimport {type InternalValidationContext} from './types'\nimport {convertToValidationMarker} from './util/convertToValidationMarker'\nimport {isLocalizedMessages, localizeMessage} from './util/localizeMessage'\nimport {pathToString} from './util/pathToString'\nimport {arrayValidators} from './validators/arrayValidator'\nimport {booleanValidators} from './validators/booleanValidator'\nimport {dateValidators} from './validators/dateValidator'\nimport {genericValidators} from './validators/genericValidator'\nimport {numberValidators} from './validators/numberValidator'\nimport {objectValidators} from './validators/objectValidator'\nimport {hasCustomSlugUniqueness, slugUniquenessValidator} from './validators/slugValidator'\nimport {stringValidators} from './validators/stringValidator'\n\nconst typeValidators = {\n Boolean: booleanValidators,\n Number: numberValidators,\n String: stringValidators,\n Array: arrayValidators,\n Object: objectValidators,\n Date: dateValidators,\n}\n\nconst isFieldRef = (constraint: unknown): constraint is {type: symbol; path: string | string[]} => {\n if (typeof constraint !== 'object' || !constraint) return false\n return (constraint as Record<string, unknown>).type === Rule.FIELD_REF\n}\n\nconst EMPTY_ARRAY: unknown[] = []\n\nconst fallbackCodeForRule = (flag: string) => {\n if (flag === 'custom') return validationMarkerCodes.custom\n if (flag === 'media') return validationMarkerCodes.mediaCustom\n if (flag === 'all') return validationMarkerCodes.ruleAllFailed\n if (flag === 'either') return validationMarkerCodes.ruleEitherFailed\n return validationMarkerCodes.validationFailed\n}\n\n/**\n * Concrete Rule implementation with validation logic.\n * This extends the base Rule class from `@sanity/schema` and adds the validate method.\n *\n * Note: `RuleClass` and `Rule` are split to fit the current `@sanity/types`\n * setup. Classes are a bit weird in the `@sanity/types` package because classes\n * create an actual javascript class while simultaneously creating a type\n * definition.\n *\n * This implicitly creates two types:\n * 1. the instance type — `Rule` and\n * 2. the static/class type - `RuleClass`\n *\n * The `RuleClass` type contains the static methods and the `Rule` instance\n * contains the instance methods.\n *\n * This package exports the RuleClass as a value without implicitly exporting\n * an instance definition. This should help reminder downstream users to import\n * from the `@sanity/types` package.\n *\n * @internal\n */\n// export class Rule extends BaseRule implements IRule {\nexport const Rule: RuleClass = class Rule extends BaseRule implements IRule {\n static array = (def?: SchemaType): Rule => new Rule(def).type('Array')\n static object = (def?: SchemaType): Rule => new Rule(def).type('Object')\n static string = (def?: SchemaType): Rule => new Rule(def).type('String')\n static number = (def?: SchemaType): Rule => new Rule(def).type('Number')\n static boolean = (def?: SchemaType): Rule => new Rule(def).type('Boolean')\n static dateTime = (def?: SchemaType): Rule => new Rule(def).type('Date')\n\n clone(): Rule {\n const rule = new Rule()\n rule._type = this._type\n rule._message = this._message\n rule._required = this._required\n rule._rules = [...this._rules]\n rule._level = this._level\n rule._fieldRules = this._fieldRules\n rule._typeDef = this._typeDef\n return rule\n }\n\n async validate(\n value: unknown,\n options: Parameters<IRule['validate']>[1],\n ): Promise<ValidationMarker[]> {\n const {__internal = {}, ...context} = options as InternalValidationContext\n const {customValidation = true, customValidationConcurrencyLimiter, markIncomplete} = __internal\n\n const valueIsEmpty = value === null || value === undefined\n\n // Short-circuit on optional, empty fields\n if (valueIsEmpty && this._required === 'optional') {\n return EMPTY_ARRAY as ValidationMarker[]\n }\n\n const rules =\n // Run only the _custom_ functions if the rule is not set to required or optional\n this._required === undefined && valueIsEmpty\n ? this._rules.filter((curr) => curr.flag === 'custom')\n : this._rules\n\n const validators = (this._type && typeValidators[this._type]) || genericValidators\n\n const results = await Promise.all(\n rules.map(async (curr) => {\n if (curr.flag === undefined) {\n throw new Error('Invalid rule, did not contain \"flag\"-property')\n }\n\n const validator: Validator | undefined = validators[curr.flag]\n if (!validator) {\n const forType = this._type ? `type \"${this._type}\"` : 'rule without declared type'\n throw new Error(`Validator for flag \"${curr.flag}\" not found for ${forType}`)\n }\n\n let specConstraint = 'constraint' in curr ? curr.constraint : null\n if (isFieldRef(specConstraint)) {\n specConstraint = get(context.parent, specConstraint.path)\n }\n\n if (curr.flag === 'custom' || curr.flag === 'media') {\n // Slug rules can be inherited from a compiled base type, so classify the\n // callback using the actual field's options at validation time.\n const usesCustomSlugUniqueness =\n specConstraint === slugUniquenessValidator &&\n hasCustomSlugUniqueness(context.type?.options)\n if (\n (!isInternalValidator(specConstraint) || usesCustomSlugUniqueness) &&\n !customValidation\n ) {\n markIncomplete?.()\n return []\n }\n }\n\n if (\n curr.flag === 'custom' &&\n customValidationConcurrencyLimiter &&\n !(specConstraint as CustomValidator)?.bypassConcurrencyLimit\n ) {\n const customValidator = specConstraint as CustomValidator\n specConstraint = (...args: Parameters<CustomValidator>) =>\n customValidationConcurrencyLimiter.run(() => customValidator(...args), context.signal)\n }\n\n const message = isLocalizedMessages(this._message)\n ? localizeMessage(this._message, context.i18n)\n : this._message\n\n try {\n // Built-in reference and composite rules need run state. Custom\n // callbacks still receive only the public validation context.\n const validatorContext =\n curr.flag === 'reference' || curr.flag === 'all' || curr.flag === 'either'\n ? {...context, __internal}\n : context\n const result = await validator(specConstraint, value, message, validatorContext)\n return convertToValidationMarker(result, this._level, context, {\n code: fallbackCodeForRule(curr.flag),\n })\n } catch (err) {\n context.signal?.throwIfAborted()\n markIncomplete?.()\n if (err instanceof ClientUnavailableError) {\n return []\n }\n\n const errorMessage = `${pathToString(\n context.path,\n )}: Exception occurred while validating value: ${err.message}`\n\n return convertToValidationMarker(\n {code: validationMarkerCodes.validationException, message: errorMessage},\n 'error',\n context,\n )\n }\n }),\n )\n\n return results.flat()\n }\n}\n","import {type SanityClient} from '@sanity/client'\n\ninterface AvailabilityResponse {\n omitted: {id: string; reason: 'existence' | 'permission'}[]\n}\n\n/** The amount of time reserved for waiting for new IDs. */\nconst BUFFER_TIME = 250\n\n/** The upper limit for IDs sent to the `doc` endpoint at once. */\nexport const MAX_BUFFER_SIZE = 100\n\n/** The `doc` endpoint is expensive, so batches are sent one at a time. */\nexport const MAX_REQUEST_CONCURRENCY = 1\n\ninterface PendingCheck {\n reject: (reason: unknown) => void\n resolve: (exists: boolean) => void\n settled: boolean\n signal?: AbortSignal\n onAbort?: () => void\n}\n\ntype Batch = Map<string, PendingCheck[]>\n\nfunction hasPendingChecks(batch: Batch): boolean {\n for (const checks of batch.values()) {\n if (checks.some((check) => !check.settled)) return true\n }\n return false\n}\n\nfunction settleCheck(check: PendingCheck, result: {exists: boolean} | {error: unknown}): void {\n if (check.settled) return\n check.settled = true\n if (check.signal && check.onAbort) {\n check.signal.removeEventListener('abort', check.onAbort)\n }\n if ('error' in result) check.reject(result.error)\n else check.resolve(result.exists)\n}\n\nexport function createBatchedGetDocumentExists(\n client: SanityClient,\n defaultSignal?: AbortSignal,\n): (options: {id: string; signal?: AbortSignal}) => Promise<boolean> {\n let buffer: Batch = new Map()\n const queuedBatches: Batch[] = []\n let bufferTimer: ReturnType<typeof setTimeout> | undefined\n let draining = false\n let activeRequest: {batch: Batch; controller: AbortController} | undefined\n\n const rejectBatch = (batch: Batch, reason: unknown) => {\n for (const checks of batch.values()) {\n for (const check of checks) settleCheck(check, {error: reason})\n }\n }\n\n const rejectPending = (reason: unknown) => {\n if (bufferTimer !== undefined) clearTimeout(bufferTimer)\n bufferTimer = undefined\n rejectBatch(buffer, reason)\n buffer = new Map()\n for (const batch of queuedBatches.splice(0)) rejectBatch(batch, reason)\n }\n\n const flush = () => {\n if (bufferTimer !== undefined) clearTimeout(bufferTimer)\n bufferTimer = undefined\n if (buffer.size === 0) return\n\n queuedBatches.push(buffer)\n buffer = new Map()\n void drain()\n }\n\n const scheduleFlush = () => {\n if (buffer.size >= MAX_BUFFER_SIZE) {\n flush()\n } else if (bufferTimer === undefined) {\n bufferTimer = setTimeout(flush, BUFFER_TIME)\n }\n }\n\n async function drain() {\n if (draining) return\n draining = true\n try {\n while (queuedBatches.length > 0) {\n defaultSignal?.throwIfAborted()\n const batch = queuedBatches.shift()\n if (!batch) continue\n const ids = [...batch.entries()]\n .filter(([, checks]) => checks.some((check) => !check.settled))\n .map(([id]) => id)\n if (ids.length === 0) continue\n\n const controller = new AbortController()\n const abortRequest = () => controller.abort(defaultSignal?.reason)\n defaultSignal?.addEventListener('abort', abortRequest, {once: true})\n activeRequest = {batch, controller}\n\n try {\n // The endpoint is intentionally limited to one request at a time.\n // oxlint-disable-next-line no-await-in-loop\n const availability = await client.request<AvailabilityResponse>({\n url: client.getDataUrl('doc', ids.join(',')),\n query: {excludeContent: 'true'},\n signal: controller.signal,\n tag: 'documents-availability',\n })\n const missingIds = new Set(\n availability.omitted.filter(({reason}) => reason === 'existence').map(({id}) => id),\n )\n for (const id of ids) {\n for (const check of batch.get(id) ?? []) {\n settleCheck(check, {exists: !missingIds.has(id)})\n }\n }\n } catch (error) {\n if (controller.signal.aborted && !defaultSignal?.aborted && !hasPendingChecks(batch)) {\n // Every caller left this batch, so its cancellation must not fail later batches.\n continue\n }\n rejectBatch(batch, error)\n rejectPending(error)\n return\n } finally {\n defaultSignal?.removeEventListener('abort', abortRequest)\n activeRequest = undefined\n }\n }\n } catch (error) {\n rejectPending(error)\n } finally {\n draining = false\n }\n }\n\n return function getDocumentExists(options) {\n const signal = options.signal || defaultSignal\n if (signal?.aborted) return Promise.reject(signal.reason)\n\n return new Promise<boolean>((resolve, reject) => {\n const check: PendingCheck = {reject, resolve, settled: false, signal}\n if (signal) {\n check.onAbort = () => {\n settleCheck(check, {error: signal.reason})\n if (activeRequest && !hasPendingChecks(activeRequest.batch)) {\n activeRequest.controller.abort(signal.reason)\n }\n }\n signal.addEventListener('abort', check.onAbort, {once: true})\n }\n\n const checks = buffer.get(options.id)\n if (checks) checks.push(check)\n else buffer.set(options.id, [check])\n scheduleFlush()\n })\n }\n}\n","import {type SanityClient} from '@sanity/client'\n\nconst MAX_BATCH_SIZE = 100\n\ninterface PendingType {\n resolve: (type: string | undefined) => void\n reject: (error: unknown) => void\n}\n\n/** Batches metadata reads and shares each target's result for one validation run. */\nexport function createBatchedGetDocumentType(\n getClient: () => SanityClient,\n signal?: AbortSignal,\n): (id: string) => Promise<string | undefined> {\n const cache = new Map<string, Promise<string | undefined>>()\n let pending = new Map<string, PendingType>()\n let timer: ReturnType<typeof setTimeout> | undefined\n\n async function flush() {\n clearTimeout(timer)\n timer = undefined\n const batch = pending\n pending = new Map()\n try {\n signal?.throwIfAborted()\n const documents = await getClient().fetch<{_id: string; _type: string}[]>(\n '*[_id in $ids]{_id, _type}',\n {ids: [...batch.keys()]},\n {perspective: 'raw', useCdn: false, signal, tag: 'validation.reference-types'},\n )\n const types = new Map(documents.map((document) => [document._id, document._type]))\n for (const [id, check] of batch) check.resolve(types.get(id))\n } catch (error) {\n for (const check of batch.values()) check.reject(error)\n }\n }\n\n return (id) => {\n if (signal?.aborted) return Promise.reject(signal.reason)\n const cached = cache.get(id)\n if (cached) return cached\n const result = new Promise<string | undefined>((resolve, reject) => {\n pending.set(id, {resolve, reject})\n })\n cache.set(id, result)\n if (pending.size >= MAX_BATCH_SIZE) void flush()\n else timer ??= setTimeout(() => void flush(), 0)\n return result\n }\n}\n","import {type CustomValidator, type ValidationContext} from '@sanity/types'\nimport {accepts} from '@sanity/util/accepts'\n\nimport {validationMarkerCodes} from '../codes'\n\nconst DEFAULT_API_VERSION = '2025-02-19'\n\nconst ASSET_FILE_TYPE_QUERY = `*[_id == $id][0]{mimeType, extension, originalFilename}`\n\ntype AssetFileType = {\n mimeType?: string | null\n extension?: string | null\n originalFilename?: string | null\n}\n\nexport type AcceptedAssetType = 'image' | 'file'\n\n// Asset ids are content hashes, so a resolved file type never changes for a given id.\nconst resolvedFileTypes = new Map<string, AssetFileType>()\n\nfunction isUnknownFileType(fileType: AssetFileType): boolean {\n return [fileType.mimeType, fileType.extension].every((value) => (value ?? '') === '')\n}\n\n/**\n * Checks a stored asset against an HTML `accept` string with the same matcher uploads and\n * copy-paste use.\n *\n * @internal\n */\nexport function assetMatchesAccept(fileType: AssetFileType, accept: string): boolean {\n const type = fileType.mimeType ?? ''\n return (\n accepts({type, name: getAssetFilename(fileType)}, accept) ||\n // Linked assets can have an original filename without the stored extension.\n Boolean(fileType.extension && accepts({type, name: `asset.${fileType.extension}`}, accept))\n )\n}\n\nfunction getAssetFilename(fileType: AssetFileType): string | undefined {\n if (fileType.originalFilename) return fileType.originalFilename\n return fileType.extension ? `asset.${fileType.extension}` : undefined\n}\n\nfunction getAssetId(value: unknown): string | undefined {\n if (typeof value === 'object' && value !== null && 'asset' in value) {\n const {asset} = value\n if (typeof asset === 'object' && asset !== null && '_ref' in asset) {\n return typeof asset._ref === 'string' ? asset._ref : undefined\n }\n }\n return undefined\n}\n\nasync function fetchAssetFileType(\n assetId: string,\n context: ValidationContext,\n): Promise<AssetFileType | null> {\n const cached = resolvedFileTypes.get(assetId)\n if (cached) return cached\n\n const fileType = await context\n .getClient({apiVersion: DEFAULT_API_VERSION})\n .fetch<AssetFileType | null>(\n ASSET_FILE_TYPE_QUERY,\n {id: assetId},\n {signal: context.signal, tag: 'validation.asset-accept'},\n )\n if (fileType) resolvedFileTypes.set(assetId, fileType)\n return fileType\n}\n\n/** @internal */\nexport function createAssetAcceptValidator(\n accept: string,\n assetType: AcceptedAssetType,\n): CustomValidator {\n return async (value, context) => {\n const assetId = getAssetId(value)\n if (assetId === undefined) return true\n\n const fileType = await fetchAssetFileType(assetId, context)\n if (fileType === null || isUnknownFileType(fileType) || assetMatchesAccept(fileType, accept)) {\n return true\n }\n\n return {\n code: validationMarkerCodes.assetNotAccepted,\n details: {accept, mimeType: fileType.mimeType, extension: fileType.extension},\n message: context.i18n.t('validation:object.asset-not-accepted', {\n context: assetType,\n mimeType: fileType.mimeType ?? fileType.extension,\n }),\n }\n }\n}\n","import {markInternalValidator} from '@sanity/schema/_internal'\nimport {\n isArrayOfObjectsSchemaType,\n type Rule,\n type RuleSpec,\n type RuleTypeConstraint,\n type SchemaType,\n type SchemaValidationValue,\n type ValidationContext,\n} from '@sanity/types'\nimport {dequal as isEqual} from 'dequal/lite'\n\nimport {Rule as RuleClass} from '../Rule'\nimport {\n type AcceptedAssetType,\n createAssetAcceptValidator,\n} from '../validators/assetAcceptValidator'\nimport {slugStructureValidator, slugUniquenessValidator} from '../validators/slugValidator'\nimport {getTypeChain} from './getTypeChain'\n\nexport {getTypeChain} from './getTypeChain'\n\nconst ruleConstraintTypes: {[P in Lowercase<RuleTypeConstraint>]: true} = {\n array: true,\n boolean: true,\n date: true,\n number: true,\n object: true,\n string: true,\n}\n\nconst isRuleConstraint = (typeString: string): typeString is Lowercase<RuleTypeConstraint> =>\n typeString in ruleConstraintTypes\n\nconst compiledValidations = new WeakMap<\n object,\n {type: SchemaType; definition: SchemaValidationValue | undefined; rules: Rule[]}\n>()\n\nexport function compileValidationRules(type: SchemaType): Rule[] {\n const inherited = Array.isArray(type.validation)\n ? compiledValidations.get(type.validation)\n : undefined\n const definition = inherited ? inherited.definition : type.validation\n const rules = normalizeValidationRules(type)\n compiledValidations.set(rules, {type, definition, rules})\n return rules\n}\n\nfunction baseRuleReducer(baseRule: Rule, type: SchemaType) {\n if (type.name === 'datetime') return baseRule.type('Date')\n if (type.name === 'date') return baseRule.type('Date')\n if (type.name === 'url') return baseRule.uri()\n if (type.name === 'slug') {\n return baseRule\n .custom(markInternalValidator(slugStructureValidator), {bypassConcurrencyLimit: true})\n .custom(markInternalValidator(slugUniquenessValidator), {bypassConcurrencyLimit: true})\n }\n if (type.name === 'reference') return baseRule.reference()\n if (type.name === 'email') return baseRule.email()\n return baseRule\n}\n\nfunction hasValueField(typeDef: SchemaType | undefined): boolean {\n if (!typeDef) return false\n if (!('fields' in typeDef) && typeDef.type) return hasValueField(typeDef.type)\n if (!('fields' in typeDef)) return false\n if (!Array.isArray(typeDef.fields)) return false\n return typeDef.fields.some((field) => field.name === 'value')\n}\n\nfunction extractValueFromListOption(option: unknown, typeDef: SchemaType): unknown {\n if (isArrayOfObjectsSchemaType(typeDef)) return option\n\n // If you define a `list` option with object items, where the item has a `value` field,\n // we don't want to treat that as the value but rather the surrounding object\n // This differs from the case where you have a title/value pair setup for a string/number, for instance\n if (typeDef.jsonType === 'object' && hasValueField(typeDef)) return option\n\n return (option as Record<string, unknown>).value === undefined\n ? option\n : (option as Record<string, unknown>).value\n}\n\nconst isUriSpec = (spec: RuleSpec): spec is Extract<RuleSpec, {flag: 'uri'}> => spec.flag === 'uri'\n\n// A `url` type auto-injects the default `.uri()` onto every array element, so a\n// custom scheme on one element cannot override the default on its siblings (GH #3298).\nfunction omitLeakedDefaultUri(rules: Rule[], typeDef: SchemaType): Rule[] {\n const isUrlType = getTypeChain(typeDef).some((type) => type.name === 'url')\n if (!isUrlType) return rules\n\n // oxlint-disable-next-line no-deprecated -- will fix in follow up PR\n const defaultUri = new RuleClass(typeDef).uri()._rules.find(isUriSpec)?.constraint\n const isDefaultUri = (spec: RuleSpec) => isUriSpec(spec) && isEqual(spec.constraint, defaultUri)\n const isCustomUri = (spec: RuleSpec) => isUriSpec(spec) && !isEqual(spec.constraint, defaultUri)\n\n // oxlint-disable-next-line no-deprecated -- will fix in follow up PR\n const someElementSetsScheme = rules.some((rule) => rule._rules.some(isCustomUri))\n if (!someElementSetsScheme) return rules\n\n return rules.map((rule) => {\n // oxlint-disable-next-line no-deprecated -- will fix in follow up PR\n if (!rule._rules.some(isDefaultUri)) return rule\n const cleaned = rule.clone()\n // oxlint-disable-next-line no-deprecated -- will fix in follow up PR\n cleaned._rules = rule._rules.filter((spec) => !isDefaultUri(spec))\n return cleaned\n })\n}\n\nexport function normalizeValidationRules(\n typeDef: SchemaType | undefined,\n context?: ValidationContext,\n): Rule[] {\n if (!typeDef) {\n return []\n }\n\n const compiled = Array.isArray(typeDef.validation)\n ? compiledValidations.get(typeDef.validation)\n : undefined\n if (compiled) {\n if (compiled.type === typeDef) return compiled.rules\n // Derived fields inherit compiled rules, but their options can differ. Rebuild\n // from the authored definition instead of reusing the ancestor's constraints.\n return normalizeValidationRules({...typeDef, validation: compiled.definition}, context)\n }\n\n return [...normalizeAuthoredRules(typeDef, context), ...inferAssetAcceptRules(typeDef)]\n}\n\nfunction isAcceptedAssetType(name: string): name is AcceptedAssetType {\n return name === 'image' || name === 'file'\n}\n\nfunction getAcceptOption(typeDef: SchemaType): string {\n const options = typeDef.options\n if (\n options &&\n typeof options === 'object' &&\n 'accept' in options &&\n typeof options.accept === 'string'\n ) {\n return options.accept.trim()\n }\n return ''\n}\n\n// A separate rule, so the inferred check stays a warning whatever level the authored rules use.\nfunction inferAssetAcceptRules(typeDef: SchemaType): Rule[] {\n const accept = getAcceptOption(typeDef)\n const assetType = getTypeChain(typeDef)\n .map((type) => type.name)\n .find(isAcceptedAssetType)\n\n if (accept && assetType) {\n return [\n new RuleClass(typeDef)\n .custom(markInternalValidator(createAssetAcceptValidator(accept, assetType)), {\n bypassConcurrencyLimit: true,\n })\n .warning(),\n ]\n }\n return []\n}\n\nfunction normalizeAuthoredRules(typeDef: SchemaType, context?: ValidationContext): Rule[] {\n const compiled = Array.isArray(typeDef.validation)\n ? compiledValidations.get(typeDef.validation)\n : undefined\n if (compiled) {\n return normalizeAuthoredRules({...typeDef, validation: compiled.definition}, context)\n }\n\n const validation = typeDef.validation\n\n if (Array.isArray(validation)) {\n const rules = validation.flatMap((i) =>\n normalizeAuthoredRules(\n {\n ...typeDef,\n validation: i,\n },\n context,\n ),\n )\n return omitLeakedDefaultUri(rules, typeDef)\n }\n\n const initialRule = new RuleClass(typeDef)\n let baseRule =\n // using an object + Object.values to de-dupe the type chain by type name\n Object.values(\n getTypeChain(typeDef).reduce<Record<string, SchemaType>>((acc, type) => {\n acc[type.name] = type\n return acc\n }, {}),\n ).reduce(\n baseRuleReducer,\n isRuleConstraint(typeDef.jsonType) ? initialRule.type(typeDef.jsonType) : initialRule,\n )\n\n const options = typeDef.options\n const list =\n options && typeof options === 'object' && 'list' in options ? options.list : undefined\n if (Array.isArray(list)) {\n baseRule = baseRule.valid(list.map((option) => extractValueFromListOption(option, typeDef)))\n }\n\n if (validation && typeof validation === 'object') {\n return [validation]\n }\n\n if (!validation) {\n return [baseRule]\n }\n\n if (typeof validation === 'function') {\n return normalizeAuthoredRules(\n {\n ...typeDef,\n validation: validation(baseRule, context),\n },\n context,\n )\n }\n\n return [baseRule]\n}\n","/**\n * Simple requestIdleCallback polyfill\n * Can be removed when all browsers support requestIdleCallback: https://caniuse.com/requestidlecallback\n * @param callback -\n * @param options -\n */\nconst requestIdleCallbackShim: typeof window.requestIdleCallback = function requestIdleCallbackShim(\n callback,\n _options?,\n): number {\n const start = Date.now()\n return globalThis.setTimeout(() => {\n callback({\n didTimeout: false,\n timeRemaining() {\n return Math.max(0, Date.now() - start)\n },\n })\n }, 0) as unknown as number\n}\n\nconst cancelIdleCallbackShim: typeof window.cancelIdleCallback = function cancelIdleCallbackShim(\n handle: number,\n): void {\n return globalThis.clearTimeout(handle)\n}\n\nconst win = typeof window === 'undefined' ? undefined : window\n\nexport const requestIdleCallback = win?.requestIdleCallback || requestIdleCallbackShim\nexport const cancelIdleCallback = win?.cancelIdleCallback || cancelIdleCallbackShim\n","import {type BehaviorSubject} from 'rxjs'\n\nimport {cancelIdleCallback, requestIdleCallback} from './requestIdleCallback'\n\n/**\n * How validation work is paced.\n *\n * - `idle` (default): every rule and nested value waits for a `requestIdleCallback` before it\n * runs, so validation yields to rendering and input while a document is being edited. A page\n * that is busy or hidden grants few or no idle periods, so a run can take long to finish.\n * - `immediate`: nothing waits for idle time. The run uses the thread as soon as it can, and hands\n * it back once every {@link IMMEDIATE_YIELD_EVERY} nodes so that input and rendering get a turn\n * in between: through `scheduler.yield()` where the browser has it, and elsewhere (Safari) by\n * waiting for the next task. Meant for the moment a user is waiting on the result, such as\n * publishing.\n *\n * @internal\n */\nexport type ValidationScheduling = 'idle' | 'immediate'\n\n/** What every validation node waits for before it runs. @internal */\nexport interface Pace {\n wait(signal?: AbortSignal): Promise<void> | undefined\n dispose(): void\n}\n\n/** How many nodes an `immediate` run gets through between two yields to the browser. */\nexport const IMMEDIATE_YIELD_EVERY = 100\n\nconst microtask = Promise.resolve()\n\n// lib.dom declares `scheduler` on every global object, but Safari and Node have none, and it\n// declares no `setImmediate`, which Node has\ninterface FeatureDetectedGlobals {\n scheduler?: {yield?: () => Promise<void>}\n setImmediate?: (callback: () => void) => unknown\n}\n\nfunction getYieldToBrowser(): () => Promise<void> {\n const {scheduler, setImmediate} = globalThis as FeatureDetectedGlobals\n if (typeof scheduler?.yield === 'function') return scheduler.yield.bind(scheduler)\n if (typeof setImmediate === 'function') {\n return () => new Promise((resolve) => setImmediate(resolve))\n }\n if (typeof MessageChannel === 'function') return yieldThroughMessageChannel\n return yieldThroughTimeout\n}\n\n// One channel for every run, as React's scheduler has. Messages arrive in the order they were\n// posted, so each one resolves the yield that has waited longest.\nlet messagePort: MessagePort | undefined\nconst waitingForMessage: Array<() => void> = []\n\nfunction yieldThroughMessageChannel(): Promise<void> {\n if (!messagePort) {\n const channel = new MessageChannel()\n // oxlint-disable-next-line unicorn/prefer-add-event-listener -- unlike addEventListener, this also starts the port\n channel.port1.onmessage = () => waitingForMessage.shift()?.()\n messagePort = channel.port2\n }\n const port = messagePort\n return new Promise((resolve) => {\n waitingForMessage.push(resolve)\n port.postMessage(null)\n })\n}\n\nfunction yieldThroughTimeout(): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, 0))\n}\n\nfunction abortReason(signal: AbortSignal): unknown {\n return signal.reason ?? new DOMException('Validation aborted', 'AbortError')\n}\n\nfunction cancelWithSignal(wait: Promise<void>, signal?: AbortSignal): Promise<void> {\n if (!signal) return wait\n if (signal.aborted) return Promise.reject(abortReason(signal))\n\n return new Promise((resolve, reject) => {\n const onAbort = () => {\n signal.removeEventListener('abort', onAbort)\n reject(abortReason(signal))\n }\n signal.addEventListener('abort', onAbort, {once: true})\n void wait.then(\n () => {\n signal.removeEventListener('abort', onAbort)\n resolve()\n },\n (error) => {\n signal.removeEventListener('abort', onAbort)\n reject(error)\n },\n )\n })\n}\n\ntype IdleWaiter = (reason?: unknown) => void\n\nfunction waitForIdle(signal: AbortSignal | undefined, waiters?: Set<IdleWaiter>): Promise<void> {\n return new Promise((resolve, reject) => {\n let settled = false\n let handle: number | undefined\n\n const finish: IdleWaiter = (reason) => {\n if (settled) return\n settled = true\n if (handle !== undefined) cancelIdleCallback(handle)\n waiters?.delete(finish)\n signal?.removeEventListener('abort', onAbort)\n if (reason === undefined) resolve()\n else reject(reason)\n }\n const onAbort = () => {\n if (signal) finish(abortReason(signal))\n }\n\n if (signal?.aborted) {\n onAbort()\n return\n }\n\n waiters?.add(finish)\n signal?.addEventListener('abort', onAbort, {once: true})\n handle = requestIdleCallback(() => finish())\n })\n}\n\n/**\n * Yields to the browser once every `every` nodes and lets the others through on a microtask.\n * Every node that comes along while the yield is pending waits for that same yield.\n */\nexport function createYieldingPace(yieldToBrowser: () => Promise<void>, every: number): Pace {\n let count = 0\n let pending: Promise<void> | undefined\n return {\n wait(signal) {\n signal?.throwIfAborted()\n if (pending) return cancelWithSignal(pending, signal)\n count += 1\n if (count < every) return cancelWithSignal(microtask, signal)\n count = 0\n const settle = () => {\n if (pending === yielded) pending = undefined\n }\n // A failed browser yield lets validation continue. Cancellation is checked before the next\n // node starts and by every async validator that receives the run's signal.\n const yielded = yieldToBrowser().then(settle, settle)\n pending = yielded\n return cancelWithSignal(yielded, signal)\n },\n dispose() {},\n }\n}\n\n/** A pacer for server validation, where yielding to a browser is unnecessary. */\nexport function createUnpacedPace(): Pace {\n return {\n wait(signal) {\n signal?.throwIfAborted()\n return undefined\n },\n dispose() {},\n }\n}\n\n/**\n * The pacer for one Studio run, `idle` without a scheduling. One subscription observes scheduling\n * changes for the whole run rather than creating one RxJS subscription per validation node.\n */\nexport function createPace(scheduling?: BehaviorSubject<ValidationScheduling>): Pace {\n if (!scheduling) {\n return {\n wait: (signal) => waitForIdle(signal),\n dispose() {},\n }\n }\n\n let current = scheduling.getValue()\n let disposed = false\n const waiters = new Set<IdleWaiter>()\n const immediate = createYieldingPace(getYieldToBrowser(), IMMEDIATE_YIELD_EVERY)\n const subscription = scheduling.subscribe((next) => {\n current = next\n if (next === 'immediate') {\n for (const release of waiters) release()\n }\n })\n\n return {\n wait(signal) {\n if (disposed) return Promise.reject(new Error('Validation pace has been disposed'))\n return current === 'immediate' ? immediate.wait(signal) : waitForIdle(signal, waiters)\n },\n dispose() {\n if (disposed) return\n disposed = true\n subscription.unsubscribe()\n for (const release of waiters) release(new Error('Validation pace has been disposed'))\n immediate.dispose()\n },\n }\n}\n","import {type DocumentId, getVersionId, getVersionNameFromId, isVersionId} from '@sanity/id-utils'\nimport {type SanityDocument} from '@sanity/types'\n\ntype DocumentCheck = (options: {id: string; signal?: AbortSignal}) => Promise<boolean>\n\n/** @beta */\nexport interface ReleaseReferenceOptions {\n /** The document whose references are being checked. Variants require published references. */\n document: Pick<SanityDocument, '_id' | '_system'>\n /** Whether a document with the exact ID exists, including release unpublish markers. */\n getDocumentExists: DocumentCheck\n /** Whether the existing version document with the given ID unpublishes its document. */\n isUnpublished: DocumentCheck\n}\n\n/**\n * Resolves references from a release document the way Studio does: a reference to a document\n * in the same release exists even if it isn't published yet, unless the release unpublishes it.\n * Other documents are checked with `getDocumentExists` unchanged.\n *\n * @beta\n */\nexport function withReleaseReferences({\n document,\n getDocumentExists,\n isUnpublished,\n}: ReleaseReferenceOptions): DocumentCheck {\n const resolveReference = createReferenceResolver({document, getDocumentExists, isUnpublished})\n return async (options) => (await resolveReference(options)) !== undefined\n}\n\n/** Resolve the exact published or release document ID used by reference validation. */\nexport function createReferenceResolver({\n document,\n getDocumentExists,\n isUnpublished,\n}: ReleaseReferenceOptions): (options: {\n id: string\n signal?: AbortSignal\n}) => Promise<string | undefined> {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- any document ID can be checked\n const id = document._id as DocumentId\n // oxlint-disable-next-line typescript/no-deprecated -- support unmigrated variant documents\n const variant = document._system?.variants?.[0]?._ref ?? document._system?.variant?._ref\n if (!isVersionId(id) || variant) {\n return async (options) => ((await getDocumentExists(options)) ? options.id : undefined)\n }\n const versionName = getVersionNameFromId(id)\n\n return async ({id: referenceId, signal}) => {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- references hold document IDs\n const versionId = getVersionId(referenceId as DocumentId, versionName)\n const [versionExists, publishedExists] = await Promise.all([\n getDocumentExists({id: versionId, signal}),\n getDocumentExists({id: referenceId, signal}),\n ])\n if (!versionExists) return publishedExists ? referenceId : undefined\n return (await isUnpublished({id: versionId, signal})) ? undefined : versionId\n }\n}\n","import {type CustomValidator, type ObjectSchemaType} from '@sanity/types'\n\nimport {validationMarkerCodes} from '../codes'\n\n/**\n * Given a schema type, returns a custom validator used to warn users of unknown\n * fields found in an object.\n */\nexport const unknownFieldsValidator =\n (type: ObjectSchemaType): CustomValidator =>\n (value) => {\n if (typeof value !== 'object') return true\n if (!value) return true\n\n const fieldNames = new Set(type.fields?.map((field) => field.name))\n\n const unknownFields = Object.keys(value)\n .filter((key) => !key.startsWith('_'))\n .filter((key) => !fieldNames.has(key))\n\n return unknownFields.map((unknownField) => ({\n code: validationMarkerCodes.objectUnknownField,\n details: {fieldName: unknownField, typeName: type.name},\n message: `Field '${unknownField}' does not exist on type '${type.name}'`,\n path: [unknownField],\n }))\n }\n","/* oxlint-disable typescript/no-deprecated -- marker and Rule compatibility require legacy internals */\nimport {type SanityClient} from '@sanity/client'\nimport {markInternalValidator} from '@sanity/schema/_internal'\nimport {\n isKeyedObject,\n isTypedObject,\n type CurrentUser,\n type Rule,\n type SanityDocument,\n type Schema,\n type SchemaType,\n type ValidationMarker,\n} from '@sanity/types'\nimport {createClientConcurrencyLimiter} from '@sanity/util/client'\nimport {ConcurrencyLimiter} from '@sanity/util/concurrency-limiter'\nimport {dequal as isEqual} from 'dequal/lite'\nimport flatten from 'lodash-es/flatten.js'\nimport {type BehaviorSubject, Observable} from 'rxjs'\nimport {map} from 'rxjs/operators'\n\nimport {ClientUnavailableError} from './clientUnavailable'\nimport {type DocumentValidationMarker, validationMarkerCodes} from './codes'\nimport {getFallbackLocaleSource} from './i18n/fallback'\nimport {type LocaleSource, type ValidationLocaleSource} from './i18n/types'\nimport {resolveConditionalProperty} from './resolveConditionalProperty'\nimport {Rule as RuleClass} from './Rule'\nimport {type InternalValidationContext, type ValidationContext} from './types'\nimport {createBatchedGetDocumentExists} from './util/createBatchedGetDocumentExists'\nimport {createBatchedGetDocumentType} from './util/createBatchedGetDocumentType'\nimport {getTypeChain, normalizeValidationRules} from './util/normalizeValidationRules'\nimport {createPace, createUnpacedPace, type Pace, type ValidationScheduling} from './util/pace'\nimport {typeString} from './util/typeString'\nimport {createReferenceResolver} from './util/withReleaseReferences'\nimport {unknownFieldsValidator} from './validators/unknownFieldsValidator'\n\n// this is the number of requests allowed inflight at once. this is done to prevent\n// the validation library from overwhelming our backend.\n// NOTE: this was upped from 10 to prevent issues where many concurrency\n// `client.fetch` requests would \"clog\" custom validators from finishing due to\n// not enough concurrent requests being fulfilled\n//\n// NOTE: ensure to update the TSDoc and CLI help test if this is changed\nconst DEFAULT_MAX_FETCH_CONCURRENCY = 25\n\n// NOTE: ensure to update the TSDoc and CLI help test if this is changed\nconst DEFAULT_MAX_CUSTOM_VALIDATION_CONCURRENCY = 5\n\nconst DEFAULT_VALIDATION_CLIENT_OPTIONS = {apiVersion: '2025-02-19'} as const\n\nconst isRecord = (maybeRecord: unknown): maybeRecord is Record<string, unknown> =>\n typeof maybeRecord === 'object' && maybeRecord !== null && !Array.isArray(maybeRecord)\n\n/** Rejects on abort without waiting for work that does not observe the signal itself. */\nfunction raceWithSignal<T>(promise: Promise<T>, signal?: AbortSignal): Promise<T> {\n if (!signal) return promise\n if (signal.aborted) return Promise.reject(signal.reason)\n\n return new Promise((resolve, reject) => {\n const onAbort = () => {\n signal.removeEventListener('abort', onAbort)\n reject(signal.reason)\n }\n signal.addEventListener('abort', onAbort, {once: true})\n void promise.then(\n (value) => {\n signal.removeEventListener('abort', onAbort)\n resolve(value)\n },\n (error) => {\n signal.removeEventListener('abort', onAbort)\n reject(error)\n },\n )\n })\n}\n\nfunction throwClientUnavailable(): never {\n throw new ClientUnavailableError()\n}\n\n/**\n * Recursively extracts all `_fieldRules` from a rule and its nested constraints.\n * This handles cases where `Rule.fields()` is used inside `Rule.all()` or `Rule.either()`.\n */\nfunction extractFieldRulesFromRule(rule: Rule): NonNullable<Rule['_fieldRules']>[] {\n const results: NonNullable<Rule['_fieldRules']>[] = []\n\n // Add direct _fieldRules if present\n // oxlint-disable-next-line no-deprecated -- will fix in follow up PR\n if (rule._fieldRules) {\n // oxlint-disable-next-line no-deprecated -- will fix in follow up PR\n results.push(rule._fieldRules)\n }\n\n // Check for nested rules in 'all' or 'either' constraints\n // oxlint-disable-next-line no-deprecated -- will fix in follow up PR\n for (const ruleSpec of rule._rules) {\n if (ruleSpec.flag === 'all' || ruleSpec.flag === 'either') {\n const childRules = ruleSpec.constraint\n if (Array.isArray(childRules)) {\n for (const childRule of childRules) {\n results.push(...extractFieldRulesFromRule(childRule))\n }\n }\n }\n }\n\n return results\n}\n\n/**\n * @internal\n */\nexport function resolveTypeForArrayItem(\n item: unknown,\n candidates: SchemaType[],\n): SchemaType | undefined {\n // if there is only one type available, assume that it's the correct one\n if (candidates.length === 1) return candidates[0]\n\n const itemType = isTypedObject(item) && item._type\n const primitive =\n item === undefined || item === null || (!itemType && typeString(item).toLowerCase())\n\n if (primitive && primitive !== 'object') {\n return candidates.find((candidate) => candidate.jsonType === primitive)\n }\n\n return (\n candidates.find((candidate) => candidate.type?.name === itemType) ||\n candidates.find((candidate) => candidate.name === itemType) ||\n candidates.find((candidate) => candidate.name === 'object' && primitive === 'object')\n )\n}\n\ninterface ValidateDocumentBaseOptions {\n /**\n * The document to be validated\n */\n document: SanityDocument\n /** The compiled schema to validate against. */\n schema: ValidationSchema\n\n /**\n * Translation resources and locale used by built-in and custom validators.\n * Pass a resolved workspace's `i18n` to preserve its translations.\n * Defaults to the built-in English resources when omitted.\n */\n i18n?: ValidationLocaleSource\n\n /** Signal used to cancel validation and any work it starts. */\n signal?: AbortSignal\n\n /**\n * Function used to check if referenced documents exists (and is published).\n *\n * If you're validating many documents in bulk, you may want to query for all\n * document IDs first and provide your own implementation using those.\n *\n * If no function is provided a default one will be provided that will batch\n * call the `doc` endpoint to check for document existence.\n */\n getDocumentExists?: (options: {id: string; signal?: AbortSignal}) => Promise<boolean>\n\n /**\n * Check referenced document types against the reference field's `to` types.\n * Defaults to `true` (`false` in Studio's `validateDocument`).\n * Uses batched network reads, including for weak references.\n * Without a client, checks that need a target lookup make validation incomplete.\n * Set to `false` to perform only the existing reference shape and existence checks.\n */\n validateReferenceTypes?: boolean\n\n /**\n * The maximum amount of custom validation functions to be running\n * concurrently at once. This helps prevent custom validators from\n * overwhelming backend services (e.g. called via fetch) used in async,\n * user-defined validation functions. (i.e. `rule.custom(async() => {})`)\n *\n * Note that lowering this number may also help in cases where a custom\n * validator could potentially exhaust the fetch concurrency. This is 5 by\n * default.\n */\n maxCustomValidationConcurrency?: number\n\n /**\n * The amount of allowed inflight fetch requests at once for this validation.\n * You may need to up this value if you have complex custom validations that\n * require many `client.fetch` requests at once. It's possible for a custom\n * validator to stall if there are not enough concurrent fetch requests\n * available to fulfill the custom validation. Must be a positive integer.\n * This is 25 by default.\n */\n maxFetchConcurrency?: number\n\n /**\n * The current user, when available. Used when resolving schema `hidden`\n * conditionals so validation matches what the form shows, and exposed to\n * custom validators and schema-level `validation` functions as\n * `context.currentUser`. If omitted, hidden is resolved with no user (e.g. CLI\n * or headless validation).\n */\n currentUser?: Omit<CurrentUser, 'role'> | null\n}\n\n/**\n * Options for validating a document. Custom validation is disabled when no client is provided.\n *\n * @beta\n */\nexport type ValidateDocumentOptions = ValidateDocumentBaseOptions & ValidationClientOptions\n\n/**\n * Options for validating a batch of documents with shared request concurrency.\n * Custom validation is disabled when no client is provided.\n *\n * @beta\n */\nexport type ValidateDocumentsOptions = Omit<ValidateDocumentBaseOptions, 'document'> &\n ValidationClientOptions & {\n /** Documents to validate. Results are returned in the same order. */\n documents: SanityDocument[]\n }\n\ntype ValidationClientOptions =\n | {\n /** A configured client used for reference checks and custom validators. */\n client: ValidationClient\n /** Whether to run custom validation callbacks. Defaults to `true`. */\n customValidation?: boolean\n }\n | {\n /** Omit the client to perform local validation without custom callbacks. */\n client?: undefined\n customValidation?: false\n }\n\n/** A compiled schema accepted across compatible `@sanity/types` versions. @beta */\nexport interface ValidationSchema {\n get(name: string): unknown\n}\n\n/**\n * A configured Sanity client accepted across compatible client versions.\n *\n * This structural type describes the capabilities used internally by validation.\n * The configured client is exposed to custom validators as a `SanityClient`, so it must be compatible with the full client API.\n *\n * @beta\n */\nexport interface ValidationClient {\n fetch: SanityClient['fetch']\n getDataUrl: SanityClient['getDataUrl']\n request: SanityClient['request']\n observable: Pick<SanityClient['observable'], 'fetch'>\n withConfig(config: Parameters<SanityClient['withConfig']>[0]): ValidationClient\n}\n\n/** The result of validating a complete document. @beta */\nexport interface DocumentValidationResult {\n /**\n * Compatibility summary: any marker produces `failed`, including execution errors.\n * @deprecated Will be removed in v7. Use `complete` and inspect marker levels and codes instead.\n */\n status: 'passed' | 'failed' | 'notEvaluated'\n /**\n * Whether every applicable check could be evaluated. When false, validation is inconclusive.\n * Custom validators must throw when they cannot evaluate; returned messages are treated as findings.\n */\n complete: boolean\n /** Validation markers. */\n markers: DocumentValidationMarker[]\n}\n\n/**\n * The validation capabilities required from a resolved Studio source or workspace.\n *\n * @beta\n */\nexport interface ValidationSource {\n /** The compiled schema to validate against. */\n schema: Schema\n\n /** Factory used to get the client passed to custom validators. */\n getClient: (clientOptions: {apiVersion: string}) => SanityClient\n\n /** Internationalization utilities used for validation messages. */\n i18n: LocaleSource\n}\n\n/**\n * Options accepted by the compatibility overload for Studio workspace validation.\n *\n * @beta\n */\nexport interface ValidateDocumentWorkspaceOptions extends Omit<\n ValidateDocumentBaseOptions,\n 'schema' | 'i18n'\n> {\n /** The resolved Studio workspace or source used for validation. */\n workspace: ValidationSource\n\n /**\n * Factory used to get the client passed to custom validators.\n *\n * @deprecated For internal use only\n */\n getClient?: ValidationSource['getClient']\n\n /** Validation environment exposed to custom validators. */\n environment?: 'cli' | 'studio'\n\n /** Whether to run custom validation callbacks. Defaults to `true`. */\n customValidation?: boolean\n}\n\n/**\n * Validates a document against the schema in a resolved Studio workspace or source.\n *\n * @beta\n * @deprecated Prefer {@link validateDocument} with `{document, schema, client}` for new code.\n */\nexport function validateDocumentWithWorkspace({\n document,\n workspace,\n getClient = workspace.getClient,\n getDocumentExists,\n environment = 'studio',\n maxCustomValidationConcurrency,\n maxFetchConcurrency,\n currentUser,\n customValidation,\n signal,\n validateReferenceTypes = true,\n}: ValidateDocumentWorkspaceOptions): Promise<DocumentValidationMarker[]> {\n return validateDocumentInternal({\n currentUser,\n customValidation,\n document,\n environment,\n getClient,\n getDocumentExists,\n i18n: workspace.i18n,\n maxCustomValidationConcurrency,\n maxFetchConcurrency,\n schema: workspace.schema,\n signal,\n validateReferenceTypes,\n })\n}\n\n/**\n * Validates a document against a compiled schema. Returns failures and whether\n * validation completed\n * without deciding whether the document may be edited or published.\n *\n * @beta\n */\nexport function validateDocument(\n options: ValidateDocumentOptions,\n): Promise<DocumentValidationResult> {\n const {document, ...sharedOptions} = options\n return evaluateDocumentInternal({document, ...normalizeValidationOptions(sharedOptions)})\n}\n\n/**\n * Validates documents against a compiled schema, sharing reference-check batching\n * and the fetch concurrency limit across the batch. Results match the input order.\n * The signal cancels the entire batch and any work it starts.\n *\n * @beta\n */\nexport function validateDocuments(\n options: ValidateDocumentsOptions,\n): Promise<DocumentValidationResult[]> {\n const {documents, ...sharedOptions} = options\n return evaluateDocumentsInternal({documents, ...normalizeValidationOptions(sharedOptions)})\n}\n\nfunction normalizeValidationOptions(\n options: Omit<ValidateDocumentOptions, 'document'>,\n): Omit<ValidateDocumentInternalOptions, 'document'> {\n const {\n client,\n customValidation = Boolean(options.client),\n getDocumentExists,\n i18n,\n schema,\n ...internalOptions\n } = options\n return {\n ...internalOptions,\n customValidation,\n environment: 'cli',\n getClient: client\n ? // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- runtime-compatible clients may come from another major\n ({apiVersion}) => client.withConfig({apiVersion}) as SanityClient\n : throwClientUnavailable,\n getDocumentExists: getDocumentExists || (client ? undefined : throwClientUnavailable),\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- translation sources may use another compatible i18next version\n i18n: (i18n ?? getFallbackLocaleSource()) as LocaleSource,\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- compiled schemas may come from another compatible package version\n schema: schema as Schema,\n }\n}\n\n/** @internal */\nexport interface ValidateDocumentInternalOptions {\n document: SanityDocument\n schema: Schema\n getClient: (clientOptions: {apiVersion: string}) => SanityClient\n getDocumentExists?: (options: {id: string; signal?: AbortSignal}) => Promise<boolean>\n validateReferenceTypes?: boolean\n i18n?: LocaleSource\n environment: 'cli' | 'studio'\n maxCustomValidationConcurrency?: number\n maxFetchConcurrency?: number\n currentUser?: Omit<CurrentUser, 'role'> | null\n customValidation?: boolean\n signal?: AbortSignal\n}\n\nfunction createDocumentValidationResult(\n markers: ValidationMarker[],\n complete: boolean,\n): DocumentValidationResult {\n // Compiled rules from another version may return execution failures without calling markIncomplete.\n const isComplete = complete && !markers.some(hasEvaluationFailure)\n return {\n status: getDocumentValidationStatus(markers, isComplete),\n complete: isComplete,\n markers: markers.map(toDocumentValidationMarker),\n }\n}\n\nfunction hasEvaluationFailure(value: unknown): boolean {\n if (!isRecord(value)) return false\n switch (value.code) {\n case validationMarkerCodes.validationException:\n case validationMarkerCodes.documentUnknownType:\n return true\n case validationMarkerCodes.ruleAllFailed:\n case validationMarkerCodes.ruleEitherFailed:\n return (\n isRecord(value.details) &&\n Array.isArray(value.details.causes) &&\n value.details.causes.some(hasEvaluationFailure)\n )\n default:\n return false\n }\n}\n\nfunction getDocumentValidationStatus(\n markers: ValidationMarker[],\n complete: boolean,\n): DocumentValidationResult['status'] {\n if (markers.length > 0) return 'failed'\n if (!complete) return 'notEvaluated'\n return 'passed'\n}\n\n/** @internal */\nexport function validateDocumentInternal(\n options: ValidateDocumentInternalOptions,\n): Promise<DocumentValidationMarker[]> {\n return evaluateDocumentInternal(options).then(({markers}) => markers)\n}\n\n/** @internal */\nexport function evaluateDocumentInternal(\n options: ValidateDocumentInternalOptions,\n): Promise<DocumentValidationResult> {\n const {document, ...sharedOptions} = options\n return evaluateDocumentsInternal({documents: [document], ...sharedOptions}).then(\n ([result]) => result,\n )\n}\n\nfunction evaluateDocumentsInternal({\n documents,\n schema,\n getClient,\n getDocumentExists,\n i18n = getFallbackLocaleSource(),\n environment,\n maxCustomValidationConcurrency,\n maxFetchConcurrency,\n currentUser,\n customValidation = true,\n signal,\n validateReferenceTypes = true,\n}: Omit<ValidateDocumentInternalOptions, 'document'> & {\n documents: SanityDocument[]\n}): Promise<DocumentValidationResult[]> {\n if (signal?.aborted) return Promise.reject(signal.reason)\n if (documents.length === 0) return Promise.resolve([])\n\n const limitConcurrency = createClientConcurrencyLimiter(\n maxFetchConcurrency ?? DEFAULT_MAX_FETCH_CONCURRENCY,\n signal,\n )\n const getConcurrencyLimitedClient = (clientOptions: {apiVersion: string}) =>\n limitConcurrency(getClient(clientOptions))\n const batchedGetDocumentExists = getDocumentExists\n ? undefined\n : createBatchedGetDocumentExists(getClient(DEFAULT_VALIDATION_CLIENT_OPTIONS), signal)\n const batchedGetDocumentType = validateReferenceTypes\n ? createBatchedGetDocumentType(\n () => getConcurrencyLimitedClient(DEFAULT_VALIDATION_CLIENT_OPTIONS),\n signal,\n )\n : undefined\n\n return Promise.all(\n documents.map((document) => {\n const resolveReference = batchedGetDocumentExists\n ? createReferenceResolver({\n document,\n getDocumentExists: batchedGetDocumentExists,\n isUnpublished: ({id, signal: checkSignal}) =>\n getConcurrencyLimitedClient(DEFAULT_VALIDATION_CLIENT_OPTIONS).fetch<boolean>(\n '*[_id == $id][0]._system.delete == true',\n {id},\n {perspective: 'raw', signal: checkSignal, tag: 'validation.release-reference'},\n ),\n })\n : async (options: {id: string; signal?: AbortSignal}) =>\n (await getDocumentExists!(options)) ? options.id : undefined\n const resolvedReferences = new Map<string, string>()\n return evaluateDocument({\n document,\n getClient: getConcurrencyLimitedClient,\n i18n,\n schema,\n getDocumentExists: async (options) => {\n const resolvedId = await resolveReference(options)\n if (batchedGetDocumentType && resolvedId) resolvedReferences.set(options.id, resolvedId)\n return resolvedId !== undefined\n },\n getDocumentType: batchedGetDocumentType\n ? async (id) => {\n const resolvedId = resolvedReferences.get(id)\n return resolvedId ? batchedGetDocumentType(resolvedId) : undefined\n }\n : undefined,\n environment,\n maxCustomValidationConcurrency,\n currentUser,\n customValidation,\n signal,\n pace: createUnpacedPace(),\n })\n }),\n )\n}\n\nexport {type ValidationScheduling} from './util/pace'\n\n/**\n * @internal\n */\nexport interface ValidateDocumentObservableOptions extends Pick<\n ValidationContext,\n 'getDocumentExists' | 'i18n' | 'signal' | 'currentUser'\n> {\n /** Lookup for resolved target types. Omit to disable type checks. */\n getDocumentType?: (id: string) => Promise<string | undefined>\n getClient: (options: {apiVersion: string}) => SanityClient\n document: SanityDocument\n schema: Schema\n environment: 'cli' | 'studio'\n maxCustomValidationConcurrency?: number\n customValidation?: boolean\n /**\n * How the run is paced (see {@link ValidationScheduling}), `idle` when omitted. It can change\n * while the run is in flight: a switch to `immediate` speeds the run up without restarting it.\n */\n scheduling?: BehaviorSubject<ValidationScheduling>\n}\n\nconst customValidationConcurrencyLimiters = new WeakMap<Schema, ConcurrencyLimiter>()\n\n/**\n * Validates a document against the given schema, returning an Observable\n * @internal\n */\nexport function validateDocumentObservable(\n options: ValidateDocumentObservableOptions,\n): Observable<DocumentValidationMarker[]> {\n return evaluateDocumentObservable(options).pipe(map(({markers}) => markers))\n}\n\n/**\n * Validates a document against the given schema, including completion status.\n * @internal\n */\nexport function evaluateDocumentObservable(\n options: ValidateDocumentObservableOptions,\n): Observable<DocumentValidationResult> {\n return new Observable((subscriber) => {\n const controller = new AbortController()\n const {signal} = options\n const abort = () => controller.abort(signal?.reason)\n\n if (signal?.aborted) abort()\n else signal?.addEventListener('abort', abort, {once: true})\n\n void evaluateDocument({\n ...options,\n signal: controller.signal,\n pace: createPace(options.scheduling),\n }).then(\n (result) => {\n subscriber.next(result)\n subscriber.complete()\n },\n (error) => subscriber.error(error),\n )\n\n return () => {\n signal?.removeEventListener('abort', abort)\n controller.abort()\n }\n })\n}\n\nasync function evaluateDocument(\n options: ValidateDocumentObservableOptions & {pace: Pace},\n): Promise<DocumentValidationResult> {\n const {pace, signal} = options\n try {\n signal?.throwIfAborted()\n return await raceWithSignal(evaluateDocumentWithoutCancellation(options), signal)\n } finally {\n pace.dispose()\n }\n}\n\nasync function evaluateDocumentWithoutCancellation({\n document,\n getClient,\n i18n = getFallbackLocaleSource(),\n schema,\n getDocumentExists,\n getDocumentType,\n environment,\n maxCustomValidationConcurrency,\n currentUser,\n customValidation = true,\n signal,\n pace,\n}: ValidateDocumentObservableOptions & {pace: Pace}): Promise<DocumentValidationResult> {\n try {\n if (typeof document?._type !== 'string') {\n throw new Error(`Tried to validate a value without a '_type'`)\n }\n\n const documentType = schema.get(document._type)\n\n if (!documentType) {\n if (environment === 'studio') {\n console.warn(\n 'Schema type for object type \"%s\" not found, skipping validation',\n document._type,\n )\n return createDocumentValidationResult([], false)\n }\n\n return createDocumentValidationResult(\n [\n {\n code: validationMarkerCodes.documentUnknownType,\n details: {documentType: document._type},\n level: 'warning',\n message: `Could not find schema type for type '${document._type}', skipping validation`,\n path: [],\n },\n ],\n false,\n )\n }\n\n let customValidationConcurrencyLimiter = customValidationConcurrencyLimiters.get(schema)\n if (!customValidationConcurrencyLimiter) {\n customValidationConcurrencyLimiter = new ConcurrencyLimiter(\n maxCustomValidationConcurrency ?? DEFAULT_MAX_CUSTOM_VALIDATION_CONCURRENCY,\n )\n customValidationConcurrencyLimiters.set(schema, customValidationConcurrencyLimiter)\n }\n\n // `Rule.validate()` returns markers only, so completeness is tracked separately.\n let complete = true\n const validationOptions: ValidateItemOptions = {\n getClient,\n schema,\n parent: undefined,\n value: document,\n path: [],\n document: document,\n type: documentType,\n i18n,\n getDocumentExists,\n environment,\n customValidationConcurrencyLimiter,\n currentUser,\n customValidation,\n signal,\n __internal: {\n getDocumentType,\n markIncomplete: () => {\n complete = false\n },\n pace,\n },\n }\n\n await i18n.loadNamespaces(['validation'])\n const markers = await validateItemAsync(validationOptions)\n return createDocumentValidationResult(markers, complete)\n } catch (err) {\n if (signal?.aborted) throw signal.reason\n if (typeof document?._type !== 'string') throw err\n console.error(err)\n\n const message =\n err instanceof Error\n ? err.message\n : isRecord(err) && typeof err.message === 'string'\n ? err.message\n : 'Unknown error'\n const errorMarker: DocumentValidationMarker = {\n code: validationMarkerCodes.validationException,\n level: 'error',\n message,\n item: {message},\n path: [],\n }\n\n return createDocumentValidationResult([errorMarker], false)\n }\n}\n\n/**\n * this is used make optional properties required by replacing optionals with\n * `T[P] | undefined`. this is used to prevent errors in `validateItem` where\n * an option from a previous invocation would be incorrectly passed down.\n *\n * https://medium.com/terria/typescript-transforming-optional-properties-to-required-properties-that-may-be-undefined-7482cb4e1585\n */\ntype ExplicitUndefined<T> = {\n [P in keyof Required<T>]: Pick<T, P> extends Required<Pick<T, P>> ? T[P] : T[P] | undefined\n}\n\nexport type ValidateItemOptions = {\n value: unknown\n customValidationConcurrencyLimiter?: ConcurrencyLimiter\n hidden?: boolean\n customValidation?: boolean\n signal?: AbortSignal\n /** See {@link ValidateDocumentObservableOptions.scheduling}. */\n scheduling?: BehaviorSubject<ValidationScheduling>\n __internal?: InternalValidationContext['__internal']\n} & Pick<ValidationContext, 'currentUser'> &\n ExplicitUndefined<Omit<ValidationContext, 'hidden' | 'signal' | 'currentUser'>>\n\nexport async function validateItem(opts: ValidateItemOptions): Promise<ValidationMarker[]> {\n opts.signal?.throwIfAborted()\n const inheritedPace = opts.__internal?.pace\n const pace = inheritedPace ?? createPace(opts.scheduling)\n try {\n return await raceWithSignal(\n validateItemAsync(\n inheritedPace\n ? opts\n : {\n ...opts,\n __internal: {...opts.__internal, pace},\n },\n ),\n opts.signal,\n )\n } finally {\n if (!inheritedPace) pace.dispose()\n }\n}\n\nfunction validateRule(\n rule: Rule,\n value: unknown,\n context: InternalValidationContext,\n): Promise<ValidationMarker[]> {\n return rule.validate(value, context)\n}\n\ntype ValidationTask = () => Promise<ValidationMarker[]>\n\nexport async function runValidationTasks(\n tasks: ValidationTask[],\n concurrency: number,\n): Promise<ValidationMarker[][]> {\n const results: ValidationMarker[][] = []\n let nextIndex = 0\n let failed = false\n let failure: unknown\n\n async function worker() {\n while (!failed && nextIndex < tasks.length) {\n const task = tasks[nextIndex]\n nextIndex += 1\n try {\n // Each worker intentionally starts its next task only after its current task finishes.\n // oxlint-disable-next-line no-await-in-loop\n results.push(await task())\n } catch (error) {\n if (!failed) {\n failed = true\n failure = error\n }\n }\n }\n }\n\n await Promise.all(Array.from({length: Math.min(concurrency, tasks.length)}, () => worker()))\n if (failed) throw failure\n return results\n}\n\nasync function validateItemAsync({\n value,\n type,\n path = [],\n parent,\n customValidationConcurrencyLimiter,\n environment,\n customValidation = true,\n scheduling: _scheduling,\n __internal: inheritedInternal,\n ...restOfContext\n}: ValidateItemOptions): Promise<ValidationMarker[]> {\n // The run's pacer is created once, by `evaluateDocumentObservable` or by the outermost\n // `validateItem` call, and shared with every nested value so that the whole run is paced as one.\n const pace = inheritedInternal?.pace\n if (!pace) throw new Error('Validation item was started without a pace')\n const __internal = inheritedInternal\n\n // Track whether any ancestor in the tree is hidden.\n // It will be true if this field OR any ancestor is hidden.\n // This allows validation rules to check `context.hidden` to skip validation for hidden fields,\n // without needing to know whether the field itself or an ancestor caused it to be hidden.\n const ancestorHidden = restOfContext.hidden === true\n const resolveHiddenForType = (\n schemaType: SchemaType | undefined,\n schemaValue: unknown,\n schemaParent: unknown,\n schemaPath: ValidationContext['path'],\n ancestorHiddenValue: boolean,\n ) => {\n // If there is no schema type, fall back to the ancestor's hidden state.\n if (!schemaType) {\n return ancestorHiddenValue\n }\n return (\n ancestorHiddenValue ||\n resolveConditionalProperty(schemaType.hidden, {\n ...restOfContext,\n parent: schemaParent,\n value: schemaValue,\n path: schemaPath || [],\n currentUser: restOfContext.currentUser ?? null,\n })\n )\n }\n const hidden = resolveHiddenForType(type, value, parent, path, ancestorHidden)\n\n // Note: this validator is added here because it's conditional based on the\n // environment. It is a separate rule because `.warning()` sets the level of\n // every check on a rule, which would downgrade the schema's own checks.\n const unknownFieldsRule =\n // if the value is an object\n typeof value === 'object' &&\n value !== null &&\n // and the schema type is an object type\n type?.jsonType === 'object' &&\n // and if somewhere in it's type chain, it inherits from object or document\n getTypeChain(type).find((t) => ['object', 'document', 'file', 'image'].includes(t.name)) &&\n // and the environment is not the studio\n environment !== 'studio'\n ? new RuleClass(type)\n .custom(markInternalValidator(unknownFieldsValidator(type)), {\n bypassConcurrencyLimit: true,\n })\n .warning()\n : undefined\n\n const rules = normalizeValidationRules(type, {\n ...restOfContext,\n hidden,\n environment,\n parent,\n path,\n type,\n })\n // run validation for the current value\n const selfRules = unknownFieldsRule ? [...rules, unknownFieldsRule] : rules\n const selfChecks: ValidationTask[] = selfRules.map(\n (rule) => () =>\n validateRule(rule, value, {\n ...restOfContext,\n environment,\n hidden,\n parent,\n path,\n type,\n __internal: {\n ...__internal,\n customValidation,\n customValidationConcurrencyLimiter,\n },\n }),\n )\n\n // run validation for nested values (conditionally)\n let nestedChecks: ValidationTask[] = []\n\n const shouldRunNestedObjectValidation =\n // run nested validation for objects\n type?.jsonType === 'object' &&\n // if the value is truthy\n (!!value || // or\n // (the value is null or undefined) and the top-level value is required\n ((value === null || value === undefined) && rules.some((rule) => rule.isRequired())))\n\n if (shouldRunNestedObjectValidation) {\n const fieldTypes = type.fields.reduce<Record<string, SchemaType>>((acc, field) => {\n acc[field.name] = field.type\n return acc\n }, {})\n\n // Validation for rules set at the object level with `Rule.fields({/* ... */})`\n // Use extractFieldRulesFromRule to handle Rule.fields() inside Rule.all() or Rule.either()\n nestedChecks = nestedChecks.concat(\n rules\n .flatMap((rule) => extractFieldRulesFromRule(rule))\n .flatMap((fieldResults) => Object.entries(fieldResults))\n .flatMap(([name, validation]) => {\n const fieldType = fieldTypes[name]\n const nestedValue = isRecord(value) ? value[name] : undefined\n const fieldContext = {\n ...restOfContext,\n parent: value,\n path: path.concat(name),\n type: fieldType,\n environment,\n hidden: resolveHiddenForType(fieldType, nestedValue, value, path.concat(name), hidden),\n }\n return normalizeValidationRules({...fieldType, validation}, fieldContext).map(\n (subRule) => () =>\n validateRule(subRule, nestedValue, {\n ...fieldContext,\n __internal: {\n ...__internal,\n customValidation,\n customValidationConcurrencyLimiter,\n },\n }),\n )\n }),\n )\n\n // Validation from each field's schema `validation: Rule => {/* ... */}` function.\n // Construct child tasks only when the parent's scheduler starts them.\n nestedChecks = nestedChecks.concat(\n type.fields.map(\n (field) => () =>\n validateItemAsync({\n ...restOfContext,\n hidden,\n parent: value,\n value: isRecord(value) ? value[field.name] : undefined,\n path: path.concat(field.name),\n type: field.type,\n environment,\n customValidationConcurrencyLimiter,\n customValidation,\n __internal,\n }),\n ),\n )\n }\n\n // note: unlike objects, arrays should not run nested validation for undefined\n // values because we won't have a valid path to put a marker (i.e. missing the\n // key or index in the path) and the downstream form builder won't have a\n // valid target component\n const shouldRunNestedValidationForArrays = type?.jsonType === 'array' && Array.isArray(value)\n\n if (shouldRunNestedValidationForArrays) {\n nestedChecks = nestedChecks.concat(\n value.map(\n (item, index) => () =>\n validateItemAsync({\n ...restOfContext,\n hidden,\n parent: value,\n value: item,\n path: path.concat(isKeyedObject(item) ? {_key: item._key} : index),\n type: resolveTypeForArrayItem(item, type.of),\n environment,\n customValidationConcurrencyLimiter,\n customValidation,\n __internal,\n }),\n ),\n )\n }\n\n // A single leaf rule already emits the complete marker array.\n if (\n selfChecks.length === 1 &&\n nestedChecks.length === 0 &&\n !rules.some((rule) => extractFieldRulesFromRule(rule).length > 0)\n ) {\n const wait = pace.wait(restOfContext.signal)\n if (wait) await wait\n restOfContext.signal?.throwIfAborted()\n return selfChecks[0]()\n }\n\n // Every check waits for its turn as the run's pacer sees fit (see `ValidationScheduling`).\n const results = flatten(\n await runValidationTasks(\n [...selfChecks, ...nestedChecks].map((validateNode) => async () => {\n const wait = pace.wait(restOfContext.signal)\n if (wait) await wait\n restOfContext.signal?.throwIfAborted()\n return validateNode()\n }),\n 40,\n ),\n )\n\n // Deduplicate markers when `_fieldRules` are present because they can cause repeat markers.\n if (rules.some((rule) => extractFieldRulesFromRule(rule).length > 0)) {\n return deduplicateMarkers(results)\n }\n return results\n}\n\nfunction deduplicateMarkers(markers: ValidationMarker[]): ValidationMarker[] {\n const buckets = new Map<string, ValidationMarker[]>()\n\n return markers.filter((marker) => {\n const key = JSON.stringify([marker.level, marker.code, marker.message, marker.path])\n const bucket = buckets.get(key)\n if (!bucket) {\n buckets.set(key, [marker])\n return true\n }\n\n if (bucket.some((existing) => isEqual(existing, marker))) return false\n\n bucket.push(marker)\n return true\n })\n}\n\nfunction hasValidationMarkerCode(marker: ValidationMarker): marker is DocumentValidationMarker {\n return typeof marker.code === 'string'\n}\n\nfunction toDocumentValidationMarker(marker: ValidationMarker): DocumentValidationMarker {\n if (hasValidationMarkerCode(marker)) return marker\n\n return {\n ...marker,\n code: validationMarkerC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AS,OAAO;EAAI,CAAC,GAC7E,SAAS,QAAQ,IAAI,GAAG;EAS9B,OARK,SAKL,CAAI,OAAO,MAAM,aAAaC,OAAQ,UAAU,MAAM,CAAC,MAEvD,OAAO,KAAK,MAAM,GACX,OAPL,QAAQ,IAAI,KAAK,CAAC,MAAM,CAAC,GAClB;CAOX,CAAC;AACH;AAEA,SAAS,wBAAwB,QAA8D;CAC7F,OAAO,OAAO,OAAO,QAAS;AAChC;AAEA,SAAS,2BAA2B,QAAoD;CAGtF,OAFI,wBAAwB,MAAM,IAAU,SAErC;EACL,GAAG;EACH,MAAM,sBAAsB;CAC9B;AACF"}
1
+ {"version":3,"file":"validateDocument-ChZQiqHl.js","names":["isRecord","DEFAULT_API_VERSION","BaseRule","RuleClass","isEqual","RuleClass","isEqual"],"sources":["../src/codes.ts","../src/clientUnavailable.ts","../src/i18n/resources.ts","../src/i18n/fallback.ts","../src/resolveConditionalProperty.ts","../src/util/pathToString.ts","../src/util/convertToValidationMarker.ts","../src/util/localizeMessage.ts","../src/util/deepEqualsIgnoreKey.ts","../src/util/typeString.ts","../src/validators/genericValidator.ts","../src/validators/arrayValidator.ts","../src/validators/booleanValidator.ts","../src/util/getTypeChain.ts","../src/validators/dateValidator.ts","../src/validators/numberValidator.ts","../src/validators/objectValidator.ts","../src/validators/slugValidator.ts","../src/validators/stringValidator.ts","../src/Rule.ts","../src/util/createBatchedGetDocumentExists.ts","../src/util/createBatchedGetDocumentType.ts","../src/validators/assetAcceptValidator.ts","../src/util/normalizeValidationRules.ts","../src/util/requestIdleCallback.ts","../src/util/pace.ts","../src/util/withReleaseReferences.ts","../src/validators/unknownFieldsValidator.ts","../src/validateDocument.ts"],"sourcesContent":["import {type ValidationMarker as BaseValidationMarker} from '@sanity/types'\n\n/** Machine-readable codes emitted by built-in document validation. @beta */\nexport const validationMarkerCodes = {\n arrayDuplicateItem: 'array.duplicate-item',\n arrayExactLength: 'array.exact-length',\n arrayMaximumLength: 'array.maximum-length',\n arrayMinimumLength: 'array.minimum-length',\n assetNotAccepted: 'asset.not-accepted',\n assetRequired: 'asset.required',\n custom: 'custom',\n dateInvalidFormat: 'date.invalid-format',\n dateMaximum: 'date.maximum',\n dateMinimum: 'date.minimum',\n documentUnknownType: 'document.unknown-type',\n mediaCustom: 'media.custom',\n mediaInvalidReference: 'media.invalid-reference',\n mediaNotFound: 'media.not-found',\n numberGreaterThan: 'number.greater-than',\n numberInteger: 'number.integer',\n numberLessThan: 'number.less-than',\n numberMaximum: 'number.maximum',\n numberMinimum: 'number.minimum',\n numberPrecision: 'number.precision',\n objectUnknownField: 'object.unknown-field',\n referenceInvalid: 'reference.invalid',\n referenceNotPublished: 'reference.not-published',\n referenceTargetTypeMismatch: 'reference.target-type-mismatch',\n ruleAllFailed: 'rule.all-failed',\n ruleEitherFailed: 'rule.either-failed',\n slugInvalidType: 'slug.invalid-type',\n slugMissingCurrent: 'slug.missing-current',\n slugNotUnique: 'slug.not-unique',\n stringEmail: 'string.email',\n stringExactLength: 'string.exact-length',\n stringLowercase: 'string.lowercase',\n stringMaximumLength: 'string.maximum-length',\n stringMinimumLength: 'string.minimum-length',\n stringRegexMatch: 'string.regex-match',\n stringRegexMismatch: 'string.regex-mismatch',\n stringUppercase: 'string.uppercase',\n stringUrlCredentialsNotAllowed: 'string.url.credentials-not-allowed',\n stringUrlInvalid: 'string.url.invalid',\n stringUrlNotAbsolute: 'string.url.not-absolute',\n stringUrlNotRelative: 'string.url.not-relative',\n stringUrlSchemeNotAllowed: 'string.url.scheme-not-allowed',\n validationException: 'validation.exception',\n validationFailed: 'validation.failed',\n valueNotAllowed: 'value.not-allowed',\n valueRequired: 'value.required',\n valueTypeMismatch: 'value.type-mismatch',\n} as const\n\n/** A code emitted by a built-in validator. @beta */\nexport type BuiltInValidationMarkerCode =\n (typeof validationMarkerCodes)[keyof typeof validationMarkerCodes]\n\n/**\n * A built-in validation code or an application-defined custom code.\n * Custom validators should namespace their codes, for example `custom.seo-title`.\n * @beta\n */\nexport type ValidationMarkerCode = BuiltInValidationMarkerCode | (string & {})\n\n/** A validation marker emitted by `validateDocument`, which always has a code. @beta */\nexport type DocumentValidationMarker = Omit<BaseValidationMarker, 'code'> & {\n code: ValidationMarkerCode\n}\n","export class ClientUnavailableError extends Error {\n override name = 'ClientUnavailableError'\n\n constructor() {\n super('A Sanity client is required to run this validation check')\n }\n}\n","export const validationLocaleStrings = {\n 'array.exact-length': 'Must have exactly {{wantedLength}} items',\n 'array.exact-length_blocks': 'Must have exactly {{wantedLength}} blocks',\n 'array.item-duplicate': \"Can't be a duplicate\",\n 'array.maximum-length': 'Must have at most {{maxLength}} items',\n 'array.maximum-length_blocks': 'Must have at most {{maxLength}} blocks',\n 'array.minimum-length': 'Must have at least {{minLength}} items',\n 'array.minimum-length_blocks': 'Must have at least {{minLength}} blocks',\n 'date.invalid-format': 'Must be a valid ISO-8601 formatted date string',\n 'date.maximum': 'Must be at or before {{maxDate}}',\n 'date.minimum': 'Must be at or after {{minDate}}',\n 'generic.incorrect-type': 'Expected type \"{{expectedType}}\", got \"{{actualType}}\"',\n 'generic.not-allowed': 'Value did not match any allowed values',\n 'generic.not-allowed_hint': 'Value \"{{hint}}\" did not match any allowed values',\n 'generic.required': 'Required',\n 'number.greater-than': 'Must be greater than {{threshold}}',\n 'number.less-than': 'Must be less than {{threshold}}',\n 'number.maximum': 'Must be lower than or equal to {{maxNumber}}',\n 'number.maximum-precision': 'Max precision is {{limit}}',\n 'number.minimum': 'Must be greater than or equal to {{minNumber}}',\n 'number.non-integer': 'Must be an integer',\n 'object.asset-not-accepted': 'File type \"{{mimeType}}\" is not accepted',\n 'object.asset-not-accepted_file': 'File type \"{{mimeType}}\" is not accepted',\n 'object.asset-not-accepted_image': 'Image type \"{{mimeType}}\" is not accepted',\n 'object.asset-required': 'Asset is required',\n 'object.asset-required_file': 'File is required',\n 'object.asset-required_image': 'Image is required',\n 'object.media-not-found': 'The asset could not be found in the Media Library',\n 'object.not-media-library-asset': 'Must be a reference to a Media Library asset',\n 'object.not-reference': 'Must be a reference to a document',\n 'object.reference-not-published': 'Referenced document must be published',\n 'object.reference-target-type-mismatch':\n 'Referenced document has type \"{{actualType}}\"; expected one of: {{allowedTypes}}',\n 'slug.missing-current': 'Slug must have a value',\n 'slug.not-object': 'Slug must be an object',\n 'slug.not-unique': 'Slug is already in use',\n 'string.email': 'Must be a valid email address',\n 'string.exact-length': 'Must be exactly {{wantedLength}} characters long',\n 'string.lowercase': 'Must be all lowercase characters',\n 'string.maximum-length': 'Must be at most {{maxLength}} characters long',\n 'string.minimum-length': 'Must be at least {{minLength}} characters long',\n 'string.regex-does-not-match': 'Does not match \"{{name}}\"-pattern',\n 'string.regex-match': 'Should not match \"{{name}}\"-pattern',\n 'string.uppercase': 'Must be all uppercase characters',\n 'string.url.disallowed-scheme': 'Does not match allowed protocols/schemes',\n 'string.url.includes-credentials': 'Username/password not allowed',\n 'string.url.invalid': 'Not a valid URL',\n 'string.url.not-absolute': 'Relative URLs are not allowed',\n 'string.url.not-relative': 'Only relative URLs are allowed',\n} as const\n","import {createInstance} from 'i18next'\n\nimport {validationLocaleStrings} from './resources'\nimport {type LocaleSource} from './types'\n\nlet fallbackLocaleSource: LocaleSource | undefined\n\nexport function getFallbackLocaleSource(): LocaleSource {\n if (fallbackLocaleSource) return fallbackLocaleSource\n\n const i18n = createInstance({\n defaultNS: 'validation',\n fallbackLng: 'en-US',\n initAsync: false,\n interpolation: {escapeValue: false},\n lng: 'en-US',\n ns: ['validation'],\n resources: {'en-US': {validation: validationLocaleStrings}},\n supportedLngs: ['en-US'],\n })\n void i18n.init()\n\n fallbackLocaleSource = {\n currentLocale: {id: 'en-US'},\n loadNamespaces: (namespaces) => i18n.loadNamespaces(namespaces),\n t: i18n.t,\n }\n return fallbackLocaleSource\n}\n","import {type ConditionalProperty, type CurrentUser, type Path} from '@sanity/types'\n\ninterface ConditionalPropertyCallbackContext {\n parent?: unknown\n document?: Record<string, unknown>\n currentUser: Omit<CurrentUser, 'role'> | null\n value: unknown\n path: Path\n}\n\nexport function resolveConditionalProperty(\n property: ConditionalProperty,\n context: ConditionalPropertyCallbackContext,\n) {\n const {currentUser, document, parent, value, path} = context\n\n if (typeof property === 'boolean' || property === undefined) return Boolean(property)\n\n // oxlint-disable-next-line no-unnecessary-boolean-literal-compare -- runtime callbacks may return non-booleans\n return property({document: document as never, parent, value, currentUser, path}) === true\n}\n","import {isKeyedObject, type Path} from '@sanity/types'\n\nexport function pathToString(path: Path | undefined = []): string {\n return path.reduce<string>((target, segment, i) => {\n const segmentType = typeof segment\n if (segmentType === 'number') {\n return `${target}[${segment}]`\n }\n\n if (segmentType === 'string') {\n const separator = i === 0 ? '' : '.'\n return `${target}${separator}${segment}`\n }\n\n if (isKeyedObject(segment)) {\n return `${target}[_key==\"${segment._key}\"]`\n }\n\n throw new Error(`Unsupported path segment \"${segment}\"`)\n }, '')\n}\n","/* oxlint-disable typescript/no-deprecated -- marker compatibility requires legacy fields */\nimport {type Path, type ValidationError, type ValidationMarker} from '@sanity/types'\n\nimport {type ValidationMarkerCode, validationMarkerCodes} from '../codes'\nimport {type ValidationContext} from '../types'\nimport {pathToString} from '../util/pathToString'\n\nexport function convertToValidationMarker(\n validatorResult: true | true[] | string | string[] | ValidationError | ValidationError[],\n level: 'error' | 'warning' | 'info' | undefined,\n context: ValidationContext,\n fallback: {code: ValidationMarkerCode; details?: Record<string, unknown>} = {\n code: validationMarkerCodes.validationFailed,\n },\n): ValidationMarker[] {\n if (!context) {\n throw new Error('missing context')\n }\n\n if (validatorResult === true) return []\n\n if (Array.isArray(validatorResult)) {\n return validatorResult.flatMap((child) =>\n convertToValidationMarker(child, level, context, fallback),\n )\n }\n\n if (typeof validatorResult === 'string') {\n return convertToValidationMarker({message: validatorResult}, level, context, fallback)\n }\n\n if (typeof validatorResult.message !== 'string') {\n // in order to accept the `ValidationError`, it at least needs to have a\n // `message` in the object\n throw new Error(\n `${pathToString(\n context.path,\n )}: Validator must return 'true' if valid or an error message as a string on errors`,\n )\n }\n\n const {message, __internal_metadata} = validatorResult\n const code = validatorResult.code || fallback.code\n const details = validatorResult.details || fallback.details\n\n const normalizedPaths: Path[] = []\n if (validatorResult.path) {\n normalizedPaths.push(validatorResult.path)\n }\n\n // legacy support for `paths`\n for (const path of validatorResult.paths || []) {\n normalizedPaths.push(path)\n }\n\n // the validator result does not include any item-level relative paths,\n // then just return the top-level path with the validation result\n if (!normalizedPaths.length) {\n return [\n {\n code,\n ...(details && {details}),\n level: level || 'error',\n item: {message},\n message,\n path: context.path || [],\n __internal_metadata,\n },\n ]\n }\n\n // if the validator result did include item-level relative paths, then for\n // each item-level relative path, create a validation marker that concatenates\n // the relative path with the path from the validation context\n return normalizedPaths.map((path) => ({\n code,\n ...(details && {details}),\n path: (context.path || []).concat(path),\n level: level || 'error',\n item: {message},\n message,\n __internal_metadata,\n }))\n}\n","import {type CustomValidatorResult, type LocalizedValidationMessages} from '@sanity/types'\nimport isPlainObject from 'lodash-es/isPlainObject.js'\n\nimport {type LocaleSource} from '../i18n/types'\n\n/**\n * Extracts the correct localized validation message based on given locale source\n *\n * @param message - Localized messages to extract string from\n * @param i18n - Locale source, holding the current locale\n * @returns The localized string, or a fallback \"Unknown error\" if not found\n * @internal\n */\nexport function localizeMessage(message: LocalizedValidationMessages, i18n: LocaleSource): string {\n const {currentLocale} = i18n\n const locale = currentLocale.id\n\n // Obviously, try direct match first (`no-NB`)\n if (message[locale]) {\n return message[locale]\n }\n\n // In the case of composed languages (`en-US`, `no-NB` etc), fall back to base language (`en`)\n if (locale.includes('-')) {\n const language = locale.split('-', 1)[0]\n if (message[language]) {\n return message[language]\n }\n }\n\n // Try english as last resort\n return (\n message['en-US'] || message['en-GB'] || message.en || 'Unknown validation error (not localized)'\n )\n}\n\n/**\n * Check if passed message/result is a localized message object\n *\n * @param message - Message to check\n * @returns True if message is a localized message object, false otherwise\n * @internal\n */\nexport function isLocalizedMessages(\n message: CustomValidatorResult | undefined,\n): message is LocalizedValidationMessages {\n return (\n message !== true &&\n typeof message !== 'undefined' &&\n typeof message !== 'string' &&\n isPlainObject(message) &&\n !('message' in message)\n )\n}\n","/**\n * Modified version of fast-deep-equal (https://github.com/epoberezkin/fast-deep-equal)\n * MIT-licensed, copyright (c) 2017 Evgeny Poberezkin\n **/\n\n// NOTE: when converting to typescript, some of the checks were inlined (vs\n// having them in a variable) because the type predicate type narrowing only\n// works when type predicate is called inline in the condition that starts the\n// control flow branch.\n// see here: https://www.typescriptlang.org/docs/handbook/2/narrowing.html\nexport function deepEqualsIgnoreKey(a: unknown, b: unknown): boolean {\n if (a === b) {\n return true\n }\n\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length != b.length) return false\n for (let i = 0; i < a.length; i++) {\n if (!deepEqualsIgnoreKey(a[i], b[i])) {\n return false\n }\n }\n return true\n }\n\n if (Array.isArray(a) != Array.isArray(b)) {\n return false\n }\n\n if (a && b && typeof a === 'object' && typeof b === 'object') {\n const keys = Object.keys(a).filter((key) => key !== '_key')\n if (keys.length !== Object.keys(b).filter((key) => key !== '_key').length) {\n return false\n }\n\n if (a instanceof Date && b instanceof Date) {\n return a.getTime() === b.getTime()\n }\n\n if (a instanceof Date != b instanceof Date) {\n return false\n }\n\n if (a instanceof RegExp && b instanceof RegExp) {\n return a.toString() == b.toString()\n }\n\n if (a instanceof RegExp != b instanceof RegExp) {\n return false\n }\n\n for (let i = 0; i < keys.length; i++) {\n if (!Object.prototype.hasOwnProperty.call(b, keys[i])) {\n return false\n }\n }\n\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i] as keyof typeof a\n if (!deepEqualsIgnoreKey(a[key], b[key])) {\n return false\n }\n }\n\n return true\n }\n\n return false\n}\n","// this file was adapted from a previous dependency `type-of-is`\n// https://github.com/stephenhandley/type-of-is/blob/7138a7e79f5af7c286bf8123f60843a91aaebf38/index.js\nconst _toString = {}.toString\n\nconst builtIns = [Object, Function, Array, String, Boolean, Number, Date, RegExp, Error]\n\nfunction isBuiltIn(_constructor: unknown) {\n for (let i = 0; i < builtIns.length; i++) {\n if (builtIns[i] === _constructor) return true\n }\n return false\n}\n\nexport function typeString(obj: unknown): string {\n // [object Blah] -> Blah\n const stringType = _toString.call(obj).slice(8, -1)\n if (obj === null || obj === undefined) return stringType.toLowerCase()\n\n const constructorType = (obj as object).constructor\n if (constructorType && !isBuiltIn(constructorType)) return constructorType.name\n return stringType\n}\n","/* oxlint-disable typescript/no-deprecated -- marker compatibility requires the legacy item field */\nimport {type ValidationError, type ValidationMarker, type Validators} from '@sanity/types'\n\nimport {validationMarkerCodes} from '../codes'\nimport {type LocaleSource} from '../i18n/types'\nimport {deepEqualsIgnoreKey} from '../util/deepEqualsIgnoreKey'\nimport {isLocalizedMessages, localizeMessage} from '../util/localizeMessage'\nimport {pathToString} from '../util/pathToString'\nimport {typeString} from '../util/typeString'\n\nexport const SLOW_VALIDATOR_TIMEOUT = 5000\n\nconst formatValidationErrors = (options: {\n message: string | undefined\n results: ValidationMarker[]\n operation: 'conjunction' | 'disjunction'\n i18n: LocaleSource\n}): ValidationError => {\n const message =\n options.message ||\n (options.results.length === 1\n ? options.results[0]?.message\n : // Intentionally hard-coded to use locale conjunction/disjunctions\n options.i18n.t('{{messages, list}}', {\n messages: options.results.map((err) => err.message || err.item?.message),\n formatParams: {messages: {style: 'long', type: options.operation}},\n }))\n\n return {\n code:\n options.operation === 'conjunction'\n ? validationMarkerCodes.ruleAllFailed\n : validationMarkerCodes.ruleEitherFailed,\n details: {\n causes: options.results.map(({code, details, item, message: causeMessage, path}) => ({\n code: code || validationMarkerCodes.validationFailed,\n details,\n message: causeMessage || item?.message,\n path,\n })),\n },\n message: message || 'Validation failed',\n }\n}\n\nexport const genericValidators: Validators = {\n type: (expectedType, value, message, {i18n}) => {\n const actualType = typeString(value)\n if (actualType !== expectedType && actualType !== 'undefined') {\n return {\n code: validationMarkerCodes.valueTypeMismatch,\n details: {actualType, expectedType},\n message: message || i18n.t('validation:generic.incorrect-type', {actualType, expectedType}),\n }\n }\n\n return true\n },\n\n presence: (expected, value, message, {i18n}) => {\n if (value === undefined && expected === 'required') {\n return {\n code: validationMarkerCodes.valueRequired,\n message: message || i18n.t('validation:generic.required'),\n }\n }\n\n return true\n },\n\n all: async (children, value, message, context) => {\n const resolved = await Promise.all(children.map((child) => child.validate(value, context)))\n const results = resolved.flat()\n\n if (results.length === 0) {\n return true\n }\n\n return formatValidationErrors({\n message,\n results,\n operation: 'conjunction',\n i18n: context.i18n,\n })\n },\n\n either: async (children, value, message, context) => {\n const resolved = await Promise.all(children.map((child) => child.validate(value, context)))\n const results = resolved.flat()\n\n // if one of the results is an empty array then at least one rule match\n if (resolved.find((result) => !result.length)) {\n return true\n }\n\n return formatValidationErrors({\n message,\n results,\n operation: 'disjunction',\n i18n: context.i18n,\n })\n },\n\n valid: (allowedValues, actual, message, {i18n}) => {\n const valueType = typeof actual\n if (valueType === 'undefined') {\n return true\n }\n\n const value = (valueType === 'number' || valueType === 'string') && `${actual}`\n const strValue = value && value.length > 30 ? `${value.slice(0, 30)}…` : value\n\n if (allowedValues.some((expected) => deepEqualsIgnoreKey(expected, actual))) {\n return true\n }\n\n return {\n code: validationMarkerCodes.valueNotAllowed,\n details: {allowedValuesCount: allowedValues.length},\n message:\n message ||\n i18n.t(\n 'validation:generic.not-allowed',\n value ? {context: 'hint', replace: {hint: strValue}} : {},\n ),\n }\n },\n\n custom: async (fn, value, message, context) => {\n const slowTimer = setTimeout(() => {\n // only show this warning in the studio\n if (context.environment !== 'studio') return\n\n console.warn(\n `Custom validator at ${pathToString(\n context.path,\n )} has taken more than ${SLOW_VALIDATOR_TIMEOUT}ms to respond`,\n )\n }, SLOW_VALIDATOR_TIMEOUT)\n\n let result\n try {\n result = await fn(value, context)\n } finally {\n clearTimeout(slowTimer)\n }\n\n if (isLocalizedMessages(result)) {\n return localizeMessage(result, context.i18n)\n }\n\n if (typeof result === 'string') {\n return message || result\n }\n\n return result\n },\n}\n","import {\n isArrayOfBlocksSchemaType,\n type Path,\n type PathSegment,\n type Validators,\n} from '@sanity/types'\n\nimport {validationMarkerCodes} from '../codes'\nimport {deepEqualsIgnoreKey} from '../util/deepEqualsIgnoreKey'\nimport {genericValidators} from './genericValidator'\n\nexport const arrayValidators: Validators = {\n ...genericValidators,\n\n min: (minLength, value, message, {i18n, type}) => {\n if (!value || value.length >= minLength) {\n return true\n }\n\n const context = isArrayOfBlocksSchemaType(type) ? 'blocks' : undefined\n return {\n code: validationMarkerCodes.arrayMinimumLength,\n details: {actualLength: value.length, minimumLength: minLength},\n message: message || i18n.t('validation:array.minimum-length', {minLength, context}),\n }\n },\n\n max: (maxLength, value, message, {i18n, type}) => {\n if (!value || value.length <= maxLength) {\n return true\n }\n\n const context = isArrayOfBlocksSchemaType(type) ? 'blocks' : undefined\n return {\n code: validationMarkerCodes.arrayMaximumLength,\n details: {actualLength: value.length, maximumLength: maxLength},\n message: message || i18n.t('validation:array.maximum-length', {maxLength, context}),\n }\n },\n\n length: (wantedLength, value, message, {i18n, type}) => {\n if (!value || value.length === wantedLength) {\n return true\n }\n\n const context = isArrayOfBlocksSchemaType(type) ? 'blocks' : undefined\n return {\n code: validationMarkerCodes.arrayExactLength,\n details: {actualLength: value.length, expectedLength: wantedLength},\n message: message || i18n.t('validation:array.exact-length', {wantedLength, context}),\n }\n },\n\n presence: (flag, value, message, {i18n}) => {\n if (flag === 'required' && !value) {\n return {\n code: validationMarkerCodes.valueRequired,\n message: message || i18n.t('validation:generic.required', {context: 'array'}),\n }\n }\n\n return true\n },\n\n valid: (allowedValues, values, message, {i18n}) => {\n const valueType = typeof values\n if (valueType === 'undefined') {\n return true\n }\n\n const paths: Path[] = []\n for (let i = 0; i < values.length; i++) {\n const value = values[i]\n if (allowedValues.some((expected) => deepEqualsIgnoreKey(expected, value))) {\n continue\n }\n\n const pathSegment: PathSegment = value && value._key ? {_key: value._key} : i\n paths.push([pathSegment])\n }\n\n // we emit the same message for each path we find in this array\n const sharedMessage = message || i18n.t('validation:generic.not-allowed')\n\n return paths.map((path) => ({\n code: validationMarkerCodes.valueNotAllowed,\n details: {allowedValuesCount: allowedValues.length},\n message: sharedMessage,\n path,\n }))\n },\n\n unique: (_unused, value, message, {i18n}) => {\n const dupeIndices = []\n if (!value) {\n return true\n }\n\n for (let x = 0; x < value.length; x++) {\n for (let y = x + 1; y < value.length; y++) {\n const itemA = value[x]\n const itemB = value[y]\n\n if (!deepEqualsIgnoreKey(itemA, itemB)) {\n continue\n }\n\n if (dupeIndices.indexOf(x) === -1) {\n dupeIndices.push(x)\n }\n\n if (dupeIndices.indexOf(y) === -1) {\n dupeIndices.push(y)\n }\n }\n }\n\n const paths = dupeIndices.map((idx) => {\n const item = value[idx]\n const pathSegment = item && item._key ? {_key: item._key} : idx\n return [pathSegment]\n })\n\n // we emit the same message for each path we find in this array\n const sharedMessage = message || i18n.t('validation:array.item-duplicate')\n\n return paths.map((path) => ({\n code: validationMarkerCodes.arrayDuplicateItem,\n message: sharedMessage,\n path,\n }))\n },\n}\n","import {type Validators} from '@sanity/types'\n\nimport {validationMarkerCodes} from '../codes'\nimport {genericValidators} from './genericValidator'\n\nexport const booleanValidators: Validators = {\n ...genericValidators,\n\n presence: (flag, value, message, {i18n}) => {\n if (flag === 'required' && typeof value !== 'boolean') {\n return {\n code: validationMarkerCodes.valueRequired,\n message: message || i18n.t('validation:generic.required', {context: 'boolean'}),\n }\n }\n\n return true\n },\n}\n","import {type SchemaType} from '@sanity/types'\n\nexport function getTypeChain(\n type: SchemaType | undefined,\n visited: Set<SchemaType> = new Set(),\n): SchemaType[] {\n if (!type) return []\n if (visited.has(type)) return []\n\n visited.add(type)\n\n const next = type.type ? getTypeChain(type.type, visited) : []\n return [...next, type]\n}\n","import {type SchemaType, type Validators} from '@sanity/types'\nimport * as legacyDateFormat from '@sanity/util/legacyDateFormat'\n\nimport {validationMarkerCodes} from '../codes'\nimport {getTypeChain} from '../util/getTypeChain'\nimport {genericValidators} from './genericValidator'\n\nfunction isRecord(obj: unknown): obj is Record<string, unknown> {\n return typeof obj === 'object' && obj !== null && !Array.isArray(obj)\n}\n\nconst isoDate =\n /^(?:[-+]\\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)?)?)?)?$/\n\n// TODO (eventually): move these to schema type package\ninterface DateTimeOptions {\n // @todo accept object representing `Intl.DateTimeFormatOptions`? how do we localize?\n dateFormat?: string\n timeFormat?: string\n}\n\nconst getFormattedDate = (type: SchemaType, value: Date, options?: DateTimeOptions) => {\n const dateOnly = getTypeChain(type).some((candidate) => candidate.name === 'date')\n const dateFormat = options?.dateFormat || legacyDateFormat.DEFAULT_DATE_FORMAT\n const timeFormat = options?.timeFormat || legacyDateFormat.DEFAULT_TIME_FORMAT\n\n // adding the time information in the date only case causes timezone information to be kept\n // instead of it being assumed to be UTC. This was a problem because midnight UTC is the previous\n // day in many other timezones resulting in the date displayed to be the previous day.\n return legacyDateFormat.format(value, dateOnly ? dateFormat : `${dateFormat} ${timeFormat}`, {\n useUTC: dateOnly,\n })\n}\n\nfunction parseDate(date: unknown): Date | null\nfunction parseDate(date: unknown, throwOnError: true): Date\nfunction parseDate(date: unknown, throwOnError = false): Date | null {\n if (!date) return null\n if (date === 'now') return new Date()\n\n // oxlint-disable-next-line no-explicit-any\n const parsed = new Date(date as any)\n const isInvalid = isNaN(parsed.getTime())\n if (isInvalid && throwOnError) {\n throw new Error(`Unable to parse \"${date}\" to a date`)\n }\n\n return isInvalid ? null : parsed\n}\n\nexport const dateValidators: Validators = {\n ...genericValidators,\n\n type: (_unused, value, message, {i18n}) => {\n if (typeof value === 'undefined' || isoDate.test(`${value}`)) {\n return true\n }\n\n return {\n code: validationMarkerCodes.dateInvalidFormat,\n details: {actualValue: value},\n message: message || i18n.t('validation:date.invalid-format'),\n }\n },\n\n min: (minDate, value, message, {type, i18n}) => {\n const dateVal = parseDate(value)\n const minDateVal = parseDate(minDate, true)\n\n if (!dateVal) {\n return true // `type()` should catch parse errors\n }\n\n if (!value || dateVal >= minDateVal) {\n return true\n }\n\n if (!type) {\n throw new Error(`\\`type\\` was not provided in validation context.`)\n }\n\n const dateTimeOptions: DateTimeOptions = isRecord(type.options)\n ? (type.options as DateTimeOptions)\n : {}\n\n return {\n code: validationMarkerCodes.dateMinimum,\n details: {actualValue: value, minimum: minDate},\n message:\n message ||\n // Note that the `minDate` passed here is _formatted_, while the raw value provided to the\n // validator is available as `providedMinDate`. This because the formatted date is likely\n // what the developer wants to present to the user\n i18n.t('validation:date.minimum', {\n minDate: getFormattedDate(type, minDateVal, dateTimeOptions),\n providedMinDate: minDate,\n }),\n }\n },\n\n max: (maxDate, value, message, {type, i18n}) => {\n const dateVal = parseDate(value)\n const maxDateVal = parseDate(maxDate, true)\n\n if (!dateVal) {\n return true // `type()` should catch parse errors\n }\n\n if (!value || dateVal <= maxDateVal) {\n return true\n }\n\n if (!type) {\n throw new Error(`\\`type\\` was not provided in validation context.`)\n }\n\n const dateTimeOptions: DateTimeOptions = isRecord(type.options)\n ? (type.options as DateTimeOptions)\n : {}\n\n return {\n code: validationMarkerCodes.dateMaximum,\n details: {actualValue: value, maximum: maxDate},\n message:\n message ||\n // Note that the `maxDate` passed here is _formatted_, while the raw value provided to the\n // validator is available as `providedMaxDate`. This because the formatted date is likely\n // what the developer wants to present to the user\n i18n.t('validation:date.maximum', {\n maxDate: getFormattedDate(type, maxDateVal, dateTimeOptions),\n providedMaxDate: maxDate,\n }),\n }\n },\n}\n","import {type Validators} from '@sanity/types'\n\nimport {validationMarkerCodes} from '../codes'\nimport {genericValidators} from './genericValidator'\n\nconst precisionRx = /(?:\\.(\\d+))?(?:[eE]([+-]?\\d+))?$/\n\nexport const numberValidators: Validators = {\n ...genericValidators,\n\n integer: (_unused, value, message, {i18n}) => {\n if (!Number.isInteger(value)) {\n return {\n code: validationMarkerCodes.numberInteger,\n details: {actualValue: value},\n message: message || i18n.t('validation:number.non-integer'),\n }\n }\n\n return true\n },\n\n precision: (limit, value, message, {i18n}) => {\n if (value === undefined) return true\n\n const places = value.toString().match(precisionRx)\n const decimals = Math.max(\n (places[1] ? places[1].length : 0) - (places[2] ? parseInt(places[2], 10) : 0),\n 0,\n )\n\n if (decimals > limit) {\n return {\n code: validationMarkerCodes.numberPrecision,\n details: {actualPrecision: decimals, maximumPrecision: limit},\n message: message || i18n.t('validation:number.maximum-precision', {limit}),\n }\n }\n\n return true\n },\n\n min: (minNumber, value, message, {i18n}) => {\n if (value >= minNumber) {\n return true\n }\n\n return {\n code: validationMarkerCodes.numberMinimum,\n details: {actualValue: value, minimum: minNumber},\n message: message || i18n.t('validation:number.minimum', {minNumber}),\n }\n },\n\n max: (maxNumber, value, message, {i18n}) => {\n if (value <= maxNumber) {\n return true\n }\n\n return {\n code: validationMarkerCodes.numberMaximum,\n details: {actualValue: value, maximum: maxNumber},\n message: message || i18n.t('validation:number.maximum', {maxNumber}),\n }\n },\n\n greaterThan: (threshold, value, message, {i18n}) => {\n if (value > threshold) {\n return true\n }\n\n return {\n code: validationMarkerCodes.numberGreaterThan,\n details: {actualValue: value, threshold},\n message: message || i18n.t('validation:number.greater-than', {threshold}),\n }\n },\n\n lessThan: (threshold, value, message, {i18n}) => {\n if (value < threshold) {\n return true\n }\n\n return {\n code: validationMarkerCodes.numberLessThan,\n details: {actualValue: value, threshold},\n message: message || i18n.t('validation:number.less-than', {threshold}),\n }\n },\n}\n","import {type DocumentId, getPublishedId} from '@sanity/id-utils'\nimport {\n type CustomValidatorResult,\n isReference,\n isReferenceSchemaType,\n type Validators,\n} from '@sanity/types'\n\nimport {validationMarkerCodes} from '../codes'\nimport {type InternalValidationContext} from '../types'\nimport {isLocalizedMessages, localizeMessage} from '../util/localizeMessage'\nimport {pathToString} from '../util/pathToString'\nimport {typeString} from '../util/typeString'\nimport {genericValidators, SLOW_VALIDATOR_TIMEOUT} from './genericValidator'\n\nconst metaKeys = ['_key', '_type', '_weak']\n\ninterface MediaLibraryAsset {\n currentVersion: Record<string, unknown>\n [key: string]: unknown\n}\n\nexport const objectValidators: Validators = {\n ...genericValidators,\n\n presence: (expected, value, message, {i18n}) => {\n if (expected !== 'required') {\n return true\n }\n\n const keys = value && Object.keys(value).filter((key) => !metaKeys.includes(key))\n\n if (value === undefined || (keys && keys.length === 0)) {\n return {\n code: validationMarkerCodes.valueRequired,\n message: message || i18n.t('validation:generic.required', {context: 'object'}),\n }\n }\n\n return true\n },\n\n reference: async (_unused, value: unknown, message, context) => {\n if (!value) {\n return true\n }\n\n const {type, document, getDocumentExists, i18n} = context\n\n if (!isReference(value)) {\n return {\n code: validationMarkerCodes.referenceInvalid,\n details: {actualType: typeString(value)},\n message: message || i18n.t('validation:object.not-reference'),\n }\n }\n\n if (!type) {\n throw new Error(`\\`type\\` was not provided in validation context`)\n }\n\n const getDocumentType = (context as InternalValidationContext).__internal?.getDocumentType\n const weak = 'weak' in type && type.weak\n if (weak && !getDocumentType) {\n return true\n }\n\n if (!getDocumentExists) {\n throw new Error(`\\`getDocumentExists\\` was not provided in validation context`)\n }\n\n const selfReference = document?._id && value._ref === getPublishedId(document._id as DocumentId)\n // A self-reference needs no lookup, even if the document is not published yet.\n const exists =\n selfReference || (await getDocumentExists({id: value._ref, signal: context.signal}))\n if (!exists && !weak) {\n return {\n code: validationMarkerCodes.referenceNotPublished,\n details: {referenceId: value._ref},\n message: i18n.t('validation:object.reference-not-published', {documentId: value._ref}),\n }\n }\n\n if (exists && getDocumentType && isReferenceSchemaType(type)) {\n const actualType = selfReference ? document?._type : await getDocumentType(value._ref)\n if (!actualType) {\n throw new Error(`Could not read the type of referenced document \"${value._ref}\"`)\n }\n const allowedTypes = type.to.map((target) => target.name)\n if (!allowedTypes.includes(actualType)) {\n return {\n code: validationMarkerCodes.referenceTargetTypeMismatch,\n details: {referenceId: value._ref, actualType, allowedTypes},\n message: i18n.t('validation:object.reference-target-type-mismatch', {\n actualType,\n allowedTypes: allowedTypes.join(', '),\n }),\n }\n }\n }\n\n return true\n },\n\n assetRequired: (flag, value, message, {i18n}) => {\n if (!value || !value.asset || !value.asset._ref) {\n return {\n __internal_metadata: {\n name: 'assetRequired',\n },\n code: validationMarkerCodes.assetRequired,\n details: {assetType: flag.assetType},\n message:\n message || i18n.t('validation:object.asset-required', {context: flag.assetType || ''}),\n }\n }\n\n return true\n },\n\n media: async (fn, value, message, context) => {\n const slowTimer = setTimeout(() => {\n // only show this warning in the studio\n if (context.environment !== 'studio') return\n\n console.warn(\n `Media validator at ${pathToString(\n context.path,\n )} has taken more than ${SLOW_VALIDATOR_TIMEOUT}ms to respond`,\n )\n }, SLOW_VALIDATOR_TIMEOUT)\n\n // If no value is provided, we assume the validation passes. This should be handled by the 'isRequired' validator.\n if (!value) {\n return true\n }\n\n // If the value is not an object or does not have a media reference, we return an error message.\n // It should not be allowed to use regular dataset assets with this validator.\n if (!value || !value.media || !value.media._ref) {\n return {\n code: validationMarkerCodes.mediaInvalidReference,\n message: context.i18n.t('validation:object.not-media-library-asset'),\n }\n }\n\n let result: CustomValidatorResult = true\n\n try {\n const [type, libraryId, documentId] = value.media._ref.split(':', 3)\n // TODO: replace this with stable resource config when available\n const resourceConfig = {resource: {type, id: libraryId}}\n const asset = await context\n .getClient({apiVersion: '2025-02-19'})\n .withConfig(resourceConfig)\n .fetch<MediaLibraryAsset | null>(\n `*[_id == $id] { ..., 'currentVersion': @.currentVersion-> { ... } }[0]`,\n {\n id: documentId,\n },\n {signal: context.signal},\n )\n if (!asset) {\n console.warn(\n `${context.i18n.t('validation:object.media-not-found')}\\nAsset ID: ${value.media._ref}`,\n )\n return {\n code: validationMarkerCodes.mediaNotFound,\n details: {referenceId: value.media._ref},\n message: context.i18n.t('validation:object.media-not-found'),\n }\n }\n\n result = await fn(\n {\n media: {\n asset: asset as unknown as Parameters<typeof fn>[0]['media']['asset'],\n },\n value,\n },\n context,\n )\n } catch (err) {\n const error = new Error(\n `Media validator at ${pathToString(\n context.path,\n )} failed with an error: ${err instanceof Error ? err.message : String(err)}`,\n {cause: err},\n )\n throw error\n } finally {\n clearTimeout(slowTimer)\n }\n\n const validationErrorMetadata = {\n __internal_metadata: {\n name: 'media',\n },\n }\n\n // Valid, no errors\n if (result === true) {\n return result\n }\n\n // Ensure we always return ValidationMarker with metadata\n return Array.isArray(result)\n ? result\n : [result].map((res) => {\n if (typeof res === 'string') {\n return {...validationErrorMetadata, message: message || res}\n }\n if (isLocalizedMessages(res)) {\n return {\n ...validationErrorMetadata,\n message: message || localizeMessage(res, context.i18n),\n }\n }\n return {...validationErrorMetadata, ...res, message: message || res.message}\n })\n },\n}\n","import {type DocumentId, getPublishedId} from '@sanity/id-utils'\nimport {\n type CustomValidator,\n isKeyedObject,\n isSlug,\n type Path,\n type SlugIsUniqueValidator,\n type SlugParent,\n type SlugSchemaType,\n type SlugValidationContext,\n} from '@sanity/types'\nimport memoize from 'lodash-es/memoize.js'\n\nimport {validationMarkerCodes} from '../codes'\nimport {typeString} from '../util/typeString'\n\nconst DEFAULT_API_VERSION = '2025-02-19'\n\nconst memoizedWarnOnArraySlug = memoize(warnOnArraySlug)\n\nexport function hasCustomSlugUniqueness(\n options: unknown,\n): options is {isUnique: SlugIsUniqueValidator} {\n return (\n typeof options === 'object' &&\n options !== null &&\n 'isUnique' in options &&\n typeof options.isUnique === 'function'\n )\n}\n\nfunction serializePath(path: Path): string {\n return path.reduce<string>((target, part, i) => {\n const isIndex = typeof part === 'number'\n const isKey = isKeyedObject(part)\n const separator = i === 0 ? '' : '.'\n const add = isIndex || isKey ? '[]' : `${separator}${part}`\n return `${target}${add}`\n }, '')\n}\n\nconst defaultIsUnique: SlugIsUniqueValidator = (slug, context) => {\n const {getClient, document, path, type} = context\n const schemaOptions = type?.options\n\n if (!document) {\n throw new Error(`\\`document\\` was not provided in validation context.`)\n }\n if (!path) {\n throw new Error(`\\`path\\` was not provided in validation context.`)\n }\n\n const disableArrayWarning = schemaOptions?.disableArrayWarning || false\n const docType = document._type\n const atPath = serializePath(path.concat('current'))\n\n if (!disableArrayWarning && atPath.includes('[]') && context.environment === 'studio') {\n memoizedWarnOnArraySlug(serializePath(path))\n }\n\n const constraints = [\n '_type == $docType',\n `!sanity::versionOf($published)`,\n `${atPath} == $slug`,\n ].join(' && ')\n\n return getClient({apiVersion: DEFAULT_API_VERSION})\n .withConfig({perspective: 'raw'})\n .fetch<boolean>(\n `!defined(*[${constraints}][0]._id)`,\n {\n docType,\n published: getPublishedId(document._id as DocumentId),\n slug,\n },\n {signal: context.signal, tag: 'validation.slug-is-unique'},\n )\n}\n\nfunction warnOnArraySlug(serializedPath: string) {\n console.warn(\n [\n `Slug field at path ${serializedPath} is within an array and cannot be automatically checked for uniqueness`,\n `If you need to check for uniqueness, provide your own \"isUnique\" method`,\n `To disable this message, set \\`disableArrayWarning: true\\` on the slug \\`options\\` field`,\n ].join('\\n'),\n )\n}\n\nexport const slugStructureValidator: CustomValidator = (value, context) => {\n if (!value) {\n return true\n }\n\n const {i18n} = context\n\n if (typeof value !== 'object' || Array.isArray(value)) {\n return {\n code: validationMarkerCodes.slugInvalidType,\n details: {actualType: typeString(value)},\n message: i18n.t('validation:slug.not-object'),\n }\n }\n\n if (!isSlug(value) || value.current.trim().length === 0) {\n return {\n code: validationMarkerCodes.slugMissingCurrent,\n message: i18n.t('validation:slug.missing-current'),\n }\n }\n\n return true\n}\n\nasync function validateSlugUniqueness(\n value: unknown,\n context: Parameters<CustomValidator>[1],\n isUnique: SlugIsUniqueValidator,\n) {\n if (!isSlug(value) || value.current.trim().length === 0) {\n return true\n }\n\n const {i18n} = context\n const slugContext: SlugValidationContext = {\n ...context,\n parent: context.parent as SlugParent,\n type: context.type as SlugSchemaType,\n defaultIsUnique,\n }\n\n const wasUnique = await isUnique(value.current, slugContext)\n if (wasUnique) {\n return true\n }\n\n return {\n code: validationMarkerCodes.slugNotUnique,\n details: {slug: value.current},\n message: i18n.t('validation:slug.not-unique', {slug: value.current}),\n }\n}\n\nexport const slugUniquenessValidator: CustomValidator = (value, context) => {\n const options = context.type?.options\n const isUnique = hasCustomSlugUniqueness(options) ? options.isUnique : defaultIsUnique\n return validateSlugUniqueness(value, context, isUnique)\n}\n","import {type Validators} from '@sanity/types'\n\nimport {validationMarkerCodes} from '../codes'\nimport {genericValidators} from './genericValidator'\n\nconst DUMMY_ORIGIN = 'http://sanity'\nconst isRelativeUrl = (url: string) => /^\\.*\\//.test(url)\n\n// WHATWG \"special\" schemes, whose hosts are domains rather than opaque strings\nconst SPECIAL_SCHEMES = new Set(['http:', 'https:', 'ws:', 'wss:', 'ftp:', 'file:'])\n// WHATWG \"forbidden domain code point\"\nconst FORBIDDEN_DOMAIN_CODE_POINT = /[\\p{Cc} #/:<>?@[\\\\\\]^|%]/u\n\n// Node follows the spec and fails to parse a domain that percent-decodes to a forbidden code point,\n// but Chrome keeps `%20` in `hostname` and accepts it, so check the decoded host ourselves\nfunction hasInvalidDomain(url: URL): boolean {\n if (!SPECIAL_SCHEMES.has(url.protocol) || url.hostname.startsWith('[')) return false\n try {\n return FORBIDDEN_DOMAIN_CODE_POINT.test(decodeURIComponent(url.hostname))\n } catch {\n return true\n }\n}\nconst emailRegex =\n /^(([^<>()[\\]\\\\.,;:\\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,}))$/\n\nexport const stringValidators: Validators = {\n ...genericValidators,\n\n min: (minLength, value, message, {i18n}) => {\n if (!value || value.length >= minLength) {\n return true\n }\n\n return {\n code: validationMarkerCodes.stringMinimumLength,\n details: {actualLength: value.length, minimumLength: minLength},\n message: message || i18n.t('validation:string.minimum-length', {minLength}),\n }\n },\n\n max: (maxLength, value, message, {i18n}) => {\n if (!value || value.length <= maxLength) {\n return true\n }\n\n return {\n code: validationMarkerCodes.stringMaximumLength,\n details: {actualLength: value.length, maximumLength: maxLength},\n message: message || i18n.t('validation:string.maximum-length', {maxLength}),\n }\n },\n\n length: (wantedLength, value, message, {i18n}) => {\n const strValue = value || ''\n if (strValue.length === wantedLength) {\n return true\n }\n\n return {\n code: validationMarkerCodes.stringExactLength,\n details: {actualLength: strValue.length, expectedLength: wantedLength},\n message: message || i18n.t('validation:string.exact-length', {wantedLength}),\n }\n },\n\n uri: (constraints, value, message, {i18n}) => {\n const strValue = value || ''\n if (!strValue) {\n return true // `presence()` should catch empty values\n }\n\n const {options} = constraints\n const {allowCredentials, relativeOnly} = options\n const allowRelative = options.allowRelative || relativeOnly\n\n const invalidUrl = {\n code: validationMarkerCodes.stringUrlInvalid,\n message: message || i18n.t('validation:string.url.invalid'),\n }\n\n let url\n try {\n // WARNING: Safari checks for a given `base` param by looking at the length of arguments passed\n // to new URL(str, base), and will fail if invoked with new URL(strValue, undefined)\n url = allowRelative ? new URL(strValue, DUMMY_ORIGIN) : new URL(strValue)\n } catch {\n return invalidUrl\n }\n\n if (hasInvalidDomain(url)) {\n return invalidUrl\n }\n\n if (relativeOnly && url.origin !== DUMMY_ORIGIN) {\n return {\n code: validationMarkerCodes.stringUrlNotRelative,\n message: message || i18n.t('validation:string.url.not-relative'),\n }\n }\n\n if (!allowRelative && url.origin === DUMMY_ORIGIN && isRelativeUrl(strValue)) {\n return {\n code: validationMarkerCodes.stringUrlNotAbsolute,\n message: message || i18n.t('validation:string.url.not-absolute'),\n }\n }\n\n if (!allowCredentials && (url.username || url.password)) {\n return {\n code: validationMarkerCodes.stringUrlCredentialsNotAllowed,\n message: message || i18n.t('validation:string.url.includes-credentials'),\n }\n }\n\n const urlScheme = url.protocol.replace(/:$/, '')\n const isRelative = isRelativeUrl(strValue)\n const matchesAllowedScheme =\n isRelative || options.scheme.some((scheme) => scheme.test(urlScheme))\n if (!matchesAllowedScheme) {\n return {\n code: validationMarkerCodes.stringUrlSchemeNotAllowed,\n details: {scheme: urlScheme},\n message: message || i18n.t('validation:string.url.disallowed-scheme', {scheme: urlScheme}),\n }\n }\n\n return true\n },\n\n stringCasing: (casing, value, message, {i18n}) => {\n const strValue = value || ''\n if (casing === 'uppercase' && strValue !== strValue.toLocaleUpperCase()) {\n return {\n code: validationMarkerCodes.stringUppercase,\n message: message || i18n.t('validation:string.uppercase'),\n }\n }\n\n if (casing === 'lowercase' && strValue !== strValue.toLocaleLowerCase()) {\n return {\n code: validationMarkerCodes.stringLowercase,\n message: message || i18n.t('validation:string.lowercase'),\n }\n }\n\n return true\n },\n\n presence: (flag, value, message, {i18n}) => {\n if (flag === 'required' && !value) {\n return {\n code: validationMarkerCodes.valueRequired,\n message: message || i18n.t('validation:generic.required', {context: 'string'}),\n }\n }\n\n return true\n },\n\n regex: (options, value, message, {i18n}) => {\n const {pattern, name, invert} = options\n const regName = name || `${pattern.toString()}`\n const strValue = value || ''\n // Regexes with global or sticky flags are stateful (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/lastIndex).\n // This resets the state stored from the previous check\n pattern.lastIndex = 0\n const matches = pattern.test(strValue)\n if ((!invert && !matches) || (invert && matches)) {\n return {\n code: invert\n ? validationMarkerCodes.stringRegexMatch\n : validationMarkerCodes.stringRegexMismatch,\n details: {invert, name: regName, pattern: pattern.source},\n message:\n message ||\n (invert\n ? i18n.t('validation:string.regex-match', {name: regName})\n : i18n.t('validation:string.regex-does-not-match', {name: regName})),\n }\n }\n\n return true\n },\n\n email: (_unused, value, message, {i18n}) => {\n const strValue = `${value || ''}`.trim()\n if (!strValue || emailRegex.test(strValue)) {\n return true\n }\n\n return {\n code: validationMarkerCodes.stringEmail,\n message: message || i18n.t('validation:string.email'),\n }\n },\n}\n","/* oxlint-disable typescript/no-deprecated -- this is the concrete implementation of the legacy Rule internals */\nimport {Rule as BaseRule} from '@sanity/schema'\nimport {isInternalValidator} from '@sanity/schema/_internal'\nimport {\n type CustomValidator,\n type Rule as IRule,\n type RuleClass,\n type SchemaType,\n type ValidationMarker,\n type Validator,\n} from '@sanity/types'\nimport get from 'lodash-es/get.js'\n\nimport {ClientUnavailableError} from './clientUnavailable'\nimport {validationMarkerCodes} from './codes'\nimport {type InternalValidationContext} from './types'\nimport {convertToValidationMarker} from './util/convertToValidationMarker'\nimport {isLocalizedMessages, localizeMessage} from './util/localizeMessage'\nimport {pathToString} from './util/pathToString'\nimport {arrayValidators} from './validators/arrayValidator'\nimport {booleanValidators} from './validators/booleanValidator'\nimport {dateValidators} from './validators/dateValidator'\nimport {genericValidators} from './validators/genericValidator'\nimport {numberValidators} from './validators/numberValidator'\nimport {objectValidators} from './validators/objectValidator'\nimport {hasCustomSlugUniqueness, slugUniquenessValidator} from './validators/slugValidator'\nimport {stringValidators} from './validators/stringValidator'\n\nconst typeValidators = {\n Boolean: booleanValidators,\n Number: numberValidators,\n String: stringValidators,\n Array: arrayValidators,\n Object: objectValidators,\n Date: dateValidators,\n}\n\nconst isFieldRef = (constraint: unknown): constraint is {type: symbol; path: string | string[]} => {\n if (typeof constraint !== 'object' || !constraint) return false\n return (constraint as Record<string, unknown>).type === Rule.FIELD_REF\n}\n\nconst EMPTY_ARRAY: unknown[] = []\n\nconst fallbackCodeForRule = (flag: string) => {\n if (flag === 'custom') return validationMarkerCodes.custom\n if (flag === 'media') return validationMarkerCodes.mediaCustom\n if (flag === 'all') return validationMarkerCodes.ruleAllFailed\n if (flag === 'either') return validationMarkerCodes.ruleEitherFailed\n return validationMarkerCodes.validationFailed\n}\n\n/**\n * Concrete Rule implementation with validation logic.\n * This extends the base Rule class from `@sanity/schema` and adds the validate method.\n *\n * Note: `RuleClass` and `Rule` are split to fit the current `@sanity/types`\n * setup. Classes are a bit weird in the `@sanity/types` package because classes\n * create an actual javascript class while simultaneously creating a type\n * definition.\n *\n * This implicitly creates two types:\n * 1. the instance type — `Rule` and\n * 2. the static/class type - `RuleClass`\n *\n * The `RuleClass` type contains the static methods and the `Rule` instance\n * contains the instance methods.\n *\n * This package exports the RuleClass as a value without implicitly exporting\n * an instance definition. This should help reminder downstream users to import\n * from the `@sanity/types` package.\n *\n * @internal\n */\n// export class Rule extends BaseRule implements IRule {\nexport const Rule: RuleClass = class Rule extends BaseRule implements IRule {\n static array = (def?: SchemaType): Rule => new Rule(def).type('Array')\n static object = (def?: SchemaType): Rule => new Rule(def).type('Object')\n static string = (def?: SchemaType): Rule => new Rule(def).type('String')\n static number = (def?: SchemaType): Rule => new Rule(def).type('Number')\n static boolean = (def?: SchemaType): Rule => new Rule(def).type('Boolean')\n static dateTime = (def?: SchemaType): Rule => new Rule(def).type('Date')\n\n clone(): Rule {\n const rule = new Rule()\n rule._type = this._type\n rule._message = this._message\n rule._required = this._required\n rule._rules = [...this._rules]\n rule._level = this._level\n rule._fieldRules = this._fieldRules\n rule._typeDef = this._typeDef\n return rule\n }\n\n async validate(\n value: unknown,\n options: Parameters<IRule['validate']>[1],\n ): Promise<ValidationMarker[]> {\n const {__internal = {}, ...context} = options as InternalValidationContext\n const {customValidation = true, customValidationConcurrencyLimiter, markIncomplete} = __internal\n\n const valueIsEmpty = value === null || value === undefined\n\n // Short-circuit on optional, empty fields\n if (valueIsEmpty && this._required === 'optional') {\n return EMPTY_ARRAY as ValidationMarker[]\n }\n\n const rules =\n // Run only the _custom_ functions if the rule is not set to required or optional\n this._required === undefined && valueIsEmpty\n ? this._rules.filter((curr) => curr.flag === 'custom')\n : this._rules\n\n const validators = (this._type && typeValidators[this._type]) || genericValidators\n\n const results = await Promise.all(\n rules.map(async (curr) => {\n if (curr.flag === undefined) {\n throw new Error('Invalid rule, did not contain \"flag\"-property')\n }\n\n const validator: Validator | undefined = validators[curr.flag]\n if (!validator) {\n const forType = this._type ? `type \"${this._type}\"` : 'rule without declared type'\n throw new Error(`Validator for flag \"${curr.flag}\" not found for ${forType}`)\n }\n\n let specConstraint = 'constraint' in curr ? curr.constraint : null\n if (isFieldRef(specConstraint)) {\n specConstraint = get(context.parent, specConstraint.path)\n }\n\n if (curr.flag === 'custom' || curr.flag === 'media') {\n // Slug rules can be inherited from a compiled base type, so classify the\n // callback using the actual field's options at validation time.\n const usesCustomSlugUniqueness =\n specConstraint === slugUniquenessValidator &&\n hasCustomSlugUniqueness(context.type?.options)\n if (\n (!isInternalValidator(specConstraint) || usesCustomSlugUniqueness) &&\n !customValidation\n ) {\n markIncomplete?.()\n return []\n }\n }\n\n if (\n curr.flag === 'custom' &&\n customValidationConcurrencyLimiter &&\n !(specConstraint as CustomValidator)?.bypassConcurrencyLimit\n ) {\n const customValidator = specConstraint as CustomValidator\n specConstraint = (...args: Parameters<CustomValidator>) =>\n customValidationConcurrencyLimiter.run(() => customValidator(...args), context.signal)\n }\n\n const message = isLocalizedMessages(this._message)\n ? localizeMessage(this._message, context.i18n)\n : this._message\n\n try {\n // Built-in reference and composite rules need run state. Custom\n // callbacks still receive only the public validation context.\n const validatorContext =\n curr.flag === 'reference' || curr.flag === 'all' || curr.flag === 'either'\n ? {...context, __internal}\n : context\n const result = await validator(specConstraint, value, message, validatorContext)\n return convertToValidationMarker(result, this._level, context, {\n code: fallbackCodeForRule(curr.flag),\n })\n } catch (err) {\n context.signal?.throwIfAborted()\n markIncomplete?.()\n if (err instanceof ClientUnavailableError) {\n return []\n }\n\n const errorMessage = `${pathToString(\n context.path,\n )}: Exception occurred while validating value: ${err.message}`\n\n return convertToValidationMarker(\n {code: validationMarkerCodes.validationException, message: errorMessage},\n 'error',\n context,\n )\n }\n }),\n )\n\n return results.flat()\n }\n}\n","import {type SanityClient} from '@sanity/client'\n\ninterface AvailabilityResponse {\n omitted: {id: string; reason: 'existence' | 'permission'}[]\n}\n\n/** The amount of time reserved for waiting for new IDs. */\nconst BUFFER_TIME = 250\n\n/** The upper limit for IDs sent to the `doc` endpoint at once. */\nexport const MAX_BUFFER_SIZE = 100\n\n/** The `doc` endpoint is expensive, so batches are sent one at a time. */\nexport const MAX_REQUEST_CONCURRENCY = 1\n\ninterface PendingCheck {\n reject: (reason: unknown) => void\n resolve: (exists: boolean) => void\n settled: boolean\n signal?: AbortSignal\n onAbort?: () => void\n}\n\ntype Batch = Map<string, PendingCheck[]>\n\nfunction hasPendingChecks(batch: Batch): boolean {\n for (const checks of batch.values()) {\n if (checks.some((check) => !check.settled)) return true\n }\n return false\n}\n\nfunction settleCheck(check: PendingCheck, result: {exists: boolean} | {error: unknown}): void {\n if (check.settled) return\n check.settled = true\n if (check.signal && check.onAbort) {\n check.signal.removeEventListener('abort', check.onAbort)\n }\n if ('error' in result) check.reject(result.error)\n else check.resolve(result.exists)\n}\n\nexport function createBatchedGetDocumentExists(\n client: SanityClient,\n defaultSignal?: AbortSignal,\n): (options: {id: string; signal?: AbortSignal}) => Promise<boolean> {\n let buffer: Batch = new Map()\n const queuedBatches: Batch[] = []\n let bufferTimer: ReturnType<typeof setTimeout> | undefined\n let draining = false\n let activeRequest: {batch: Batch; controller: AbortController} | undefined\n\n const rejectBatch = (batch: Batch, reason: unknown) => {\n for (const checks of batch.values()) {\n for (const check of checks) settleCheck(check, {error: reason})\n }\n }\n\n const rejectPending = (reason: unknown) => {\n if (bufferTimer !== undefined) clearTimeout(bufferTimer)\n bufferTimer = undefined\n rejectBatch(buffer, reason)\n buffer = new Map()\n for (const batch of queuedBatches.splice(0)) rejectBatch(batch, reason)\n }\n\n const flush = () => {\n if (bufferTimer !== undefined) clearTimeout(bufferTimer)\n bufferTimer = undefined\n if (buffer.size === 0) return\n\n queuedBatches.push(buffer)\n buffer = new Map()\n void drain()\n }\n\n const scheduleFlush = () => {\n if (buffer.size >= MAX_BUFFER_SIZE) {\n flush()\n } else if (bufferTimer === undefined) {\n bufferTimer = setTimeout(flush, BUFFER_TIME)\n }\n }\n\n async function drain() {\n if (draining) return\n draining = true\n try {\n while (queuedBatches.length > 0) {\n defaultSignal?.throwIfAborted()\n const batch = queuedBatches.shift()\n if (!batch) continue\n const ids = [...batch.entries()]\n .filter(([, checks]) => checks.some((check) => !check.settled))\n .map(([id]) => id)\n if (ids.length === 0) continue\n\n const controller = new AbortController()\n const abortRequest = () => controller.abort(defaultSignal?.reason)\n defaultSignal?.addEventListener('abort', abortRequest, {once: true})\n activeRequest = {batch, controller}\n\n try {\n // The endpoint is intentionally limited to one request at a time.\n // oxlint-disable-next-line no-await-in-loop\n const availability = await client.request<AvailabilityResponse>({\n url: client.getDataUrl('doc', ids.join(',')),\n query: {excludeContent: 'true'},\n signal: controller.signal,\n tag: 'documents-availability',\n })\n const missingIds = new Set(\n availability.omitted.filter(({reason}) => reason === 'existence').map(({id}) => id),\n )\n for (const id of ids) {\n for (const check of batch.get(id) ?? []) {\n settleCheck(check, {exists: !missingIds.has(id)})\n }\n }\n } catch (error) {\n if (controller.signal.aborted && !defaultSignal?.aborted && !hasPendingChecks(batch)) {\n // Every caller left this batch, so its cancellation must not fail later batches.\n continue\n }\n rejectBatch(batch, error)\n rejectPending(error)\n return\n } finally {\n defaultSignal?.removeEventListener('abort', abortRequest)\n activeRequest = undefined\n }\n }\n } catch (error) {\n rejectPending(error)\n } finally {\n draining = false\n }\n }\n\n return function getDocumentExists(options) {\n const signal = options.signal || defaultSignal\n if (signal?.aborted) return Promise.reject(signal.reason)\n\n return new Promise<boolean>((resolve, reject) => {\n const check: PendingCheck = {reject, resolve, settled: false, signal}\n if (signal) {\n check.onAbort = () => {\n settleCheck(check, {error: signal.reason})\n if (activeRequest && !hasPendingChecks(activeRequest.batch)) {\n activeRequest.controller.abort(signal.reason)\n }\n }\n signal.addEventListener('abort', check.onAbort, {once: true})\n }\n\n const checks = buffer.get(options.id)\n if (checks) checks.push(check)\n else buffer.set(options.id, [check])\n scheduleFlush()\n })\n }\n}\n","import {type SanityClient} from '@sanity/client'\n\nconst MAX_BATCH_SIZE = 100\n\ninterface PendingType {\n resolve: (type: string | undefined) => void\n reject: (error: unknown) => void\n}\n\n/** Batches metadata reads and shares each target's result for one validation run. */\nexport function createBatchedGetDocumentType(\n getClient: () => SanityClient,\n signal?: AbortSignal,\n): (id: string) => Promise<string | undefined> {\n const cache = new Map<string, Promise<string | undefined>>()\n let pending = new Map<string, PendingType>()\n let timer: ReturnType<typeof setTimeout> | undefined\n\n async function flush() {\n clearTimeout(timer)\n timer = undefined\n const batch = pending\n pending = new Map()\n try {\n signal?.throwIfAborted()\n const documents = await getClient().fetch<{_id: string; _type: string}[]>(\n '*[_id in $ids]{_id, _type}',\n {ids: [...batch.keys()]},\n {perspective: 'raw', useCdn: false, signal, tag: 'validation.reference-types'},\n )\n const types = new Map(documents.map((document) => [document._id, document._type]))\n for (const [id, check] of batch) check.resolve(types.get(id))\n } catch (error) {\n for (const check of batch.values()) check.reject(error)\n }\n }\n\n return (id) => {\n if (signal?.aborted) return Promise.reject(signal.reason)\n const cached = cache.get(id)\n if (cached) return cached\n const result = new Promise<string | undefined>((resolve, reject) => {\n pending.set(id, {resolve, reject})\n })\n cache.set(id, result)\n if (pending.size >= MAX_BATCH_SIZE) void flush()\n else timer ??= setTimeout(() => void flush(), 0)\n return result\n }\n}\n","import {type CustomValidator, type ValidationContext} from '@sanity/types'\nimport {accepts} from '@sanity/util/accepts'\n\nimport {validationMarkerCodes} from '../codes'\n\nconst DEFAULT_API_VERSION = '2025-02-19'\n\nconst ASSET_FILE_TYPE_QUERY = `*[_id == $id][0]{mimeType, extension, originalFilename}`\n\ntype AssetFileType = {\n mimeType?: string | null\n extension?: string | null\n originalFilename?: string | null\n}\n\nexport type AcceptedAssetType = 'image' | 'file'\n\n// Asset ids are content hashes, so a resolved file type never changes for a given id.\nconst resolvedFileTypes = new Map<string, AssetFileType>()\n\nfunction isUnknownFileType(fileType: AssetFileType): boolean {\n return [fileType.mimeType, fileType.extension].every((value) => (value ?? '') === '')\n}\n\n/**\n * Checks a stored asset against an HTML `accept` string with the same matcher uploads and\n * copy-paste use.\n *\n * @internal\n */\nexport function assetMatchesAccept(fileType: AssetFileType, accept: string): boolean {\n const type = fileType.mimeType ?? ''\n return (\n accepts({type, name: getAssetFilename(fileType)}, accept) ||\n // Linked assets can have an original filename without the stored extension.\n Boolean(fileType.extension && accepts({type, name: `asset.${fileType.extension}`}, accept))\n )\n}\n\nfunction getAssetFilename(fileType: AssetFileType): string | undefined {\n if (fileType.originalFilename) return fileType.originalFilename\n return fileType.extension ? `asset.${fileType.extension}` : undefined\n}\n\nfunction getAssetId(value: unknown): string | undefined {\n if (typeof value === 'object' && value !== null && 'asset' in value) {\n const {asset} = value\n if (typeof asset === 'object' && asset !== null && '_ref' in asset) {\n return typeof asset._ref === 'string' ? asset._ref : undefined\n }\n }\n return undefined\n}\n\nasync function fetchAssetFileType(\n assetId: string,\n context: ValidationContext,\n): Promise<AssetFileType | null> {\n const cached = resolvedFileTypes.get(assetId)\n if (cached) return cached\n\n const fileType = await context\n .getClient({apiVersion: DEFAULT_API_VERSION})\n .fetch<AssetFileType | null>(\n ASSET_FILE_TYPE_QUERY,\n {id: assetId},\n {signal: context.signal, tag: 'validation.asset-accept'},\n )\n if (fileType) resolvedFileTypes.set(assetId, fileType)\n return fileType\n}\n\n/** @internal */\nexport function createAssetAcceptValidator(\n accept: string,\n assetType: AcceptedAssetType,\n): CustomValidator {\n return async (value, context) => {\n const assetId = getAssetId(value)\n if (assetId === undefined) return true\n\n const fileType = await fetchAssetFileType(assetId, context)\n if (fileType === null || isUnknownFileType(fileType) || assetMatchesAccept(fileType, accept)) {\n return true\n }\n\n return {\n code: validationMarkerCodes.assetNotAccepted,\n details: {accept, mimeType: fileType.mimeType, extension: fileType.extension},\n message: context.i18n.t('validation:object.asset-not-accepted', {\n context: assetType,\n mimeType: fileType.mimeType ?? fileType.extension,\n }),\n }\n }\n}\n","import {markInternalValidator} from '@sanity/schema/_internal'\nimport {\n isArrayOfObjectsSchemaType,\n type Rule,\n type RuleSpec,\n type RuleTypeConstraint,\n type SchemaType,\n type SchemaValidationValue,\n type ValidationContext,\n} from '@sanity/types'\nimport {dequal as isEqual} from 'dequal/lite'\n\nimport {Rule as RuleClass} from '../Rule'\nimport {\n type AcceptedAssetType,\n createAssetAcceptValidator,\n} from '../validators/assetAcceptValidator'\nimport {slugStructureValidator, slugUniquenessValidator} from '../validators/slugValidator'\nimport {getTypeChain} from './getTypeChain'\n\nexport {getTypeChain} from './getTypeChain'\n\nconst ruleConstraintTypes: {[P in Lowercase<RuleTypeConstraint>]: true} = {\n array: true,\n boolean: true,\n date: true,\n number: true,\n object: true,\n string: true,\n}\n\nconst isRuleConstraint = (typeString: string): typeString is Lowercase<RuleTypeConstraint> =>\n typeString in ruleConstraintTypes\n\nconst compiledValidations = new WeakMap<\n object,\n {type: SchemaType; definition: SchemaValidationValue | undefined; rules: Rule[]}\n>()\n\nexport function compileValidationRules(type: SchemaType): Rule[] {\n const inherited = Array.isArray(type.validation)\n ? compiledValidations.get(type.validation)\n : undefined\n const definition = inherited ? inherited.definition : type.validation\n const rules = normalizeValidationRules(type)\n compiledValidations.set(rules, {type, definition, rules})\n return rules\n}\n\nfunction baseRuleReducer(baseRule: Rule, type: SchemaType) {\n if (type.name === 'datetime') return baseRule.type('Date')\n if (type.name === 'date') return baseRule.type('Date')\n if (type.name === 'url') return baseRule.uri()\n if (type.name === 'slug') {\n return baseRule\n .custom(markInternalValidator(slugStructureValidator), {bypassConcurrencyLimit: true})\n .custom(markInternalValidator(slugUniquenessValidator), {bypassConcurrencyLimit: true})\n }\n if (type.name === 'reference') return baseRule.reference()\n if (type.name === 'email') return baseRule.email()\n return baseRule\n}\n\nfunction hasValueField(typeDef: SchemaType | undefined): boolean {\n if (!typeDef) return false\n if (!('fields' in typeDef) && typeDef.type) return hasValueField(typeDef.type)\n if (!('fields' in typeDef)) return false\n if (!Array.isArray(typeDef.fields)) return false\n return typeDef.fields.some((field) => field.name === 'value')\n}\n\nfunction extractValueFromListOption(option: unknown, typeDef: SchemaType): unknown {\n if (isArrayOfObjectsSchemaType(typeDef)) return option\n\n // If you define a `list` option with object items, where the item has a `value` field,\n // we don't want to treat that as the value but rather the surrounding object\n // This differs from the case where you have a title/value pair setup for a string/number, for instance\n if (typeDef.jsonType === 'object' && hasValueField(typeDef)) return option\n\n return (option as Record<string, unknown>).value === undefined\n ? option\n : (option as Record<string, unknown>).value\n}\n\nconst isUriSpec = (spec: RuleSpec): spec is Extract<RuleSpec, {flag: 'uri'}> => spec.flag === 'uri'\n\n// A `url` type auto-injects the default `.uri()` onto every array element, so a\n// custom scheme on one element cannot override the default on its siblings (GH #3298).\nfunction omitLeakedDefaultUri(rules: Rule[], typeDef: SchemaType): Rule[] {\n const isUrlType = getTypeChain(typeDef).some((type) => type.name === 'url')\n if (!isUrlType) return rules\n\n // oxlint-disable-next-line no-deprecated -- will fix in follow up PR\n const defaultUri = new RuleClass(typeDef).uri()._rules.find(isUriSpec)?.constraint\n const isDefaultUri = (spec: RuleSpec) => isUriSpec(spec) && isEqual(spec.constraint, defaultUri)\n const isCustomUri = (spec: RuleSpec) => isUriSpec(spec) && !isEqual(spec.constraint, defaultUri)\n\n // oxlint-disable-next-line no-deprecated -- will fix in follow up PR\n const someElementSetsScheme = rules.some((rule) => rule._rules.some(isCustomUri))\n if (!someElementSetsScheme) return rules\n\n return rules.map((rule) => {\n // oxlint-disable-next-line no-deprecated -- will fix in follow up PR\n if (!rule._rules.some(isDefaultUri)) return rule\n const cleaned = rule.clone()\n // oxlint-disable-next-line no-deprecated -- will fix in follow up PR\n cleaned._rules = rule._rules.filter((spec) => !isDefaultUri(spec))\n return cleaned\n })\n}\n\nexport function normalizeValidationRules(\n typeDef: SchemaType | undefined,\n context?: ValidationContext,\n): Rule[] {\n if (!typeDef) {\n return []\n }\n\n const compiled = Array.isArray(typeDef.validation)\n ? compiledValidations.get(typeDef.validation)\n : undefined\n if (compiled) {\n if (compiled.type === typeDef) return compiled.rules\n // Derived fields inherit compiled rules, but their options can differ. Rebuild\n // from the authored definition instead of reusing the ancestor's constraints.\n return normalizeValidationRules({...typeDef, validation: compiled.definition}, context)\n }\n\n return [...normalizeAuthoredRules(typeDef, context), ...inferAssetAcceptRules(typeDef)]\n}\n\nfunction isAcceptedAssetType(name: string): name is AcceptedAssetType {\n return name === 'image' || name === 'file'\n}\n\nfunction getAcceptOption(typeDef: SchemaType): string {\n const options = typeDef.options\n if (\n options &&\n typeof options === 'object' &&\n 'accept' in options &&\n typeof options.accept === 'string'\n ) {\n return options.accept.trim()\n }\n return ''\n}\n\n// A separate rule, so the inferred check stays a warning whatever level the authored rules use.\nfunction inferAssetAcceptRules(typeDef: SchemaType): Rule[] {\n const accept = getAcceptOption(typeDef)\n const assetType = getTypeChain(typeDef)\n .map((type) => type.name)\n .find(isAcceptedAssetType)\n\n if (accept && assetType) {\n return [\n new RuleClass(typeDef)\n .custom(markInternalValidator(createAssetAcceptValidator(accept, assetType)), {\n bypassConcurrencyLimit: true,\n })\n .warning(),\n ]\n }\n return []\n}\n\nfunction normalizeAuthoredRules(typeDef: SchemaType, context?: ValidationContext): Rule[] {\n const compiled = Array.isArray(typeDef.validation)\n ? compiledValidations.get(typeDef.validation)\n : undefined\n if (compiled) {\n return normalizeAuthoredRules({...typeDef, validation: compiled.definition}, context)\n }\n\n const validation = typeDef.validation\n\n if (Array.isArray(validation)) {\n const rules = validation.flatMap((i) =>\n normalizeAuthoredRules(\n {\n ...typeDef,\n validation: i,\n },\n context,\n ),\n )\n return omitLeakedDefaultUri(rules, typeDef)\n }\n\n const initialRule = new RuleClass(typeDef)\n let baseRule =\n // using an object + Object.values to de-dupe the type chain by type name\n Object.values(\n getTypeChain(typeDef).reduce<Record<string, SchemaType>>((acc, type) => {\n acc[type.name] = type\n return acc\n }, {}),\n ).reduce(\n baseRuleReducer,\n isRuleConstraint(typeDef.jsonType) ? initialRule.type(typeDef.jsonType) : initialRule,\n )\n\n const options = typeDef.options\n const list =\n options && typeof options === 'object' && 'list' in options ? options.list : undefined\n if (Array.isArray(list)) {\n baseRule = baseRule.valid(list.map((option) => extractValueFromListOption(option, typeDef)))\n }\n\n if (validation && typeof validation === 'object') {\n return [validation]\n }\n\n if (!validation) {\n return [baseRule]\n }\n\n if (typeof validation === 'function') {\n return normalizeAuthoredRules(\n {\n ...typeDef,\n validation: validation(baseRule, context),\n },\n context,\n )\n }\n\n return [baseRule]\n}\n","/**\n * Simple requestIdleCallback polyfill\n * Can be removed when all browsers support requestIdleCallback: https://caniuse.com/requestidlecallback\n * @param callback -\n * @param options -\n */\nconst requestIdleCallbackShim: typeof window.requestIdleCallback = function requestIdleCallbackShim(\n callback,\n _options?,\n): number {\n const start = Date.now()\n return globalThis.setTimeout(() => {\n callback({\n didTimeout: false,\n timeRemaining() {\n return Math.max(0, Date.now() - start)\n },\n })\n }, 0) as unknown as number\n}\n\nconst cancelIdleCallbackShim: typeof window.cancelIdleCallback = function cancelIdleCallbackShim(\n handle: number,\n): void {\n return globalThis.clearTimeout(handle)\n}\n\nconst win = typeof window === 'undefined' ? undefined : window\n\nexport const requestIdleCallback = win?.requestIdleCallback || requestIdleCallbackShim\nexport const cancelIdleCallback = win?.cancelIdleCallback || cancelIdleCallbackShim\n","import {type BehaviorSubject} from 'rxjs'\n\nimport {cancelIdleCallback, requestIdleCallback} from './requestIdleCallback'\n\n/**\n * How validation work is paced.\n *\n * - `idle` (default): every rule and nested value waits for a `requestIdleCallback` before it\n * runs, so validation yields to rendering and input while a document is being edited. A page\n * that is busy or hidden grants few or no idle periods, so a run can take long to finish.\n * - `immediate`: nothing waits for idle time. The run uses the thread as soon as it can, and hands\n * it back once every {@link IMMEDIATE_YIELD_EVERY} nodes so that input and rendering get a turn\n * in between: through `scheduler.yield()` where the browser has it, and elsewhere (Safari) by\n * waiting for the next task. Meant for the moment a user is waiting on the result, such as\n * publishing.\n *\n * @internal\n */\nexport type ValidationScheduling = 'idle' | 'immediate'\n\n/** What every validation node waits for before it runs. @internal */\nexport interface Pace {\n wait(signal?: AbortSignal): Promise<void> | undefined\n dispose(): void\n}\n\n/** How many nodes an `immediate` run gets through between two yields to the browser. */\nexport const IMMEDIATE_YIELD_EVERY = 100\n\nconst microtask = Promise.resolve()\n\n// lib.dom declares `scheduler` on every global object, but Safari and Node have none, and it\n// declares no `setImmediate`, which Node has\ninterface FeatureDetectedGlobals {\n scheduler?: {yield?: () => Promise<void>}\n setImmediate?: (callback: () => void) => unknown\n}\n\nfunction getYieldToBrowser(): () => Promise<void> {\n const {scheduler, setImmediate} = globalThis as FeatureDetectedGlobals\n if (typeof scheduler?.yield === 'function') return scheduler.yield.bind(scheduler)\n if (typeof setImmediate === 'function') {\n return () => new Promise((resolve) => setImmediate(resolve))\n }\n if (typeof MessageChannel === 'function') return yieldThroughMessageChannel\n return yieldThroughTimeout\n}\n\n// One channel for every run, as React's scheduler has. Messages arrive in the order they were\n// posted, so each one resolves the yield that has waited longest.\nlet messagePort: MessagePort | undefined\nconst waitingForMessage: Array<() => void> = []\n\nfunction yieldThroughMessageChannel(): Promise<void> {\n if (!messagePort) {\n const channel = new MessageChannel()\n // oxlint-disable-next-line unicorn/prefer-add-event-listener -- unlike addEventListener, this also starts the port\n channel.port1.onmessage = () => waitingForMessage.shift()?.()\n messagePort = channel.port2\n }\n const port = messagePort\n return new Promise((resolve) => {\n waitingForMessage.push(resolve)\n port.postMessage(null)\n })\n}\n\nfunction yieldThroughTimeout(): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, 0))\n}\n\nfunction abortReason(signal: AbortSignal): unknown {\n return signal.reason ?? new DOMException('Validation aborted', 'AbortError')\n}\n\nfunction cancelWithSignal(wait: Promise<void>, signal?: AbortSignal): Promise<void> {\n if (!signal) return wait\n if (signal.aborted) return Promise.reject(abortReason(signal))\n\n return new Promise((resolve, reject) => {\n const onAbort = () => {\n signal.removeEventListener('abort', onAbort)\n reject(abortReason(signal))\n }\n signal.addEventListener('abort', onAbort, {once: true})\n void wait.then(\n () => {\n signal.removeEventListener('abort', onAbort)\n resolve()\n },\n (error) => {\n signal.removeEventListener('abort', onAbort)\n reject(error)\n },\n )\n })\n}\n\ntype IdleWaiter = (reason?: unknown) => void\n\nfunction waitForIdle(signal: AbortSignal | undefined, waiters?: Set<IdleWaiter>): Promise<void> {\n return new Promise((resolve, reject) => {\n let settled = false\n let handle: number | undefined\n\n const finish: IdleWaiter = (reason) => {\n if (settled) return\n settled = true\n if (handle !== undefined) cancelIdleCallback(handle)\n waiters?.delete(finish)\n signal?.removeEventListener('abort', onAbort)\n if (reason === undefined) resolve()\n else reject(reason)\n }\n const onAbort = () => {\n if (signal) finish(abortReason(signal))\n }\n\n if (signal?.aborted) {\n onAbort()\n return\n }\n\n waiters?.add(finish)\n signal?.addEventListener('abort', onAbort, {once: true})\n handle = requestIdleCallback(() => finish())\n })\n}\n\n/**\n * Yields to the browser once every `every` nodes and lets the others through on a microtask.\n * Every node that comes along while the yield is pending waits for that same yield.\n */\nexport function createYieldingPace(yieldToBrowser: () => Promise<void>, every: number): Pace {\n let count = 0\n let pending: Promise<void> | undefined\n return {\n wait(signal) {\n signal?.throwIfAborted()\n if (pending) return cancelWithSignal(pending, signal)\n count += 1\n if (count < every) return cancelWithSignal(microtask, signal)\n count = 0\n const settle = () => {\n if (pending === yielded) pending = undefined\n }\n // A failed browser yield lets validation continue. Cancellation is checked before the next\n // node starts and by every async validator that receives the run's signal.\n const yielded = yieldToBrowser().then(settle, settle)\n pending = yielded\n return cancelWithSignal(yielded, signal)\n },\n dispose() {},\n }\n}\n\n/** A pacer for server validation, where yielding to a browser is unnecessary. */\nexport function createUnpacedPace(): Pace {\n return {\n wait(signal) {\n signal?.throwIfAborted()\n return undefined\n },\n dispose() {},\n }\n}\n\n/**\n * The pacer for one Studio run, `idle` without a scheduling. One subscription observes scheduling\n * changes for the whole run rather than creating one RxJS subscription per validation node.\n */\nexport function createPace(scheduling?: BehaviorSubject<ValidationScheduling>): Pace {\n if (!scheduling) {\n return {\n wait: (signal) => waitForIdle(signal),\n dispose() {},\n }\n }\n\n let current = scheduling.getValue()\n let disposed = false\n const waiters = new Set<IdleWaiter>()\n const immediate = createYieldingPace(getYieldToBrowser(), IMMEDIATE_YIELD_EVERY)\n const subscription = scheduling.subscribe((next) => {\n current = next\n if (next === 'immediate') {\n for (const release of waiters) release()\n }\n })\n\n return {\n wait(signal) {\n if (disposed) return Promise.reject(new Error('Validation pace has been disposed'))\n return current === 'immediate' ? immediate.wait(signal) : waitForIdle(signal, waiters)\n },\n dispose() {\n if (disposed) return\n disposed = true\n subscription.unsubscribe()\n for (const release of waiters) release(new Error('Validation pace has been disposed'))\n immediate.dispose()\n },\n }\n}\n","import {type DocumentId, getVersionId, getVersionNameFromId, isVersionId} from '@sanity/id-utils'\nimport {type SanityDocument} from '@sanity/types'\n\ntype DocumentCheck = (options: {id: string; signal?: AbortSignal}) => Promise<boolean>\n\n/** @beta */\nexport interface ReleaseReferenceOptions {\n /** The document whose references are being checked. Variants require published references. */\n document: Pick<SanityDocument, '_id' | '_system'>\n /** Whether a document with the exact ID exists, including release unpublish markers. */\n getDocumentExists: DocumentCheck\n /** Whether the existing version document with the given ID unpublishes its document. */\n isUnpublished: DocumentCheck\n}\n\n/**\n * Resolves references from a release document the way Studio does: a reference to a document\n * in the same release exists even if it isn't published yet, unless the release unpublishes it.\n * Other documents are checked with `getDocumentExists` unchanged.\n *\n * @beta\n */\nexport function withReleaseReferences({\n document,\n getDocumentExists,\n isUnpublished,\n}: ReleaseReferenceOptions): DocumentCheck {\n const resolveReference = createReferenceResolver({document, getDocumentExists, isUnpublished})\n return async (options) => (await resolveReference(options)) !== undefined\n}\n\n/** Resolve the exact published or release document ID used by reference validation. */\nexport function createReferenceResolver({\n document,\n getDocumentExists,\n isUnpublished,\n}: ReleaseReferenceOptions): (options: {\n id: string\n signal?: AbortSignal\n}) => Promise<string | undefined> {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- any document ID can be checked\n const id = document._id as DocumentId\n // oxlint-disable-next-line typescript/no-deprecated -- support unmigrated variant documents\n const variant = document._system?.variants?.[0]?._ref ?? document._system?.variant?._ref\n if (!isVersionId(id) || variant) {\n return async (options) => ((await getDocumentExists(options)) ? options.id : undefined)\n }\n const versionName = getVersionNameFromId(id)\n\n return async ({id: referenceId, signal}) => {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- references hold document IDs\n const versionId = getVersionId(referenceId as DocumentId, versionName)\n const [versionExists, publishedExists] = await Promise.all([\n getDocumentExists({id: versionId, signal}),\n getDocumentExists({id: referenceId, signal}),\n ])\n if (!versionExists) return publishedExists ? referenceId : undefined\n return (await isUnpublished({id: versionId, signal})) ? undefined : versionId\n }\n}\n","import {type CustomValidator, type ObjectSchemaType} from '@sanity/types'\n\nimport {validationMarkerCodes} from '../codes'\n\n/**\n * Given a schema type, returns a custom validator used to warn users of unknown\n * fields found in an object.\n */\nexport const unknownFieldsValidator =\n (type: ObjectSchemaType): CustomValidator =>\n (value) => {\n if (typeof value !== 'object') return true\n if (!value) return true\n\n const fieldNames = new Set(type.fields?.map((field) => field.name))\n\n const unknownFields = Object.keys(value)\n .filter((key) => !key.startsWith('_'))\n .filter((key) => !fieldNames.has(key))\n\n return unknownFields.map((unknownField) => ({\n code: validationMarkerCodes.objectUnknownField,\n details: {fieldName: unknownField, typeName: type.name},\n message: `Field '${unknownField}' does not exist on type '${type.name}'`,\n path: [unknownField],\n }))\n }\n","/* oxlint-disable typescript/no-deprecated -- marker and Rule compatibility require legacy internals */\nimport {type SanityClient} from '@sanity/client'\nimport {markInternalValidator} from '@sanity/schema/_internal'\nimport {\n isKeyedObject,\n isTypedObject,\n type CurrentUser,\n type Rule,\n type SanityDocument,\n type Schema,\n type SchemaType,\n type ValidationMarker,\n} from '@sanity/types'\nimport {createClientConcurrencyLimiter} from '@sanity/util/client'\nimport {ConcurrencyLimiter} from '@sanity/util/concurrency-limiter'\nimport {dequal as isEqual} from 'dequal/lite'\nimport flatten from 'lodash-es/flatten.js'\nimport {type BehaviorSubject, Observable} from 'rxjs'\nimport {map} from 'rxjs/operators'\n\nimport {ClientUnavailableError} from './clientUnavailable'\nimport {type DocumentValidationMarker, validationMarkerCodes} from './codes'\nimport {getFallbackLocaleSource} from './i18n/fallback'\nimport {type LocaleSource, type ValidationLocaleSource} from './i18n/types'\nimport {resolveConditionalProperty} from './resolveConditionalProperty'\nimport {Rule as RuleClass} from './Rule'\nimport {type InternalValidationContext, type ValidationContext} from './types'\nimport {createBatchedGetDocumentExists} from './util/createBatchedGetDocumentExists'\nimport {createBatchedGetDocumentType} from './util/createBatchedGetDocumentType'\nimport {getTypeChain, normalizeValidationRules} from './util/normalizeValidationRules'\nimport {createPace, createUnpacedPace, type Pace, type ValidationScheduling} from './util/pace'\nimport {typeString} from './util/typeString'\nimport {createReferenceResolver} from './util/withReleaseReferences'\nimport {unknownFieldsValidator} from './validators/unknownFieldsValidator'\n\n// this is the number of requests allowed inflight at once. this is done to prevent\n// the validation library from overwhelming our backend.\n// NOTE: this was upped from 10 to prevent issues where many concurrency\n// `client.fetch` requests would \"clog\" custom validators from finishing due to\n// not enough concurrent requests being fulfilled\n//\n// NOTE: ensure to update the TSDoc and CLI help test if this is changed\nconst DEFAULT_MAX_FETCH_CONCURRENCY = 25\n\n// NOTE: ensure to update the TSDoc and CLI help test if this is changed\nconst DEFAULT_MAX_CUSTOM_VALIDATION_CONCURRENCY = 5\n\nconst DEFAULT_VALIDATION_CLIENT_OPTIONS = {apiVersion: '2025-02-19'} as const\n\nconst isRecord = (maybeRecord: unknown): maybeRecord is Record<string, unknown> =>\n typeof maybeRecord === 'object' && maybeRecord !== null && !Array.isArray(maybeRecord)\n\n/** Rejects on abort without waiting for work that does not observe the signal itself. */\nfunction raceWithSignal<T>(promise: Promise<T>, signal?: AbortSignal): Promise<T> {\n if (!signal) return promise\n if (signal.aborted) return Promise.reject(signal.reason)\n\n return new Promise((resolve, reject) => {\n const onAbort = () => {\n signal.removeEventListener('abort', onAbort)\n reject(signal.reason)\n }\n signal.addEventListener('abort', onAbort, {once: true})\n void promise.then(\n (value) => {\n signal.removeEventListener('abort', onAbort)\n resolve(value)\n },\n (error) => {\n signal.removeEventListener('abort', onAbort)\n reject(error)\n },\n )\n })\n}\n\nfunction throwClientUnavailable(): never {\n throw new ClientUnavailableError()\n}\n\n/**\n * Recursively extracts all `_fieldRules` from a rule and its nested constraints.\n * This handles cases where `Rule.fields()` is used inside `Rule.all()` or `Rule.either()`.\n */\nfunction extractFieldRulesFromRule(rule: Rule): NonNullable<Rule['_fieldRules']>[] {\n const results: NonNullable<Rule['_fieldRules']>[] = []\n\n // Add direct _fieldRules if present\n // oxlint-disable-next-line no-deprecated -- will fix in follow up PR\n if (rule._fieldRules) {\n // oxlint-disable-next-line no-deprecated -- will fix in follow up PR\n results.push(rule._fieldRules)\n }\n\n // Check for nested rules in 'all' or 'either' constraints\n // oxlint-disable-next-line no-deprecated -- will fix in follow up PR\n for (const ruleSpec of rule._rules) {\n if (ruleSpec.flag === 'all' || ruleSpec.flag === 'either') {\n const childRules = ruleSpec.constraint\n if (Array.isArray(childRules)) {\n for (const childRule of childRules) {\n results.push(...extractFieldRulesFromRule(childRule))\n }\n }\n }\n }\n\n return results\n}\n\n/**\n * @internal\n */\nexport function resolveTypeForArrayItem(\n item: unknown,\n candidates: SchemaType[],\n): SchemaType | undefined {\n // if there is only one type available, assume that it's the correct one\n if (candidates.length === 1) return candidates[0]\n\n const itemType = isTypedObject(item) && item._type\n const primitive =\n item === undefined || item === null || (!itemType && typeString(item).toLowerCase())\n\n if (primitive && primitive !== 'object') {\n return candidates.find((candidate) => candidate.jsonType === primitive)\n }\n\n return (\n candidates.find((candidate) => candidate.type?.name === itemType) ||\n candidates.find((candidate) => candidate.name === itemType) ||\n candidates.find((candidate) => candidate.name === 'object' && primitive === 'object')\n )\n}\n\ninterface ValidateDocumentBaseOptions {\n /**\n * The document to be validated\n */\n document: SanityDocument\n /** The compiled schema to validate against. */\n schema: ValidationSchema\n\n /**\n * Translation resources and locale used by built-in and custom validators.\n * Pass a resolved workspace's `i18n` to preserve its translations.\n * Defaults to the built-in English resources when omitted.\n */\n i18n?: ValidationLocaleSource\n\n /** Signal used to cancel validation and any work it starts. */\n signal?: AbortSignal\n\n /**\n * Function used to check if referenced documents exists (and is published).\n *\n * If you're validating many documents in bulk, you may want to query for all\n * document IDs first and provide your own implementation using those.\n *\n * If no function is provided a default one will be provided that will batch\n * call the `doc` endpoint to check for document existence.\n */\n getDocumentExists?: (options: {id: string; signal?: AbortSignal}) => Promise<boolean>\n\n /**\n * Check referenced document types against the reference field's `to` types.\n * Defaults to `true` (`false` in Studio's `validateDocument`).\n * Uses batched network reads, including for weak references.\n * Without a client, checks that need a target lookup make validation incomplete.\n * Set to `false` to perform only the existing reference shape and existence checks.\n */\n validateReferenceTypes?: boolean\n\n /**\n * The maximum amount of custom validation functions to be running\n * concurrently at once. This helps prevent custom validators from\n * overwhelming backend services (e.g. called via fetch) used in async,\n * user-defined validation functions. (i.e. `rule.custom(async() => {})`)\n *\n * Note that lowering this number may also help in cases where a custom\n * validator could potentially exhaust the fetch concurrency. This is 5 by\n * default.\n */\n maxCustomValidationConcurrency?: number\n\n /**\n * The amount of allowed inflight fetch requests at once for this validation.\n * You may need to up this value if you have complex custom validations that\n * require many `client.fetch` requests at once. It's possible for a custom\n * validator to stall if there are not enough concurrent fetch requests\n * available to fulfill the custom validation. Must be a positive integer.\n * This is 25 by default.\n */\n maxFetchConcurrency?: number\n\n /**\n * The current user, when available. Used when resolving schema `hidden`\n * conditionals so validation matches what the form shows, and exposed to\n * custom validators and schema-level `validation` functions as\n * `context.currentUser`. If omitted, hidden is resolved with no user (e.g. CLI\n * or headless validation).\n */\n currentUser?: Omit<CurrentUser, 'role'> | null\n}\n\n/**\n * Options for validating a document. Custom validation is disabled when no client is provided.\n *\n * @beta\n */\nexport type ValidateDocumentOptions = ValidateDocumentBaseOptions & ValidationClientOptions\n\n/**\n * Options for validating a batch of documents with shared request concurrency.\n * Custom validation is disabled when no client is provided.\n *\n * @beta\n */\nexport type ValidateDocumentsOptions = Omit<ValidateDocumentBaseOptions, 'document'> &\n ValidationClientOptions & {\n /** Documents to validate. Results are returned in the same order. */\n documents: SanityDocument[]\n }\n\ntype ValidationClientOptions =\n | {\n /** A configured client used for reference checks and custom validators. */\n client: ValidationClient\n /** Whether to run custom validation callbacks. Defaults to `true`. */\n customValidation?: boolean\n }\n | {\n /** Omit the client to perform local validation without custom callbacks. */\n client?: undefined\n customValidation?: false\n }\n\n/** A compiled schema accepted across compatible `@sanity/types` versions. @beta */\nexport interface ValidationSchema {\n get(name: string): unknown\n}\n\n/**\n * A configured Sanity client accepted across compatible client versions.\n *\n * This structural type describes the capabilities used internally by validation.\n * The configured client is exposed to custom validators as a `SanityClient`, so it must be compatible with the full client API.\n *\n * @beta\n */\nexport interface ValidationClient {\n fetch: SanityClient['fetch']\n getDataUrl: SanityClient['getDataUrl']\n request: SanityClient['request']\n observable: Pick<SanityClient['observable'], 'fetch'>\n withConfig(config: Parameters<SanityClient['withConfig']>[0]): ValidationClient\n}\n\n/** The result of validating a complete document. @beta */\nexport interface DocumentValidationResult {\n /**\n * Compatibility summary: any marker produces `failed`, including execution errors.\n * @deprecated Will be removed in v7. Use `complete` and inspect marker levels and codes instead.\n */\n status: 'passed' | 'failed' | 'notEvaluated'\n /**\n * Whether every applicable check could be evaluated. When false, validation is inconclusive.\n * Custom validators must throw when they cannot evaluate; returned messages are treated as findings.\n */\n complete: boolean\n /** Validation markers. */\n markers: DocumentValidationMarker[]\n}\n\n/**\n * The validation capabilities required from a resolved Studio source or workspace.\n *\n * @beta\n */\nexport interface ValidationSource {\n /** The compiled schema to validate against. */\n schema: Schema\n\n /** Factory used to get the client passed to custom validators. */\n getClient: (clientOptions: {apiVersion: string}) => SanityClient\n\n /** Internationalization utilities used for validation messages. */\n i18n: LocaleSource\n}\n\n/**\n * Options accepted by the compatibility overload for Studio workspace validation.\n *\n * @beta\n */\nexport interface ValidateDocumentWorkspaceOptions extends Omit<\n ValidateDocumentBaseOptions,\n 'schema' | 'i18n'\n> {\n /** The resolved Studio workspace or source used for validation. */\n workspace: ValidationSource\n\n /**\n * Factory used to get the client passed to custom validators.\n *\n * @deprecated For internal use only\n */\n getClient?: ValidationSource['getClient']\n\n /** Validation environment exposed to custom validators. */\n environment?: 'cli' | 'studio'\n\n /** Whether to run custom validation callbacks. Defaults to `true`. */\n customValidation?: boolean\n}\n\n/**\n * Validates a document against the schema in a resolved Studio workspace or source.\n *\n * @beta\n * @deprecated Prefer {@link validateDocument} with `{document, schema, client}` for new code.\n */\nexport function validateDocumentWithWorkspace({\n document,\n workspace,\n getClient = workspace.getClient,\n getDocumentExists,\n environment = 'studio',\n maxCustomValidationConcurrency,\n maxFetchConcurrency,\n currentUser,\n customValidation,\n signal,\n validateReferenceTypes = true,\n}: ValidateDocumentWorkspaceOptions): Promise<DocumentValidationMarker[]> {\n return validateDocumentInternal({\n currentUser,\n customValidation,\n document,\n environment,\n getClient,\n getDocumentExists,\n i18n: workspace.i18n,\n maxCustomValidationConcurrency,\n maxFetchConcurrency,\n schema: workspace.schema,\n signal,\n validateReferenceTypes,\n })\n}\n\n/**\n * Validates a document against a compiled schema. Returns failures and whether\n * validation completed\n * without deciding whether the document may be edited or published.\n *\n * @beta\n */\nexport function validateDocument(\n options: ValidateDocumentOptions,\n): Promise<DocumentValidationResult> {\n const {document, ...sharedOptions} = options\n return evaluateDocumentInternal({document, ...normalizeValidationOptions(sharedOptions)})\n}\n\n/**\n * Validates documents against a compiled schema, sharing reference-check batching\n * and the fetch concurrency limit across the batch. Results match the input order.\n * The signal cancels the entire batch and any work it starts.\n *\n * @beta\n */\nexport function validateDocuments(\n options: ValidateDocumentsOptions,\n): Promise<DocumentValidationResult[]> {\n const {documents, ...sharedOptions} = options\n return evaluateDocumentsInternal({documents, ...normalizeValidationOptions(sharedOptions)})\n}\n\nfunction normalizeValidationOptions(\n options: Omit<ValidateDocumentOptions, 'document'>,\n): Omit<ValidateDocumentInternalOptions, 'document'> {\n const {\n client,\n customValidation = Boolean(options.client),\n getDocumentExists,\n i18n,\n schema,\n ...internalOptions\n } = options\n return {\n ...internalOptions,\n customValidation,\n environment: 'cli',\n getClient: client\n ? // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- runtime-compatible clients may come from another major\n ({apiVersion}) => client.withConfig({apiVersion}) as SanityClient\n : throwClientUnavailable,\n getDocumentExists: getDocumentExists || (client ? undefined : throwClientUnavailable),\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- translation sources may use another compatible i18next version\n i18n: (i18n ?? getFallbackLocaleSource()) as LocaleSource,\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- compiled schemas may come from another compatible package version\n schema: schema as Schema,\n }\n}\n\n/** @internal */\nexport interface ValidateDocumentInternalOptions {\n document: SanityDocument\n schema: Schema\n getClient: (clientOptions: {apiVersion: string}) => SanityClient\n getDocumentExists?: (options: {id: string; signal?: AbortSignal}) => Promise<boolean>\n validateReferenceTypes?: boolean\n i18n?: LocaleSource\n environment: 'cli' | 'studio'\n maxCustomValidationConcurrency?: number\n maxFetchConcurrency?: number\n currentUser?: Omit<CurrentUser, 'role'> | null\n customValidation?: boolean\n signal?: AbortSignal\n}\n\nfunction createDocumentValidationResult(\n markers: ValidationMarker[],\n complete: boolean,\n): DocumentValidationResult {\n // Compiled rules from another version may return execution failures without calling markIncomplete.\n const isComplete = complete && !markers.some(hasEvaluationFailure)\n return {\n status: getDocumentValidationStatus(markers, isComplete),\n complete: isComplete,\n markers: markers.map(toDocumentValidationMarker),\n }\n}\n\nfunction hasEvaluationFailure(value: unknown): boolean {\n if (!isRecord(value)) return false\n switch (value.code) {\n case validationMarkerCodes.validationException:\n case validationMarkerCodes.documentUnknownType:\n return true\n case validationMarkerCodes.ruleAllFailed:\n case validationMarkerCodes.ruleEitherFailed:\n return (\n isRecord(value.details) &&\n Array.isArray(value.details.causes) &&\n value.details.causes.some(hasEvaluationFailure)\n )\n default:\n return false\n }\n}\n\nfunction getDocumentValidationStatus(\n markers: ValidationMarker[],\n complete: boolean,\n): DocumentValidationResult['status'] {\n if (markers.length > 0) return 'failed'\n if (!complete) return 'notEvaluated'\n return 'passed'\n}\n\n/** @internal */\nexport function validateDocumentInternal(\n options: ValidateDocumentInternalOptions,\n): Promise<DocumentValidationMarker[]> {\n return evaluateDocumentInternal(options).then(({markers}) => markers)\n}\n\n/** @internal */\nexport function evaluateDocumentInternal(\n options: ValidateDocumentInternalOptions,\n): Promise<DocumentValidationResult> {\n const {document, ...sharedOptions} = options\n return evaluateDocumentsInternal({documents: [document], ...sharedOptions}).then(\n ([result]) => result,\n )\n}\n\nfunction evaluateDocumentsInternal({\n documents,\n schema,\n getClient,\n getDocumentExists,\n i18n = getFallbackLocaleSource(),\n environment,\n maxCustomValidationConcurrency,\n maxFetchConcurrency,\n currentUser,\n customValidation = true,\n signal,\n validateReferenceTypes = true,\n}: Omit<ValidateDocumentInternalOptions, 'document'> & {\n documents: SanityDocument[]\n}): Promise<DocumentValidationResult[]> {\n if (signal?.aborted) return Promise.reject(signal.reason)\n if (documents.length === 0) return Promise.resolve([])\n\n const limitConcurrency = createClientConcurrencyLimiter(\n maxFetchConcurrency ?? DEFAULT_MAX_FETCH_CONCURRENCY,\n signal,\n )\n const getConcurrencyLimitedClient = (clientOptions: {apiVersion: string}) =>\n limitConcurrency(getClient(clientOptions))\n const batchedGetDocumentExists = getDocumentExists\n ? undefined\n : createBatchedGetDocumentExists(getClient(DEFAULT_VALIDATION_CLIENT_OPTIONS), signal)\n const batchedGetDocumentType = validateReferenceTypes\n ? createBatchedGetDocumentType(\n () => getConcurrencyLimitedClient(DEFAULT_VALIDATION_CLIENT_OPTIONS),\n signal,\n )\n : undefined\n\n return Promise.all(\n documents.map((document) => {\n const resolveReference = batchedGetDocumentExists\n ? createReferenceResolver({\n document,\n getDocumentExists: batchedGetDocumentExists,\n isUnpublished: ({id, signal: checkSignal}) =>\n getConcurrencyLimitedClient(DEFAULT_VALIDATION_CLIENT_OPTIONS).fetch<boolean>(\n '*[_id == $id][0]._system.delete == true',\n {id},\n {perspective: 'raw', signal: checkSignal, tag: 'validation.release-reference'},\n ),\n })\n : async (options: {id: string; signal?: AbortSignal}) =>\n (await getDocumentExists!(options)) ? options.id : undefined\n const resolvedReferences = new Map<string, string>()\n return evaluateDocument({\n document,\n getClient: getConcurrencyLimitedClient,\n i18n,\n schema,\n getDocumentExists: async (options) => {\n const resolvedId = await resolveReference(options)\n if (batchedGetDocumentType && resolvedId) resolvedReferences.set(options.id, resolvedId)\n return resolvedId !== undefined\n },\n getDocumentType: batchedGetDocumentType\n ? async (id) => {\n const resolvedId = resolvedReferences.get(id)\n return resolvedId ? batchedGetDocumentType(resolvedId) : undefined\n }\n : undefined,\n environment,\n maxCustomValidationConcurrency,\n currentUser,\n customValidation,\n signal,\n pace: createUnpacedPace(),\n })\n }),\n )\n}\n\nexport {type ValidationScheduling} from './util/pace'\n\n/**\n * @internal\n */\nexport interface ValidateDocumentObservableOptions extends Pick<\n ValidationContext,\n 'getDocumentExists' | 'i18n' | 'signal' | 'currentUser'\n> {\n /** Lookup for resolved target types. Omit to disable type checks. */\n getDocumentType?: (id: string) => Promise<string | undefined>\n getClient: (options: {apiVersion: string}) => SanityClient\n document: SanityDocument\n schema: Schema\n environment: 'cli' | 'studio'\n maxCustomValidationConcurrency?: number\n customValidation?: boolean\n /**\n * How the run is paced (see {@link ValidationScheduling}), `idle` when omitted. It can change\n * while the run is in flight: a switch to `immediate` speeds the run up without restarting it.\n */\n scheduling?: BehaviorSubject<ValidationScheduling>\n}\n\nconst customValidationConcurrencyLimiters = new WeakMap<Schema, ConcurrencyLimiter>()\n\n/**\n * Validates a document against the given schema, returning an Observable\n * @internal\n */\nexport function validateDocumentObservable(\n options: ValidateDocumentObservableOptions,\n): Observable<DocumentValidationMarker[]> {\n return evaluateDocumentObservable(options).pipe(map(({markers}) => markers))\n}\n\n/**\n * Validates a document against the given schema, including completion status.\n * @internal\n */\nexport function evaluateDocumentObservable(\n options: ValidateDocumentObservableOptions,\n): Observable<DocumentValidationResult> {\n return new Observable((subscriber) => {\n const controller = new AbortController()\n const {signal} = options\n const abort = () => controller.abort(signal?.reason)\n\n if (signal?.aborted) abort()\n else signal?.addEventListener('abort', abort, {once: true})\n\n void evaluateDocument({\n ...options,\n signal: controller.signal,\n pace: createPace(options.scheduling),\n }).then(\n (result) => {\n subscriber.next(result)\n subscriber.complete()\n },\n (error) => subscriber.error(error),\n )\n\n return () => {\n signal?.removeEventListener('abort', abort)\n controller.abort()\n }\n })\n}\n\nasync function evaluateDocument(\n options: ValidateDocumentObservableOptions & {pace: Pace},\n): Promise<DocumentValidationResult> {\n const {pace, signal} = options\n try {\n signal?.throwIfAborted()\n return await raceWithSignal(evaluateDocumentWithoutCancellation(options), signal)\n } finally {\n pace.dispose()\n }\n}\n\nasync function evaluateDocumentWithoutCancellation({\n document,\n getClient,\n i18n = getFallbackLocaleSource(),\n schema,\n getDocumentExists,\n getDocumentType,\n environment,\n maxCustomValidationConcurrency,\n currentUser,\n customValidation = true,\n signal,\n pace,\n}: ValidateDocumentObservableOptions & {pace: Pace}): Promise<DocumentValidationResult> {\n try {\n if (typeof document?._type !== 'string') {\n throw new Error(`Tried to validate a value without a '_type'`)\n }\n\n const documentType = schema.get(document._type)\n\n if (!documentType) {\n if (environment === 'studio') {\n console.warn(\n 'Schema type for object type \"%s\" not found, skipping validation',\n document._type,\n )\n return createDocumentValidationResult([], false)\n }\n\n return createDocumentValidationResult(\n [\n {\n code: validationMarkerCodes.documentUnknownType,\n details: {documentType: document._type},\n level: 'warning',\n message: `Could not find schema type for type '${document._type}', skipping validation`,\n path: [],\n },\n ],\n false,\n )\n }\n\n let customValidationConcurrencyLimiter = customValidationConcurrencyLimiters.get(schema)\n if (!customValidationConcurrencyLimiter) {\n customValidationConcurrencyLimiter = new ConcurrencyLimiter(\n maxCustomValidationConcurrency ?? DEFAULT_MAX_CUSTOM_VALIDATION_CONCURRENCY,\n )\n customValidationConcurrencyLimiters.set(schema, customValidationConcurrencyLimiter)\n }\n\n // `Rule.validate()` returns markers only, so completeness is tracked separately.\n let complete = true\n const validationOptions: ValidateItemOptions = {\n getClient,\n schema,\n parent: undefined,\n value: document,\n path: [],\n document: document,\n type: documentType,\n i18n,\n getDocumentExists,\n environment,\n customValidationConcurrencyLimiter,\n currentUser,\n customValidation,\n signal,\n __internal: {\n getDocumentType,\n markIncomplete: () => {\n complete = false\n },\n pace,\n },\n }\n\n await i18n.loadNamespaces(['validation'])\n const markers = await validateItemAsync(validationOptions)\n return createDocumentValidationResult(markers, complete)\n } catch (err) {\n if (signal?.aborted) throw signal.reason\n if (typeof document?._type !== 'string') throw err\n console.error(err)\n\n const message =\n err instanceof Error\n ? err.message\n : isRecord(err) && typeof err.message === 'string'\n ? err.message\n : 'Unknown error'\n const errorMarker: DocumentValidationMarker = {\n code: validationMarkerCodes.validationException,\n level: 'error',\n message,\n item: {message},\n path: [],\n }\n\n return createDocumentValidationResult([errorMarker], false)\n }\n}\n\n/**\n * this is used make optional properties required by replacing optionals with\n * `T[P] | undefined`. this is used to prevent errors in `validateItem` where\n * an option from a previous invocation would be incorrectly passed down.\n *\n * https://medium.com/terria/typescript-transforming-optional-properties-to-required-properties-that-may-be-undefined-7482cb4e1585\n */\ntype ExplicitUndefined<T> = {\n [P in keyof Required<T>]: Pick<T, P> extends Required<Pick<T, P>> ? T[P] : T[P] | undefined\n}\n\nexport type ValidateItemOptions = {\n value: unknown\n customValidationConcurrencyLimiter?: ConcurrencyLimiter\n hidden?: boolean\n customValidation?: boolean\n signal?: AbortSignal\n /** See {@link ValidateDocumentObservableOptions.scheduling}. */\n scheduling?: BehaviorSubject<ValidationScheduling>\n __internal?: InternalValidationContext['__internal']\n} & Pick<ValidationContext, 'currentUser'> &\n ExplicitUndefined<Omit<ValidationContext, 'hidden' | 'signal' | 'currentUser'>>\n\nexport async function validateItem(opts: ValidateItemOptions): Promise<ValidationMarker[]> {\n opts.signal?.throwIfAborted()\n const inheritedPace = opts.__internal?.pace\n const pace = inheritedPace ?? createPace(opts.scheduling)\n try {\n return await raceWithSignal(\n validateItemAsync(\n inheritedPace\n ? opts\n : {\n ...opts,\n __internal: {...opts.__internal, pace},\n },\n ),\n opts.signal,\n )\n } finally {\n if (!inheritedPace) pace.dispose()\n }\n}\n\nfunction validateRule(\n rule: Rule,\n value: unknown,\n context: InternalValidationContext,\n): Promise<ValidationMarker[]> {\n return rule.validate(value, context)\n}\n\ntype ValidationTask = () => Promise<ValidationMarker[]>\n\nexport async function runValidationTasks(\n tasks: ValidationTask[],\n concurrency: number,\n): Promise<ValidationMarker[][]> {\n const results: ValidationMarker[][] = []\n let nextIndex = 0\n let failed = false\n let failure: unknown\n\n async function worker() {\n while (!failed && nextIndex < tasks.length) {\n const task = tasks[nextIndex]\n nextIndex += 1\n try {\n // Each worker intentionally starts its next task only after its current task finishes.\n // oxlint-disable-next-line no-await-in-loop\n results.push(await task())\n } catch (error) {\n if (!failed) {\n failed = true\n failure = error\n }\n }\n }\n }\n\n await Promise.all(Array.from({length: Math.min(concurrency, tasks.length)}, () => worker()))\n if (failed) throw failure\n return results\n}\n\nasync function validateItemAsync({\n value,\n type,\n path = [],\n parent,\n customValidationConcurrencyLimiter,\n environment,\n customValidation = true,\n scheduling: _scheduling,\n __internal: inheritedInternal,\n ...restOfContext\n}: ValidateItemOptions): Promise<ValidationMarker[]> {\n // The run's pacer is created once, by `evaluateDocumentObservable` or by the outermost\n // `validateItem` call, and shared with every nested value so that the whole run is paced as one.\n const pace = inheritedInternal?.pace\n if (!pace) throw new Error('Validation item was started without a pace')\n const __internal = inheritedInternal\n\n // Track whether any ancestor in the tree is hidden.\n // It will be true if this field OR any ancestor is hidden.\n // This allows validation rules to check `context.hidden` to skip validation for hidden fields,\n // without needing to know whether the field itself or an ancestor caused it to be hidden.\n const ancestorHidden = restOfContext.hidden === true\n const resolveHiddenForType = (\n schemaType: SchemaType | undefined,\n schemaValue: unknown,\n schemaParent: unknown,\n schemaPath: ValidationContext['path'],\n ancestorHiddenValue: boolean,\n ) => {\n // If there is no schema type, fall back to the ancestor's hidden state.\n if (!schemaType) {\n return ancestorHiddenValue\n }\n return (\n ancestorHiddenValue ||\n resolveConditionalProperty(schemaType.hidden, {\n ...restOfContext,\n parent: schemaParent,\n value: schemaValue,\n path: schemaPath || [],\n currentUser: restOfContext.currentUser ?? null,\n })\n )\n }\n const hidden = resolveHiddenForType(type, value, parent, path, ancestorHidden)\n\n // Note: this validator is added here because it's conditional based on the\n // environment. It is a separate rule because `.warning()` sets the level of\n // every check on a rule, which would downgrade the schema's own checks.\n const unknownFieldsRule =\n // if the value is an object\n typeof value === 'object' &&\n value !== null &&\n // and the schema type is an object type\n type?.jsonType === 'object' &&\n // and if somewhere in it's type chain, it inherits from object or document\n getTypeChain(type).find((t) => ['object', 'document', 'file', 'image'].includes(t.name)) &&\n // and the environment is not the studio\n environment !== 'studio'\n ? new RuleClass(type)\n .custom(markInternalValidator(unknownFieldsValidator(type)), {\n bypassConcurrencyLimit: true,\n })\n .warning()\n : undefined\n\n const rules = normalizeValidationRules(type, {\n ...restOfContext,\n hidden,\n environment,\n parent,\n path,\n type,\n })\n // run validation for the current value\n const selfRules = unknownFieldsRule ? [...rules, unknownFieldsRule] : rules\n const selfChecks: ValidationTask[] = selfRules.map(\n (rule) => () =>\n validateRule(rule, value, {\n ...restOfContext,\n environment,\n hidden,\n parent,\n path,\n type,\n __internal: {\n ...__internal,\n customValidation,\n customValidationConcurrencyLimiter,\n },\n }),\n )\n\n // run validation for nested values (conditionally)\n let nestedChecks: ValidationTask[] = []\n\n const shouldRunNestedObjectValidation =\n // run nested validation for objects\n type?.jsonType === 'object' &&\n // if the value is truthy\n (!!value || // or\n // (the value is null or undefined) and the top-level value is required\n ((value === null || value === undefined) && rules.some((rule) => rule.isRequired())))\n\n if (shouldRunNestedObjectValidation) {\n const fieldTypes = type.fields.reduce<Record<string, SchemaType>>((acc, field) => {\n acc[field.name] = field.type\n return acc\n }, {})\n\n // Validation for rules set at the object level with `Rule.fields({/* ... */})`\n // Use extractFieldRulesFromRule to handle Rule.fields() inside Rule.all() or Rule.either()\n nestedChecks = nestedChecks.concat(\n rules\n .flatMap((rule) => extractFieldRulesFromRule(rule))\n .flatMap((fieldResults) => Object.entries(fieldResults))\n .flatMap(([name, validation]) => {\n const fieldType = fieldTypes[name]\n const nestedValue = isRecord(value) ? value[name] : undefined\n const fieldContext = {\n ...restOfContext,\n parent: value,\n path: path.concat(name),\n type: fieldType,\n environment,\n hidden: resolveHiddenForType(fieldType, nestedValue, value, path.concat(name), hidden),\n }\n return normalizeValidationRules({...fieldType, validation}, fieldContext).map(\n (subRule) => () =>\n validateRule(subRule, nestedValue, {\n ...fieldContext,\n __internal: {\n ...__internal,\n customValidation,\n customValidationConcurrencyLimiter,\n },\n }),\n )\n }),\n )\n\n // Validation from each field's schema `validation: Rule => {/* ... */}` function.\n // Construct child tasks only when the parent's scheduler starts them.\n nestedChecks = nestedChecks.concat(\n type.fields.map(\n (field) => () =>\n validateItemAsync({\n ...restOfContext,\n hidden,\n parent: value,\n value: isRecord(value) ? value[field.name] : undefined,\n path: path.concat(field.name),\n type: field.type,\n environment,\n customValidationConcurrencyLimiter,\n customValidation,\n __internal,\n }),\n ),\n )\n }\n\n // note: unlike objects, arrays should not run nested validation for undefined\n // values because we won't have a valid path to put a marker (i.e. missing the\n // key or index in the path) and the downstream form builder won't have a\n // valid target component\n const shouldRunNestedValidationForArrays = type?.jsonType === 'array' && Array.isArray(value)\n\n if (shouldRunNestedValidationForArrays) {\n nestedChecks = nestedChecks.concat(\n value.map(\n (item, index) => () =>\n validateItemAsync({\n ...restOfContext,\n hidden,\n parent: value,\n value: item,\n path: path.concat(isKeyedObject(item) ? {_key: item._key} : index),\n type: resolveTypeForArrayItem(item, type.of),\n environment,\n customValidationConcurrencyLimiter,\n customValidation,\n __internal,\n }),\n ),\n )\n }\n\n // A single leaf rule already emits the complete marker array.\n if (\n selfChecks.length === 1 &&\n nestedChecks.length === 0 &&\n !rules.some((rule) => extractFieldRulesFromRule(rule).length > 0)\n ) {\n const wait = pace.wait(restOfContext.signal)\n if (wait) await wait\n restOfContext.signal?.throwIfAborted()\n return selfChecks[0]()\n }\n\n // Every check waits for its turn as the run's pacer sees fit (see `ValidationScheduling`).\n const results = flatten(\n await runValidationTasks(\n [...selfChecks, ...nestedChecks].map((validateNode) => async () => {\n const wait = pace.wait(restOfContext.signal)\n if (wait) await wait\n restOfContext.signal?.throwIfAborted()\n return validateNode()\n }),\n 40,\n ),\n )\n\n // Deduplicate markers when `_fieldRules` are present because they can cause repeat markers.\n if (rules.some((rule) => extractFieldRulesFromRule(rule).length > 0)) {\n return deduplicateMarkers(results)\n }\n return results\n}\n\nfunction deduplicateMarkers(markers: ValidationMarker[]): ValidationMarker[] {\n const buckets = new Map<string, ValidationMarker[]>()\n\n return markers.filter((marker) => {\n const key = JSON.stringify([marker.level, marker.code, marker.message, marker.path])\n const bucket = buckets.get(key)\n if (!bucket) {\n buckets.set(key, [marker])\n return true\n }\n\n if (bucket.some((existing) => isEqual(existing, marker))) return false\n\n bucket.push(marker)\n return true\n })\n}\n\nfunction hasValidationMarkerCode(marker: ValidationMarker): marker is DocumentValidationMarker {\n return typeof marker.code === 'string'\n}\n\nfunction toDocumentValidationMarker(marker: ValidationMarker): DocumentValidationMarker {\n if (hasValidationMarkerCode(marker)) return marker\n\n return {\n ...marker,\n code: validationMarkerCodes.validationFailed,\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAGA,MAAa,wBAAwB;CACnC,oBAAoB;CACpB,kBAAkB;CAClB,oBAAoB;CACpB,oBAAoB;CACpB,kBAAkB;CAClB,eAAe;CACf,QAAQ;CACR,mBAAmB;CACnB,aAAa;CACb,aAAa;CACb,qBAAqB;CACrB,aAAa;CACb,uBAAuB;CACvB,eAAe;CACf,mBAAmB;CACnB,eAAe;CACf,gBAAgB;CAChB,eAAe;CACf,eAAe;CACf,iBAAiB;CACjB,oBAAoB;CACpB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ACF"}
@@ -1,8 +1,8 @@
1
+ import { SanityClient } from "@sanity/client";
1
2
  import { CurrentUser, SanityDocument, Schema, SchemaType, ValidationContext, ValidationContext as ValidationContext$1, ValidationMarker } from "@sanity/types";
2
3
  import { ConcurrencyLimiter } from "@sanity/util/concurrency-limiter";
3
4
  import { BehaviorSubject, Observable } from "rxjs";
4
5
  import { TFunction } from "i18next";
5
- import { SanityClient } from "@sanity/client";
6
6
  /**
7
7
  * Translation utilities accepted across compatible Studio and i18next versions.
8
8
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sanity/validation",
3
- "version": "6.25.0-next.30",
3
+ "version": "6.25.0-next.63",
4
4
  "description": "Document validation for Sanity schemas",
5
5
  "keywords": [
6
6
  "cms",
@@ -42,11 +42,11 @@
42
42
  "access": "public"
43
43
  },
44
44
  "dependencies": {
45
- "@sanity/client": "^8.16.0",
45
+ "@sanity/client": "^8.17.0",
46
46
  "@sanity/id-utils": "^1.1.0",
47
- "@sanity/schema": "6.25.0-next.30+11148d0bdd",
48
- "@sanity/types": "6.25.0-next.30+11148d0bdd",
49
- "@sanity/util": "6.25.0-next.30+11148d0bdd",
47
+ "@sanity/schema": "6.25.0-next.63+837355d823",
48
+ "@sanity/types": "6.25.0-next.63+837355d823",
49
+ "@sanity/util": "6.25.0-next.63+837355d823",
50
50
  "dequal": "^2.0.3",
51
51
  "i18next": "^26.7.2",
52
52
  "lodash-es": "^4.18.1",
@@ -61,7 +61,7 @@
61
61
  "tsdown": "^0.23.7",
62
62
  "typescript": "^7.0.2",
63
63
  "vite": "^8.3.8",
64
- "vitest": "^5.1.0"
64
+ "vitest": "^5.1.1"
65
65
  },
66
66
  "browserslist": [
67
67
  "node >=22.12",