UNPKG

@sanity/media-library-types

Version:

Type definitions for common Sanity Media Library data structures

1,987 lines (1,813 loc) 78.9 kB
import { Asset as Asset_3 } from "@sanity/media-library-types"; import { AssetInstanceDocument as AssetInstanceDocument_2 } from "@sanity/media-library-types"; import { ClientPerspective } from "@sanity/client"; import { ComponentType } from "react"; import { ElementType } from "react"; import { ReactNode } from "react"; import { SanityClient } from "@sanity/client"; import { StackablePerspective } from "@sanity/client"; /** * Types of array actions that can be performed * @beta */ declare type ArrayActionName = /** * Add any item to the array at any position */ | "add" /** * Add item after an existing item */ | "addBefore" /** * Add item after an existing item */ | "addAfter" /** * Remove any item */ | "remove" /** * Duplicate item */ | "duplicate" /** * Copy item */ | "copy"; /** @public */ declare interface ArrayDefinition extends BaseSchemaDefinition { type: "array"; of: ArrayOfType[]; initialValue?: InitialValueProperty<any, unknown[]>; validation?: ValidationBuilder<ArrayRule<unknown[]>, unknown[]>; options?: ArrayOptions; } /** @public */ declare type ArrayOfEntry<T> = Omit<T, "name" | "hidden"> & { name?: string; }; /** @public */ declare type ArrayOfType< TType extends IntrinsicTypeName = IntrinsicTypeName, TAlias extends IntrinsicTypeName | undefined = undefined, > = | IntrinsicArrayOfDefinition[TType] | ArrayOfEntry<TypeAliasDefinition<AutocompleteString, TAlias>>; /** @public */ declare interface ArrayOptions<V = unknown> extends SearchConfiguration, BaseSchemaTypeOptions { list?: TitledListValue<V>[] | V[]; layout?: "list" | "tags" | "grid"; /** @deprecated This option does not have any effect anymore */ direction?: "horizontal" | "vertical"; sortable?: boolean; modal?: ModalOptions; /** @alpha This API may change */ insertMenu?: InsertMenuOptions; /** * A boolean flag to enable or disable tree editing for the array. * If there are any nested arrays, they will inherit this value. * @deprecated tree editing beta feature has been disabled */ treeEditing?: boolean; /** * A list of array actions to disable * Possible options are defined by {@link ArrayActionName} * @beta */ disableActions?: ArrayActionName[]; } /** @public */ declare interface ArrayRule<Value> extends RuleDef<ArrayRule<Value>, Value> { min: (length: number | FieldReference) => ArrayRule<Value>; max: (length: number | FieldReference) => ArrayRule<Value>; length: (length: number | FieldReference) => ArrayRule<Value>; unique: () => ArrayRule<Value>; } /** @public */ declare interface ArraySchemaType<V = unknown> extends BaseSchemaType { jsonType: "array"; of: (Exclude<SchemaType, ArraySchemaType> | ReferenceSchemaType)[]; options?: ArrayOptions<V> & { layout?: V extends string ? "tag" : "grid"; }; } export declare interface Asset< AssetInstance extends AssetInstanceDocument = AssetInstanceDocument, > { _id: string; _originalId?: string; _type: SanityAsset["_type"]; title: string; assetType: AssetInstance["_type"]; cdnAccessPolicy: SanityAsset["cdnAccessPolicy"]; currentVersion: { _ref: string; }; aspects?: unknown; versions: AssetVersion<AssetInstance>[]; collections: SanityAssetCollection[]; _createdAt: string; _updatedAt: string; _rev: string; url?: string; } /** @public */ declare interface Asset_2 extends SanityDocument { url: string; path: string; assetId: string; extension: string; mimeType: string; sha1hash: string; size: number; originalFilename?: string; label?: string; title?: string; description?: string; creditLine?: string; source?: AssetSourceSpec; } export declare interface AssetAspectDocument extends BaseDocument { _type: "sanity.asset.aspect"; /** * The asset type this aspect definition applies to * Undefined means that it applies to all asset types */ assetType?: Asset["assetType"]; definition: FieldDefinition; public?: boolean; } /** @public */ declare type AssetFromSource = { kind: "assetDocumentId" | "file" | "base64" | "url"; value: string | File_2; assetDocumentProps?: ImageAsset; mediaLibraryProps?: { mediaLibraryId: string; assetId: string; assetInstanceId: string; }; }; export declare type AssetInstanceDocument = | SanityImageAsset | SanityVideoAsset | SanityFileAsset; export declare interface AssetSelectionItem { asset: Asset; assetInstanceId?: string | null; } declare interface AssetSelectionItemWithLegacySupport extends AssetSelectionItem { assetId: string; assetType: string; assetInstanceId: string; } /** @public */ declare interface AssetSource { name: string; /** @deprecated provide `i18nKey` instead */ title?: string; i18nKey?: string; component: ComponentType<AssetSourceComponentProps>; icon?: ComponentType; /** @beta */ Uploader?: AssetSourceUploaderClass; /** * Specifies how uploads should be initiated for this source. * * - `'picker'` (default): The studio opens a native file picker first, * then passes the selected files to the source via the `uploader` prop. * Progress is tracked via the uploader and shown in the studio UI. * * - `'component'`: The studio renders the source component directly with * `action: 'upload'`. The source provides its own UI for selecting and * uploading files, and tracks progress internally. When complete, the * source calls `onSelect` with the uploaded assets. * * @beta */ uploadMode?: "picker" | "component"; /** * Resolve how to open an asset in its original source. * * This function is called for each AssetSource when determining if * "Open in Source" should be available. The plugin should check * `asset.source.name` to determine if it can handle this asset. * * Return values: * - `{ type: 'url', url: string }` - Open the URL (in new window by default) * - `{ type: 'component' }` - Render the asset source component with action='openInSource' * - `false` or `undefined` - This plugin cannot handle this asset * * @beta */ openInSource?: (asset: Asset_2) => AssetSourceOpenInSourceResult; } /** @public */ declare type AssetSourceComponentAction = "select" | "upload" | "openInSource"; /** @public */ declare interface AssetSourceComponentProps { action?: AssetSourceComponentAction; assetSource: AssetSource; assetType?: "file" | "image" | "sanity.video"; accept: string; selectionType: "single"; dialogHeaderTitle?: React.ReactNode; selectedAssets: Asset_2[]; onClose: () => void; onSelect: (assetFromSource: AssetFromSource[]) => void; onChangeAction?: (action: AssetSourceComponentAction) => void; schemaType?: ImageSchemaType | FileSchemaType; /** * The uploader instance for tracking upload progress. * * When `action` is `'upload'`: * - If `uploader` is provided: Picker mode. Files are available via * `uploader.getFiles()`. The source should upload these files and report * progress via the uploader. * - If `uploader` is undefined: Component mode. The source should show its * own file selection UI, handle uploads internally, and call `onSelect` * when complete. * * @beta */ uploader?: AssetSourceUploader; /** * The asset to open in source. Only provided when action is 'openInSource'. * @beta */ assetToOpen?: Asset_2; } /** * The result of calling `AssetSource.openInSource`. * @beta */ declare type AssetSourceOpenInSourceResult = | { type: "url"; url: string; target?: "_blank" | "_self"; } | { type: "component"; } | false | undefined; /** @public */ declare interface AssetSourceSpec { id: string; name: string; url?: string; } /** @beta */ declare interface AssetSourceUploader { upload( files: globalThis.File[], options?: { /** * The schema type of the field the asset is being uploaded to. * May be of interest to the uploader to read file and image options. */ schemaType?: SchemaType; /** * The uploader may send patches directly to the field * Typed 'unknown' as we don't have patch definitions in sanity/types yet. */ onChange?: (patch: unknown) => void; }, ): AssetSourceUploadFile[]; /** * Abort the upload of a file */ abort(file?: AssetSourceUploadFile): void; /** * Get the files that are currently being uploaded */ getFiles(): AssetSourceUploadFile[]; /** * Subscribe to upload events from the uploader */ subscribe(subscriber: (event: AssetSourceUploadEvent) => void): () => void; /** * Update the status of a file. Will be emitted to subscribers. */ updateFile( fileId: string, data: { progress?: number; status?: string; error?: Error; }, ): void; /** * Reset the uploader (clear files). Should be called by the uploader when all files are done. */ reset(): void; } /** @beta */ declare type AssetSourceUploaderClass = new ( ...args: any[] ) => AssetSourceUploader; /** @beta */ declare type AssetSourceUploadEvent = | AssetSourceUploadEventProgress | AssetSourceUploadEventStatus | AssetSourceUploadEventAllComplete | AssetSourceUploadEventError | AssetSourceUploadEventAbort; /** * Emitted when all files are done, either successfully, aborted or with errors * @beta */ declare type AssetSourceUploadEventAbort = { type: "abort"; /** * Files aborted */ files: AssetSourceUploadFile[]; }; /** * Emitted when all files are done, either successfully, aborted or with errors * @beta */ declare type AssetSourceUploadEventAllComplete = { type: "all-complete"; files: AssetSourceUploadFile[]; }; /** * Emitted when all files are done, either successfully, aborted or with errors * @beta */ declare type AssetSourceUploadEventError = { type: "error"; /** * Files errored */ files: AssetSourceUploadFile[]; }; /** * Emitted when a file upload is progressing * @beta */ declare type AssetSourceUploadEventProgress = { type: "progress"; file: AssetSourceUploadFile; progress: number; }; /** * Emitted when a file upload is changing status * @beta */ declare type AssetSourceUploadEventStatus = { type: "status"; file: AssetSourceUploadFile; status: AssetSourceUploadFile["status"]; }; /** @beta */ declare interface AssetSourceUploadFile { id: string; file: globalThis.File; progress: number; status: | "pending" | "uploading" | "complete" | "error" | "aborted" | "alreadyExists"; error?: Error; result?: unknown; } export declare interface AssetVersion< AssetInstance extends AssetInstanceDocument = AssetInstanceDocument, > { _key: string; _type: SanityAssetVersion["_type"]; title?: string; instance: AssetInstance; } /** * Enhances VSCode autocomplete by using a distinct type for strings. * * `AllowOtherStrings` is defined as `string & {}`, an intersection that behaves * like `string` but is treated differently by TypeScript's type system for * internal processing. This helps in improving the specificity and relevance of * autocomplete suggestions by potentially prioritizing `IntrinsicTypeName` * over general string inputs, addressing issues where `string` type suggestions * might overshadow more useful specific literals. * * @beta */ declare type AutocompleteString = string & {}; export declare type BaseDocument = { _id: string; _type: string; _rev: string; _createdAt: string; _updatedAt: string; [key: string]: any; }; /** @public */ declare interface BaseSchemaDefinition { name: string; title?: string; description?: string | React.JSX.Element; hidden?: ConditionalProperty; readOnly?: ConditionalProperty; icon?: ComponentType | ReactNode; validation?: unknown; initialValue?: unknown; deprecated?: DeprecatedProperty; } /** @public */ declare interface BaseSchemaType extends Partial<DeprecationConfiguration> { name: string; title?: string; description?: string; type?: SchemaType; liveEdit?: boolean; readOnly?: ConditionalProperty; hidden?: ConditionalProperty; icon?: ComponentType; initialValue?: InitialValueProperty<any, any>; validation?: SchemaValidationValue; preview?: PreviewConfig; /** @beta */ components?: { block?: ComponentType<any>; inlineBlock?: ComponentType<any>; annotation?: ComponentType<any>; diff?: ComponentType<any>; field?: ComponentType<any>; input?: ComponentType<any>; item?: ComponentType<any>; preview?: ComponentType<any>; portableText?: { plugins?: ComponentType<any>; }; }; /** * @deprecated This will be removed. */ placeholder?: string; } /** * `BaseOptions` applies to all type options. * * It can be extended by interface declaration merging in plugins to provide generic options to all types and fields. * * @public * */ declare interface BaseSchemaTypeOptions { sanityCreate?: SanityCreateOptions; canvasApp?: CanvasAppOptions; } /** * Schema definition for text block decorators. * * @public * @example The default set of decorators * ```ts * { * name: 'blockContent', * title: 'Content', * type: 'array', * of: [ * { * type: 'block', * marks: { * decorators: [ * {title: 'Strong', value: 'strong'}, * {title: 'Emphasis', value: 'em'}, * {title: 'Underline', value: 'underline'}, * {title: 'Strike', value: 'strike-through'}, * {title: 'Code', value: 'code'}, * ] * } * } * ] * } * ``` */ declare interface BlockDecoratorDefinition { title: string; i18nTitleKey?: string; value: string; icon?: ReactNode | ComponentType; } /** * Schema definition for text blocks. * * @public * @example the default block definition * ```ts * { * name: 'blockContent', * title: 'Content', * type: 'array', * of: [ * { * type: 'block', * marks: { * decorators: [ * {title: 'Strong', value: 'strong'}, * {title: 'Emphasis', value: 'em'}, * {title: 'Underline', value: 'underline'}, * {title: 'Strike', value: 'strike-through'}, * {title: 'Code', value: 'code'}, * ], * annotations: [ * { * type: 'object', * name: 'link', * fields: [ * { * type: 'string', * name: 'href', * }, * ], * }, * ] * }, * styles: [ * {title: 'Normal', value: 'normal'}, * {title: 'H1', value: 'h1'}, * {title: 'H2', value: 'h2'}, * {title: 'H3', value: 'h3'}, * {title: 'H4', value: 'h4'}, * {title: 'H5', value: 'h5'}, * {title: 'H6', value: 'h6'}, * {title: 'Quote', value: 'blockquote'} * ], * lists: [ * {title: 'Bullet', value: 'bullet'}, * {title: 'Number', value: 'number'}, * ], * }, * ] * } * ``` */ declare interface BlockDefinition extends BaseSchemaDefinition { type: "block"; styles?: BlockStyleDefinition[]; lists?: BlockListDefinition[]; marks?: BlockMarksDefinition; of?: ArrayOfType<"object" | "reference">[]; /** Block types do not support initialValue - the runtime schema validation rejects it. */ initialValue?: never; options?: BlockOptions; validation?: ValidationBuilder<BlockRule, PortableTextBlock>; } /** * Schema definition for a text block list style. * * @public * @example The defaults lists * ```ts * { * name: 'blockContent', * title: 'Content', * type: 'array', * of: [ * { * type: 'block', * lists: [ * {title: 'Bullet', value: 'bullet'}, * {title: 'Number', value: 'number'}, * ] * } * ] * } * ``` */ declare interface BlockListDefinition { title: string; i18nTitleKey?: string; value: string; icon?: ReactNode | ComponentType; } /** * Schema definition for text block marks (decorators and annotations). * * @public */ declare interface BlockMarksDefinition { decorators?: BlockDecoratorDefinition[]; annotations?: ArrayOfType<"object" | "reference">[]; } /** * Schema options for a Block schema definition * @public */ declare interface BlockOptions extends BaseSchemaTypeOptions { /** * Turn on or off the builtin browser spellchecking. Default is on. */ spellCheck?: boolean; unstable_whitespaceOnPasteMode?: "preserve" | "normalize" | "remove"; /** * When enabled, the editor will restrict all line breaks and soft breaks, * forcing content to remain on a single line. This will also update * the styling of the editor to reflect the single-line constraint. * * Pasting content that is on multiple lines will be normalized to a single line, if possible. * * @defaultValue false */ oneLine?: boolean; } /** @public */ declare interface BlockRule extends RuleDef<BlockRule, PortableTextBlock> {} /** * Schema definition for a text block style. * A text block may have a block style like 'header', 'normal', 'lead' * attached to it, which is stored on the `.style` property for that block. * * @public * @remarks The first defined style will become the default style.´´ * @example The default set of styles * ```ts * { * name: 'blockContent', * title: 'Content', * type: 'array', * of: [ * { * type: 'block', * styles: [ * {title: 'Normal', value: 'normal'}, * {title: 'H1', value: 'h1'}, * {title: 'H2', value: 'h2'}, * {title: 'H3', value: 'h3'}, * {title: 'H4', value: 'h4'}, * {title: 'H5', value: 'h5'}, * {title: 'H6', value: 'h6'}, * {title: 'Quote', value: 'blockquote'} * ] * } * ] * } * ``` * @example Example of defining a block type with custom styles and render components. * ```ts * defineArrayMember({ * type: 'block', * styles: [ * { * title: 'Paragraph', * value: 'paragraph', * component: ParagraphStyle, * }, * { * title: 'Lead', * value: 'lead', * component: LeadStyle, * }, * { * title: 'Heading', * value: 'heading', * component: HeadingStyle, * }, * ], * }) * ``` */ declare interface BlockStyleDefinition { title: string; value: string; i18nTitleKey?: string; icon?: ReactNode | ComponentType; } /** @public */ declare interface BooleanDefinition extends BaseSchemaDefinition { type: "boolean"; options?: BooleanOptions; initialValue?: InitialValueProperty<any, boolean>; validation?: ValidationBuilder<BooleanRule, boolean>; } /** @public */ declare interface BooleanOptions extends BaseSchemaTypeOptions { layout?: "switch" | "checkbox"; } /** @public */ declare interface BooleanRule extends RuleDef<BooleanRule, boolean> {} /** @public */ declare interface BooleanSchemaType extends BaseSchemaType { jsonType: "boolean"; options?: BooleanOptions; initialValue?: InitialValueProperty<any, boolean>; } /** * Options for configuring how Canvas app interfaces with the type or field. * * @public */ declare interface CanvasAppOptions { /** Set to true to exclude a type or field from appearing in Canvas */ exclude?: boolean; /** * A short description of what the type or field is used for. * Purpose can be used to improve how and when content mapping uses the field. * */ purpose?: string; } /** @public */ declare interface CollapseOptions { collapsed?: boolean; collapsible?: boolean; /** * @deprecated Use `collapsible` instead */ collapsable?: boolean; } /** @public */ declare type ConditionalProperty = | boolean | ConditionalPropertyCallback | undefined; /** @public */ declare type ConditionalPropertyCallback = ( context: ConditionalPropertyCallbackContext, ) => boolean; /** @public */ declare interface ConditionalPropertyCallbackContext { document: SanityDocument | undefined; parent: any; value: any; currentUser: Omit<CurrentUser, "role"> | null; path: Path; } /** @public */ declare interface CrossDatasetReferenceDefinition extends BaseSchemaDefinition { type: "crossDatasetReference"; weak?: boolean; to: { type: string; title?: string; icon?: ComponentType; preview?: PreviewConfig; /** * @deprecated Unused. Configuring search is no longer supported. */ __experimental_search?: { path: string | string[]; weight?: number; mapWith?: string; }[]; }[]; dataset: string; studioUrl?: (document: { id: string; type?: string }) => string | null; tokenId?: string; options?: ReferenceOptions; /** * @deprecated Cross-project references are no longer supported, only cross-dataset */ projectId?: string; } /** @public */ declare interface CurrentUser { id: string; name: string; email: string; profileImage?: string; provider?: string; /** @deprecated use `roles` instead */ role: string; roles: Role[]; } /** @public */ declare interface CustomValidator<T = unknown> { ( value: T, context: ValidationContext, ): CustomValidatorResult | Promise<CustomValidatorResult>; bypassConcurrencyLimit?: boolean; } /** @public */ declare type CustomValidatorResult = | true | string | ValidationError | ValidationError[] | LocalizedValidationMessages; /** @public */ declare interface DateDefinition extends BaseSchemaDefinition { type: "date"; options?: DateOptions; placeholder?: string; validation?: ValidationBuilder<DateRule, string>; initialValue?: InitialValueProperty<any, string>; } /** @public */ declare interface DateOptions extends BaseSchemaTypeOptions { dateFormat?: string; } /** @public */ declare interface DateRule extends RuleDef<DateRule, string> { /** * @param minDate - Minimum date (inclusive). minDate should be in ISO 8601 format. */ min: (minDate: string | FieldReference) => DateRule; /** * @param maxDate - Maximum date (inclusive). maxDate should be in ISO 8601 format. */ max: (maxDate: string | FieldReference) => DateRule; } /** @public */ declare interface DatetimeDefinition extends BaseSchemaDefinition { type: "datetime"; options?: DatetimeOptions; placeholder?: string; validation?: ValidationBuilder<DatetimeRule, string>; initialValue?: InitialValueProperty<any, string>; } /** @public */ declare interface DatetimeOptions extends BaseSchemaTypeOptions { dateFormat?: string; timeFormat?: string; timeStep?: number; displayTimeZone?: string; allowTimeZoneSwitch?: boolean; } /** @public */ declare interface DatetimeRule extends RuleDef<DatetimeRule, string> { /** * @param minDate - Minimum date (inclusive). minDate should be in ISO 8601 format. */ min: (minDate: string | FieldReference) => DatetimeRule; /** * @param maxDate - Maximum date (inclusive). maxDate should be in ISO 8601 format. */ max: (maxDate: string | FieldReference) => DatetimeRule; } /** @public */ declare interface DeprecatedProperty { reason: string; } /** * @public */ declare interface DeprecationConfiguration { deprecated: DeprecatedProperty; } /** @public */ declare interface DocumentDefinition extends Omit<ObjectDefinition, "type"> { type: "document"; liveEdit?: boolean; /** @beta */ orderings?: SortOrdering[]; options?: DocumentOptions; validation?: ValidationBuilder<DocumentRule, SanityDocument>; initialValue?: InitialValueProperty<any, Record<string, unknown>>; /** @deprecated Unused. Use the new field-level search config. */ __experimental_search?: { path: string; weight: number; mapWith?: string; }[]; /** @alpha */ __experimental_omnisearch_visibility?: boolean; /** * Determines whether the large preview title is displayed in the document pane form * @alpha * */ __experimental_formPreviewTitle?: boolean; } /** * This exists only to allow for extensions using declaration-merging. * * @public */ declare interface DocumentOptions extends BaseSchemaTypeOptions {} /** @public */ declare interface DocumentRule extends RuleDef<DocumentRule, SanityDocument> {} /** @public */ declare interface EmailDefinition extends BaseSchemaDefinition { type: "email"; options?: EmailOptions; placeholder?: string; validation?: ValidationBuilder<EmailRule, string>; initialValue?: InitialValueProperty<any, string>; } /** @public */ declare interface EmailOptions extends BaseSchemaTypeOptions {} /** @public */ declare interface EmailRule extends RuleDef<EmailRule, string> {} /** @public */ declare interface EnumListProps<V = unknown> { list?: Array<TitledListValue<V> | V>; layout?: "radio" | "dropdown"; direction?: "horizontal" | "vertical"; } /** * The shape of a field definition. Note, it's recommended to use the * `defineField` function instead of using this type directly. * * Where `defineField` infers the exact field type, * FieldDefinition is a compromise union of all types a field can have. * * A field definition can be a reference to another registered top-level type * or a inline type definition. * * @public */ declare type FieldDefinition< TType extends IntrinsicTypeName = IntrinsicTypeName, TAlias extends IntrinsicTypeName | undefined = undefined, > = ( | InlineFieldDefinition[TType] | TypeAliasDefinition<AutocompleteString, TAlias> ) & FieldDefinitionBase; /** @public */ declare interface FieldDefinitionBase { fieldset?: string; group?: string | string[]; } /** @public */ declare interface FieldGroup { name: string; icon?: ComponentType; title?: string; description?: string; i18n?: I18nTextRecord<"title">; hidden?: ConditionalProperty; default?: boolean; fields?: ObjectField[]; } /** @public */ declare type FieldGroupDefinition = { name: string; title?: string; hidden?: ConditionalProperty; icon?: ComponentType; default?: boolean; i18n?: I18nTextRecord<"title">; }; /** * Holds a reference to a different field * NOTE: Only use this through {@link Rule.valueOfField} * * @public */ declare interface FieldReference { type: symbol; path: string | string[]; } /** @public */ declare type FieldRules = { [fieldKey: string]: SchemaValidationValue; }; /** @public */ declare type Fieldset = SingleFieldSet | MultiFieldSet; /** @public */ declare interface FieldsetDefinition { name: string; title?: string; description?: string; group?: string; hidden?: ConditionalProperty; readOnly?: ConditionalProperty; options?: ObjectOptions; } /** @public */ declare interface File_2 { [key: string]: unknown; asset?: Reference; } /** @public */ declare interface FileDefinition extends Omit< ObjectDefinition, "type" | "fields" | "options" | "groups" | "validation" > { type: "file"; fields?: ObjectDefinition["fields"]; options?: FileOptions; validation?: ValidationBuilder<FileRule, FileValue>; initialValue?: InitialValueProperty<any, FileValue>; } /** @public */ declare interface FileOptions extends ObjectOptions { storeOriginalFilename?: boolean; accept?: string; sources?: AssetSource[]; mediaLibrary?: MediaLibraryOptions; /** * When set to `true`, hides the upload UI, only allowing selection of existing assets from the media library. * Useful for centralized asset management workflows where ad-hoc uploads should be prevented. */ disableNew?: boolean; } /** @public */ declare interface FileRule extends RuleDef<FileRule, FileValue> { /** * Require a file field has an asset. * * @example * ```ts * defineField({ * name: 'file', * title: 'File', * type: 'file', * validation: (Rule) => Rule.required().assetRequired(), * }) * ``` */ assetRequired(): FileRule; } /** @public */ declare interface FileSchemaType extends Omit<ObjectSchemaType, "options"> { options?: FileOptions; } export declare type FileStatus = | "pending" | "uploading" | "complete" | "error" | "alreadyExists"; /** * Wrapper object for the file upload with progress and status */ export declare interface FileUpload { id: string; file: File; status: FileStatus; progress: number; error?: Error; } /** @public */ declare interface FileValue { asset?: Reference; [index: string]: unknown; } declare type Geopoint = { _type: "geopoint"; lat?: number; lng?: number; alt?: number; }; /** @public */ declare interface GeopointDefinition extends BaseSchemaDefinition { type: "geopoint"; options?: GeopointOptions; validation?: ValidationBuilder<GeopointRule, GeopointValue>; initialValue?: InitialValueProperty<any, Omit<GeopointValue, "_type">>; } /** @public */ declare interface GeopointOptions extends BaseSchemaTypeOptions {} /** @public */ declare interface GeopointRule extends RuleDef<GeopointRule, GeopointValue> {} /** * Geographical point representing a pair of latitude and longitude coordinates, * stored as degrees, in the World Geodetic System 1984 (WGS 84) format. Also * includes an optional `alt` property representing the altitude in meters. * * @public */ declare interface GeopointValue { /** * Type of the object. Must be `geopoint`. */ _type: "geopoint"; /** * Latitude in degrees */ lat: number; /** * Longitude in degrees */ lng: number; /** * Altitude in meters */ alt?: number; } /** @public */ declare interface GlobalDocumentReferenceDefinition extends BaseSchemaDefinition { type: "globalDocumentReference"; weak?: boolean; to: { type: string; title?: string; icon?: ComponentType; preview?: PreviewConfig; }[]; resourceType: string; resourceId: string; options?: ReferenceOptions; studioUrl?: | string | ((document: { id: string; type?: string }) => string | null); } /** @public */ declare interface HotspotOptions { previews?: HotspotPreview[]; } /** @public */ declare interface HotspotPreview { title: string; aspectRatio: number; } /** @public */ declare type I18nTextRecord<K extends string> = { [P in K]?: { key: string; ns: string; }; }; /** @public */ declare interface ImageAsset extends Asset_2 { _type: "sanity.imageAsset"; metadata: ImageMetadata; } /** @public */ declare interface ImageCrop { _type?: "sanity.imageCrop"; left: number; bottom: number; right: number; top: number; } /** @public */ declare interface ImageDefinition extends Omit< ObjectDefinition, "type" | "fields" | "options" | "groups" | "validation" > { type: "image"; fields?: FieldDefinition[]; options?: ImageOptions; validation?: ValidationBuilder<ImageRule, ImageValue>; initialValue?: InitialValueProperty<any, ImageValue>; } /** @public */ declare interface ImageDimensions { _type: "sanity.imageDimensions"; height: number; width: number; aspectRatio: number; } /** @public */ declare interface ImageHotspot { _type?: "sanity.imageHotspot"; width: number; height: number; x: number; y: number; } /** @public */ declare interface ImageMetadata { [key: string]: unknown; _type: "sanity.imageMetadata"; dimensions: ImageDimensions; palette?: ImagePalette; lqip?: string; blurHash?: string; thumbHash?: string; hasAlpha: boolean; isOpaque: boolean; } /** @public */ declare type ImageMetadataType = | "blurhash" | "thumbhash" | "lqip" | "palette" | "exif" | "image" | "location"; /** @public */ declare interface ImageOptions extends FileOptions { metadata?: ImageMetadataType[]; hotspot?: boolean | HotspotOptions; } /** @public */ declare interface ImagePalette { _type: "sanity.imagePalette"; darkMuted?: ImageSwatch; darkVibrant?: ImageSwatch; dominant?: ImageSwatch; lightMuted?: ImageSwatch; lightVibrant?: ImageSwatch; muted?: ImageSwatch; vibrant?: ImageSwatch; } /** @public */ declare interface ImageRule extends RuleDef<ImageRule, ImageValue> { /** * Require an image field has an asset. * * @example * ```ts * defineField({ * name: 'image', * title: 'Image', * type: 'image', * validation: (Rule) => Rule.required().assetRequired(), * }) * ``` */ assetRequired(): ImageRule; } /** @public */ declare interface ImageSchemaType extends Omit<ObjectSchemaType, "options"> { options?: ImageOptions; } /** @public */ declare interface ImageSwatch { _type: "sanity.imagePaletteSwatch"; background: string; foreground: string; population: number; title?: string; } /** @public */ declare interface ImageValue extends FileValue { crop?: ImageCrop; hotspot?: ImageHotspot; [index: string]: unknown; } /** @public */ declare type IndexTuple = [number | "", number | ""]; /** @public */ declare type InitialValueProperty<Params, Value> = | Value | InitialValueResolver<Params, Value> | undefined; /** @public */ declare type InitialValueResolver<Params, Value> = ( params: Params | undefined, context: InitialValueResolverContext, ) => Promise<Value> | Value; /** @public */ declare interface InitialValueResolverContext { projectId: string; dataset: string; schema: Schema; currentUser: CurrentUser | null; getClient: (options: { apiVersion: string }) => SanityClient; } /** @public */ declare type InlineFieldDefinition = { [K in keyof IntrinsicDefinitions]: Omit< IntrinsicDefinitions[K], "initialValue" | "validation" > & { validation?: SchemaValidationValue; initialValue?: InitialValueProperty<any, any>; }; }; /** @alpha This API may change */ declare interface InsertMenuOptions { /** * @defaultValue `'auto'` * `filter: 'auto'` automatically turns on filtering if there are more than 5 * schema types added to the menu. */ filter?: "auto" | boolean | undefined; groups?: | Array<{ name: string; title?: string; of?: Array<string>; }> | undefined; /** defaultValue `true` */ showIcons?: boolean | undefined; /** @defaultValue `[{name: 'list'}]` */ views?: | Array< | { name: "list"; } | { name: "grid"; previewImageUrl?: (schemaTypeName: string) => string | undefined; } > | undefined; } declare const internalGroqTypeReferenceTo: unique symbol; /** @public */ declare type IntrinsicArrayOfDefinition = { [K in keyof IntrinsicDefinitions]: Omit< ArrayOfEntry<IntrinsicDefinitions[K]>, "validation" | "initialValue" > & { validation?: SchemaValidationValue; initialValue?: InitialValueProperty<any, any>; }; }; /** * `IntrinsicDefinitions` is a lookup map for "predefined" schema definitions. * Schema types in `IntrinsicDefinitions` will have good type-completion and type-safety in {@link defineType}, * {@link defineField} and {@link defineArrayMember} once the `type` property is provided. * * By default, `IntrinsicDefinitions` contains all standard Sanity schema types (`array`, `string`, `number` ect), * but it is an interface and as such, open for extension. * * This type can be extended using declaration merging; this way new entries can be added. * See {@link defineType} for examples on how this can be accomplished. * * @see defineType * * @public */ declare interface IntrinsicDefinitions { array: ArrayDefinition; block: BlockDefinition; boolean: BooleanDefinition; date: DateDefinition; datetime: DatetimeDefinition; document: DocumentDefinition; file: FileDefinition; geopoint: GeopointDefinition; image: ImageDefinition; number: NumberDefinition; object: ObjectDefinition; reference: ReferenceDefinition; crossDatasetReference: CrossDatasetReferenceDefinition; globalDocumentReference: GlobalDocumentReferenceDefinition; slug: SlugDefinition; string: StringDefinition; text: TextDefinition; url: UrlDefinition; email: EmailDefinition; } /** * A union of all intrinsic types allowed natively in the schema. * * @see IntrinsicDefinitions * * @public */ declare type IntrinsicTypeName = IntrinsicDefinitions[keyof IntrinsicDefinitions]["type"]; /** @public */ declare type KeyedSegment = { _key: string; }; /** * Holds localized validation messages for a given field. * * @example Custom message for English (US) and Norwegian (Bokmål): * ``` * { * 'en-US': 'Needs to start with a capital letter', * 'no-NB': 'Må starte med stor bokstav', * } * ``` * @public */ declare interface LocalizedValidationMessages { [locale: string]: string; } /** @public */ declare type MediaAssetTypes = AssetInstanceDocument_2["_type"]; /** @public */ declare interface MediaLibraryFilter { name: string; query: string; } /** @public */ declare interface MediaLibraryOptions { filters?: MediaLibraryFilter[]; } /** @public */ declare interface MediaValidationValue< T extends MediaAssetTypes = MediaAssetTypes, > { /** * Media information */ media: { /** * The Media Library Asset. */ asset: Asset_3 & { currentVersion: Extract< AssetInstanceDocument_2, { _type: T; } >; }; }; /** * The field value which the media is used in. */ value: unknown; } /** @public */ declare interface MediaValidator<T extends MediaAssetTypes = MediaAssetTypes> { ( value: MediaValidationValue<T>, context: ValidationContext, ): CustomValidatorResult | Promise<CustomValidatorResult>; } /** @public */ /** @public */ declare interface ModalOptions { type?: "dialog" | "popover"; width?: 1 | 2 | 3 | 4 | 5 | "auto" | (1 | 2 | 3 | 4 | 5 | "auto")[]; } /** @public */ declare interface MultiFieldSet { name: string; title?: string; description?: string; single?: false; group?: string | string[]; options?: CollapseOptions & { columns?: number; }; fields: ObjectField[]; hidden?: ConditionalProperty; readOnly?: ConditionalProperty; } /** @public */ declare interface NumberDefinition extends BaseSchemaDefinition { type: "number"; options?: NumberOptions; placeholder?: string; validation?: ValidationBuilder<NumberRule, number>; initialValue?: InitialValueProperty<any, number>; } /** @public */ declare interface NumberOptions extends EnumListProps<number>, BaseSchemaTypeOptions {} /** @public */ declare interface NumberRule extends RuleDef<NumberRule, number> { min: (minNumber: number | FieldReference) => NumberRule; max: (maxNumber: number | FieldReference) => NumberRule; lessThan: (limit: number | FieldReference) => NumberRule; greaterThan: (limit: number | FieldReference) => NumberRule; integer: () => NumberRule; precision: (limit: number | FieldReference) => NumberRule; positive: () => NumberRule; negative: () => NumberRule; } /** @public */ declare interface NumberSchemaType extends BaseSchemaType { jsonType: "number"; options?: NumberOptions; initialValue?: InitialValueProperty<any, number>; } /** @public */ declare interface ObjectDefinition extends BaseSchemaDefinition { type: "object"; /** * Object must have at least one field. This is validated at Studio startup. */ fields: FieldDefinition[]; groups?: FieldGroupDefinition[]; fieldsets?: FieldsetDefinition[]; preview?: PreviewConfig; options?: ObjectOptions; validation?: ValidationBuilder<ObjectRule, Record<string, unknown>>; initialValue?: InitialValueProperty<any, Record<string, unknown>>; } /** @public */ declare interface ObjectField<T extends SchemaType = SchemaType> { name: string; fieldset?: string; group?: string | string[]; type: ObjectFieldType<T>; } /** @public */ declare type ObjectFieldType<T extends SchemaType = SchemaType> = T & { hidden?: ConditionalProperty; readOnly?: ConditionalProperty; }; /** @public */ declare interface ObjectOptions extends BaseSchemaTypeOptions { collapsible?: boolean; collapsed?: boolean; columns?: number; modal?: ModalOptions; } /** @public */ declare interface ObjectRule extends RuleDef< ObjectRule, Record<string, unknown> > {} /** @public */ declare interface ObjectSchemaType extends BaseSchemaType { jsonType: "object"; fields: ObjectField[]; groups?: FieldGroup[]; fieldsets?: Fieldset[]; initialValue?: InitialValueProperty<any, Record<string, unknown>>; weak?: boolean; /** @deprecated Unused. Use the new field-level search config. */ __experimental_search?: { path: (string | number)[]; weight: number; mapWith?: string; }[]; /** @alpha */ __experimental_omnisearch_visibility?: boolean; /** @alpha */ __experimental_actions?: string[]; /** @alpha */ __experimental_formPreviewTitle?: boolean; /** * @beta */ orderings?: SortOrdering[]; options?: any; } /** @public */ declare type Path = PathSegment[]; /** @public */ declare type PathSegment = string | number | KeyedSegment | IndexTuple; /** * Media Library capabilities that the consumer can declare it supports */ export declare type PluginCapabilities = { privateAssets?: boolean; }; /** * Filter that the plugin consumer can use to limit the assets shown */ export declare type PluginFilter = { type: "groq"; name: string; query: string; }; /** * Payload used to configure the plugin behavior */ export declare type PluginPayload = { auth: "token" | "cookie"; capabilities?: PluginCapabilities; disableNavigation?: boolean; pluginFilters?: PluginFilter[]; scheme: "light" | "dark"; selectAssetTypes: PluginSelectAssetType[]; selectionType: "single" | "multiple"; /** * Opaque string the host generates to **partition persisted picker UI state** (e.g. folder path, * search query, filters) in the Media Library iframe. Huey derives `localStorage` key suffixes * from this value; embedders often derive it from project + dataset + workspace (or any stable * context). */ pickerPersistenceKey?: string; }; export declare type PluginPostMessage = | PluginPostMessageAbortUploadRequest | PluginPostMessageAssetSelection | PluginPostMessageDocumentUpdate | PluginPostMessagePageLoaded | PluginPostMessagePageUnloaded | PluginPostMessageTokenRequest | PluginPostMessageTokenResponse | PluginPostMessageUploadFilesProgress | PluginPostMessageUploadFilesRequest | PluginPostMessageUploadFilesResponse; export declare type PluginPostMessageAbortUploadRequest = { type: "abortUploadRequest"; files?: { id: string; }[]; }; export declare type PluginPostMessageAssetSelection = { type: "assetSelection"; selection: AssetSelectionItemWithLegacySupport[]; }; /** * Message sent from the plugin that a document has been updated */ export declare type PluginPostMessageDocumentUpdate = { type: "documentUpdate"; document: { _id: string; _type: string; _rev: string; }; }; /** * Message sent from a plugin page to notify the host that the page is loaded and ready to be interacted with */ export declare type PluginPostMessagePageLoaded = { type: "pageLoaded"; page: string; }; /** * Message sent from a plugin page that a page is unloaded by the user (for closing the dialog and similar) */ export declare type PluginPostMessagePageUnloaded = { type: "pageUnloaded"; page: string; }; export declare type PluginPostMessageTokenRequest = { type: "tokenRequest"; }; export declare type PluginPostMessageTokenResponse = { type: "tokenResponse"; token: string | null; }; /** * Message sent from the plugin when files are uploading */ export declare type PluginPostMessageUploadFilesProgress = { type: "uploadProgress"; files: FileUpload[]; }; /** * Message sent from the plugin that the user wants to upload files */ export declare type PluginPostMessageUploadFilesRequest = { type: "uploadRequest"; files: { id: string; file: File; }[]; }; /** * Message sent from the app that the pending uploads are uploaded */ export declare type PluginPostMessageUploadFilesResponse = { type: "uploadResponse"; assets: AssetSelectionItemWithLegacySupport[]; }; /** * Asset types that can be selected by the plugin */ export declare type PluginSelectAssetType = "file" | "image" | "video"; /** @public */ declare type PortableTextBlock = PortableTextTextBlock | PortableTextObject; /** @public */ declare interface PortableTextObject { _type: string; _key: string; [other: string]: unknown; } /** @public */ declare interface PortableTextSpan { _key: string; _type: "span"; text: string; marks?: string[]; } /** @public */ declare interface PortableTextTextBlock< TChild = PortableTextSpan | PortableTextObject, > { _type: string; _key: string; children: TChild[]; markDefs?: PortableTextObject[]; listItem?: string; style?: string; level?: number; } /** @public */ declare interface PrepareViewOptions { /** @beta */ ordering?: SortOrdering; } /** @public */ declare interface PreviewConfig< Select extends Record<string, string> = Record<string, string>, PrepareValue extends Record<keyof Select, any> = Record<keyof Select, any>, > { select?: Select; prepare?: ( value: PrepareValue, viewOptions?: PrepareViewOptions, ) => PreviewValue; } /** @public */ declare interface PreviewValue { _id?: string; _createdAt?: string; _updatedAt?: string; title?: string; subtitle?: string; description?: string; media?: ReactNode | ElementType; imageUrl?: string; } /** @public */ declare interface Reference { _type: string; _ref: string; _key?: string; _weak?: boolean; _strengthenOnPublish?: { type: string; weak?: boolean; template?: { id: string; params: Record<string, string | number | boolean>; }; }; } /** @public */ declare interface ReferenceBaseOptions extends BaseSchemaTypeOptions { /** * When `true`, hides the "Create new" button in the reference input, * preventing users from creating new documents from this field. * * For more granular control (e.g., allowing creation of only specific types, * or conditionally hiding the button based on document state), use the * `creationTypeFilter` option instead. */ disableNew?: boolean; /** * Callback function to dynamically filter which document types can be created * from this reference field based on the current document state. * * This allows you to conditionally restrict the types available in the * "Create new" dropdown based on other field values in the document. * * **Important**: This only affects document creation, not which existing documents * appear in search results. To filter search results, use the `filter` option instead. * * @param context - Contains the current document, parent value, and field path * @param toTypes - Array of all types configured in the reference field's `to` property * @returns Array of type options that should be available for creation. Return the * original `toTypes` array to allow all types, a filtered subset to restrict * available types, or an empty array `[]` to hide the "Create new" button entirely. */ creationTypeFilter?: ReferenceTypeFilter; } /** @public */ declare interface ReferenceDefinition extends BaseSchemaDefinition { type: "reference"; to: ReferenceTo; weak?: boolean; options?: ReferenceOptions; validation?: ValidationBuilder<ReferenceRule, ReferenceValue>; initialValue?: InitialValueProperty<any, Omit<ReferenceValue, "_type">>; } /** @public */ declare type ReferenceFilterOptions = | ReferenceFilterResolverOptions | ReferenceFilterQueryOptions; /** @public */ declare interface ReferenceFilterQueryOptions { filter: string; filterParams?: Record<string, unknown>; } /** @public */ declare type ReferenceFilterResolver = ( context: ReferenceFilterResolverContext, ) => ReferenceFilterSearchOptions | Promise<ReferenceFilterSearchOptions>; /** @public */ declare interface ReferenceFilterResolverContext { document: SanityDocument; parent?: Record<string, unknown> | Record<string, unknown>[]; parentPath: Path; perspective: StackablePerspective[]; getClient: (options: { apiVersion: string }) => SanityClient; } /** @public */ declare interface ReferenceFilterResolverOptions { filter?: ReferenceFilterResolver; filterParams?: never; } /** @public */ declare type ReferenceFilterSearchOptions = { filter?: string; params?: Record<string, unknown>; tag?: string; maxFieldDepth?: number; strategy?: SearchStrategy; perspective?: Exclude<ClientPerspective, "raw" | "previewDrafts">; }; /** * Types are closed for extension. To add properties via declaration merging to this type, * redeclare and add the properties to the interfaces that make up ReferenceOptions type. * * @see ReferenceFilterOptions * @see ReferenceFilterResolverOptions * @see ReferenceBaseOptions * * @public */ declare type ReferenceOptions = ReferenceBaseOptions & ReferenceFilterOptions; /** @public */ declare interface ReferenceRule extends RuleDef< ReferenceRule, ReferenceValue > {} /** @public */ declare interface ReferenceSchemaType extends Omit< ObjectSchemaType, "options" > { jsonType: "object"; to: ObjectSchemaType[]; weak?: boolean; options?: ReferenceOptions; } /** @public */ declare type ReferenceTo = | SchemaTypeDefinition | TypeReference | Array<SchemaTypeDefinition | TypeReference>; /** * Function type for filtering which document types can be created from a reference field. * * The `creationTypeFilter` specifically controls the types * available when clicking "Create new" in the reference input. * * This is distinct from the `filter` option, which controls which existing documents appear in search results. * * @param context - Information about the current document and fi