@sanity/validation 6.22.1-next.3 → 6.23.0-next.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -24,6 +24,7 @@ if (!complete) {
24
24
  - `status` is deprecated; use `complete` and inspect marker levels and codes. It treats any marker as `failed`.
25
25
  - Built-in codes: `validationMarkerCodes`. Custom validators can return namespaced codes such as `custom.seo-title`.
26
26
  - Omit `client` for local checks without custom callbacks or network checks. Skipped checks make `complete` false. Use `customValidation: false` to skip custom callbacks while keeping network checks.
27
+ - Pass `i18n: workspace.i18n` to `validateDocument`/`validateDocuments` to preserve the workspace's locale and translation resources, including those used by custom validators through `context.i18n`.
27
28
  - Precompiled rules retain their original package version's behavior; recompile with the current version for current callback-skipping and concurrency semantics.
28
29
 
29
30
  ## Batch validation
@@ -37,6 +38,12 @@ const results = await validateDocuments({documents, schema, client, maxFetchConc
37
38
 
38
39
  `maxFetchConcurrency` defaults to 25. One `signal` cancels the entire batch.
39
40
 
41
+ ## Reference target types
42
+
43
+ Reference targets are checked against the field's `to` types by default.
44
+ Set `validateReferenceTypes: false` to disable these checks and their network reads.
45
+ If a target's type cannot be checked, validation is marked incomplete.
46
+
40
47
  ## Cancellation
41
48
 
42
49
  ```ts
@@ -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-CnUrz4db.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-DESiHtPx.js";
2
2
  import { Path, Rule as Rule$1, RuleClass, Schema, SchemaType, SchemaValidationValue, ValidationContext as ValidationContext$1, ValidationError, ValidationMarker } from "@sanity/types";
3
3
  export declare function getFallbackLocaleSource(): LocaleSource;
4
4
  export declare const validationLocaleStrings: {
@@ -32,6 +32,7 @@ export declare const validationLocaleStrings: {
32
32
  readonly 'object.not-media-library-asset': 'Must be a reference to a Media Library asset';
33
33
  readonly 'object.not-reference': 'Must be a reference to a document';
34
34
  readonly 'object.reference-not-published': 'Referenced document must be published';
35
+ readonly 'object.reference-target-type-mismatch': 'Referenced document has type "{{actualType}}"; expected one of: {{allowedTypes}}';
35
36
  readonly 'slug.missing-current': 'Slug must have a value';
36
37
  readonly 'slug.not-object': 'Slug must be an object';
37
38
  readonly 'slug.not-unique': 'Slug is already in use';
package/lib/_internal.js CHANGED
@@ -1,4 +1,4 @@
1
- import { _ as convertToValidationMarker, a as validateDocumentInternal, b as validationLocaleStrings, d as compileValidationRules, f as normalizeValidationRules, g as typeString, h as getTypeChain, l as validateItem, m as Rule, n as evaluateDocumentObservable, o as validateDocumentObservable, p as accepts, r as resolveTypeForArrayItem, t as evaluateDocumentInternal, v as pathToString, y as getFallbackLocaleSource } from "./validateDocument-BRt0o35E.js";
1
+ import { _ as convertToValidationMarker, a as validateDocumentInternal, b as validationLocaleStrings, d as compileValidationRules, f as normalizeValidationRules, g as typeString, h as getTypeChain, l as validateItem, m as Rule, n as evaluateDocumentObservable, o as validateDocumentObservable, p as accepts, r as resolveTypeForArrayItem, t as evaluateDocumentInternal, v as pathToString, y as getFallbackLocaleSource } from "./validateDocument-DlWnxcIz.js";
2
2
  function inferFromSchemaType(typeDef) {
3
3
  return traverse(typeDef, /* @__PURE__ */ new Set()), typeDef;
4
4
  }
package/lib/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { C as validationMarkerCodes, 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-CnUrz4db.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-DESiHtPx.js";
2
2
  import { SanityDocument } from "@sanity/types";
3
3
  type DocumentCheck = (options: {
4
4
  id: string;
@@ -21,5 +21,5 @@ interface ReleaseReferenceOptions {
21
21
  * @beta
22
22
  */
23
23
  export declare function withReleaseReferences({ document, getDocumentExists, isUnpublished }: ReleaseReferenceOptions): DocumentCheck;
24
- export { type BuiltInValidationMarkerCode, type DocumentValidationMarker, type DocumentValidationResult, type ReleaseReferenceOptions, type ValidateDocumentOptions, type ValidateDocumentWorkspaceOptions, type ValidateDocumentsOptions, type ValidationClient, type ValidationMarkerCode, type ValidationSchema, type ValidationSource, validateDocument, validateDocumentWithWorkspace, validateDocuments, validationMarkerCodes };
24
+ export { type BuiltInValidationMarkerCode, type DocumentValidationMarker, type DocumentValidationResult, type ReleaseReferenceOptions, type ValidateDocumentOptions, type ValidateDocumentWorkspaceOptions, type ValidateDocumentsOptions, type ValidationClient, type ValidationLocaleSource, type ValidationMarkerCode, type ValidationSchema, type ValidationSource, validateDocument, validateDocumentWithWorkspace, validateDocuments, validationMarkerCodes };
25
25
  //# sourceMappingURL=index.d.ts.map
package/lib/index.js CHANGED
@@ -1 +1 @@
1
- export { i as validateDocument, s as validateDocumentWithWorkspace, c as validateDocuments, x as validationMarkerCodes, u as withReleaseReferences } from "./validateDocument-BRt0o35E.js";
1
+ export { i as validateDocument, s as validateDocumentWithWorkspace, c as validateDocuments, x as validationMarkerCodes, u as withReleaseReferences } from "./validateDocument-DlWnxcIz.js";
@@ -3,11 +3,22 @@ import { ConcurrencyLimiter } from "@sanity/util/concurrency-limiter";
3
3
  import { BehaviorSubject, Observable } from "rxjs";
4
4
  import { TFunction } from "i18next";
5
5
  import { SanityClient } from "@sanity/client";
6
- interface LocaleSource {
6
+ /**
7
+ * Translation utilities accepted across compatible Studio and i18next versions.
8
+ *
9
+ * @beta
10
+ */
11
+ interface ValidationLocaleSource {
12
+ /** The locale used for localized validation messages. */
7
13
  currentLocale: {
8
14
  id: string;
9
15
  };
16
+ /** Loads translation resources needed by built-in or custom validators. */
10
17
  loadNamespaces(namespaces: string[]): Promise<void>;
18
+ /** Translates a key with optional interpolation and formatting options. */
19
+ t: (key: string, options?: Record<string, unknown>) => string;
20
+ }
21
+ interface LocaleSource extends ValidationLocaleSource {
11
22
  t: TFunction;
12
23
  }
13
24
  /**
@@ -56,6 +67,7 @@ declare module '@sanity/types' {
56
67
  }
57
68
  interface InternalValidationContext extends ValidationContext {
58
69
  __internal?: {
70
+ getDocumentType?: (id: string) => Promise<string | undefined>;
59
71
  customValidation?: boolean;
60
72
  customValidationConcurrencyLimiter?: {
61
73
  ready: (signal?: AbortSignal) => Promise<void>;
@@ -92,6 +104,7 @@ declare const validationMarkerCodes: {
92
104
  readonly objectUnknownField: 'object.unknown-field';
93
105
  readonly referenceInvalid: 'reference.invalid';
94
106
  readonly referenceNotPublished: 'reference.not-published';
107
+ readonly referenceTargetTypeMismatch: 'reference.target-type-mismatch';
95
108
  readonly ruleAllFailed: 'rule.all-failed';
96
109
  readonly ruleEitherFailed: 'rule.either-failed';
97
110
  readonly slugInvalidType: 'slug.invalid-type';
@@ -139,6 +152,12 @@ interface ValidateDocumentBaseOptions {
139
152
  document: SanityDocument;
140
153
  /** The compiled schema to validate against. */
141
154
  schema: ValidationSchema;
155
+ /**
156
+ * Translation resources and locale used by built-in and custom validators.
157
+ * Pass a resolved workspace's `i18n` to preserve its translations.
158
+ * Defaults to the built-in English resources when omitted.
159
+ */
160
+ i18n?: ValidationLocaleSource;
142
161
  /** Signal used to cancel validation and any work it starts. */
143
162
  signal?: AbortSignal;
144
163
  /**
@@ -154,6 +173,14 @@ interface ValidateDocumentBaseOptions {
154
173
  id: string;
155
174
  signal?: AbortSignal;
156
175
  }) => Promise<boolean>;
176
+ /**
177
+ * Check referenced document types against the reference field's `to` types.
178
+ * Defaults to `true` (`false` in Studio's `validateDocument`).
179
+ * Uses batched network reads, including for weak references.
180
+ * Without a client, checks that need a target lookup make validation incomplete.
181
+ * Set to `false` to perform only the existing reference shape and existence checks.
182
+ */
183
+ validateReferenceTypes?: boolean;
157
184
  /**
158
185
  * The maximum amount of custom validation functions to be running
159
186
  * concurrently at once. This helps prevent custom validators from
@@ -263,7 +290,7 @@ interface ValidationSource {
263
290
  *
264
291
  * @beta
265
292
  */
266
- interface ValidateDocumentWorkspaceOptions extends Omit<ValidateDocumentBaseOptions, 'schema'> {
293
+ interface ValidateDocumentWorkspaceOptions extends Omit<ValidateDocumentBaseOptions, 'schema' | 'i18n'> {
267
294
  /** The resolved Studio workspace or source used for validation. */
268
295
  workspace: ValidationSource;
269
296
  /**
@@ -283,7 +310,7 @@ interface ValidateDocumentWorkspaceOptions extends Omit<ValidateDocumentBaseOpti
283
310
  * @beta
284
311
  * @deprecated Prefer {@link validateDocument} with `{document, schema, client}` for new code.
285
312
  */
286
- declare function validateDocumentWithWorkspace({ document, workspace, getClient, getDocumentExists, environment, maxCustomValidationConcurrency, maxFetchConcurrency, currentUser, customValidation, signal }: ValidateDocumentWorkspaceOptions): Promise<DocumentValidationMarker[]>;
313
+ declare function validateDocumentWithWorkspace({ document, workspace, getClient, getDocumentExists, environment, maxCustomValidationConcurrency, maxFetchConcurrency, currentUser, customValidation, signal, validateReferenceTypes }: ValidateDocumentWorkspaceOptions): Promise<DocumentValidationMarker[]>;
287
314
  /**
288
315
  * Validates a document against a compiled schema. Returns failures and whether
289
316
  * validation completed
@@ -311,6 +338,7 @@ interface ValidateDocumentInternalOptions {
311
338
  id: string;
312
339
  signal?: AbortSignal;
313
340
  }) => Promise<boolean>;
341
+ validateReferenceTypes?: boolean;
314
342
  i18n?: LocaleSource;
315
343
  environment: 'cli' | 'studio';
316
344
  maxCustomValidationConcurrency?: number;
@@ -327,6 +355,8 @@ declare function evaluateDocumentInternal(options: ValidateDocumentInternalOptio
327
355
  * @internal
328
356
  */
329
357
  interface ValidateDocumentObservableOptions extends Pick<ValidationContext$1, 'getDocumentExists' | 'i18n' | 'signal' | 'currentUser'> {
358
+ /** Lookup for resolved target types. Omit to disable type checks. */
359
+ getDocumentType?: (id: string) => Promise<string | undefined>;
330
360
  getClient: (options: {
331
361
  apiVersion: string;
332
362
  }) => SanityClient;
@@ -370,5 +400,5 @@ type ValidateItemOptions = {
370
400
  __internal?: InternalValidationContext['__internal'];
371
401
  } & Pick<ValidationContext$1, 'currentUser'> & ExplicitUndefined<Omit<ValidationContext$1, 'hidden' | 'signal' | 'currentUser'>>;
372
402
  declare function validateItem(opts: ValidateItemOptions): Promise<ValidationMarker[]>;
373
- export { validationMarkerCodes as C, LocaleSource as E, ValidationMarkerCode as S, ValidationScheduling as T, validateDocumentWithWorkspace as _, ValidateDocumentWorkspaceOptions as a, BuiltInValidationMarkerCode as b, ValidationClient as c, evaluateDocumentInternal as d, evaluateDocumentObservable as f, validateDocumentObservable as g, validateDocumentInternal as h, ValidateDocumentOptions as i, ValidationSchema as l, validateDocument as m, ValidateDocumentInternalOptions as n, ValidateDocumentsOptions as o, resolveTypeForArrayItem as p, ValidateDocumentObservableOptions as r, ValidateItemOptions as s, DocumentValidationResult as t, ValidationSource as u, validateDocuments as v, ValidationContext$1 as w, DocumentValidationMarker as x, validateItem as y };
374
- //# sourceMappingURL=validateDocument-CnUrz4db.d.ts.map
403
+ export { validationMarkerCodes as C, ValidationLocaleSource as D, LocaleSource as E, ValidationMarkerCode as S, ValidationScheduling as T, validateDocumentWithWorkspace as _, ValidateDocumentWorkspaceOptions as a, BuiltInValidationMarkerCode as b, ValidationClient as c, evaluateDocumentInternal as d, evaluateDocumentObservable as f, validateDocumentObservable as g, validateDocumentInternal as h, ValidateDocumentOptions as i, ValidationSchema as l, validateDocument as m, ValidateDocumentInternalOptions as n, ValidateDocumentsOptions as o, resolveTypeForArrayItem as p, ValidateDocumentObservableOptions as r, ValidateItemOptions as s, DocumentValidationResult as t, ValidationSource as u, validateDocuments as v, ValidationContext$1 as w, DocumentValidationMarker as x, validateItem as y };
404
+ //# sourceMappingURL=validateDocument-DESiHtPx.d.ts.map
@@ -1,5 +1,5 @@
1
1
  import { isInternalValidator, markInternalValidator } from "@sanity/schema/_internal";
2
- import { isArrayOfBlocksSchemaType, isArrayOfObjectsSchemaType, isKeyedObject, isReference, isSlug, isTypedObject } from "@sanity/types";
2
+ import { isArrayOfBlocksSchemaType, isArrayOfObjectsSchemaType, isKeyedObject, isReference, isReferenceSchemaType, isSlug, isTypedObject } from "@sanity/types";
3
3
  import { createClientConcurrencyLimiter } from "@sanity/util/client";
4
4
  import { ConcurrencyLimiter } from "@sanity/util/concurrency-limiter";
5
5
  import { dequal } from "dequal/lite";
@@ -38,6 +38,7 @@ const validationMarkerCodes = {
38
38
  objectUnknownField: "object.unknown-field",
39
39
  referenceInvalid: "reference.invalid",
40
40
  referenceNotPublished: "reference.not-published",
41
+ referenceTargetTypeMismatch: "reference.target-type-mismatch",
41
42
  ruleAllFailed: "rule.all-failed",
42
43
  ruleEitherFailed: "rule.either-failed",
43
44
  slugInvalidType: "slug.invalid-type",
@@ -99,6 +100,7 @@ const validationLocaleStrings = {
99
100
  "object.not-media-library-asset": "Must be a reference to a Media Library asset",
100
101
  "object.not-reference": "Must be a reference to a document",
101
102
  "object.reference-not-published": "Referenced document must be published",
103
+ "object.reference-target-type-mismatch": "Referenced document has type \"{{actualType}}\"; expected one of: {{allowedTypes}}",
102
104
  "slug.missing-current": "Slug must have a value",
103
105
  "slug.not-object": "Slug must be an object",
104
106
  "slug.not-unique": "Slug is already in use",
@@ -218,6 +220,39 @@ function createBatchedGetDocumentExists(client, defaultSignal) {
218
220
  });
219
221
  };
220
222
  }
223
+ /** Batches metadata reads and shares each target's result for one validation run. */
224
+ function createBatchedGetDocumentType(getClient, signal) {
225
+ let cache = /* @__PURE__ */ new Map(), pending = /* @__PURE__ */ new Map(), timer;
226
+ async function flush() {
227
+ clearTimeout(timer), timer = void 0;
228
+ let batch = pending;
229
+ pending = /* @__PURE__ */ new Map();
230
+ try {
231
+ signal?.throwIfAborted();
232
+ let documents = await getClient().fetch("*[_id in $ids]{_id, _type}", { ids: [...batch.keys()] }, {
233
+ perspective: "raw",
234
+ useCdn: !1,
235
+ signal,
236
+ tag: "validation.reference-types"
237
+ }), types = new Map(documents.map((document) => [document._id, document._type]));
238
+ for (let [id, check] of batch) check.resolve(types.get(id));
239
+ } catch (error) {
240
+ for (let check of batch.values()) check.reject(error);
241
+ }
242
+ }
243
+ return (id) => {
244
+ if (signal?.aborted) return Promise.reject(signal.reason);
245
+ let cached = cache.get(id);
246
+ if (cached) return cached;
247
+ let result = new Promise((resolve, reject) => {
248
+ pending.set(id, {
249
+ resolve,
250
+ reject
251
+ });
252
+ });
253
+ return cache.set(id, result), pending.size >= 100 ? flush() : timer ??= setTimeout(() => void flush(), 0), result;
254
+ };
255
+ }
221
256
  function pathToString(path = []) {
222
257
  return path.reduce((target, segment, i) => {
223
258
  let segmentType = typeof segment;
@@ -633,17 +668,36 @@ const dateValidators = {
633
668
  message: message || i18n.t("validation:object.not-reference")
634
669
  };
635
670
  if (!type) throw Error("`type` was not provided in validation context");
636
- if ("weak" in type && type.weak) return !0;
671
+ let getDocumentType = context.__internal?.getDocumentType, weak = "weak" in type && type.weak;
672
+ if (weak && !getDocumentType) return !0;
637
673
  if (!getDocumentExists) throw Error("`getDocumentExists` was not provided in validation context");
638
- let documentId = document?._id;
639
- return documentId && value._ref == getPublishedId(documentId) || await getDocumentExists({
674
+ let selfReference = document?._id && value._ref === getPublishedId(document._id), exists = selfReference || await getDocumentExists({
640
675
  id: value._ref,
641
676
  signal: context.signal
642
- }) ? !0 : {
677
+ });
678
+ if (!exists && !weak) return {
643
679
  code: validationMarkerCodes.referenceNotPublished,
644
680
  details: { referenceId: value._ref },
645
681
  message: i18n.t("validation:object.reference-not-published", { documentId: value._ref })
646
682
  };
683
+ if (exists && getDocumentType && isReferenceSchemaType(type)) {
684
+ let actualType = selfReference ? document?._type : await getDocumentType(value._ref);
685
+ if (!actualType) throw Error(`Could not read the type of referenced document "${value._ref}"`);
686
+ let allowedTypes = type.to.map((target) => target.name);
687
+ if (!allowedTypes.includes(actualType)) return {
688
+ code: validationMarkerCodes.referenceTargetTypeMismatch,
689
+ details: {
690
+ referenceId: value._ref,
691
+ actualType,
692
+ allowedTypes
693
+ },
694
+ message: i18n.t("validation:object.reference-target-type-mismatch", {
695
+ actualType,
696
+ allowedTypes: allowedTypes.join(", ")
697
+ })
698
+ };
699
+ }
700
+ return !0;
647
701
  },
648
702
  assetRequired: (flag, value, message, { i18n }) => !value || !value.asset || !value.asset._ref ? {
649
703
  __internal_metadata: { name: "assetRequired" },
@@ -894,7 +948,7 @@ const slugUniquenessValidator = (value, context) => {
894
948
  }
895
949
  let message = isLocalizedMessages(this._message) ? localizeMessage(this._message, context.i18n) : this._message;
896
950
  try {
897
- let validatorContext = curr.flag === "all" || curr.flag === "either" ? {
951
+ let validatorContext = curr.flag === "reference" || curr.flag === "all" || curr.flag === "either" ? {
898
952
  ...context,
899
953
  __internal
900
954
  } : context;
@@ -1179,8 +1233,17 @@ function createPace(scheduling) {
1179
1233
  * @beta
1180
1234
  */
1181
1235
  function withReleaseReferences({ document, getDocumentExists, isUnpublished }) {
1236
+ let resolveReference = createReferenceResolver({
1237
+ document,
1238
+ getDocumentExists,
1239
+ isUnpublished
1240
+ });
1241
+ return async (options) => await resolveReference(options) !== void 0;
1242
+ }
1243
+ /** Resolve the exact published or release document ID used by reference validation. */
1244
+ function createReferenceResolver({ document, getDocumentExists, isUnpublished }) {
1182
1245
  let id = document._id, variant = document._system?.variants?.[0]?._ref ?? document._system?.variant?._ref;
1183
- if (!isVersionId(id) || variant) return getDocumentExists;
1246
+ if (!isVersionId(id) || variant) return async (options) => await getDocumentExists(options) ? options.id : void 0;
1184
1247
  let versionName = getVersionNameFromId(id);
1185
1248
  return async ({ id: referenceId, signal }) => {
1186
1249
  let versionId = getVersionId(referenceId, versionName), [versionExists, publishedExists] = await Promise.all([getDocumentExists({
@@ -1190,10 +1253,10 @@ function withReleaseReferences({ document, getDocumentExists, isUnpublished }) {
1190
1253
  id: referenceId,
1191
1254
  signal
1192
1255
  })]);
1193
- return versionExists ? !await isUnpublished({
1256
+ return versionExists ? await isUnpublished({
1194
1257
  id: versionId,
1195
1258
  signal
1196
- }) : publishedExists;
1259
+ }) ? void 0 : versionId : publishedExists ? referenceId : void 0;
1197
1260
  };
1198
1261
  }
1199
1262
  /**
@@ -1256,7 +1319,7 @@ function resolveTypeForArrayItem(item, candidates) {
1256
1319
  * @beta
1257
1320
  * @deprecated Prefer {@link validateDocument} with `{document, schema, client}` for new code.
1258
1321
  */
1259
- function validateDocumentWithWorkspace({ document, workspace, getClient = workspace.getClient, getDocumentExists, environment = "studio", maxCustomValidationConcurrency, maxFetchConcurrency, currentUser, customValidation, signal }) {
1322
+ function validateDocumentWithWorkspace({ document, workspace, getClient = workspace.getClient, getDocumentExists, environment = "studio", maxCustomValidationConcurrency, maxFetchConcurrency, currentUser, customValidation, signal, validateReferenceTypes = !0 }) {
1260
1323
  return validateDocumentInternal({
1261
1324
  currentUser,
1262
1325
  customValidation,
@@ -1268,7 +1331,8 @@ function validateDocumentWithWorkspace({ document, workspace, getClient = worksp
1268
1331
  maxCustomValidationConcurrency,
1269
1332
  maxFetchConcurrency,
1270
1333
  schema: workspace.schema,
1271
- signal
1334
+ signal,
1335
+ validateReferenceTypes
1272
1336
  });
1273
1337
  }
1274
1338
  /**
@@ -1300,14 +1364,14 @@ function validateDocuments(options) {
1300
1364
  });
1301
1365
  }
1302
1366
  function normalizeValidationOptions(options) {
1303
- let { client, customValidation = !!options.client, getDocumentExists, schema, ...internalOptions } = options;
1367
+ let { client, customValidation = !!options.client, getDocumentExists, i18n, schema, ...internalOptions } = options;
1304
1368
  return {
1305
1369
  ...internalOptions,
1306
1370
  customValidation,
1307
1371
  environment: "cli",
1308
1372
  getClient: client ? ({ apiVersion }) => client.withConfig({ apiVersion }) : throwClientUnavailable,
1309
1373
  getDocumentExists: getDocumentExists || (client ? void 0 : throwClientUnavailable),
1310
- i18n: getFallbackLocaleSource(),
1374
+ i18n: i18n ?? getFallbackLocaleSource(),
1311
1375
  schema
1312
1376
  };
1313
1377
  }
@@ -1344,16 +1408,12 @@ function evaluateDocumentInternal(options) {
1344
1408
  ...sharedOptions
1345
1409
  }).then(([result]) => result);
1346
1410
  }
1347
- function evaluateDocumentsInternal({ documents, schema, getClient, getDocumentExists, i18n = getFallbackLocaleSource(), environment, maxCustomValidationConcurrency, maxFetchConcurrency, currentUser, customValidation = !0, signal }) {
1411
+ function evaluateDocumentsInternal({ documents, schema, getClient, getDocumentExists, i18n = getFallbackLocaleSource(), environment, maxCustomValidationConcurrency, maxFetchConcurrency, currentUser, customValidation = !0, signal, validateReferenceTypes = !0 }) {
1348
1412
  if (signal?.aborted) return Promise.reject(signal.reason);
1349
1413
  if (documents.length === 0) return Promise.resolve([]);
1350
- let limitConcurrency = createClientConcurrencyLimiter(maxFetchConcurrency ?? 25, signal), getConcurrencyLimitedClient = (clientOptions) => limitConcurrency(getClient(clientOptions)), batchedGetDocumentExists = getDocumentExists ? void 0 : createBatchedGetDocumentExists(getClient(DEFAULT_VALIDATION_CLIENT_OPTIONS), signal);
1351
- return Promise.all(documents.map((document) => evaluateDocument({
1352
- document,
1353
- getClient: getConcurrencyLimitedClient,
1354
- i18n,
1355
- schema,
1356
- getDocumentExists: batchedGetDocumentExists ? withReleaseReferences({
1414
+ let limitConcurrency = createClientConcurrencyLimiter(maxFetchConcurrency ?? 25, signal), getConcurrencyLimitedClient = (clientOptions) => limitConcurrency(getClient(clientOptions)), batchedGetDocumentExists = getDocumentExists ? void 0 : createBatchedGetDocumentExists(getClient(DEFAULT_VALIDATION_CLIENT_OPTIONS), signal), batchedGetDocumentType = validateReferenceTypes ? createBatchedGetDocumentType(() => getConcurrencyLimitedClient(DEFAULT_VALIDATION_CLIENT_OPTIONS), signal) : void 0;
1415
+ return Promise.all(documents.map((document) => {
1416
+ let resolveReference = batchedGetDocumentExists ? createReferenceResolver({
1357
1417
  document,
1358
1418
  getDocumentExists: batchedGetDocumentExists,
1359
1419
  isUnpublished: ({ id, signal: checkSignal }) => getConcurrencyLimitedClient(DEFAULT_VALIDATION_CLIENT_OPTIONS).fetch("*[_id == $id][0]._system.delete == true", { id }, {
@@ -1361,14 +1421,28 @@ function evaluateDocumentsInternal({ documents, schema, getClient, getDocumentEx
1361
1421
  signal: checkSignal,
1362
1422
  tag: "validation.release-reference"
1363
1423
  })
1364
- }) : getDocumentExists,
1365
- environment,
1366
- maxCustomValidationConcurrency,
1367
- currentUser,
1368
- customValidation,
1369
- signal,
1370
- pace: createUnpacedPace()
1371
- })));
1424
+ }) : async (options) => await getDocumentExists(options) ? options.id : void 0, resolvedReferences = /* @__PURE__ */ new Map();
1425
+ return evaluateDocument({
1426
+ document,
1427
+ getClient: getConcurrencyLimitedClient,
1428
+ i18n,
1429
+ schema,
1430
+ getDocumentExists: async (options) => {
1431
+ let resolvedId = await resolveReference(options);
1432
+ return batchedGetDocumentType && resolvedId && resolvedReferences.set(options.id, resolvedId), resolvedId !== void 0;
1433
+ },
1434
+ getDocumentType: batchedGetDocumentType ? async (id) => {
1435
+ let resolvedId = resolvedReferences.get(id);
1436
+ return resolvedId ? batchedGetDocumentType(resolvedId) : void 0;
1437
+ } : void 0,
1438
+ environment,
1439
+ maxCustomValidationConcurrency,
1440
+ currentUser,
1441
+ customValidation,
1442
+ signal,
1443
+ pace: createUnpacedPace()
1444
+ });
1445
+ }));
1372
1446
  }
1373
1447
  const customValidationConcurrencyLimiters = /* @__PURE__ */ new WeakMap();
1374
1448
  /**
@@ -1404,7 +1478,7 @@ async function evaluateDocument(options) {
1404
1478
  pace.dispose();
1405
1479
  }
1406
1480
  }
1407
- async function evaluateDocumentWithoutCancellation({ document, getClient, i18n = getFallbackLocaleSource(), schema, getDocumentExists, environment, maxCustomValidationConcurrency, currentUser, customValidation = !0, signal, pace }) {
1481
+ async function evaluateDocumentWithoutCancellation({ document, getClient, i18n = getFallbackLocaleSource(), schema, getDocumentExists, getDocumentType, environment, maxCustomValidationConcurrency, currentUser, customValidation = !0, signal, pace }) {
1408
1482
  try {
1409
1483
  if (typeof document?._type != "string") throw Error("Tried to validate a value without a '_type'");
1410
1484
  let documentType = schema.get(document._type);
@@ -1433,6 +1507,7 @@ async function evaluateDocumentWithoutCancellation({ document, getClient, i18n =
1433
1507
  customValidation,
1434
1508
  signal,
1435
1509
  __internal: {
1510
+ getDocumentType,
1436
1511
  markIncomplete: () => {
1437
1512
  complete = !1;
1438
1513
  },
@@ -1601,4 +1676,4 @@ function toDocumentValidationMarker(marker) {
1601
1676
  }
1602
1677
  export { convertToValidationMarker as _, validateDocumentInternal as a, validationLocaleStrings as b, validateDocuments as c, compileValidationRules as d, normalizeValidationRules as f, typeString as g, getTypeChain as h, validateDocument as i, validateItem as l, Rule$2 as m, evaluateDocumentObservable as n, validateDocumentObservable as o, accepts as p, resolveTypeForArrayItem as r, validateDocumentWithWorkspace as s, evaluateDocumentInternal as t, withReleaseReferences as u, pathToString as v, validationMarkerCodes as x, getFallbackLocaleSource as y };
1603
1678
 
1604
- //# sourceMappingURL=validateDocument-BRt0o35E.js.map
1679
+ //# sourceMappingURL=validateDocument-DlWnxcIz.js.map