@sanity/agent-schema 0.1.0 → 0.2.0

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.
@@ -0,0 +1,286 @@
1
+ import { a as ValidateValueFn, c as ValidationErrorCode, h as ManifestSchemaType, i as PatchOperations, l as ValidationResult, n as InsertOperation, o as ValidationContext, r as LocalizationConfig, s as ValidationError, t as FieldSchemaLookupResult } from "../_chunks-dts/types.js";
2
+ /**
3
+ * Validate an array value and its items.
4
+ */
5
+ declare function validateArray(value: unknown, fieldSchema: ManifestSchemaType, path: string, schema: ManifestSchemaType[], errors: ValidationError[], context: ValidationContext, validateValue: ValidateValueFn): Promise<void>;
6
+ /**
7
+ * Validate that new items don't duplicate existing array items or each other.
8
+ * Used by patch operations (APPEND, INSERT) to check uniqueItems constraints
9
+ * against the existing document state.
10
+ */
11
+ declare function validateUniqueItems(newItems: unknown[], existingArray: unknown[], pathPrefix: string, errors: ValidationError[]): void;
12
+ interface PathResolutionResult {
13
+ /** The resolved field schema, or null if not found */
14
+ schema: ManifestSchemaType | null;
15
+ /** How the schema was resolved: 'schema' (static), 'document' (dynamic), or null (failed) */
16
+ resolvedVia: 'schema' | 'document' | null;
17
+ }
18
+ /**
19
+ * Resolve field schema at path, using document for accurate type resolution.
20
+ *
21
+ * When a document is provided and the path contains array selectors, we use
22
+ * document-based resolution to determine the correct type at each array access.
23
+ * This is essential for union arrays where multiple types have the same field name.
24
+ *
25
+ * @param path - Dot-notation path, may include array selectors like [_key=="abc"]
26
+ * @param typeSchema - The document type schema to start navigation from
27
+ * @param allSchemas - All available schemas for type resolution
28
+ * @param document - Optional existing document for dynamic resolution
29
+ * @returns Resolution result with schema and resolution method
30
+ */
31
+ declare function resolveFieldSchemaAtPath(path: string, typeSchema: ManifestSchemaType, allSchemas: ManifestSchemaType[], document?: Record<string, unknown>): PathResolutionResult;
32
+ /**
33
+ * Validate a document-level language field value against available languages.
34
+ *
35
+ * This validator is called when:
36
+ * 1. The document uses document-level translation
37
+ * 2. The field being validated is the language field (e.g., "language", "locale")
38
+ * 3. There are known available languages to validate against
39
+ *
40
+ * @param value - The language value to validate
41
+ * @param languageFieldName - Name of the language field (e.g., "language", "locale")
42
+ * @param availableLanguages - List of valid language codes from existing documents
43
+ * @param path - The field path for error reporting
44
+ * @param errors - Array to collect validation errors
45
+ */
46
+ declare function validateDocumentLanguageField(value: unknown, languageFieldName: string, availableLanguages: string[], path: string, errors: ValidationError[]): void;
47
+ /**
48
+ * Validate a field-level language key (the _key in internationalizedArray items).
49
+ *
50
+ * This validator is called when processing arrays with options.languages,
51
+ * to ensure that array item _key values match configured language IDs.
52
+ *
53
+ * @param key - The _key value from an array item
54
+ * @param allowedLanguages - List of allowed languages with id and title
55
+ * @param path - The field path for error reporting
56
+ * @param errors - Array to collect validation errors
57
+ */
58
+ declare function validateFieldLevelLanguageKey(key: string, allowedLanguages: Array<{
59
+ id: string;
60
+ title: string | null;
61
+ }>, path: string, errors: ValidationError[]): void;
62
+ /**
63
+ * Validate a field-level language field value (v5 format where language is a dedicated field).
64
+ *
65
+ * In v5 of the internationalized-array plugin, the language code is stored in a
66
+ * dedicated `language` field instead of `_key`.
67
+ */
68
+ declare function validateFieldLevelLanguageField(languageValue: unknown, allowedLanguages: Array<{
69
+ id: string;
70
+ title: string | null;
71
+ }>, path: string, errors: ValidationError[]): void;
72
+ type LanguageOption = {
73
+ id: string;
74
+ title: string | null;
75
+ };
76
+ interface SchemaWithOptions {
77
+ name?: string;
78
+ type?: string;
79
+ fields?: Array<{
80
+ name: string;
81
+ type: string;
82
+ }>;
83
+ of?: Array<{
84
+ name?: string;
85
+ type?: string;
86
+ fields?: Array<{
87
+ name: string;
88
+ type: string;
89
+ }>;
90
+ }>;
91
+ options?: {
92
+ languages?: LanguageOption[];
93
+ };
94
+ }
95
+ /**
96
+ * Detect whether an internationalized array uses v5 format (dedicated `language` field)
97
+ * by checking if the array's value type has a `language` field in its schema.
98
+ */
99
+ declare function isV5InternationalizedArray(fieldSchema: SchemaWithOptions, allSchemas: SchemaWithOptions[]): boolean;
100
+ /**
101
+ * Check if a field schema represents an internationalized array type.
102
+ *
103
+ * @param fieldSchema - The field schema to check
104
+ * @returns true if the field is an internationalized array
105
+ */
106
+ declare function isInternationalizedArrayField(fieldSchema: SchemaWithOptions): boolean;
107
+ /**
108
+ * Validate a SET operation against internationalized array language constraints.
109
+ *
110
+ * Handles two cases:
111
+ * 1. Setting the whole array (value is an array) — validates each item's _key
112
+ * 2. Setting a _key directly (path ends with `._key`) — validates the new key value
113
+ *
114
+ * Resolves the field schema from the path. No-ops if the field isn't an internationalized array.
115
+ *
116
+ * @param path - The SET operation path
117
+ * @param value - The new value being set
118
+ * @param fieldSchema - The resolved field schema for the path
119
+ * @param typeSchema - The document type schema (for resolving parent paths)
120
+ * @param allSchemas - All schemas for resolving named types
121
+ * @param errors - Array to collect validation errors
122
+ */
123
+ declare function validateInternationalizedArraySet(path: string, value: unknown, fieldSchema: ManifestSchemaType, typeSchema: ManifestSchemaType, allSchemas: ManifestSchemaType[], errors: ValidationError[]): void;
124
+ /**
125
+ * Validate language keys for items being added to an internationalized array.
126
+ *
127
+ * Callers should check `isInternationalizedArrayField()` before calling this.
128
+ *
129
+ * @param items - Array items to validate
130
+ * @param fieldSchema - The field schema (may be a named type reference)
131
+ * @param allSchemas - All schemas for resolving named types
132
+ * @param path - The array field path (e.g., 'description')
133
+ * @param errors - Array to collect validation errors
134
+ */
135
+ declare function validateInternationalizedArrayItems(items: unknown[], fieldSchema: SchemaWithOptions, allSchemas: SchemaWithOptions[], path: string, errors: ValidationError[]): void;
136
+ /**
137
+ * Validate an object value and its fields.
138
+ */
139
+ declare function validateObject(value: unknown, fieldSchema: ManifestSchemaType, path: string, schema: ManifestSchemaType[], errors: ValidationError[], context: ValidationContext, validateValue: ValidateValueFn): Promise<void>;
140
+ /**
141
+ * Get valid image metadata field names for a given image path.
142
+ *
143
+ * This uses the navigation logic to find the image field schema
144
+ * and extract valid metadata field names. Used for silent filtering of metadata.
145
+ *
146
+ * @param imagePath - The path to the image field
147
+ * @param typeSchema - The document type schema
148
+ * @param schema - All available schemas
149
+ * @returns Set of valid metadata field names, or null if path is invalid
150
+ */
151
+ declare function getValidImageMetadataFields(imagePath: string, typeSchema: ManifestSchemaType, schema: ManifestSchemaType[]): Set<string> | null;
152
+ /**
153
+ * Get the field schema(s) at a given path in the document type.
154
+ *
155
+ * For union types (arrays with multiple `of` types), returns ALL possible schemas.
156
+ * This is important for validating fields that might exist in some but not all union types.
157
+ *
158
+ * @param path - Dot-notation path, may include array selectors like [_key=="abc"]
159
+ * @param documentType - The document type name
160
+ * @param schema - Full schema array
161
+ * @param existingDocument - Optional document to validate path existence against
162
+ * @returns Object with schemas array and any validation errors
163
+ */
164
+ declare function getFieldSchemaAtPath(path: string, documentType: string, schema: ManifestSchemaType[], existingDocument?: Record<string, unknown>): FieldSchemaLookupResult;
165
+ /**
166
+ * Validate that a path points to an image field.
167
+ *
168
+ * This is a convenience wrapper around getFieldSchemaAtPath that checks
169
+ * whether the field at the path is an image type.
170
+ *
171
+ * @param path - Dot-notation path to the field
172
+ * @param documentType - The document type name
173
+ * @param schema - Full schema array
174
+ * @param existingDocument - Optional document to validate path existence against
175
+ * @returns Validation result with errors if path is invalid or not an image field
176
+ */
177
+ declare function validateImagePath(path: string, documentType: string, schema: ManifestSchemaType[], existingDocument?: Record<string, unknown>): ValidationResult;
178
+ /**
179
+ * Validates metadata fields for an image against the schema
180
+ * Removes fields that don't exist in the image field's schema definition
181
+ *
182
+ * @param metadata - The metadata object to validate (e.g., {alt: "...", caption: "..."})
183
+ * @param imagePath - The path to the image field (e.g., "heroImage" or "content[_key=="abc"].image")
184
+ * @param typeSchema - The document type schema
185
+ * @param schema - All available schemas
186
+ * @returns Cleaned metadata object with only valid fields, or undefined if no valid fields
187
+ */
188
+ declare function validateImageMetadata(metadata: Record<string, string>, imagePath: string, typeSchema: ManifestSchemaType, schema: ManifestSchemaType[]): Record<string, string> | undefined;
189
+ /**
190
+ * Validate a Portable Text block value.
191
+ *
192
+ * Blocks have special validation requirements:
193
+ * - children must be an array containing spans and inline objects (from block.of)
194
+ * - markDefs must be an array containing annotations (from block.marks.annotations)
195
+ * - style, listItem, level are optional fields
196
+ */
197
+ declare function validateBlock(value: unknown, fieldSchema: ManifestSchemaType, path: string, schema: ManifestSchemaType[], errors: ValidationError[], context: ValidationContext, validateValue: ValidateValueFn): Promise<void>;
198
+ /**
199
+ * Validate a primitive value against its schema type.
200
+ */
201
+ declare function validatePrimitive(value: unknown, schemaType: string, path: string, errors: ValidationError[], fieldSchema?: ManifestSchemaType): void;
202
+ /**
203
+ * Validate a value against schema validation rules (min, max, enum, uniqueItems).
204
+ *
205
+ * Supports two schema formats:
206
+ * - Manifest format: { flag: 'min', constraint: 5 }
207
+ * - Encoded format (from @sanity/descriptors): { type: 'minimum', value: '5' }
208
+ */
209
+ declare function validateSchemaRules(value: unknown, fieldSchema: ManifestSchemaType, path: string, errors: ValidationError[], warnings?: ValidationError[]): void;
210
+ /**
211
+ * Validate a reference value.
212
+ * Checks structure and optionally validates existence via client.
213
+ */
214
+ declare function validateReference(value: unknown, fieldSchema: ManifestSchemaType, path: string, errors: ValidationError[], context: ValidationContext): Promise<void>;
215
+ /**
216
+ * Validate a slug value.
217
+ */
218
+ declare function validateSlug(value: unknown, path: string, errors: ValidationError[]): void;
219
+ /**
220
+ * Validate a geopoint value.
221
+ */
222
+ declare function validateGeopoint(value: unknown, path: string, errors: ValidationError[]): void;
223
+ /**
224
+ * Validate an image value structure.
225
+ * Note: Asset existence is validated separately in reference validation.
226
+ */
227
+ declare function validateImage(value: unknown, path: string, errors: ValidationError[], fieldSchema?: ManifestSchemaType, schema?: ManifestSchemaType[]): void;
228
+ /**
229
+ * Validate a file value structure.
230
+ */
231
+ declare function validateFile(value: unknown, path: string, errors: ValidationError[]): void;
232
+ /**
233
+ * Create a validation error with consistent formatting.
234
+ */
235
+ declare function createError(path: string, code: ValidationErrorCode, message: string, received: string, expected: string, fix: string): ValidationError;
236
+ /**
237
+ * Format a value for display in error messages.
238
+ * Handles truncation for long values.
239
+ */
240
+ declare function formatValue(value: unknown): string;
241
+ /**
242
+ * Map Sanity schema type to expected JavaScript type.
243
+ * See SANITY_SCHEMA_STRUCTURE.md for full reference.
244
+ */
245
+ declare function getExpectedJsType(schemaType: string): 'string' | 'number' | 'boolean' | 'array' | 'object';
246
+ /**
247
+ * Get the actual JavaScript type of a value.
248
+ */
249
+ declare function getActualJsType(value: unknown): 'string' | 'number' | 'boolean' | 'array' | 'object' | 'null' | 'undefined';
250
+ /**
251
+ * Get the uniqueness key for an array item based on its type.
252
+ * - References: unique by _ref
253
+ * - Primitives: unique by value
254
+ * - Objects: strip _key and compare rest
255
+ */
256
+ declare function getUniquenessKey(item: unknown): string;
257
+ /**
258
+ * Get a value from an object using a path string.
259
+ * Supports dot notation, array index notation [0], and _key selectors [_key=="value"].
260
+ */
261
+ declare function getValueAtPath(obj: unknown, path: string): unknown;
262
+ /**
263
+ * Validate that an object only contains allowed properties.
264
+ * Reports errors for any unknown properties found.
265
+ *
266
+ * @param obj - The object to validate
267
+ * @param allowedProperties - Set of property names that are allowed
268
+ * @param path - The path to the object for error reporting
269
+ * @param typeName - Human-readable type name for error messages (e.g., "reference", "slug")
270
+ * @param errors - Array to collect validation errors
271
+ */
272
+ declare function validateNoExtraProperties(obj: Record<string, unknown>, allowedProperties: Set<string>, path: string, typeName: string, errors: ValidationError[]): void;
273
+ /**
274
+ * Format validation errors for display to the LLM.
275
+ *
276
+ * @param errors - List of validation errors
277
+ * @returns Formatted error message
278
+ */
279
+ declare function formatValidationErrors(errors: ValidationError[]): string;
280
+ /**
281
+ * Validate a single value against its schema.
282
+ * This is the core recursive validator that dispatches to type-specific validators.
283
+ */
284
+ declare function validateValue(value: unknown, fieldSchema: ManifestSchemaType, path: string, errors: ValidationError[], context: ValidationContext, schema: ManifestSchemaType[], warnings?: ValidationError[]): Promise<void>;
285
+ export { type FieldSchemaLookupResult, type InsertOperation, type LocalizationConfig, type PatchOperations, type ValidateValueFn, type ValidationContext, type ValidationError, type ValidationErrorCode, type ValidationResult, createError, formatValidationErrors, formatValue, getActualJsType, getExpectedJsType, getFieldSchemaAtPath, getUniquenessKey, getValidImageMetadataFields, getValueAtPath, isInternationalizedArrayField, isV5InternationalizedArray, resolveFieldSchemaAtPath, validateArray, validateBlock, validateDocumentLanguageField, validateFieldLevelLanguageField, validateFieldLevelLanguageKey, validateFile, validateGeopoint, validateImage, validateImageMetadata, validateImagePath, validateInternationalizedArrayItems, validateInternationalizedArraySet, validateNoExtraProperties, validateObject, validatePrimitive, validateReference, validateSchemaRules, validateSlug, validateUniqueItems, validateValue };
286
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/validation/array.validator.ts","../../src/validation/document-path-resolver.ts","../../src/validation/language.validator.ts","../../src/validation/object.validator.ts","../../src/validation/path-validation.ts","../../src/validation/portable-text.validator.ts","../../src/validation/primitive.validator.ts","../../src/validation/reference.validator.ts","../../src/validation/special-types.validator.ts","../../src/validation/utils.ts","../../src/validation/validate-value.ts"],"mappings":";;;;iBAYsB,aAAA,CACpB,KAAA,WACA,WAAA,EAAa,kBAAA,EACb,IAAA,UACA,MAAA,EAAQ,kBAAA,IACR,MAAA,EAAQ,eAAA,IACR,OAAA,EAAS,iBAAA,EACT,aAAA,EAAe,eAAA,GACd,OAAA;;;;;;iBA8Na,mBAAA,CACd,QAAA,aACA,aAAA,aACA,UAAA,UACA,MAAA,EAAQ,eAAA;AAAA,UCvOA,oBAAA;EDKA;ECHR,MAAA,EAAQ,kBAAA;EDJR;ECMA,WAAA;AAAA;;;;;;;;;;;;;AD+NF;iBCxMgB,wBAAA,CACd,IAAA,UACA,UAAA,EAAY,kBAAA,EACZ,UAAA,EAAY,kBAAA,IACZ,QAAA,GAAW,MAAA,oBACV,oBAAA;;;;;;;;;;;;;;;iBCxBa,6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