UNPKG

@sanity/client

Version:

Client for retrieving, creating and patching data from Sanity.io

1,689 lines (1,580 loc) 201 kB
import {ClientConfig as ClientConfig_2} from '@sanity/client' import type {HttpContext} from 'get-it' import {Observable} from 'rxjs' import {Requester} from 'get-it' import {adapter as unstable__adapter} from 'get-it' import {environment as unstable__environment} from 'get-it' /** @public */ export declare type Action = | CreateAction | ReplaceDraftAction | EditAction | DeleteAction | DiscardAction | PublishAction | UnpublishAction | VersionAction | ReleaseAction /** @internal */ export declare interface ActionError { type: 'actionError' description: string items?: ActionErrorItem[] } /** @internal */ export declare interface ActionErrorItem { error: { type: string description: string value?: unknown } index: number } /** @beta */ declare interface AgentActionAsync { /** * When async: true, requests responds with status 201 and \{_id\} as response body as soon as the request is validated. * The instruction operation will carry on in the background. * * When async: false (default), requests respond with status 200 and the document value after instruction has been applied. * * async: true is incompatible with noWrite, as async: true does not return the resulting document */ async: true } /** @beta */ export declare type AgentActionParam< TParamConfig extends { docIdRequired: boolean } = { docIdRequired: false }, > = | string | ConstantAgentActionParam | FieldAgentActionParam<TParamConfig> | DocumentAgentActionParam<TParamConfig> | GroqAgentActionParam /** @beta */ export declare type AgentActionParams< TParamConfig extends { docIdRequired: boolean } = { docIdRequired: false }, > = Record<string, AgentActionParam<TParamConfig>> /** @beta */ export declare type AgentActionPath = AgentActionPathSegment[] /** @beta */ export declare type AgentActionPathSegment = | string | { _key: string } /** @beta */ declare interface AgentActionRequestBase extends AgentActionSchema { /** * When localeSettings is provided on the request, instruct can write to date and datetime fields. * Otherwise, such fields will be ignored. */ localeSettings?: { /** * A valid Unicode BCP 47 locale identifier used to interpret and format * natural language inputs and date output. Examples include "en-US", "fr-FR", or "ja-JP". * * This affects how phrases like "next Friday" or "in two weeks" are parsed, * and how resulting dates are presented (e.g., 12-hour vs 24-hour format). * * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#getcanonicalocales */ locale: string /** * A valid IANA time zone identifier used to resolve relative and absolute * date expressions to a specific point in time. Examples include * "America/New_York", "Europe/Paris", or "Asia/Tokyo". * * This ensures phrases like "tomorrow at 9am" are interpreted correctly * based on the user's local time. * * @see https://en.wikipedia.org/wiki/List_of_tz_database_time_zones */ timeZone: string } /** * Controls how much variance the instructions will run with. * * Value must be in the range [0, 1] (inclusive). * * Defaults: * - generate: 0.3 * - translate: 0 * - transform: 0 */ temperature?: number } /** @beta */ declare interface AgentActionSchema { /** schemaId as reported by sanity deploy / sanity schema store */ schemaId: string /** * ### forcePublishedWrite: false (default) * By default, agent actions will never write to a published document. * * Instead, they will force the use of a draft ID ("drafts.some-id") instead of the published ID ("some-id"), * even when a published ID is provided. * * Actions will use state from an existing draft if it exists, * or use the published document to create a draft, if no draft exists. * * Successful responses contains the _id that was mutated by the action. * * * ### forcePublishedWrite: true * * When forcePublishedWrite: true an agent action will write to the exact id provided. * The action will also not fallback to published state for draft ids. * * * ### Versioned ids (releases) * * When an ID on the form "versions.<release>.some-id" is provided, agent actions will * always behave as if `forcePublishedWrite: true`. * That is, only the exact document state of the id provided is considered and mutated. * */ forcePublishedWrite?: boolean /** * When a type or field in the schema has a function set for `hidden` or `readOnly`, it is conditional. * * By default, Generate will not output to conditional `readOnly` and `hidden` fields, * ie, they are considered to resolve to `readOnly: true` / `hidden: true`. * * `conditionalPaths` param allows setting the default conditional value for * `hidden` and `readOnly` to false, * or individually set `hidden` and `readOnly` state for individual document paths. * * Note: fields and types with explicit readOnly: true or hidden: true in the schema, are not available to Generate, * and cannot be changed via conditionalPaths * * conditionalPaths state only apply to fields and types that have conditional `hidden` or `readOnly` in their schema definition. * * Consider using `hidden: () => true` in schema config, if a field should be writeable only by Generate and never * visible in the studio – then make the field visible to the Generate using `conditionalPaths`. * * @see GenerateRequestBase#target */ conditionalPaths?: { defaultReadOnly?: boolean defaultHidden?: boolean paths?: { /** path here is not a relative path: it must be the full document path, regardless of `path` param used in targets */ path: AgentActionPath readOnly: boolean hidden: boolean }[] } } /** @public */ declare class AgentActionsClient { #private constructor(client: SanityClient, httpRequest: HttpRequest) /** * Run an instruction to generate content in a target document. * @param request - instruction request */ generate<DocumentShape extends Record<string, Any>>( request: GenerateInstruction<DocumentShape>, ): Promise< (typeof request)['async'] extends true ? { _id: string } : IdentifiedSanityDocumentStub & DocumentShape > /** * Transform a target document based on a source. * @param request - translation request */ transform<DocumentShape extends Record<string, Any>>( request: TransformDocument<DocumentShape>, ): Promise< (typeof request)['async'] extends true ? { _id: string } : IdentifiedSanityDocumentStub & DocumentShape > /** * Translate a target document based on a source. * @param request - translation request */ translate<DocumentShape extends Record<string, Any>>( request: TranslateDocument<DocumentShape>, ): Promise< (typeof request)['async'] extends true ? { _id: string } : IdentifiedSanityDocumentStub & DocumentShape > /** * Run a raw instruction and return the result either as text or json * @param request - prompt request */ prompt<const DocumentShape extends Record<string, Any>>( request: PromptRequest<DocumentShape>, ): Promise<(typeof request)['format'] extends 'json' ? DocumentShape : string> /** * Patch a document using a schema aware API. * Does not use an LLM, but uses the schema to ensure paths and values matches the schema. * @param request - instruction request */ patch<DocumentShape extends Record<string, Any>>( request: PatchDocument<DocumentShape>, ): Promise< (typeof request)['async'] extends true ? { _id: string } : IdentifiedSanityDocumentStub & DocumentShape > } /** @beta */ declare interface AgentActionSync { /** * By default, noWrite: false. * Write enabled operations will mutate the target document, and emit AI presence in the studio. * * When noWrite: true, the api will not mutate any documents nor emit presence. * Ie, when true, no changes will be made to content-lake * * noWrite: true is incompatible with async: true, * as noWrite implies that you will use the return value of the operation */ noWrite?: boolean /** * When async: true, requests responds with status 201 and \{_id\} as response body as soon as the request is validated. * The instruction operation will carry on in the background. * * When async: false (default), requests respond with status 200 and the document value after instruction has been applied. * * async: true is incompatible with noWrite: true, as async: true does not return the resulting document */ async?: false } /** * @beta */ export declare interface AgentActionTarget { /** * Root target path. * * Use this to have the instruction only affect a part of the document. * * To further control the behavior of individual paths under the root, use `include`, `exclude`, `types.include` * and `types.exclude`. * * Example: * * `path: ['body', {_key: 'someKey'}, 'nestedObject']` * * Here, the instruction will only write to fields under the nestedObject. * * Default: [] = the document itself * * @see #AgentActionPathSegment * @see #AgentActionPath * */ path?: AgentActionPathSegment | AgentActionPath /** * maxPathDepth controls how deep into the schema from the target root the instruction will affect. * * Depth is based on path segments: * - `title` has depth 1 * - `array[_key="no"].title` has depth 3 * * Be careful not to set this too high in studios with recursive document schemas, as it could have * negative impact on performance; both for runtime and quality of responses. * * Default: 4 */ maxPathDepth?: number /** * By default, all children up to `target.maxPathDepth` are included. * Fields or array items not on the exclude list, are implicitly included. */ exclude?: AgentActionPathSegment[] /** * Types can be used to exclude array item types or all fields directly under the target path of a certain type. * If you do exclude: ['string'] all string fields under the target will be excluded, for instance. * * `types.include` and `types.exclude` are mutually exclusive. */ types?: AgentActionTypeConfig } /** @beta */ declare interface AgentActionTargetInclude { path: AgentActionPathSegment | AgentActionPath /** * By default, all children up to `target.maxPathDepth` are included. * Fields or array items not on the exclude list, are implicitly included. */ exclude?: AgentActionPathSegment[] /** * Types can be used to exclude array item types or all fields directly under the target path of a certain type. * If you do exclude: ['string'] all string fields under the target will be excluded, for instance. * * `types.include` and `types.exclude` are mutually exclusive. */ types?: AgentActionTypeConfig } /** @beta */ declare type AgentActionTypeConfig = | { include: string[] exclude?: never } | { exclude: string[] include?: never } /** @internal */ export declare type AllDocumentIdsMutationOptions = BaseMutationOptions & { returnFirst: false returnDocuments: false } /** @internal */ export declare type AllDocumentsMutationOptions = BaseMutationOptions & { returnFirst: false returnDocuments?: true } /** * Used to tag types that is set to `any` as a temporary measure, but should be replaced with proper typings in the future * @internal */ export declare type Any = any declare type AnyNonNullable = Exclude<any, null | undefined> /** @internal */ export declare interface ApiError { error: string message: string statusCode: number } /** * Archives an `active` release, and deletes all the release documents. * * @public */ export declare interface ArchiveReleaseAction { actionType: 'sanity.action.release.archive' releaseId: string } /** @public */ export declare type AssetMetadataType = | 'location' | 'exif' | 'image' | 'palette' | 'lqip' | 'blurhash' | 'none' /** @internal */ export declare class AssetsClient { #private constructor(client: SanityClient, httpRequest: HttpRequest) /** * Uploads a file asset to the configured dataset * * @param assetType - Asset type (file) * @param body - Asset content - can be a browser File instance, a Blob, a Node.js Buffer instance or a Node.js ReadableStream. * @param options - Options to use for the upload */ upload( assetType: 'file', body: UploadBody, options?: UploadClientConfig, ): Promise<SanityAssetDocument> /** * Uploads an image asset to the configured dataset * * @param assetType - Asset type (image) * @param body - Asset content - can be a browser File instance, a Blob, a Node.js Buffer instance or a Node.js ReadableStream. * @param options - Options to use for the upload */ upload( assetType: 'image', body: UploadBody, options?: UploadClientConfig, ): Promise<SanityImageAssetDocument> /** * Uploads a file or an image asset to the configured dataset * * @param assetType - Asset type (file/image) * @param body - Asset content - can be a browser File instance, a Blob, a Node.js Buffer instance or a Node.js ReadableStream. * @param options - Options to use for the upload */ upload( assetType: 'file' | 'image', body: UploadBody, options?: UploadClientConfig, ): Promise<SanityAssetDocument | SanityImageAssetDocument> } /** @internal */ export declare type AttributeSet = { [key: string]: Any } /** @internal */ export declare interface AuthProvider { name: string title: string url: string } /** @internal */ export declare type AuthProviderResponse = { providers: AuthProvider[] } /** @internal */ export declare type BaseActionOptions = RequestOptions & { transactionId?: string skipCrossDatasetReferenceValidation?: boolean dryRun?: boolean } /** @internal */ export declare type BaseMutationOptions = RequestOptions & { visibility?: 'sync' | 'async' | 'deferred' returnDocuments?: boolean returnFirst?: boolean dryRun?: boolean autoGenerateArrayKeys?: boolean skipCrossDatasetReferenceValidation?: boolean transactionId?: string } /** @internal */ export declare class BasePatch { protected selection: PatchSelection protected operations: PatchOperations constructor(selection: PatchSelection, operations?: PatchOperations) /** * Sets the given attributes to the document. Does NOT merge objects. * The operation is added to the current patch, ready to be commited by `commit()` * * @param attrs - Attributes to set. To set a deep attribute, use JSONMatch, eg: \{"nested.prop": "value"\} */ set(attrs: AttributeSet): this /** * Sets the given attributes to the document if they are not currently set. Does NOT merge objects. * The operation is added to the current patch, ready to be commited by `commit()` * * @param attrs - Attributes to set. To set a deep attribute, use JSONMatch, eg: \{"nested.prop": "value"\} */ setIfMissing(attrs: AttributeSet): this /** * Performs a "diff-match-patch" operation on the string attributes provided. * The operation is added to the current patch, ready to be commited by `commit()` * * @param attrs - Attributes to perform operation on. To set a deep attribute, use JSONMatch, eg: \{"nested.prop": "dmp"\} */ diffMatchPatch(attrs: AttributeSet): this /** * Unsets the attribute paths provided. * The operation is added to the current patch, ready to be commited by `commit()` * * @param attrs - Attribute paths to unset. */ unset(attrs: string[]): this /** * Increment a numeric value. Each entry in the argument is either an attribute or a JSON path. The value may be a positive or negative integer or floating-point value. The operation will fail if target value is not a numeric value, or doesn't exist. * * @param attrs - Object of attribute paths to increment, values representing the number to increment by. */ inc(attrs: {[key: string]: number}): this /** * Decrement a numeric value. Each entry in the argument is either an attribute or a JSON path. The value may be a positive or negative integer or floating-point value. The operation will fail if target value is not a numeric value, or doesn't exist. * * @param attrs - Object of attribute paths to decrement, values representing the number to decrement by. */ dec(attrs: {[key: string]: number}): this /** * Provides methods for modifying arrays, by inserting, appending and replacing elements via a JSONPath expression. * * @param at - Location to insert at, relative to the given selector, or 'replace' the matched path * @param selector - JSONPath expression, eg `comments[-1]` or `blocks[_key=="abc123"]` * @param items - Array of items to insert/replace */ insert(at: 'before' | 'after' | 'replace', selector: string, items: Any[]): this /** * Append the given items to the array at the given JSONPath * * @param selector - Attribute/path to append to, eg `comments` or `person.hobbies` * @param items - Array of items to append to the array */ append(selector: string, items: Any[]): this /** * Prepend the given items to the array at the given JSONPath * * @param selector - Attribute/path to prepend to, eg `comments` or `person.hobbies` * @param items - Array of items to prepend to the array */ prepend(selector: string, items: Any[]): this /** * Change the contents of an array by removing existing elements and/or adding new elements. * * @param selector - Attribute or JSONPath expression for array * @param start - Index at which to start changing the array (with origin 0). If greater than the length of the array, actual starting index will be set to the length of the array. If negative, will begin that many elements from the end of the array (with origin -1) and will be set to 0 if absolute value is greater than the length of the array.x * @param deleteCount - An integer indicating the number of old array elements to remove. * @param items - The elements to add to the array, beginning at the start index. If you don't specify any elements, splice() will only remove elements from the array. */ splice(selector: string, start: number, deleteCount?: number, items?: Any[]): this /** * Adds a revision clause, preventing the document from being patched if the `_rev` property does not match the given value * * @param rev - Revision to lock the patch to */ ifRevisionId(rev: string): this /** * Return a plain JSON representation of the patch */ serialize(): PatchMutationOperation /** * Return a plain JSON representation of the patch */ toJSON(): PatchMutationOperation /** * Clears the patch of all operations */ reset(): this protected _assign(op: keyof PatchOperations, props: Any, merge?: boolean): this protected _set(op: keyof PatchOperations, props: Any): this } /** @internal */ export declare class BaseTransaction { protected operations: Mutation[] protected trxId?: string constructor(operations?: Mutation[], transactionId?: string) /** * Creates a new Sanity document. If `_id` is provided and already exists, the mutation will fail. If no `_id` is given, one will automatically be generated by the database. * The operation is added to the current transaction, ready to be commited by `commit()` * * @param doc - Document to create. Requires a `_type` property. */ create<R extends Record<string, Any> = Record<string, Any>>(doc: SanityDocumentStub<R>): this /** * Creates a new Sanity document. If a document with the same `_id` already exists, the create operation will be ignored. * The operation is added to the current transaction, ready to be commited by `commit()` * * @param doc - Document to create if it does not already exist. Requires `_id` and `_type` properties. */ createIfNotExists<R extends Record<string, Any> = Record<string, Any>>( doc: IdentifiedSanityDocumentStub<R>, ): this /** * Creates a new Sanity document, or replaces an existing one if the same `_id` is already used. * The operation is added to the current transaction, ready to be commited by `commit()` * * @param doc - Document to create or replace. Requires `_id` and `_type` properties. */ createOrReplace<R extends Record<string, Any> = Record<string, Any>>( doc: IdentifiedSanityDocumentStub<R>, ): this /** * Deletes the document with the given document ID * The operation is added to the current transaction, ready to be commited by `commit()` * * @param documentId - Document ID to delete */ delete(documentId: string): this /** * Gets the current transaction ID, if any */ transactionId(): string | undefined /** * Set the ID of this transaction. * * @param id - Transaction ID */ transactionId(id: string): this /** * Return a plain JSON representation of the transaction */ serialize(): Mutation[] /** * Return a plain JSON representation of the transaction */ toJSON(): Mutation[] /** * Clears the transaction of all operations */ reset(): this protected _add(mut: Mutation): this } /** * @public * The server sent a `channelError` message. Usually indicative of a bad or malformed request */ export declare class ChannelError extends Error { readonly name = 'ChannelError' readonly data?: unknown constructor(message: string, data: unknown) } /** * An error occurred. This is different from a network-level error (which will be emitted as 'error'). * Possible causes are things such as malformed filters, non-existant datasets or similar. * * @public */ export declare type ChannelErrorEvent = { type: 'channelError' message: string } /** @public */ export declare interface ClientConfig { projectId?: string dataset?: string /** @defaultValue true */ useCdn?: boolean token?: string /** @internal */ '~experimental_resource'?: ClientConfigResource /** * What perspective to use for the client. See {@link https://www.sanity.io/docs/perspectives|perspective documentation} * @remarks * As of API version `v2025-02-19`, the default perspective has changed from `raw` to `published`. {@link https://www.sanity.io/changelog/676aaa9d-2da6-44fb-abe5-580f28047c10|Changelog} * @defaultValue 'published' */ perspective?: ClientPerspective apiHost?: string /** @remarks * As of API version `v2025-02-19`, the default perspective has changed from `raw` to `published`. {@link https://www.sanity.io/changelog/676aaa9d-2da6-44fb-abe5-580f28047c10|Changelog} */ apiVersion?: string proxy?: string /** * Optional request tag prefix for all request tags */ requestTagPrefix?: string /** * Optional default headers to include with all requests * * @remarks request-specific headers will override any default headers with the same name. */ headers?: Record<string, string> ignoreBrowserTokenWarning?: boolean withCredentials?: boolean allowReconfigure?: boolean timeout?: number /** Number of retries for requests. Defaults to 5. */ maxRetries?: number /** * The amount of time, in milliseconds, to wait before retrying, given an attemptNumber (starting at 0). * * Defaults to exponential back-off, starting at 100ms, doubling for each attempt, together with random * jitter between 0 and 100 milliseconds. More specifically the following algorithm is used: * * Delay = 100 * 2^attemptNumber + randomNumberBetween0and100 */ retryDelay?: (attemptNumber: number) => number /** * @deprecated Don't use */ useProjectHostname?: boolean /** * @deprecated Don't use */ requester?: Requester /** * Adds a `resultSourceMap` key to the API response, with the type `ContentSourceMap` */ resultSourceMap?: boolean | 'withKeyArraySelector' /** *@deprecated set `cache` and `next` options on `client.fetch` instead */ fetch?: | { cache?: ResponseQueryOptions['cache'] next?: ResponseQueryOptions['next'] } | boolean /** * Options for how, if enabled, Content Source Maps are encoded into query results using steganography */ stega?: StegaConfig | boolean } declare type ClientConfigResource = | { type: 'canvas' id: string } | { type: 'media-library' id: string } | { type: 'dataset' id: string } | { type: 'dashboard' id: string } /** @public */ export declare class ClientError extends Error { response: ErrorProps['response'] statusCode: ErrorProps['statusCode'] responseBody: ErrorProps['responseBody'] details: ErrorProps['details'] constructor(res: Any, context?: HttpContext) } /** @public */ export declare type ClientPerspective = | DeprecatedPreviewDrafts | 'published' | 'drafts' | 'raw' | StackablePerspective[] /** @public */ export declare type ClientReturn< GroqString extends string, Fallback = Any, > = GroqString extends keyof SanityQueries ? SanityQueries[GroqString] : Fallback /** * @public * @deprecated -- use `ClientConfig` instead */ export declare interface ClientStegaConfig extends ClientConfig {} /** * Sanity API specific EventSource handler shared between the listen and live APIs * * Since the `EventSource` API is not provided by all environments, this function enables custom initialization of the EventSource instance * for runtimes that requires polyfilling or custom setup logic (e.g. custom HTTP headers) * via the passed `initEventSource` function which must return an EventSource instance. * * Possible errors to be thrown on the returned observable are: * - {@link MessageError} * - {@link MessageParseError} * - {@link ChannelError} * - {@link DisconnectError} * - {@link ConnectionFailedError} * * @param initEventSource - A function that returns an EventSource instance or an Observable that resolves to an EventSource instance * @param events - an array of named events from the API to listen for. * * @internal */ export declare function connectEventSource<EventName extends string>( initEventSource: () => EventSourceInstance | Observable<EventSourceInstance>, events: EventName[], ): Observable<ServerSentEvent<EventName>> /** * @public * Thrown if the EventSource connection could not be established. * Note that ConnectionFailedErrors are rare, and disconnects will normally be handled by the EventSource instance itself and emitted as `reconnect` events. */ export declare class ConnectionFailedError extends Error { readonly name = 'ConnectionFailedError' } /** * Include a string in the instruction: do not have to escape $ signs in the string. * * ```ts * client.agent.action.generate({ * schemaId, * documentId, * instruction: 'Give the following topic:\n $topic \n ---\nGenerate the full article.', * instructionParams: { * topic: { * type: 'constant', * value: 'Grapefruit' * }, * }, * }) * ``` * * `type: 'constant'` can also be provided directly as a string, as a shorthand: * * ```ts * client.agent.action.generate({ * schemaId, * documentId, * instruction: 'Give the following topic:\n $topic \n ---\nGenerate the full article.', * instructionParams: { * topic: 'Grapefruit' * }, * }) * ``` * * @beta * */ export declare interface ConstantAgentActionParam { type: 'constant' value: string } /** @public */ export declare interface ContentSourceMap { mappings: ContentSourceMapMappings documents: ContentSourceMapDocuments paths: ContentSourceMapPaths } /** @public */ declare interface ContentSourceMap_2 { mappings: ContentSourceMapMappings_2 documents: ContentSourceMapDocuments_2 paths: ContentSourceMapPaths_2 } /** @public */ export declare interface ContentSourceMapDocument extends ContentSourceMapDocumentBase { _projectId?: undefined _dataset?: undefined } /** @public */ declare interface ContentSourceMapDocument_2 extends ContentSourceMapDocumentBase_2 { _projectId?: undefined _dataset?: undefined } /** @public */ export declare interface ContentSourceMapDocumentBase { _id: string _type: string } /** @public */ declare interface ContentSourceMapDocumentBase_2 { _id: string _type: string } /** @public */ export declare type ContentSourceMapDocuments = ( | ContentSourceMapDocument | ContentSourceMapRemoteDocument )[] /** @public */ declare type ContentSourceMapDocuments_2 = ( | ContentSourceMapDocument_2 | ContentSourceMapRemoteDocument_2 )[] /** * DocumentValueSource is a path to a value within a document * @public */ export declare interface ContentSourceMapDocumentValueSource { type: 'documentValue' document: number path: number } /** * DocumentValueSource is a path to a value within a document * @public */ declare interface ContentSourceMapDocumentValueSource_2 { type: 'documentValue' document: number path: number } /** * When a value is not from a source, its a literal * @public */ export declare interface ContentSourceMapLiteralSource { type: 'literal' } /** * When a value is not from a source, its a literal * @public */ declare interface ContentSourceMapLiteralSource_2 { type: 'literal' } /** @public */ export declare type ContentSourceMapMapping = ContentSourceMapValueMapping /** @public */ declare type ContentSourceMapMapping_2 = ContentSourceMapValueMapping_2 /** @public */ export declare type ContentSourceMapMappings = Record<string, ContentSourceMapMapping> /** @public */ declare type ContentSourceMapMappings_2 = Record<string, ContentSourceMapMapping_2> /** @alpha */ export declare type ContentSourceMapParsedPath = ( | string | number | ContentSourceMapParsedPathKeyedSegment )[] /** @alpha */ export declare type ContentSourceMapParsedPathKeyedSegment = { _key: string _index: number } /** @public */ export declare type ContentSourceMapPaths = string[] /** @public */ declare type ContentSourceMapPaths_2 = string[] /** @public */ export declare type ContentSourceMapQueryResponse = | RawQueryResponse<unknown> | Pick<RawQueryResponse<unknown>, 'result' | 'resultSourceMap'> /** @public */ export declare interface ContentSourceMapRemoteDocument extends ContentSourceMapDocumentBase { _projectId: string _dataset: string } /** @public */ declare interface ContentSourceMapRemoteDocument_2 extends ContentSourceMapDocumentBase_2 { _projectId: string _dataset: string } /** @public */ export declare type ContentSourceMapSource = | ContentSourceMapDocumentValueSource | ContentSourceMapLiteralSource | ContentSourceMapUnknownSource /** @public */ declare type ContentSourceMapSource_2 = | ContentSourceMapDocumentValueSource_2 | ContentSourceMapLiteralSource_2 | ContentSourceMapUnknownSource_2 /** * When a field source is unknown * @public */ export declare interface ContentSourceMapUnknownSource { type: 'unknown' } /** * When a field source is unknown * @public */ declare interface ContentSourceMapUnknownSource_2 { type: 'unknown' } /** * ValueMapping is a mapping when for value that is from a single source value * It may refer to a field within a document or a literal value * @public */ export declare interface ContentSourceMapValueMapping { type: 'value' source: ContentSourceMapSource } /** * ValueMapping is a mapping when for value that is from a single source value * It may refer to a field within a document or a literal value * @public */ declare interface ContentSourceMapValueMapping_2 { type: 'value' source: ContentSourceMapSource_2 } /** @public */ export declare class CorsOriginError extends Error { projectId: string addOriginUrl?: URL constructor({projectId}: {projectId: string}) } /** * Creates a new draft document. The published version of the document must not already exist. * If the draft version of the document already exists the action will fail by default, but * this can be adjusted to instead leave the existing document in place. * * @public */ export declare type CreateAction = { actionType: 'sanity.action.document.create' /** * ID of the published document to create a draft for. */ publishedId: string /** * Document to create. Requires a `_type` property. */ attributes: IdentifiedSanityDocumentStub /** * ifExists controls what to do if the draft already exists */ ifExists: 'fail' | 'ignore' } /** * @deprecated -- Use `import {createClient} from '@sanity/client'` instead * @public */ export declare const createClient: (config: ClientConfig_2) => SanityClient /** * Creates a new release under the given id, with metadata. * * @public */ export declare interface CreateReleaseAction { actionType: 'sanity.action.release.create' releaseId: string metadata?: Partial<ReleaseDocument['metadata']> } /** * Creates a new version of an existing document, attached to the release as given * by `document._id` * * @public */ export declare interface CreateVersionAction { actionType: 'sanity.action.document.version.create' publishedId: string document: IdentifiedSanityDocumentStub } /** @public */ export declare interface CurrentSanityUser { id: string name: string email: string profileImage: string | null role: string } /** @public */ export declare type DatasetAclMode = 'public' | 'private' | 'custom' /** @public */ export declare type DatasetResponse = { datasetName: string aclMode: DatasetAclMode } /** @internal */ export declare class DatasetsClient { #private constructor(client: SanityClient, httpRequest: HttpRequest) /** * Create a new dataset with the given name * * @param name - Name of the dataset to create * @param options - Options for the dataset */ create( name: string, options?: { aclMode?: DatasetAclMode }, ): Promise<DatasetResponse> /** * Edit a dataset with the given name * * @param name - Name of the dataset to edit * @param options - New options for the dataset */ edit( name: string, options?: { aclMode?: DatasetAclMode }, ): Promise<DatasetResponse> /** * Delete a dataset with the given name * * @param name - Name of the dataset to delete */ delete(name: string): Promise<{ deleted: true }> /** * Fetch a list of datasets for the configured project */ list(): Promise<DatasetsResponse> } /** @public */ export declare type DatasetsResponse = { name: string aclMode: DatasetAclMode createdAt: string createdByUserId: string addonFor: string | null datasetProfile: string features: string[] tags: string[] }[] /** * Deletes the published version of a document and optionally some (likely all known) draft versions. * If any draft version exists that is not specified for deletion this is an error. * If the purge flag is set then the document history is also deleted. * * @public */ export declare type DeleteAction = { actionType: 'sanity.action.document.delete' /** * Published document ID to delete */ publishedId: string /** * Draft document ID to delete */ includeDrafts: string[] /** * Delete document history */ purge?: boolean } /** * Deletes a `archived` or `published` release, and all the release documents versions. * * @public */ export declare interface DeleteReleaseAction { actionType: 'sanity.action.release.delete' releaseId: string } /** * @deprecated use 'drafts' instead */ declare type DeprecatedPreviewDrafts = 'previewDrafts' /** * Delete the draft version of a document. * It is an error if it does not exist. If the purge flag is set, the document history is also deleted. * * @public * @deprecated Use {@link DiscardVersionAction} instead */ export declare type DiscardAction = { actionType: 'sanity.action.document.discard' /** * Draft document ID to delete */ draftId: string /** * Delete document history */ purge?: boolean } /** * Delete a version of a document. * * @public */ export declare interface DiscardVersionAction { actionType: 'sanity.action.document.version.discard' versionId: string purge?: boolean } /** * The listener has been told to explicitly disconnect. * This is a rare situation, but may occur if the API knows reconnect attempts will fail, * eg in the case of a deleted dataset, a blocked project or similar events. * @public */ export declare class DisconnectError extends Error { readonly name = 'DisconnectError' readonly reason?: string constructor(message: string, reason?: string, options?: ErrorOptions) } /** * The listener has been told to explicitly disconnect and not reconnect. * This is a rare situation, but may occur if the API knows reconnect attempts will fail, * eg in the case of a deleted dataset, a blocked project or similar events. * * Note that this is not treated as an error on the observable, but will complete the observable. * * @public */ export declare type DisconnectEvent = { type: 'disconnect' reason: string } declare type DocIdParam< TParamConfig extends { docIdRequired: boolean } = { docIdRequired: false }, > = TParamConfig['docIdRequired'] extends true ? { documentId: string } : { /** * If omitted, implicitly uses the documentId of the instruction target */ documentId?: string } /** * * Includes a LLM-friendly version of the document in the instruction * * ```ts * client.agent.action.generate({ * schemaId, * documentId, * instruction: 'Give the following document value:\n $document \n ---\nGenerate keywords.', * instructionParams: { * document: { * type: 'document', * }, * }, * target: {path: 'keywords' } * }) * ``` * * @beta * */ export declare type DocumentAgentActionParam< TParamConfig extends { docIdRequired: boolean } = { docIdRequired: false }, > = { type: 'document' } & DocIdParam<TParamConfig> /** @internal */ export declare type EditableReleaseDocument = Omit< PartialExcept<ReleaseDocument, '_id'>, 'metadata' | '_type' > & { _id: string metadata: Partial<ReleaseDocument['metadata']> } /** * Modifies an existing draft document. * It applies the given patch to the document referenced by draftId. * If there is no such document then one is created using the current state of the published version and then that is updated accordingly. * * @public */ export declare type EditAction = { actionType: 'sanity.action.document.edit' /** * Draft document ID to edit */ draftId: string /** * Published document ID to create draft from, if draft does not exist */ publishedId: string /** * Patch operations to apply */ patch: PatchOperations } /** * Edits an existing release, updating the metadata. * * @public */ export declare interface EditReleaseAction { actionType: 'sanity.action.release.edit' releaseId: string patch: PatchOperations } /** * @internal */ export declare function encodeIntoResult<Result>( result: Result, csm: ContentSourceMap_2, encoder: Encoder, ): Result /** * @internal */ export declare type Encoder = (context: { sourcePath: ContentSourceMapParsedPath sourceDocument: ContentSourceMapDocuments_2[number] resultPath: ContentSourceMapParsedPath value: string }) => string /** @public */ export declare interface ErrorProps { message: string response: Any statusCode: number responseBody: Any details: Any } /** * @internal */ export declare type EventSourceEvent<Name extends string> = ServerSentEvent<Name> /** * @internal */ export declare type EventSourceInstance = InstanceType<typeof globalThis.EventSource> /** * * * Includes a LLM-friendly version of the field value in the instruction * * ```ts * client.agent.action.generate({ * schemaId, * documentId, * instruction: 'Give the following field value:\n $pte \n ---\nGenerate keywords.', * instructionParams: { * pte: { * type: 'field', * path: ['pteField'], * }, * }, * target: {path: 'keywords' } * }) * * ``` * * @beta * */ export declare type FieldAgentActionParam< TParamConfig extends { docIdRequired: boolean } = { docIdRequired: false }, > = { type: 'field' /** * Examples: 'title', ['array', \{_key: 'arrayItemKey'\}, 'field'] */ path: AgentActionPathSegment | AgentActionPath } & DocIdParam<TParamConfig> /** @public */ export declare type FilterDefault = (props: { /** * The path to the value in the source document, for example if you queried for a document like this: * `*[_type == "author"][0]{"slug": slug.current}` * Then the `sourcePath` for `result.slug` would be `['slug', 'current']`. * */ sourcePath: ContentSourceMapParsedPath /** * If `sourcePath` alone isn't enough to tell you if it's safe to contain stega strings, then you can use `sourceDocument` * for additional metadata. * It'll always have a `_type` property, which can be used to trace it to the Studio Schema that were used initially. * It also has `_id` to help you debug and look at the whole document when troubleshooting. * Finally, if the document origins in a Cross Dataset Reference you'll also have `_projectId` and `_dataset` properties to help you trace it. */ sourceDocument: ContentSourceMapDocuments_2[number] /** * If you don't colocate your Studio Schemas with your GROQ queries it might be hard to make sense of `sourcePath`, * as it operates on the original shape of a document. * In that case `resultPath` can be used, as it mirrors the path to the value in the result. * For example in a query like this: * `*[_type == "author"][0]{"slug": slug.current}` * The `resultPath` for `result.slug` would be `['slug']`, while `sourcePath` will be `['slug', 'current']`. */ resultPath: ContentSourceMapParsedPath /** * You can also use your own string validation logic to determine if it's safe. */ value: string /** * If you want to keep the default filtering behavior, but only override it for a specific path, you can use `filterDefault` to do that. * For example, here all "icon" documents in a Page Builder skips encoding: * ```ts { filter: (props) => { switch (props.sourceDocument._type) { case 'icon': return false default: return props.filterDefault(props) } } } * ``` */ filterDefault: FilterDefault }) => boolean /** @public */ declare type FilterDefault_2 = (props: { /** * The path to the value in the source document, for example if you queried for a document like this: * `*[_type == "author"][0]{"slug": slug.current}` * Then the `sourcePath` for `result.slug` would be `['slug', 'current']`. * */ sourcePath: ContentSourceMapParsedPath /** * If `sourcePath` alone isn't enough to tell you if it's safe to contain stega strings, then you can use `sourceDocument` * for additional metadata. * It'll always have a `_type` property, which can be used to trace it to the Studio Schema that were used initially. * It also has `_id` to help you debug and look at the whole document when troubleshooting. * Finally, if the document origins in a Cross Dataset Reference you'll also have `_projectId` and `_dataset` properties to help you trace it. */ sourceDocument: ContentSourceMapDocuments_2[number] /** * If you don't colocate your Studio Schemas with your GROQ queries it might be hard to make sense of `sourcePath`, * as it operates on the original shape of a document. * In that case `resultPath` can be used, as it mirrors the path to the value in the result. * For example in a query like this: * `*[_type == "author"][0]{"slug": slug.current}` * The `resultPath` for `result.slug` would be `['slug']`, while `sourcePath` will be `['slug', 'current']`. */ resultPath: ContentSourceMapParsedPath /** * You can also use your own string validation logic to determine if it's safe. */ value: string /** * If you want to keep the default filtering behavior, but only override it for a specific path, you can use `filterDefault` to do that. * For example, here all "icon" documents in a Page Builder skips encoding: * ```ts { filter: (props) => { switch (props.sourceDocument._type) { case 'icon': return false default: return props.filterDefault(props) } } } * ``` */ filterDefault: FilterDefault_2 }) => boolean /** @public */ export declare interface FilteredResponseQueryOptions extends ResponseQueryOptions { filterResponse?: true } /** @internal */ export declare type FirstDocumentIdMutationOptions = BaseMutationOptions & { returnFirst?: true returnDocuments: false } /** @internal */ export declare type FirstDocumentMutationOptions = BaseMutationOptions & { returnFirst?: true returnDocuments?: true } /** * Formats a GROQ query parse error into a human-readable string. * * @param error - The error object containing details about the parse error. * @param tag - An optional tag to include in the error message. * @returns A formatted error message string. * @public */ export declare function formatQueryParseError(error: QueryParseError, tag?: string | null): string /** @beta */ declare type GenerateAsyncInstruction<T extends Record<string, Any> = Record<string, Any>> = ( | GenerateExistingDocumentRequest | GenerateTargetDocumentRequest<T> ) & GenerateRequestBase & AgentActionAsync /** * Instruction for an existing document. * @beta */ declare interface GenerateExistingDocumentRequest { /** * @see #AgentActionSchema.forcePublishedWrite */ documentId: string targetDocument?: never } /** @beta */ export declare type GenerateInstruction<T extends Record<string, Any> = Record<string, Any>> = | GenerateSyncInstruction<T> | GenerateAsyncInstruction<T> /** @beta */ export declare type GenerateOperation = 'set' | 'append' | 'mixed' /** @beta */ declare interface GenerateRequestBase extends AgentActionRequestBase { /** schemaId as reported by sanity deploy / sanity schema store */ schemaId: string /** * Instruct the LLM how it should generate content. Be as specific and detailed as needed. * * The LLM only has access to information in the instruction, plus the target schema. * * String template with support for $variable from `instructionParams`. * */ instruction: string /** * param values for the string template, keys are the variable name, ie if the template has "$variable", one key must be "variable" * * ### Examples * * #### Constant * * ##### Shorthand * ```ts * client.agent.action.generate({ * schemaId, * documentId, * instruction: 'Give the following topic:\n $topic \n ---\nGenerate the full article.', * instructionParams: { * topic: 'Grapefruit' * }, * }) * ``` * ##### Object-form * * ```ts * client.agent.action.generate({ * schemaId, * documentId, * instruction: 'Give the following topic:\n $topic \n ---\nGenerate the full article.', * instructionParams: { * topic: { * type: 'constant', * value: 'Grapefruit' * }, * }, * }) * ``` * #### Field * ```ts * client.agent.action.generate({ * schemaId, * documentId, * instruction: 'Give the following field value:\n $pte \n ---\nGenerate keywords.', * instructionParams: { * pte: { * type: 'field', * path: ['pteField'], * }, * }, * target: {path: 'keywords' } * }) * ``` * #### Document * ```ts * client.agent.action.generate({ * schemaId, * documentId, * instruction: 'Give the following document value:\n $document \n ---\nGenerate keywords.', * instructionParams: { * document: { * type: 'document', * }, * }, * target: {path: 'keywords' } * }) * ``` * * #### GROQ * ```ts * client.agent.action.generate({ * schemaId, * documentId, * instruction: 'Give the following list of titles:\n $list \n ---\nGenerate a similar title.', * instructionParams: { * list: { * type: 'groq', * query: '* [_type==$type].title', * params: {type: 'article'} * }, * }, * target: {path: 'title' } * }) * ``` * */ instructionParams?: AgentActionParams /** * Target defines which parts of the document will be affected by the instruction. * It can be an array, so multiple parts of the document can be separately configured in detail. * * Omitting target implies that the document itself is the root. * * Notes: * - instruction can only affect fields up to `maxPathDepth` * - when multiple targets are provided, they will be coalesced into a single target sharing a common target root. * It is therefor an error to provide conflicting include/exclude across targets (ie, include title in one, and exclude it in another) * * ## Generating images * * Generate will generate images the same was as AI Assist, for images that have been configured using * [AI Assist schema options](https://github.com/sanity-io/assist/tree/main/plugin#image-generation). * * To generate images _without_ changing the schema, directly target an image asset path. * * For example, all