@sanity/validation 6.21.0-next.1 → 6.21.0-next.106

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
@@ -1,90 +1,57 @@
1
1
  # @sanity/validation
2
2
 
3
- Validates complete Sanity documents against a compiled Sanity schema.
3
+ Validate Sanity documents against a compiled schema.
4
4
 
5
5
  ```ts
6
- import {validateDocument, validationMarkerCodes} from '@sanity/validation'
6
+ import {validateDocument} from '@sanity/validation'
7
7
 
8
- const result = await validateDocument({document, schema, client})
8
+ const {complete, markers} = await validateDocument({document, schema, client})
9
9
 
10
- for (const marker of result.markers) {
11
- if (marker.code === validationMarkerCodes.stringMinimumLength) {
12
- const {actualLength, minimumLength} = marker.details || {}
13
- if (typeof actualLength === 'number' && typeof minimumLength === 'number') {
14
- console.log(`Expected at least ${minimumLength} characters, got ${actualLength}`)
15
- }
16
- }
10
+ if (!complete) {
11
+ console.log('Validation is inconclusive', markers)
12
+ } else {
13
+ console.log(
14
+ 'Fully evaluated',
15
+ markers.filter(({level}) => level === 'error'),
16
+ )
17
17
  }
18
-
19
- const summary = result.markers
20
- .map((marker) => {
21
- const path = marker.path
22
- .map((segment) => (typeof segment === 'object' ? segment._key : segment))
23
- .join('.')
24
-
25
- return `[${marker.level}] ${path || '<document>'}: ${marker.message} (${marker.code})`
26
- })
27
- .join('\n')
28
18
  ```
29
19
 
30
- Every failed marker includes a stable machine-readable `code` alongside its localized `message`,
31
- `level`, and `path`. Built-in failures may also include structured `details`. Custom validators can
32
- return their own `code` and `details`; custom codes should be namespaced, for example
33
- `custom.seo-title`.
20
+ - `markers`: document findings with a stable `code`, localized `message`, `level`, `path`, and optional `details`.
21
+ - `complete`: whether every applicable check could be evaluated. When `false`, treat validation as inconclusive even if markers exist.
22
+ - Markers retain Studio behavior. When incomplete, top-level codes alone cannot classify findings: composite rules can wrap execution failures in `details.causes`.
23
+ - Custom validators should return messages for findings and throw when they cannot evaluate.
24
+ - `status` is deprecated; use `complete` and inspect marker levels and codes. It treats any marker as `failed`.
25
+ - Built-in codes: `validationMarkerCodes`. Custom validators can return namespaced codes such as `custom.seo-title`.
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
+ - Precompiled rules retain their original package version's behavior; recompile with the current version for current callback-skipping and concurrency semantics.
34
28
 
35
- When a check cannot run, `result.status` is `notEvaluated`. Omitting `client` disables custom
36
- callbacks and skips network checks. Pass `customValidation: false` to disable custom callbacks while
37
- still providing a client.
38
-
39
- Pass one `AbortSignal` to cancel validation and its pending network work. Built-in checks and client
40
- requests made through a custom validator's `context.getClient()` inherit this signal. A custom
41
- `getDocumentExists` callback receives it as an argument; custom work using another API should pass
42
- `context.signal` to that API. Cancellation rejects with the signal's reason (an `AbortError` when
43
- no custom reason was supplied). Work that does not accept an abort signal cannot be stopped, even
44
- though validation itself rejects immediately.
29
+ ## Batch validation
45
30
 
46
31
  ```ts
47
- const controller = new AbortController()
48
- const validation = validateDocument({document, schema, client, signal: controller.signal})
49
- const reason = new Error('Validation cancelled')
50
-
51
- controller.abort(reason)
52
- try {
53
- await validation
54
- } catch (error) {
55
- if (error !== reason) throw error
56
- }
57
- ```
32
+ import {validateDocuments} from '@sanity/validation'
58
33
 
59
- The package does not apply mutations or decide whether a document may be edited or published.
34
+ const results = await validateDocuments({documents, schema, client, maxFetchConcurrency: 10})
35
+ // Results follow input order; reference batching and fetch concurrency are shared.
36
+ ```
60
37
 
61
- ## Validating multiple documents
38
+ `maxFetchConcurrency` defaults to 25. One `signal` cancels the entire batch.
62
39
 
63
- Use `validateDocuments` to validate documents in parallel with shared reference-check batching and
64
- one fetch concurrency limit for the entire batch. `maxFetchConcurrency` defaults to 25.
40
+ ## Cancellation
65
41
 
66
42
  ```ts
67
- import {validateDocuments} from '@sanity/validation'
68
-
69
- const results = await validateDocuments({
70
- documents,
71
- schema,
72
- client,
73
- maxFetchConcurrency: 10,
74
- })
75
-
76
- for (const [index, result] of results.entries()) {
77
- console.log(documents[index]._id, result.status, result.markers)
78
- }
43
+ const controller = new AbortController()
44
+ const pending = validateDocument({document, schema, client, signal: controller.signal})
45
+ controller.abort() // `pending` rejects with the abort reason.
79
46
  ```
80
47
 
81
- Passing a `signal` cancels the entire batch and its pending network work.
48
+ Custom validators receive `context.signal`; pass it to external work. Requests through
49
+ `context.getClient()` inherit it automatically. `getDocumentExists` also receives the signal;
50
+ work that does not support cancellation may keep running after validation rejects.
82
51
 
83
52
  ## Migrating from `sanity`
84
53
 
85
- Add `@sanity/validation` as a direct dependency. The workspace-based API is available as a
86
- deprecated compatibility helper, so call sites that only import the validation function can
87
- migrate by changing the imported symbol:
54
+ Add `@sanity/validation` as a direct dependency. For existing workspace-based calls:
88
55
 
89
56
  ```ts
90
57
  import {validateDocumentWithWorkspace} from '@sanity/validation'
@@ -92,7 +59,9 @@ import {validateDocumentWithWorkspace} from '@sanity/validation'
92
59
  const markers = await validateDocumentWithWorkspace({document, workspace})
93
60
  ```
94
61
 
95
- Call sites that also import `ValidateDocumentOptions` from `sanity` should use
96
- `ValidateDocumentWorkspaceOptions` for the workspace-shaped options.
62
+ This deprecated helper returns only markers and cannot report completeness. Its options type is
63
+ `ValidateDocumentWorkspaceOptions`. Prefer `validateDocument({document, schema, client})` for new code.
64
+
65
+ ## Benchmarks
97
66
 
98
- Prefer `validateDocument({document, schema, client})` for new code.
67
+ After building, run `pnpm --filter @sanity/validation bench`. Results: `.vitest/benchmarks/`.
@@ -1,4 +1,4 @@
1
- import { C as ValidationMarkerCode, E as LocaleSource, T as ValidationContext, b 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, y as validateItem } from "./validateDocument-CsrlJc5I.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-Bqq2KtlY.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: {
package/lib/_internal.js CHANGED
@@ -1,4 +1,4 @@
1
- import { _ as getFallbackLocaleSource, a as validateDocumentInternal, d as normalizeValidationRules, f as Rule, g as pathToString, h as convertToValidationMarker, l as validateItem, m as typeString, n as evaluateDocumentObservable, o as validateDocumentObservable, p as getTypeChain, r as resolveTypeForArrayItem, t as evaluateDocumentInternal, u as compileValidationRules, v as validationLocaleStrings } from "./validateDocument-5SD3VaOT.js";
1
+ import { _ as getFallbackLocaleSource, a as validateDocumentInternal, d as normalizeValidationRules, f as Rule, g as pathToString, h as convertToValidationMarker, l as validateItem, m as typeString, n as evaluateDocumentObservable, o as validateDocumentObservable, p as getTypeChain, r as resolveTypeForArrayItem, t as evaluateDocumentInternal, u as compileValidationRules, v as validationLocaleStrings } from "./validateDocument-lfNM88pm.js";
2
2
  function inferFromSchemaType(typeDef) {
3
3
  return traverse(typeDef, /* @__PURE__ */ new Set()), typeDef;
4
4
  }
package/lib/index.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { C as ValidationMarkerCode, S as DocumentValidationMarker, _ as validateDocumentWithWorkspace, a as ValidateDocumentWorkspaceOptions, c as ValidationClient, i as ValidateDocumentOptions, l as ValidationSchema, m as validateDocument, o as ValidateDocumentsOptions, t as DocumentValidationResult, u as ValidationSource, v as validateDocuments, w as validationMarkerCodes, x as BuiltInValidationMarkerCode } from "./validateDocument-CsrlJc5I.js";
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-Bqq2KtlY.js";
2
2
  export { type BuiltInValidationMarkerCode, type DocumentValidationMarker, type DocumentValidationResult, type ValidateDocumentOptions, type ValidateDocumentWorkspaceOptions, type ValidateDocumentsOptions, type ValidationClient, type ValidationMarkerCode, type ValidationSchema, type ValidationSource, validateDocument, validateDocumentWithWorkspace, validateDocuments, validationMarkerCodes };
package/lib/index.js CHANGED
@@ -1 +1 @@
1
- export { i as validateDocument, s as validateDocumentWithWorkspace, c as validateDocuments, y as validationMarkerCodes } from "./validateDocument-5SD3VaOT.js";
1
+ export { i as validateDocument, s as validateDocumentWithWorkspace, c as validateDocuments, y as validationMarkerCodes } from "./validateDocument-lfNM88pm.js";
@@ -10,6 +10,26 @@ interface LocaleSource {
10
10
  loadNamespaces(namespaces: string[]): Promise<void>;
11
11
  t: TFunction;
12
12
  }
13
+ /**
14
+ * How validation work is paced.
15
+ *
16
+ * - `idle` (default): every rule and nested value waits for a `requestIdleCallback` before it
17
+ * runs, so validation yields to rendering and input while a document is being edited. A page
18
+ * that is busy or hidden grants few or no idle periods, so a run can take long to finish.
19
+ * - `immediate`: nothing waits for idle time. The run uses the thread as soon as it can, and hands
20
+ * it back once every {@link IMMEDIATE_YIELD_EVERY} nodes so that input and rendering get a turn
21
+ * in between: through `scheduler.yield()` where the browser has it, and elsewhere (Safari) by
22
+ * waiting for the next task. Meant for the moment a user is waiting on the result, such as
23
+ * publishing.
24
+ *
25
+ * @internal
26
+ */
27
+ type ValidationScheduling = 'idle' | 'immediate';
28
+ /** What every validation node waits for before it runs. @internal */
29
+ interface Pace {
30
+ wait(signal?: AbortSignal): Promise<void> | undefined;
31
+ dispose(): void;
32
+ }
13
33
  declare module '@sanity/types' {
14
34
  /**
15
35
  * Extended validation context that includes internationalization
@@ -44,7 +64,7 @@ interface InternalValidationContext extends ValidationContext {
44
64
  };
45
65
  markIncomplete?: () => void;
46
66
  /** The run's pacer: what every node of the run waits for before it runs. */
47
- pace?: () => Observable<never>;
67
+ pace?: Pace;
48
68
  };
49
69
  }
50
70
  /** Machine-readable codes emitted by built-in document validation. @beta */
@@ -107,21 +127,6 @@ type ValidationMarkerCode = BuiltInValidationMarkerCode | (string & {});
107
127
  type DocumentValidationMarker = Omit<ValidationMarker, 'code'> & {
108
128
  code: ValidationMarkerCode;
109
129
  };
110
- /**
111
- * How validation work is paced.
112
- *
113
- * - `idle` (default): every rule and nested value waits for a `requestIdleCallback` before it
114
- * runs, so validation yields to rendering and input while a document is being edited. A page
115
- * that is busy or hidden grants few or no idle periods, so a run can take long to finish.
116
- * - `immediate`: nothing waits for idle time. The run uses the thread as soon as it can, and hands
117
- * it back once every {@link IMMEDIATE_YIELD_EVERY} nodes so that input and rendering get a turn
118
- * in between: through `scheduler.yield()` where the browser has it, and elsewhere (Safari) by
119
- * waiting for the next task. Meant for the moment a user is waiting on the result, such as
120
- * publishing.
121
- *
122
- * @internal
123
- */
124
- type ValidationScheduling = 'idle' | 'immediate';
125
130
  /**
126
131
  * @internal
127
132
  */
@@ -218,14 +223,23 @@ interface ValidationSchema {
218
223
  interface ValidationClient {
219
224
  fetch: SanityClient['fetch'];
220
225
  getDataUrl: SanityClient['getDataUrl'];
221
- observable: Pick<SanityClient['observable'], 'fetch' | 'request'>;
226
+ request: SanityClient['request'];
227
+ observable: Pick<SanityClient['observable'], 'fetch'>;
222
228
  withConfig(config: Parameters<SanityClient['withConfig']>[0]): ValidationClient;
223
229
  }
224
230
  /** The result of validating a complete document. @beta */
225
231
  interface DocumentValidationResult {
226
- /** Whether validation passed, failed, or could not be fully evaluated. */
232
+ /**
233
+ * Compatibility summary: any marker produces `failed`, including execution errors.
234
+ * @deprecated Will be removed in v7. Use `complete` and inspect marker levels and codes instead.
235
+ */
227
236
  status: 'passed' | 'failed' | 'notEvaluated';
228
- /** Validation rules that failed. */
237
+ /**
238
+ * Whether every applicable check could be evaluated. When false, validation is inconclusive.
239
+ * Custom validators must throw when they cannot evaluate; returned messages are treated as findings.
240
+ */
241
+ complete: boolean;
242
+ /** Validation markers. */
229
243
  markers: DocumentValidationMarker[];
230
244
  }
231
245
  /**
@@ -355,5 +369,5 @@ type ValidateItemOptions = {
355
369
  __internal?: InternalValidationContext['__internal'];
356
370
  } & Pick<ValidationContext$1, 'currentUser'> & ExplicitUndefined<Omit<ValidationContext$1, 'hidden' | 'signal' | 'currentUser'>>;
357
371
  declare function validateItem(opts: ValidateItemOptions): Promise<ValidationMarker[]>;
358
- export { ValidationMarkerCode as C, LocaleSource as E, DocumentValidationMarker as S, ValidationContext$1 as T, validateDocumentWithWorkspace as _, ValidateDocumentWorkspaceOptions as a, ValidationScheduling 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, validationMarkerCodes as w, BuiltInValidationMarkerCode as x, validateItem as y };
359
- //# sourceMappingURL=validateDocument-CsrlJc5I.d.ts.map
372
+ 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 };
373
+ //# sourceMappingURL=validateDocument-Bqq2KtlY.d.ts.map