UNPKG

@sanity/client

Version:

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

9,979 lines 354 kB
import { FetchFunction, RequestOptions as RequestOptions$1, TimeoutErrorLike, isTimeoutError } from "get-it";
import { Observable } from "rxjs";
import { ContentSourceMapDocuments as ContentSourceMapDocuments$1, ContentSourceMapParsedPath, ContentSourceMapParsedPath as ContentSourceMapParsedPath$1, ContentSourceMapParsedPathKeyedSegment, ResolveStudioUrl, StudioBaseRoute, StudioBaseUrl, StudioUrl, StudioUrl as StudioUrl$1 } from "@sanity/client/csm";
import { EventSourceConstructor } from "eventsource";
import { ClientPerspective as ClientPerspective$1 } from "@sanity/client";
/** @public */
interface StegaConfig {
  /**
       * Enable or disable stega encoded strings in query results
       * ```ts
        {
          enabled: process.env.VERCEL_ENV !== 'production'
        }
      * ```
      * @defaultValue `false`
      */
  enabled?: boolean;
  /**
   * Where the Studio is hosted.
   * If it's embedded in the app, use the base path for example `/studio`.
   * Otherwise provide the full URL to where the Studio is hosted, for example: `https://blog.sanity.studio`.
   *
   */
  studioUrl?: StudioUrl$1 | ResolveStudioUrl;
  filter?: FilterDefault;
  /**
   * Specify a `console.log` compatible logger to see debug logs, which keys are encoded and which are not.
   */
  logger?: Logger;
  /**
   * Set to `true` to omit cross dataset reference specific data from encoded strings
   */
  omitCrossDatasetReferenceData?: boolean;
}
/** @public */
type StegaConfigRequiredKeys = Extract<keyof StegaConfig, 'enabled'>;
/** @public */
type InitializedStegaConfig = Omit<StegaConfig, StegaConfigRequiredKeys> & Required<Pick<StegaConfig, StegaConfigRequiredKeys>>;
/** @public */
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$1;
  /**
   * 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$1[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$1;
  /**
   * 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 */
type Logger = typeof console | Partial<Pick<typeof console, 'debug' | 'error' | 'groupCollapsed' | 'groupEnd' | 'log' | 'table'>>;
/**
 * 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
 * */
interface ConstantAgentActionParam {
  type: 'constant';
  value: string;
}
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 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
 * */
type FieldAgentActionParam<TParamConfig extends {
  docIdRequired: boolean;
} = {
  docIdRequired: false;
}> = {
  type: 'field';
  /**
   * Examples: 'title', ['array', \{_key: 'arrayItemKey'\}, 'field']
   */
  path: AgentActionPathSegment | AgentActionPath;
} & DocIdParam<TParamConfig>;
/**
 *
 * 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
 * */
type DocumentAgentActionParam<TParamConfig extends {
  docIdRequired: boolean;
} = {
  docIdRequired: false;
}> = {
  type: 'document';
} & DocIdParam<TParamConfig>;
/**
 * Includes a LLM-friendly version of GROQ query result in the instruction
 *
 * ```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' }
 * })
 * ```
 * @beta
 * */
interface GroqAgentActionParam {
  type: 'groq';
  query: string;
  params?: Record<string, string>;
  perspective?: ClientPerspective$1;
}
/**  @beta */
type AgentActionTypeConfig = {
  include: string[];
  exclude?: never;
} | {
  exclude: string[];
  include?: never;
};
/**  @beta */
type AgentActionPathSegment = string | {
  _key: string;
};
/**  @beta */
type AgentActionPath = AgentActionPathSegment[];
/**  @beta */
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
 */
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 */
type AgentActionParam<TParamConfig extends {
  docIdRequired: boolean;
} = {
  docIdRequired: false;
}> = string | ConstantAgentActionParam | FieldAgentActionParam<TParamConfig> | DocumentAgentActionParam<TParamConfig> | GroqAgentActionParam;
/** @beta */
type AgentActionParams<TParamConfig extends {
  docIdRequired: boolean;
} = {
  docIdRequired: false;
}> = Record<string, AgentActionParam<TParamConfig>>;
/** @beta */
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;
    }[];
  };
}
/** @beta */
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 */
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 */
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 */
type PatchOperation = 'set' | 'append' | 'mixed' | 'unset';
type AnyNonNullable = Exclude<any, null | undefined>;
/**  @beta */
interface PatchRequestBase extends AgentActionSchema {
  /**
   * 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 therefore an error to provide conflicting include/exclude across targets (ie, include title in one, and exclude it in another)
   *
   * @see AgentActionRequestBase#conditionalPaths
   */
  target: PatchTarget | PatchTarget[];
}
/**  @beta */
type PatchTarget = {
  /**
   * Determines how the target path will be patched.
   *
   * ### Operation types
   * - `'set'` – an *overwriting* operation: sets the full field value for primitive targets, and merges the provided value with existing values for objects
   * - `'append'`:
   *    – array fields: appends new items to the end of the array,
   *    - string fields: '"existing content" "new content"'
   *    - text fields: '"existing content"\\n"new content"'
   *    - number fields: existing + new
   *    - other field types not mentioned will set instead (dates, url)
   * - `'mixed'` –  sets non-array fields, and appends to array fields
   * - `'unset'` – removes whatever value is on the target path
   *
   * All operations except unset requires a `value`.
   *
   * #### Appending in the middle of arrays
   * To append to an array, use the 'append' operation, and provide an array value with one or more array items.
   *
   * `target: {path: ['array'], operation: 'append', value: [{_type: 'item' _key: 'a'}]}` will append the items in the value to the existing array.
   *
   * To insert in the middle of the array, use `target: {path: ['array', {_key: 'appendAfterKey'}], operation: 'append', value: [{_type: 'item' _key: 'a'}]}`.
   * Here, `{_type: 'item' _key: 'a'}` will be appended after the array item with key `'appendAfterKey'`
   *
   * It is optional to provide a _key for inserted array items; if one isn't provided, it will be generated.
   */
  operation: PatchOperation;
  path: AgentActionPathSegment | AgentActionPath;
} & ({
  operation: 'unset';
  value?: never;
} | {
  operation: Exclude<PatchOperation, 'unset'>;
  value: AnyNonNullable;
});
/**
 * Patches an existing document
 * @beta
 */
interface PatchExistingDocumentRequest {
  /**
   * @see #AgentActionSchema.forcePublishedWrite
   */
  documentId: string;
  targetDocument?: never;
}
/**
 * Create a new document, then patch it
 * @beta
 */
interface PatchTargetDocumentRequest<T extends Record<string, Any> = Record<string, Any>> {
  /**
   * @see #AgentActionSchema.forcePublishedWrite
   */
  targetDocument: GenerateTargetDocument<T>;
  documentId?: never;
}
/** @beta */
type PatchDocumentSync<T extends Record<string, Any> = Record<string, Any>> = (PatchExistingDocumentRequest | PatchTargetDocumentRequest<T>) & PatchRequestBase & AgentActionSync;
/** @beta */
type PatchDocumentAsync<T extends Record<string, Any> = Record<string, Any>> = (PatchExistingDocumentRequest | PatchTargetDocumentRequest<T>) & PatchRequestBase & AgentActionAsync;
/** @beta */
type PatchDocument<T extends Record<string, Any> = Record<string, Any>> = PatchDocumentSync<T> | PatchDocumentAsync<T>;
/**  @beta */
interface PromptRequestBase {
  /**
   * 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.prompt({
   *   instruction: 'Give the following topic:\n $topic \n ---\nReturns some facts about it',
   *   instructionParams: {
   *     topic: 'Grapefruit'
   *   },
   * })
   * ```
   * ##### Object-form
   *
   * ```ts
   * client.agent.action.prompt({
   *   instruction: 'Give the following topic:\n $topic \n ---\nReturns some facts about it.',
   *   instructionParams: {
   *     topic: {
   *       type: 'constant',
   *       value: 'Grapefruit'
   *     },
   *   },
   * })
   * ```
   * #### Field
   * ```ts
   * client.agent.action.prompt({
   *   instruction: 'Give the following field value:\n $pte \n ---\nGenerate keywords.',
   *   instructionParams: {
   *     pte: {
   *       type: 'field',
   *       path: ['pteField'],
   *       documentId: 'someSanityDocId'
   *     },
   *   },
   * })
   * ```
   * #### Document
   * ```ts
   * client.agent.action.prompt({
   *   json: true,
   *   instruction: 'Given the following document:$document\nCreate a JSON string[] array with keywords describing it.',
   *   instructionParams: {
   *     document: {
   *       type: 'document',
   *       documentId: 'someSanityDocId'
   *     },
   *   },
   * })
   * ```
   *
   * #### GROQ
   * ```ts
   * client.agent.action.prompt({
   *   instruction: 'Return the best title amongst these: $titles.',
   *   instructionParams: {
   *     titles: {
   *       type: 'groq',
   *       query: '* [_type==$type].title',
   *       params: {type: 'article'}
   *     },
   *   },
   * })
   * ```
   * */
  instructionParams?: AgentActionParams<{
    docIdRequired: true;
  }>;
  /**
   * Controls how much variance the instructions will run with.
   *
   * Value must be in the range [0, 1] (inclusive).
   *
   * Default: 0.3
   */
  temperature?: number;
}
/**
 * @beta
 */
interface PromptJsonResponse<T extends Record<string, Any> = Record<string, Any>> {
  /**
   *
   * When format is 'json', the response will be json according to the instruction.
   * Note: In addition to setting this to 'json',  `instruction` MUST include the word 'JSON', or 'json' for this to work.
   */
  format: 'json';
}
interface PromptTextResponse {
  /**
   * When format is 'string', the response will be a raw text response to the instruction.
   */
  format?: 'string';
}
/** @beta */
type PromptRequest<T extends Record<string, Any> = Record<string, Any>> = (PromptTextResponse | PromptJsonResponse<T>) & PromptRequestBase;
/** @beta */
interface TransformRequestBase extends AgentActionRequestBase {
  /** schemaId as reported by sanity deploy / sanity schema store */
  schemaId: string;
  /**
   * The source document the transformation will use as input.
   *
   * @see #AgentActionSchema.forcePublishedWrite
   */
  documentId: string;
  /**
   * The source document's content is first copied to the target,
   * then it is transformed according to the instruction.
   *
   * When omitted, the source document (documentId) is also the target document.
   *
   *  @see #AgentActionSchema.forcePublishedWrite
   */
  targetDocument?: TransformTargetDocument;
  /**
   * Instruct the LLM how to transform the input to th output.
   *
   * String template with support for $variable from `instructionParams`.
   *
   * Capped to 2000 characters, after variables has been injected.
   * */
  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.transform({
   *   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.transform({
   *   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.transform({
   *   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.transform({
   *   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)
   *
   * Default max depth for transform: 12
   *
   * ## Transforming images
   *
   * To transform an existing image, directly target an image asset path.
   *
   * For example, all the following will transform the image into the provided asset:
   * * `target: {path: ['image', 'asset'] }`
   * * `target: {path: 'image', include: ['asset'] }`
   *
   * Image transform can be combined with regular content targets:
   * * `target: [{path: ['image', 'asset'] }, {include: ['title', 'description']}]`
   *
   * Image transform can have per-path instructions, just like any other target paths:
   * * `target: [{path: ['image', 'asset'], instruction: 'Make the sky blue' }`
   *
   * @see AgentActionRequestBase#conditionalPaths
   */
  target?: TransformTarget | TransformTarget[];
}
/**
 * @see #AgentActionSchema.forcePublishedWrite
 *
 * @beta
 */
type TransformTargetDocument = {
  operation: 'edit';
  _id: string;
} | {
  operation: 'create';
  _id?: string;
} | {
  operation: 'createIfNotExists';
  _id: string;
} | {
  operation: 'createOrReplace';
  _id: string;
};
/**
 *
 * @see #TransformOperation
 * @beta
 */
type ImageDescriptionOperation = {
  type: 'image-description';
  /**
   * When omitted, parent image value will be inferred from the arget path.
   *
   * When specified, the `sourcePath` should be a path to an image (or image asset) field:
   * - `['image']`
   * - `['wrapper', 'mainImage']`
   * - `['heroImage', 'asset'] // the asset segment is optional, but supported`
   */
  sourcePath?: AgentActionPath;
} & ({
  /**
   * When omitted, parent image value will be inferred from the target path.
   *
   * When specified, the `sourcePath` should be a path to an image (or image asset) field:
   * - `['image']`
   * - `['wrapper', 'mainImage']`
   * - `['heroImage', 'asset'] // the asset segment is optional, but supported`
   *
   * Incompatible with `imageUrl`
   *
   */
  sourcePath?: AgentActionPath;
  imageUrl?: never;
} | {
  /**
   * When specified, the image source to be described will be fetched from the URL.
   *
   * Incompatible with `sourcePath`
   */
  imageUrl?: `https://${string}`;
  sourcePath?: never;
});
/**
 *
 * ## `set` by default
 * By default, Transform will change the value of every target field in place using a set operation.
 *
 * ## Image description
 *
 * ### Targeting image fields
 * Images can be transformed to a textual description by targeting a `string`, `text` or Portable Text field (`array` with `block`)
 * with `operation: {type: 'image-description'}`.
 *
 * Custom instructions for image description targets will be used to generate the description.
 *
 * Such targets must be a descendant field of an image object.
 *
 * For example:
 * - `target: {path: ['image', 'description'], operation: {type: 'image-description'} }`
 * - `target: {path: ['array', {_key: 'abc'}, 'alt'], operation: {type: 'image-description'} } //assuming the item in the array on the key-ed path is an image`
 * - `target: {path: ['image'], include: ['portableTextField'], operation: {type: 'image-description'}, instruction: 'Use formatting and headings to describe the image in great detail' }`
 *
 * ### Targeting non-image fields
 * If the target image description lives outside an image object, use the `sourcePath` option to specify the path to the image field.
 * `sourcePath` must be an image or image asset field.
 *
 * For example:
 * - `target: {path: ['description'], operation: operation: {type: 'image-description', sourcePath: ['image', 'asset'] }`
 * - `target: {path: ['wrapper', 'title'], operation: {type: 'image-description', sourcePath: ['array', {_key: 'abc'}, 'image'] }`
 * - `target: {path: ['wrapper'], include: ['portableTextField'], operation: {type: 'image-description', sourcePath: ['image', 'asset'] }, instruction: 'Use formatting and headings to describe the image in great detail' }`
 *
 * ### Targeting images outside the document (URL)
 * If the source image is available on a https URL outside the target document, it is possible to get a description for it using `imageUrl`.
 *
 * Example:
 * - `target: {path: ['description'], operation: operation: {type: 'image-description', imageUrL: 'https://www.sanity.io/static/images/favicons/android-icon-192x192.png?v=2' }`
 * @beta
 */
type TransformOperation = 'set' | ImageDescriptionOperation;
/**
 * @see #TransformOperation
 * @beta
 * */
interface TransformTargetInclude extends AgentActionTargetInclude {
  /**
   * Specifies a tailored instruction of this target.
   *
   * String template with support for $variable from `instructionParams`.  */
  instruction?: string;
  /**
   * By default, all children up to `target.maxPathDepth` are included.
   *
   * When `include` is specified, only segments explicitly listed will be included.
   *
   * Fields or array items not on the include list, are implicitly excluded.
   */
  include?: (AgentActionPathSegment | TransformTargetInclude)[];
  /**
   * Default: `set`
   * @see #TransformOperation
   */
  operation?: TransformOperation;
}
/**
 * @see #TransformOperation
 * @beta
 * */
interface TransformTarget extends AgentActionTarget {
  /**
   * Specifies a tailored instruction of this target.
   *
   * String template with support for $variable from `instructionParams`.
   * */
  instruction?: string;
  /**
   * By default, all children up to `target.maxPathDepth` are included.
   *
   * When `include` is specified, only segments explicitly listed will be included.
   *
   * Fields or array items not on the include list, are implicitly excluded.
   */
  include?: (AgentActionPathSegment | TransformTargetInclude)[];
  /**
   * Default: `set`
   * @see #TransformOperation
   */
  operation?: TransformOperation;
}
/** @beta */
type TransformDocumentSync<T extends Record<string, Any> = Record<string, Any>> = TransformRequestBase & AgentActionSync;
/** @beta */
type TransformDocumentAsync = TransformRequestBase & AgentActionAsync;
/** @beta */
type TransformDocument<T extends Record<string, Any> = Record<string, Any>> = TransformDocumentSync<T> | TransformDocumentAsync;
/**  @beta */
interface TranslateRequestBase extends AgentActionRequestBase {
  /** schemaId as reported by sanity deploy / sanity schema store */
  schemaId: string;
  /**
   * The source document the transformation will use as input.
   * @see #AgentActionSchema.forcePublishedWrite
   */
  documentId: string;
  /**
   * The target document will first get content copied over from the source,
   * then it is translated according to the instruction.
   *
   * When omitted, the source document (documentId) is also the target document.
   *
   * @see #AgentActionSchema.forcePublishedWrite
   */
  targetDocument?: TransformTargetDocument;
  /**
   * While optional, it is recommended
   */
  fromLanguage?: TranslateLanguage;
  toLanguage: TranslateLanguage;
  /**
   * `styleGuide` can be used to tailor how the translation should be preformed.
   *
   * String template using $variable from styleGuideParams.
   *
   * Capped to 2000 characters, after variables has been injected.
   *
   * @see #protectedPhrases
   */
  styleGuide?: string;
  /** param values for the string template, keys are the variable name, ie if the template has "$variable", one key must be "variable" */
  styleGuideParams?: AgentActionParams;
  /**
   * When the input string contains any phrase from `protectedPhrases`, the LLM will be instructed not
   * to translate them.
   *
   * It is recommended to use `protectedPhrases` instead of `styleGuide` for deny-list words and phrases,
   * since it keeps token cost low, resulting in faster responses, and limits how much information the LLM
   * has to process, since only phrases that are actually in the input string will be included in the final prompt.
   */
  protectedPhrases?: string[];
  /**
   * When specified, the `toLanguage.id` will be stored in the specified path in the target document.
   *
   * The file _can_ be hidden: true (unlike other fields in the target, which will be ignored)
   */
  languageFieldPath?: AgentActionPathSegment | AgentActionPath;
  /**
   * 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)
   *
   * @see AgentActionRequestBase#conditionalPaths
   */
  target?: TranslateTarget | TranslateTarget[];
}
/**  @beta */
interface TranslateLanguage {
  /**
   * Language code
   */
  id: string;
  /**
   * While optional, it is recommended to provide a language title
   */
  title?: string;
}
/**  @beta */
interface TranslateTargetInclude extends AgentActionTargetInclude {
  /** String template using $variable from styleGuideParams.  */
  styleGuide?: string;
  /**
   * By default, all children up to `target.maxPathDepth` are included.
   *
   * When `include` is specified, only segments explicitly listed will be included.
   *
   * Fields or array items not on the include list, are implicitly excluded.
   */
  include?: (AgentActionPathSegment | TranslateTargetInclude)[];
}
/**  @beta */
interface TranslateTarget extends AgentActionTarget {
  /** String template using $variable from styleGuideParams.  */
  styleGuide?: string;
  /**
   * By default, all children up to `target.maxPathDepth` are included.
   *
   * When `include` is specified, only segments explicitly listed will be included.
   *
   * Fields or array items not on the include list, are implicitly excluded.
   */
  include?: (AgentActionPathSegment | TranslateTargetInclude)[];
}
/** @beta */
type TranslateDocumentSync<T extends Record<string, Any> = Record<string, Any>> = TranslateRequestBase & AgentActionSync;
/** @beta */
type TranslateDocumentAsync = TranslateRequestBase & AgentActionAsync;
/** @beta */
type TranslateDocument<T extends Record<string, Any> = Record<string, Any>> = TranslateDocumentSync<T> | TranslateDocumentAsync;
/** @public */
declare class ObservableAgentsActionClient {
  #private;
  constructor(client: ObservableSanityClient, 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>): Observable<(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>): Observable<(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>): Observable<(typeof request)['async'] extends true ? {
    _id: string;
  } : IdentifiedSanityDocumentStub & DocumentShape>;
}
/** @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>;
}
/** @internal */
declare class ObservableAssetsClient {
  #private;
  constructor(client: ObservableSanityClient, 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): Observable<UploadEvent<{
    document: 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): Observable<UploadEvent<{
    document: 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): Observable<UploadEvent<{
    document: SanityAssetDocument | SanityImageAssetDocument;
  }>>;
}
/** @internal */
declare class AssetsClient {
  #private;
  constructor(client: SanityClient, httpRequest: HttpRequest);
  /**
   * Uploads a file asset to the configured dataset
   *
   * Note: when the client is configured against a Media Library
   * (`resource: {type: 'media-library', id}`), this resolves to a
   * {@link MediaLibraryAssetDocument} at runtime, not to a
   * {@link SanityAssetDocument}. The declared type cannot express that: the
   * shape depends on the client's configuration rather than on the arguments,
   * so an overload cannot discriminate it, and widening the return type into a
   * union would be a breaking change for every existing caller. Narrow the
   * result yourself (for example, check for `currentVersion`) if you upload to
   * a Media Library. Typing this honestly is deferred to the next major.
   *
   * @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
   *
   * Note: against a Media Library this resolves to a
   * {@link MediaLibraryAssetDocument} at runtime. See the `'file'` overload
   * above for why the declared type cannot say so.
   *
   * @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>;
}
/**
 * Maps an array of listen events names to their corresponding listen event type, e.g:
 * ```
 * type Test = MapListenEventNamesToListenEvents<Doc, ['welcome']>
 *    // ^? WelcomeEvent
 * ```
 *
 * @public
 */
type MapListenEventNamesToListenEvents<R extends Record<string, Any> = Record<string, Any>, Events extends (ResumableListenEventNames | ListenEventName)[] = (ResumableListenEventNames | ListenEventName)[]> = Events extends (infer E)[] ? E extends 'welcome' ? WelcomeEvent : E extends 'mutation' ? MutationEvent<R> : E extends 'reconnect' ? ReconnectEvent : E extends 'welcomeback' ? WelcomeBackEvent : E extends 'reset' ? ResetEvent : E extends 'open' ? OpenEvent : never : never;
/**
 * Maps a ListenOptions object and returns the Listen events opted for, e.g:
 * ```
 * type Test = ListenEventFromOptions<Doc, {events: ['welcome', 'mutation']}>
 *    // ^? WelcomeEvent | MutationEvent<Doc>
 * ```
 *
 * @public
 */
type ListenEventFromOptions<R extends Record<string, Any> = Record<string, Any>, Opts extends ListenOptions | ResumableListenOptions | undefined = undefined> = Opts extends ListenOptions | ResumableListenOptions ? Opts['events'] extends (ResumableListenEventNames | ListenEventName)[] ? MapListenEventNamesToListenEvents<R, Opts['events']> : ListenEvent<R> : MutationEvent<R>;
/**
 * Set up a listener that will be notified when mutations occur on documents matching the provided query/filter.
 *
 * @param query - GROQ-filter to listen to changes for
 * @param params - Optional query parameters
 * @param options - Optional listener options
 * @public
 */
declare function _listen<R extends Record<string, Any> = Record<string, Any>>(this: SanityClient | ObservableSanityClient, query: string, params?: ListenParams): Observable<MutationEvent<R>>;
/**
 * Set up a listener that will be notified when mutations occur on documents matching the provided query/filter.
 *
 * @param query - GROQ-filter to listen to changes for
 * @param params - Optional query parameters
 * @param options - Optional listener options
 * @public
 */
declare function _listen<R extends Record<string, Any> = Record<string, Any>, Opts extends ListenOptions | ResumableListenOptions = ListenOptions | ResumableListenOptions>(this: SanityClient | ObservableSanityClient, query: string, params?: ListenParams, options?: Opts): Observable<ListenEventFromOptions<R, Opts>>;
/** @internal */
declare const possibleRequestOptions: readonly ['headers', 'signal', 'tag', 'timeout', 'token'];
/**
 * Request options honored by the collaboration comments methods.
 *
 * @alpha
 */
type CollaborationCommentsRequestOptions = Pick<RequestOptions, (typeof possibleRequestOptions)[number]>;
/**
 * Options for collaboration comments write methods.
 *
 * @alpha
 */
type CollaborationCommentsWriteOptions = CollaborationCommentsRequestOptions & {
  /** Transaction ID to associate the write with */
  transactionId?: string;
};
/**
 * Listener options for `collaboration.comments.listen`.
 *
 * `includeAllVersions` is left out: comments are stored as `sanity.comment`
 * documents with no drafts or versions, so it would never make a difference.
 *
 * @alpha
 */
type CollaborationCommentsListenOptions = Omit<ListenOptions, 'includeAllVersions'> | Omit<ResumableListenOptions, 'includeAllVersions'>;
/**
 * Status of a comment thread. Replies always share the status of their parent comment.
 *
 * @alpha
 */
type CollaborationCommentStatus = 'open' | 'resolved';
/**
 * Emoji short names that can be used as comment reactions.
 *
 * @alpha
 */
type CollaborationCommentReactionShortName = ':-1:' | ':+1:' | ':eyes:' | ':heart:' | ':heavy_plus_sign:' | ':rocket:';
/**
 * A single Portable Text block, as used in comment messages and content snapshots.
 *
 * @alpha
 */
interface CollaborationCommentPortableTextBlock {
  _type: string;
  children: Array<{
    _type: string;
    [key: string]: Any;
  }>;
  [key: string]: Any;
}
/**
 * Comment message, as an array of Portable Text blocks.
 *
 * @alpha
 */
type CollaborationCommentMessage = CollaborationCommentPortableTextBlock[];
/**
 * The text an inline comment was anchored to, resolved by the API when the
 * comment was created.
 *
 * Holds one entry per Portable Text block the selection spans, keyed by the
 * block it came from. `text` is the plain text of that block with the selected
 * part wrapped in the marker characters `\uF000` (start) and `\uF001` (end).
 *
 * @alpha
 */
interface CollaborationCommentSelection {
  type: 'text';
  value: {
    _key: string;
    text: string;
  }[];
}
/**
 * A comment document, as stored by the Comments API.
 *
 * @alpha
 */
interface CollaborationCommentDocument extends SanityDocument {
  _type: 'sanity.comment';
  _system?: {
    /** ID of the user that created the comment */
    createdBy?: string;
  };
  /** ID shared by a top-level comment and all of its replies */
  threadId?: string;
  /** Set on replies, pointing to the comment being replied to */
  parentCommentId?: string;
  message: CollaborationCommentMessage;
  reactions: {
    _key: string;
    shortName: CollaborationCommentReactionShortName;
    userId: string;
    addedAt: string;
  }[];
  /** Arbitrary metadata stored with the comment by the creating application */
  context?: Record<string, unknown>;
  target: {
    /** Global document reference (`resourceType:resourceId:documentId`, using the published document ID) */
    document: {
      _ref: `${string}:${string}:${string}`;
      _type: 'globalDocumentReference';
      _weak: true;
    };
    documentType: string;
    /** The exact document ID the comment was created against, e.g. a draft or version ID */
    sourceDocumentId: string;
    documentRevisionId?: string;
    /**
     * Set for field and inline comments. `field` is the `path` the comment was
     * created with; `selection` is set for inline comments only.
     */
    path?: {
      field: string;
      selection?: CollaborationCommentSelection;
    };
  };
  /**
   * Copy of the commented content, as it looked when the comment was created.
   * Set for inline comments only, and holds just the selected fragment of each
   * Portable Text block the selection spans.
   */
  contentSnapshot?: CollaborationCommentPortableTextBlock[];
  status: CollaborationCommentStatus;
  /** Set when the message has been updated after creation */
  lastEditedAt?: string;
}
/**
 * Inline text selection within a Portable Text field.
 * Each endpoint pairs the `_key` of a Portable Text block with a character
 * offset into that block's plain text.
 *
 * @alpha
 */
interface CollaborationCommentRange {
  start: {
    _key: string;
    offset: number;
  };
  end: {
    _key: string;
    offset: number;
  };
}
/**
 * Portable Text covering a comment `range`. Callers can send just the blocks
 * from the `range` start `_key` through end `_key`, or the full field.
 *
 * @alpha
 */
type CollaborationCommentFieldValue = Array<{
  _type: string;
  _key: string;
  [key: string]: Any;
}>;
/**
 * Target for a top-level comment. Inline selections require both `path` and
 * `range`; field-level comments may set `path` alone.
 *
 * The created comment stores this in a different shape: `path` becomes
 * `target.path.field`, and `range` is resolved against the document into
 * `target.path.selection` and `contentSnapshot` rather than being stored.
 *
 * An optional `fieldValue` is Portable Text covering the `range`. When set,
 * the `range` is resolved from those blocks instead of from the live document.
 *
 * @alpha
 */
type CollaborationCommentTarget = {
  documentId: string;
  documentType: string;
  documentRevisionId?: string;
} & ({
  /** Path to the field containing the inline comment selection */
  path: string;
  range: CollaborationCommentRange;
  /**
   * Portable Text covering the `range`. When set, the `range` is resolved
   * from these blocks instead of from the live document.
   */
  fieldValue?: CollaborationCommentFieldValue;
} | {
  /** Path to the commented field */
  path?: string;
  range?: never;
  fieldValue?: never;
});
/**
 * Comment to create with `collaboration.comments.create`.
 *
 * A top-level comment requires `target`; a reply requires `parentCommentId` (never both).
 * Replies inherit `target`, `status`, and `threadId` from the parent comment.
 *
 * ### Examples
 *
 * #### Top-level comment
 * ```ts
 * // `message` is an array of Portable Text blocks
 * await client.collaboration.comments.create({
 *   message,
 *   target: {documentId: 'doc-1', documentType: 'article'},
 * })
 * ```
 *
 * #### Inline comment
 * ```ts
 * await client.collaboration.comments.create({
 *   message,
 *   target: {
 *     documentId: 'doc-1',
 *     documentType: 'article',
 *     path: 'body',
 *     range: {start: {_key: 'block-1', offset: 0}, end: {_key: 'block-1', offset: 5}},
 *   },
 * })
 * ```
 *
 * #### Reply
 * ```ts
 * await client.collaboration.comments.create({
 *   message,
 *   parentCommentId: 'comment-1',
 * })
 * ```
 *
 * @alpha
 */
type CollaborationCommentCreate = {
  /** Provide to control the ID of the created comment document */
  _id?: string;
  message: CollaborationCommentMessage;
  context?: Record<string, unknown>;
} & ({
  target: CollaborationCommentTarget;
  threadId?: string;
  parentCommentId?: never;
} | {
  parentCommentId: string;
  target?: never;
  threadId?: never;
});
/**
 * Fields that can be updated on an existing comment.
 *
 * A `range` re-anchors the comment within the field it already targets.
 * Pass `null` to remove the selection and leave a field-level comment.
 * An optional `fieldValue` is Portable Text covering that `range`; when set,
 * the `range` is resolved from those blocks instead of from the live document.
 * `fieldValue` cannot be sent alone or together with `range: null`.
 *
 * @alpha
 */
type CollaborationCommentUpdate = {
  /** Replaces the current message */
  message?: CollaborationCommentMessage;
  /** Cascades to the comment's replies */
  status?: CollaborationCommentStatus;
} & ({
  range: CollaborationCommentRange;
  /**
   * Portable Text covering the `range`. When set, the `range` is resolved
   * from these blocks instead of from the live document.
   */
  fieldValue?: CollaborationCommentFieldValue;
} | {
  range: null;
  fieldValue?: never;
} | {
  range?: undefined;
  fieldValue?: never;
});
/**
 * Comments on the configured organization resource.
 *
 * Requires `collaboration.organizationId`, plus either `resource` or `projectId` and `dataset`.
 *
 * @alpha
 */
declare class ObservableCollaborationCommentsClient {
  #private;
  constructor(client: ObservableSanityClient, httpRequest: HttpRequest);
  /**
   * Create a comment or reply on the configured resource.
   *
   * A top-level comment requires `target`; a reply requires `parentCommentId` (never both).
   * Replies inherit `target`, `status`, and `threadId` from the parent comment.
   *
   * @param body - Comment to create
   * @param options - Optional request options
   * @returns The created comment
   */
  create(body: CollaborationCommentCreate, options?: CollaborationCommentsWriteOptions): Observable<CollaborationCommentDocument>;
  /**
   * Update an existing comment.
   *
   * Updating `status` cascades to the comment's replies.
   *
   * @param id - Comment document ID
   * @param body - Fields to update
   * @param options - Optional request options
   * @returns The updated comment
   */
  update(id: string, body: CollaborationCommentUpdate, options?: CollaborationCommentsWriteOptions): Observable<CollaborationCommentDocument>;
  /**
   * Delete a comment and its replies.
   *
   * @param id - Comment document ID
   * @param options - Optional request options
   * @returns Mutation result, where `documentIds` covers the comment and every deleted reply
   */
  delete(id: string, options?: CollaborationCommentsWriteOptions): Observable<MultipleMutationResult>;
  /**
   * Add the current user's reaction to a comment.
   *
   * @param id - Comment document ID
   * @param shortName - Emoji short name, for example `:+1:`
   * @param options - Optional request options
   * @returns The comment, with the reaction applied
   */
  addReaction(id: string, shortName: CollaborationCommentReactionShortName, options?: CollaborationCommentsWriteOptions): Observable<CollaborationCommentDocument>;
  /**
   * Remove the current user's reaction from a comment.
   *
   * @param id - Comment document ID
   * @param shortName - Emoji short name, for example `:+1:`
   * @param options - Optional request options
   * @returns The comment, with the reaction removed
   */
  removeReaction(id: string, shortName: CollaborationCommentReactionShortName, options?: CollaborationCommentsWriteOptions): Observable<CollaborationCommentDocument>;
  /**
   * Build the global document reference used by `target.document._ref`, for use in
   * queries and listeners.
   *
   * The reference is built from the configured `resource` and the published ID of
   * the given document ID, since comment references always use published IDs.
   *
   * @example
   * ```ts
   * client.collaboration.comments.listen(
   *   '*[_type == "sanity.comment" && target.document._ref == $ref]',
   *   {ref: client.collaboration.comments.getTargetDocumentRef('doc-1')},
   * )
   * ```
   *
   * @param documentId - Document ID, in published, draft or version form
   * @returns Global document reference, of the form `resourceType:resourceId:documentId`
   */
  getTargetDocumentRef(documentId: string): CollaborationCommentDocument['target']['document']['_ref'];
  /**
   * Fetch comments on the configured resource.
   *
   * Takes the same `query` and `params` as `client.fetch`, and switches from a
   * GET to a POST for queries too large for the request URL in the same way,
   * but queries the comments endpoint, which accepts none of the query options
   * `client.fetch` does (`perspective`, `useCdn`, `filterResponse`,
   * `resultSourceMap`, stega).
   *
   * The query runs against the organization store, which is not scoped to
   * comments, so filter on `_type == "sanity.comment"`.
   *
   * @param query - GROQ-query to perform
   * @param params - Optional query parameters
   * @param options - Optional request options
   */
  fetch<R = unknown>(query: string, params?: QueryParams, options?: CollaborationCommentsRequestOptions): Observable<R>;
  /**
   * Listen for changes to comments on the configured resource.
   *
   * Mirrors `client.listen(query, params)`, and emits mutation events.
   *
   * @param query - GROQ-filter to listen to changes for
   * @param params - Optional query parameters
   */
  listen(query: string, params?: QueryParams): Observable<MutationEvent<CollaborationCommentDocument>>;
  /**
   * Listen for changes to comments on the configured resource.
   *
   * Mirrors `client.listen(query, params, options)`.
   *
   * @param query - GROQ-filter to listen to changes for
   * @param params - Optional query parameters
   * @param options - The same listener options `client.listen` takes, forwarded
   *   to the organization store's listener
   */
  listen<Opts extends CollaborationCommentsListenOptions>(query: string, params: QueryParams | undefined, options: Opts): Observable<ListenEventFromOptions<CollaborationCommentDocument, Opts>>;
}
/**
 * Comments on the configured organization resource.
 *
 * Requires `collaboration.organizationId`, plus either `resource` or `projectId` and `dataset`.
 *
 * @alpha
 */
declare class CollaborationCommentsClient {
  #private;
  constructor(client: SanityClient, httpRequest: HttpRequest);
  /**
   * Create a comment or reply on the configured resource.
   *
   * A top-level comment requires `target`; a reply requires `parentCommentId` (never both).
   * Replies inherit `target`, `status`, and `threadId` from the parent comment.
   *
   * @param body - Comment to create
   * @param options - Optional request options
   * @returns The created comment
   */
  create(body: CollaborationCommentCreate, options?: CollaborationCommentsWriteOptions): Promise<CollaborationCommentDocument>;
  /**
   * Update an existing comment.
   *
   * Updating `status` cascades to the comment's replies.
   *
   * @param id - Comment document ID
   * @param body - Fields to update
   * @param options - Optional request options
   * @returns The updated comment
   */
  update(id: string, body: CollaborationCommentUpdate, options?: CollaborationCommentsWriteOptions): Promise<CollaborationCommentDocument>;
  /**
   * Delete a comment and its replies.
   *
   * @param id - Comment document ID
   * @param options - Optional request options
   * @returns Mutation result, where `documentIds` covers the comment and every deleted reply
   */
  delete(id: string, options?: CollaborationCommentsWriteOptions): Promise<MultipleMutationResult>;
  /**
   * Add the current user's reaction to a comment.
   *
   * @param id - Comment document ID
   * @param shortName - Emoji short name, for example `:+1:`
   * @param options - Optional request options
   * @returns The comment, with the reaction applied
   */
  addReaction(id: string, shortName: CollaborationCommentReactionShortName, options?: CollaborationCommentsWriteOptions): Promise<CollaborationCommentDocument>;
  /**
   * Remove the current user's reaction from a comment.
   *
   * @param id - Comment document ID
   * @param shortName - Emoji short name, for example `:+1:`
   * @param options - Optional request options
   * @returns The comment, with the reaction removed
   */
  removeReaction(id: string, shortName: CollaborationCommentReactionShortName, options?: CollaborationCommentsWriteOptions): Promise<CollaborationCommentDocument>;
  /**
   * Build the global document reference used by `target.document._ref`, for use in
   * queries and listeners.
   *
   * The reference is built from the configured `resource` and the published ID of
   * the given document ID, since comment references always use published IDs.
   *
   * @example
   * ```ts
   * const comments = await client.collaboration.comments.fetch(
   *   '*[_type == "sanity.comment" && target.document._ref == $ref]',
   *   {ref: client.collaboration.comments.getTargetDocumentRef('doc-1')},
   * )
   * ```
   *
   * @param documentId - Document ID, in published, draft or version form
   * @returns Global document reference, of the form `resourceType:resourceId:documentId`
   */
  getTargetDocumentRef(documentId: string): CollaborationCommentDocument['target']['document']['_ref'];
  /**
   * Fetch comments on the configured resource.
   *
   * Takes the same `query` and `params` as `client.fetch`, and switches from a
   * GET to a POST for queries too large for the request URL in the same way,
   * but queries the comments endpoint, which accepts none of the query options
   * `client.fetch` does (`perspective`, `useCdn`, `filterResponse`,
   * `resultSourceMap`, stega).
   *
   * The query runs against the organization store, which is not scoped to
   * comments, so filter on `_type == "sanity.comment"`.
   *
   * @param query - GROQ-query to perform
   * @param params - Optional query parameters
   * @param options - Optional request options
   */
  fetch<R = unknown>(query: string, params?: QueryParams, options?: CollaborationCommentsRequestOptions): Promise<R>;
  /**
   * Listen for changes to comments on the configured resource.
   *
   * Mirrors `client.listen(query, params)`, and emits mutation events.
   *
   * @param query - GROQ-filter to listen to changes for
   * @param params - Optional query parameters
   */
  listen(query: string, params?: QueryParams): Observable<MutationEvent<CollaborationCommentDocument>>;
  /**
   * Listen for changes to comments on the configured resource.
   *
   * Mirrors `client.listen(query, params, options)`.
   *
   * @param query - GROQ-filter to listen to changes for
   * @param params - Optional query parameters
   * @param options - The same listener options `client.listen` takes, forwarded
   *   to the organization store's listener
   */
  listen<Opts extends CollaborationCommentsListenOptions>(query: string, params: QueryParams | undefined, options: Opts): Observable<ListenEventFromOptions<CollaborationCommentDocument, Opts>>;
}
/**
 * This file was auto-generated by openapi-typescript.
 * Do not make direct changes to the file.
 */
interface paths {
  '/{apiVersion}/context/knowledge-bases': {
    parameters: {
      query?: never;
      header?: never;
      path?: never;
      cookie?: never;
    };
    /**
     * List knowledge bases
     * @description Returns the organization's knowledge bases visible to the caller, cursor-paginated.
     */
    get: operations['listKnowledgeBases'];
    put?: never;
    /**
     * Create a knowledge base
     * @description Creates a knowledge base bound to a Sanity dataset, where its content documents will be stored.
     */
    post: operations['createKnowledgeBase'];
    delete?: never;
    options?: never;
    head?: never;
    patch?: never;
    trace?: never;
  };
  '/{apiVersion}/context/knowledge-bases/{knowledgeBaseId}': {
    parameters: {
      query?: never;
      header?: never;
      path?: never;
      cookie?: never;
    };
    /**
     * Get a knowledge base
     * @description Returns the knowledge base object: metadata and state. Resolves from the id alone, the public id (`kb...`) or the uuid; access is decided against the knowledge base's own organization, and an id the caller cannot read returns 404. For the built content, use the outline or entries endpoints.
     */
    get: operations['getKnowledgeBase'];
    put?: never;
    post?: never;
    /**
     * Delete a knowledge base
     * @description Removes the knowledge base and everything it owns: sources, imports, and revisions. Content documents in the bound dataset are deleted best-effort, and stored source files are reclaimed by a separate cleanup.
     */
    delete: operations['deleteKnowledgeBase'];
    options?: never;
    head?: never;
    /**
     * Update a knowledge base
     * @description Edits the name and description, or the recurring refresh controls (`refreshEnabled`, `refreshFrequency`). Refresh fields return 422 for knowledge bases with no web or dataset source. Disabling pauses the schedule; manual refresh still works.
     */
    patch: operations['updateKnowledgeBase'];
    trace?: never;
  };
  '/{apiVersion}/context/knowledge-bases/{knowledgeBaseId}/build': {
    parameters: {
      query?: never;
      header?: never;
      path?: never;
      cookie?: never;
    };
    get?: never;
    put?: never;
    /**
     * Trigger a knowledge base build
     * @description Queues a build over the current corpus and returns a job id right away. If a build is already running, you get that job instead of a second one.
     */
    post: operations['buildKnowledgeBase'];
    delete?: never;
    options?: never;
    head?: never;
    patch?: never;
    trace?: never;
  };
  '/{apiVersion}/context/knowledge-bases/{knowledgeBaseId}/build/cancel': {
    parameters: {
      query?: never;
      header?: never;
      path?: never;
      cookie?: never;
    };
    get?: never;
    put?: never;
    /**
     * Cancel an in-progress build
     * @description Cancels the running build and resets the knowledge base so it can be rebuilt.
     */
    post: operations['cancelKnowledgeBaseBuild'];
    delete?: never;
    options?: never;
    head?: never;
    patch?: never;
    trace?: never;
  };
  '/{apiVersion}/context/knowledge-bases/{knowledgeBaseId}/entries/{entryPath}/rebuild': {
    parameters: {
      query?: never;
      header?: never;
      path?: never;
      cookie?: never;
    };
    get?: never;
    put?: never;
    /**
     * Rebuild an entry from its sources
     * @description Queues a re-write of the entry at this path from its cited sources and the active instructions, and returns a job id right away. The response also names the other entries citing any of the same sources: a source-tied rule affects every page citing that source, so those may change too.
     */
    post: operations['rebuildEntry'];
    delete?: never;
    options?: never;
    head?: never;
    patch?: never;
    trace?: never;
  };
  '/{apiVersion}/context/knowledge-bases/{knowledgeBaseId}/imports': {
    parameters: {
      query?: never;
      header?: never;
      path?: never;
      cookie?: never;
    };
    /**
     * List imports
     * @description Everything added to this knowledge base, one row per import: a file upload, web crawl, dataset bind, or inline text. Cursor-paginated. The sources each import produced live under `/sources`.
     */
    get: operations['listImports'];
    put?: never;
    /**
     * Create an import (text, crawl, or dataset)
     * @description Adds content, discriminated on `type`: `text` for inline content, `crawl` for a website, `dataset` for a GROQ-filtered Sanity dataset. Each variant queues processing and returns a job id to poll. For files, use `POST .../imports/uploads` instead. Re-adding an existing crawl url returns 409 `webSourceRootConflict`; exceeding the crawl root limit returns 409 `webSourceRootLimitExceeded`. Supports the `Idempotency-Key` header.
     */
    post: operations['createImport'];
    delete?: never;
    options?: never;
    head?: never;
    patch?: never;
    trace?: never;
  };
  '/{apiVersion}/context/knowledge-bases/{knowledgeBaseId}/imports/uploads': {
    parameters: {
      query?: never;
      header?: never;
      path?: never;
      cookie?: never;
    };
    get?: never;
    put?: never;
    /**
     * Start a file-upload import
     * @description Creates a file-upload import and returns a single-use signed upload URL. PUT the file bytes to it, then call `POST .../imports/uploads/{importId}/complete` to start ingestion. The bytes never pass through this API. Supports the `Idempotency-Key` header.
     */
    post: operations['startUpload'];
    delete?: never;
    options?: never;
    head?: never;
    patch?: never;
    trace?: never;
  };
  '/{apiVersion}/context/knowledge-bases/{knowledgeBaseId}/imports/uploads/{importId}/complete': {
    parameters: {
      query?: never;
      header?: never;
      path?: never;
      cookie?: never;
    };
    get?: never;
    put?: never;
    /**
     * Complete a file-upload import
     * @description Call after the file bytes are uploaded to the signed URL. Starts processing and returns a job id to poll.
     */
    post: operations['completeUpload'];
    delete?: never;
    options?: never;
    head?: never;
    patch?: never;
    trace?: never;
  };
  '/{apiVersion}/context/knowledge-bases/{knowledgeBaseId}/imports/{importId}': {
    parameters: {
      query?: never;
      header?: never;
      path?: never;
      cookie?: never;
    };
    /**
     * Get a single import
     * @description Returns one import with its kind and processing status.
     */
    get: operations['getImport'];
    put?: never;
    post?: never;
    /**
     * Delete an import
     * @description Removes the import and every source it produced, and cancels its ingest if one is still running. Use it to discard something added by mistake.
     */
    delete: operations['deleteImport'];
    options?: never;
    head?: never;
    patch?: never;
    trace?: never;
  };
  '/{apiVersion}/context/knowledge-bases/{knowledgeBaseId}/imports/{importId}/download': {
    parameters: {
      query?: never;
      header?: never;
      path?: never;
      cookie?: never;
    };
    /**
     * Get a download URL for an import
     * @description Mints a short-lived signed URL serving the import's original bytes as an attachment. Use it before `expiresAt`; the bytes never pass through this API. Only file and text imports carry original bytes; crawls and dataset binds return 409 `importInvalidState`.
     */
    get: operations['downloadImport'];
    put?: never;
    post?: never;
    delete?: never;
    options?: never;
    head?: never;
    patch?: never;
    trace?: never;
  };
  '/{apiVersion}/context/knowledge-bases/{knowledgeBaseId}/instructions': {
    parameters: {
      query?: never;
      header?: never;
      path?: never;
      cookie?: never;
    };
    get?: never;
    put?: never;
    /**
     * Author a human instruction
     * @description Creates a standing rule that every future build honors. Tie it to one or more sources with `scopeSourceIds`, or leave it null to apply knowledge-base-wide. Pass `rebuildPaths` to immediately rebuild those entries under the new rule; the response carries the rebuild job id, or null when the rebuild could not start (the rule is saved either way). Pass `verified` after a completed synchronous contradiction check to skip the background one; if the requested rebuild fails to start, the background check runs anyway so the contradicting pages get filed as issues.
     */
    post: operations['createInstruction'];
    delete?: never;
    options?: never;
    head?: never;
    patch?: never;
    trace?: never;
  };
  '/{apiVersion}/context/knowledge-bases/{knowledgeBaseId}/instructions/{instructionId}': {
    parameters: {
      query?: never;
      header?: never;
      path?: never;
      cookie?: never;
    };
    get?: never;
    put?: never;
    post?: never;
    /**
     * Delete an instruction
     * @description Deletes the rule. Builds stop honoring it from the next run.
     */
    delete: operations['deleteInstruction'];
    options?: never;
    head?: never;
    /**
     * Edit an instruction
     * @description Edits the statement or scope. The change applies from the next build. Any edit re-affirms the rule: an archived rule returns to active, re-anchored to the sources' current content.
     */
    patch: operations['updateInstruction'];
    trace?: never;
  };
  '/{apiVersion}/context/knowledge-bases/{knowledgeBaseId}/issues/apply': {
    parameters: {
      query?: never;
      header?: never;
      path?: never;
      cookie?: never;
    };
    get?: never;
    put?: never;
    /**
     * Apply accepted issues to a Context
     * @description Queues a job that applies accepted issues, rewrites the affected entries, and commits a new revision. Returns a job id. Issue ids that no longer exist are skipped.
     */
    post: operations['applyIssues'];
    delete?: never;
    options?: never;
    head?: never;
    patch?: never;
    trace?: never;
  };
  '/{apiVersion}/context/knowledge-bases/{knowledgeBaseId}/issues/{issueId}/dismiss': {
    parameters: {
      query?: never;
      header?: never;
      path?: never;
      cookie?: never;
    };
    get?: never;
    put?: never;
    /**
     * Dismiss an issue
     * @description Marks the issue rejected. Idempotent: dismissing an issue that already left the queue returns it as-is. 422 `issueDocumentInvalid` when the document was hand-edited into an unverifiable shape; 409 `issueTransitionConflict` on a concurrent edit, safe to retry.
     */
    post: operations['dismissIssue'];
    delete?: never;
    options?: never;
    head?: never;
    patch?: never;
    trace?: never;
  };
  '/{apiVersion}/context/knowledge-bases/{knowledgeBaseId}/issues/{issueId}/reopen': {
    parameters: {
      query?: never;
      header?: never;
      path?: never;
      cookie?: never;
    };
    get?: never;
    put?: never;
    /**
     * Reopen an accepted conflict
     * @description Returns an accepted conflict to triage, clearing its resolution and deleting the instruction it minted. Idempotent for issues that are not accepted conflicts.
     */
    post: operations['reopenIssue'];
    delete?: never;
    options?: never;
    head?: never;
    patch?: never;
    trace?: never;
  };
  '/{apiVersion}/context/knowledge-bases/{knowledgeBaseId}/issues/{issueId}/resolve': {
    parameters: {
      query?: never;
      header?: never;
      path?: never;
      cookie?: never;
    };
    get?: never;
    put?: never;
    /**
     * Resolve a conflict issue
     * @description Settles a conflict with one of two choices: `keep_existing` or `accept_new` (rewrites the entry; the returned `jobId` tracks it). Only conflict issues are resolvable, and a dismissed issue must be reopened first. The decision becomes a standing instruction for every future build; `resolvedBy` records who decided.
     */
    post: operations['resolveIssue'];
    delete?: never;
    options?: never;
    head?: never;
    patch?: never;
    trace?: never;
  };
  '/{apiVersion}/context/knowledge-bases/{knowledgeBaseId}/jobs/{jobId}': {
    parameters: {
      query?: never;
      header?: never;
      path?: never;
      cookie?: never;
    };
    /**
     * Get a job by id
     * @description Returns the status of a job, such as a build or an import. Job ids come from the endpoint that queued the work.
     */
    get: operations['getJob'];
    put?: never;
    post?: never;
    delete?: never;
    options?: never;
    head?: never;
    patch?: never;
    trace?: never;
  };
  '/{apiVersion}/context/knowledge-bases/{knowledgeBaseId}/refresh': {
    parameters: {
      query?: never;
      header?: never;
      path?: never;
      cookie?: never;
    };
    get?: never;
    put?: never;
    /**
     * Trigger an incremental refresh
     * @description Queues a refresh: recrawls each web source, diffs the corpus against the last build, and files change issues. Returns a job id, with `started: false` when a refresh was already in flight. Supports the `Idempotency-Key` header.
     */
    post: operations['refreshKnowledgeBase'];
    delete?: never;
    options?: never;
    head?: never;
    patch?: never;
    trace?: never;
  };
  '/{apiVersion}/context/knowledge-bases/{knowledgeBaseId}/sources': {
    parameters: {
      query?: never;
      header?: never;
      path?: never;
      cookie?: never;
    };
    /**
     * List sources
     * @description The distilled units builds cite: the pages, files, and documents your imports expanded into. Read-only; add content via `/imports`. Cursor-paginated, filter by `status`.
     */
    get: operations['listSources'];
    put?: never;
    post?: never;
    delete?: never;
    options?: never;
    head?: never;
    patch?: never;
    trace?: never;
  };
  '/{apiVersion}/context/knowledge-bases/{knowledgeBaseId}/sources/{sourceId}': {
    parameters: {
      query?: never;
      header?: never;
      path?: never;
      cookie?: never;
    };
    /**
     * Get a single source
     * @description Returns one source with its metadata and processing status.
     */
    get: operations['getSource'];
    put?: never;
    post?: never;
    /**
     * Delete a source
     * @description Removes the source immediately. Entries are not modified here — citations to it are cleaned up by the next build or check for changes, where entries left without sources become removal proposals. Human-edited entries are never modified.
     */
    delete: operations['deleteSource'];
    options?: never;
    head?: never;
    patch?: never;
    trace?: never;
  };
  '/{apiVersion}/context/knowledge-bases/{knowledgeBaseId}/sources/{sourceId}/content': {
    parameters: {
      query?: never;
      header?: never;
      path?: never;
      cookie?: never;
    };
    /**
     * Read a source's distilled content
     * @description The distilled markdown builds cite, the same text the pipeline itself reads. Use it to verify an issue's claims against the sources its `citedSourceIds` name. Optional `startLine` and `endLine` (1-indexed, inclusive) fetch just a span. JSON by default; `?format=markdown` returns the raw text. 409 `sourceNotDistilled` until distillation has produced content.
     */
    get: operations['getSourceContent'];
    put?: never;
    post?: never;
    delete?: never;
    options?: never;
    head?: never;
    patch?: never;
    trace?: never;
  };
  '/{apiVersion}/context/organizations/{organizationId}/conversations/{threadId}': {
    parameters: {
      query?: never;
      header?: never;
      path?: never;
      cookie?: never;
    };
    get?: never;
    /**
     * Record a conversation
     * @description Upserts the conversation telemetry for one thread. `threadId` identifies the conversation within your organization — reuse means the same conversation. Messages replace the stored transcript wholesale; `metadata` and model fields only overwrite when present. Last write per thread wins — retries are safe.
     */
    put: operations['saveConversation'];
    post?: never;
    delete?: never;
    options?: never;
    head?: never;
    /**
     * Record a classification verdict
     * @description Records the classification your own model produced for one thread: exactly one of `coreMetrics` (a verdict — the server stamps `classifiedAt` and clears any recorded failure) or `classificationError` (why classification failed; an earlier verdict stays untouched). No revision guard — like the ingest upsert the writer is an automated classifier, so last write wins and a re-classification simply overwrites.
     */
    patch: operations['classifyConversation'];
    trace?: never;
  };
}
interface components {
  schemas: {
    /** @description A `sanity.context.conversation` document, one agent conversation transcript with its classification, stored in the organization store. Not returned by any endpoint raw; published so GROQ reads can be typed. Write through the conversation ingest and classify endpoints, never with a raw client. */
    ConversationDoc: {
      _id: string;
      _rev: string;
      /** Format: date-time */
      _createdAt: string;
      /** Format: date-time */
      _updatedAt: string;
      /** @enum {string} */
      _type: 'sanity.context.conversation';
      /** @enum {number} */
      schemaVersion: 1;
      organizationId: string;
      threadId: string;
      /** @description ConversationMetadata */
      metadata: {
        [key: string]: string | string[];
      } | null;
      /** Format: date-time */
      startedAt: string;
      /** Format: date-time */
      messagesUpdatedAt: string;
      messages: {
        /** @enum {string} */
        role: 'user' | 'assistant' | 'system' | 'tool';
        /** @default null */
        content: string | null;
        /** @default null */
        toolName: string | null;
        /**
         * @default null
         * @enum {string|null}
         */
        toolType: 'call' | 'result' | null;
      }[];
      modelProvider: string | null;
      modelId: string | null;
      /** @description ConversationTokenUsage */
      tokenUsage: {
        inputTokens?: number;
        outputTokens?: number;
        totalTokens?: number;
      } | null;
      /** @description ConversationCoreMetrics */
      coreMetrics: {
        successScore?: number;
        /** @enum {string} */
        sentiment?: 'positive' | 'neutral' | 'negative';
        contentGaps?: string[];
      } | null;
      /** Format: date-time */
      classifiedAt: string | null;
      classificationError: string | null;
    };
    /** @description A `sanity.context.entry` document, one outline node stored in the bound dataset. Not returned by any endpoint; published so GROQ reads against the dataset can be typed. The entries endpoints serve the validated wire view. */
    EntryDoc: {
      _id: string;
      _rev: string;
      /** Format: date-time */
      _createdAt: string;
      /** Format: date-time */
      _updatedAt: string;
      knowledgeBaseId: string;
      /** @enum {string} */
      _type: 'sanity.context.entry';
      schemaVersion: number;
      revisionId: string;
      path: string;
      title: string;
      tldr?: {
        scope: string;
        excludes: string;
        neighbors?: string[];
        /** @enum {string} */
        centrality: 'core' | 'standard' | 'peripheral';
      };
      body?: string;
      topicHeadings?: string[];
      citations?: {
        sourceId: string;
        supports?: string;
        spans?: {
          sourceLineStart: number;
          sourceLineEnd: number;
          quote: string;
        }[];
        claim?: {
          exact: string;
          prefix?: string;
          suffix?: string;
        };
        /** @enum {string} */
        groundingState?: 'drifted';
        _key: string;
        /** @enum {string} */
        _type: 'sanity.context.citation';
        filename: string;
        mime?: string;
        excerpt?: string;
      }[];
      /** @enum {string} */
      status: 'virtual' | 'outlined' | 'filled' | 'stale' | 'generation_failed';
      generatedAt: string;
    };
    /** @description A `sanity.context.instruction` document, a standing decision steering every build, stored in the bound dataset. Not returned by any endpoint; published so GROQ reads against the dataset can be typed. Write through the instructions endpoints, never with a raw client. */
    InstructionDoc: {
      _id: string;
      _rev: string;
      /** Format: date-time */
      _createdAt: string;
      /** Format: date-time */
      _updatedAt: string;
      knowledgeBaseId: string;
      /** @enum {string} */
      _type: 'sanity.context.instruction';
      /** @enum {number} */
      schemaVersion: 1;
      statement: string;
      scopeSources: {
        _key: string;
        sourceId: string;
        contentHash: string;
      }[] | null;
      /** @enum {string} */
      status: 'active' | 'archived';
      archivedAt: string | null;
      archivedReason: string | null;
      /** @enum {string} */
      origin: 'conflict';
      sourceIssueId: string;
    } | {
      _id: string;
      _rev: string;
      /** Format: date-time */
      _createdAt: string;
      /** Format: date-time */
      _updatedAt: string;
      knowledgeBaseId: string;
      /** @enum {string} */
      _type: 'sanity.context.instruction';
      /** @enum {number} */
      schemaVersion: 1;
      statement: string;
      scopeSources: {
        _key: string;
        sourceId: string;
        contentHash: string;
      }[] | null;
      /** @enum {string} */
      status: 'active' | 'archived';
      archivedAt: string | null;
      archivedReason: string | null;
      /** @enum {string} */
      origin: 'human';
      /** @enum {string|null} */
      sourceIssueId: null;
    };
    /** @description A `sanity.context.issue` document, a build finding awaiting triage, stored in the bound dataset. Not returned by any endpoint; published so GROQ reads and trigger filters can be typed. Status transitions flow through the issues endpoints, which own the state machine. One invariant the schema cannot express: only a `conflict` issue ever carries a non-null `resolution`. */
    IssueDoc: {
      _id: string;
      _rev: string;
      /** Format: date-time */
      _createdAt: string;
      /** Format: date-time */
      _updatedAt: string;
      knowledgeBaseId: string;
      /** @enum {string} */
      _type: 'sanity.context.issue';
      /** @enum {number} */
      schemaVersion: 1;
      /** @description IssueContent */
      content: {
        /** @enum {string} */
        kind: 'conflict' | 'gap' | 'update_required' | 'add_entry' | 'remove_entry' | 'split_entry' | 'merge_entry';
        /** @enum {string} */
        severity: 'critical' | 'suggestion';
        scopePath: string;
        issue: string;
        suggestedFix: string;
        citedSourceIds?: string[];
        claimKey?: string;
        involvedScopes?: string[];
        currentClaim?: string;
        alternativeClaim?: string;
        /** @enum {string} */
        currentAuthority?: 'primary' | 'secondary' | 'community';
        /** @enum {string} */
        alternativeAuthority?: 'primary' | 'secondary' | 'community';
        /** @enum {string} */
        suggestedResolution?: 'keep_existing' | 'accept_new';
      };
      fingerprint: string;
      revisionId: string | null;
      /** @enum {string} */
      status: 'open';
      /** @enum {string|null} */
      resolution: null;
      /** @enum {string|null} */
      resolvedAt: null;
      /** @enum {string|null} */
      resolvedBy: null;
    } | {
      _id: string;
      _rev: string;
      /** Format: date-time */
      _createdAt: string;
      /** Format: date-time */
      _updatedAt: string;
      knowledgeBaseId: string;
      /** @enum {string} */
      _type: 'sanity.context.issue';
      /** @enum {number} */
      schemaVersion: 1;
      /** @description IssueContent */
      content: {
        /** @enum {string} */
        kind: 'conflict' | 'gap' | 'update_required' | 'add_entry' | 'remove_entry' | 'split_entry' | 'merge_entry';
        /** @enum {string} */
        severity: 'critical' | 'suggestion';
        scopePath: string;
        issue: string;
        suggestedFix: string;
        citedSourceIds?: string[];
        claimKey?: string;
        involvedScopes?: string[];
        currentClaim?: string;
        alternativeClaim?: string;
        /** @enum {string} */
        currentAuthority?: 'primary' | 'secondary' | 'community';
        /** @enum {string} */
        alternativeAuthority?: 'primary' | 'secondary' | 'community';
        /** @enum {string} */
        suggestedResolution?: 'keep_existing' | 'accept_new';
      };
      fingerprint: string;
      revisionId: string | null;
      /** @enum {string} */
      status: 'accepted';
      /** Format: date-time */
      resolvedAt: string;
      resolvedBy: {
        id: string;
        /** @enum {string} */
        kind: 'user' | 'robot';
      } | null;
      /** @enum {string|null} */
      resolution: 'keep_existing' | 'accept_new' | null;
    } | {
      _id: string;
      _rev: string;
      /** Format: date-time */
      _createdAt: string;
      /** Format: date-time */
      _updatedAt: string;
      knowledgeBaseId: string;
      /** @enum {string} */
      _type: 'sanity.context.issue';
      /** @enum {number} */
      schemaVersion: 1;
      /** @description IssueContent */
      content: {
        /** @enum {string} */
        kind: 'conflict' | 'gap' | 'update_required' | 'add_entry' | 'remove_entry' | 'split_entry' | 'merge_entry';
        /** @enum {string} */
        severity: 'critical' | 'suggestion';
        scopePath: string;
        issue: string;
        suggestedFix: string;
        citedSourceIds?: string[];
        claimKey?: string;
        involvedScopes?: string[];
        currentClaim?: string;
        alternativeClaim?: string;
        /** @enum {string} */
        currentAuthority?: 'primary' | 'secondary' | 'community';
        /** @enum {string} */
        alternativeAuthority?: 'primary' | 'secondary' | 'community';
        /** @enum {string} */
        suggestedResolution?: 'keep_existing' | 'accept_new';
      };
      fingerprint: string;
      revisionId: string | null;
      /** @enum {string} */
      status: 'rejected';
      /** Format: date-time */
      resolvedAt: string;
      resolvedBy: {
        id: string;
        /** @enum {string} */
        kind: 'user' | 'robot';
      } | null;
      /** @enum {string|null} */
      resolution: null;
    };
    /** @description A `sanity.context.mcp` document, an org-owned MCP endpoint configuration stored in the organization store. Not returned by any endpoint raw; published so GROQ reads and trigger filters can be typed. Write through the mcp endpoints, never with a raw client. The mcp endpoints serve the validated wire view. */
    McpDoc: {
      _id: string;
      _rev: string;
      /** Format: date-time */
      _createdAt: string;
      /** Format: date-time */
      _updatedAt: string;
      /** @enum {string} */
      _type: 'sanity.context.mcp';
      /** @enum {number} */
      schemaVersion: 1;
      organizationId: string;
      publicId: string;
      title: string;
      name: string;
      sources: ({
        /** @enum {string} */
        type: 'knowledge-base';
        id: string;
      } | {
        /** @enum {string} */
        type: 'dataset';
        id: string;
      })[];
      instructions: string | null;
      groqFilter: string | null;
    };
  };
  responses: never;
  parameters: never;
  requestBodies: never;
  headers: never;
  pathItems: never;
}
interface operations {
  listKnowledgeBases: {
    parameters: {
      query: {
        cursor?: string;
        limit?: number;
        organizationId: string;
      };
      header?: never;
      path: {
        apiVersion: string;
      };
      cookie?: never;
    };
    requestBody?: never;
    responses: {
      /** @description Default Response */
      200: {
        headers: {
          [name: string]: unknown;
        };
        content: {
          'application/json': {
            data: {
              /** Format: uuid */
              id: string;
              publicId: string;
              organizationId: string;
              title: string;
              description: string;
              /** @enum {string} */
              state: 'created' | 'building' | 'ready' | 'review' | 'stale' | 'paused';
              activeJobId: string | null;
              isBuilding: boolean;
              buildStageState: {
                jobId: string;
                stages: {
                  /** @enum {string} */
                  id: 'tldr' | 'map' | 'triage' | 'plan' | 'organize' | 'arrange' | 'write' | 'review' | 'polish';
                  /** @enum {string} */
                  status: 'pending' | 'running' | 'done' | 'failed';
                  units?: {
                    /** @enum {string} */
                    unit: 'sources' | 'groups' | 'entries' | 'rounds';
                    done: number;
                    total?: number;
                  };
                }[];
              } | null;
              /** Format: date-time */
              lastCheckedAt: string | null;
              /** Format: date-time */
              lastChangedAt: string | null;
              hasPendingChanges: boolean;
              pendingChanges: {
                added: number;
                changed: number;
                removed: number;
              } | null;
              pipelineOutdated: boolean;
              rebuildRecommended: {
                reason: string;
                /** Format: date-time */
                at: string;
              } | null;
              hasWebSource: boolean;
              hasDatasetSource: boolean;
              sourceUsage: {
                used: number;
                limit: number;
              } | null;
              refreshEnabled: boolean;
              /** @enum {string} */
              refreshFrequency: 'weekly' | 'monthly';
              /** Format: date-time */
              refreshNextRunAt: string | null;
              refreshInFlight: boolean;
              openIssueCount: number;
              instructionCount: number;
              /** Format: date-time */
              createdAt: string;
              /** Format: date-time */
              updatedAt: string;
            }[];
            nextCursor: string | null;
          };
        };
      };
    };
  };
  createKnowledgeBase: {
    parameters: {
      query?: never;
      header?: never;
      path: {
        apiVersion: string;
      };
      cookie?: never;
    };
    requestBody: {
      content: {
        'application/json': {
          organizationId: string;
          title: string;
          description: string;
        };
      };
    };
    responses: {
      /** @description KnowledgeBase */
      201: {
        headers: {
          [name: string]: unknown;
        };
        content: {
          'application/json': {
            /** Format: uuid */
            id: string;
            publicId: string;
            organizationId: string;
            title: string;
            description: string;
            /** @enum {string} */
            state: 'created' | 'building' | 'ready' | 'review' | 'stale' | 'paused';
            activeJobId: string | null;
            isBuilding: boolean;
            buildStageState: {
              jobId: string;
              stages: {
                /** @enum {string} */
                id: 'tldr' | 'map' | 'triage' | 'plan' | 'organize' | 'arrange' | 'write' | 'review' | 'polish';
                /** @enum {string} */
                status: 'pending' | 'running' | 'done' | 'failed';
                units?: {
                  /** @enum {string} */
                  unit: 'sources' | 'groups' | 'entries' | 'rounds';
                  done: number;
                  total?: number;
                };
              }[];
            } | null;
            /** Format: date-time */
            lastCheckedAt: string | null;
            /** Format: date-time */
            lastChangedAt: string | null;
            hasPendingChanges: boolean;
            pendingChanges: {
              added: number;
              changed: number;
              removed: number;
            } | null;
            pipelineOutdated: boolean;
            rebuildRecommended: {
              reason: string;
              /** Format: date-time */
              at: string;
            } | null;
            hasWebSource: boolean;
            hasDatasetSource: boolean;
            sourceUsage: {
              used: number;
              limit: number;
            } | null;
            refreshEnabled: boolean;
            /** @enum {string} */
            refreshFrequency: 'weekly' | 'monthly';
            /** Format: date-time */
            refreshNextRunAt: string | null;
            refreshInFlight: boolean;
            openIssueCount: number;
            instructionCount: number;
            /** Format: date-time */
            createdAt: string;
            /** Format: date-time */
            updatedAt: string;
          };
        };
      };
    };
  };
  getKnowledgeBase: {
    parameters: {
      query?: never;
      header?: never;
      path: {
        knowledgeBaseId: string;
      };
      cookie?: never;
    };
    requestBody?: never;
    responses: {
      /** @description KnowledgeBase */
      200: {
        headers: {
          [name: string]: unknown;
        };
        content: {
          'application/json': {
            /** Format: uuid */
            id: string;
            publicId: string;
            organizationId: string;
            title: string;
            description: string;
            /** @enum {string} */
            state: 'created' | 'building' | 'ready' | 'review' | 'stale' | 'paused';
            activeJobId: string | null;
            isBuilding: boolean;
            buildStageState: {
              jobId: string;
              stages: {
                /** @enum {string} */
                id: 'tldr' | 'map' | 'triage' | 'plan' | 'organize' | 'arrange' | 'write' | 'review' | 'polish';
                /** @enum {string} */
                status: 'pending' | 'running' | 'done' | 'failed';
                units?: {
                  /** @enum {string} */
                  unit: 'sources' | 'groups' | 'entries' | 'rounds';
                  done: number;
                  total?: number;
                };
              }[];
            } | null;
            /** Format: date-time */
            lastCheckedAt: string | null;
            /** Format: date-time */
            lastChangedAt: string | null;
            hasPendingChanges: boolean;
            pendingChanges: {
              added: number;
              changed: number;
              removed: number;
            } | null;
            pipelineOutdated: boolean;
            rebuildRecommended: {
              reason: string;
              /** Format: date-time */
              at: string;
            } | null;
            hasWebSource: boolean;
            hasDatasetSource: boolean;
            sourceUsage: {
              used: number;
              limit: number;
            } | null;
            refreshEnabled: boolean;
            /** @enum {string} */
            refreshFrequency: 'weekly' | 'monthly';
            /** Format: date-time */
            refreshNextRunAt: string | null;
            refreshInFlight: boolean;
            openIssueCount: number;
            instructionCount: number;
            /** Format: date-time */
            createdAt: string;
            /** Format: date-time */
            updatedAt: string;
          };
        };
      };
    };
  };
  deleteKnowledgeBase: {
    parameters: {
      query?: never;
      header?: never;
      path: {
        knowledgeBaseId: string;
      };
      cookie?: never;
    };
    requestBody?: never;
    responses: {
      /** @description Default Response */
      204: {
        headers: {
          [name: string]: unknown;
        };
        content: {
          'application/json': null;
        };
      };
    };
  };
  updateKnowledgeBase: {
    parameters: {
      query?: never;
      header?: never;
      path: {
        knowledgeBaseId: string;
      };
      cookie?: never;
    };
    requestBody: {
      content: {
        'application/json': {
          title?: string;
          description?: string;
          refreshEnabled?: boolean;
          /** @enum {string} */
          refreshFrequency?: 'weekly' | 'monthly';
        };
      };
    };
    responses: {
      /** @description KnowledgeBase */
      200: {
        headers: {
          [name: string]: unknown;
        };
        content: {
          'application/json': {
            /** Format: uuid */
            id: string;
            publicId: string;
            organizationId: string;
            title: string;
            description: string;
            /** @enum {string} */
            state: 'created' | 'building' | 'ready' | 'review' | 'stale' | 'paused';
            activeJobId: string | null;
            isBuilding: boolean;
            buildStageState: {
              jobId: string;
              stages: {
                /** @enum {string} */
                id: 'tldr' | 'map' | 'triage' | 'plan' | 'organize' | 'arrange' | 'write' | 'review' | 'polish';
                /** @enum {string} */
                status: 'pending' | 'running' | 'done' | 'failed';
                units?: {
                  /** @enum {string} */
                  unit: 'sources' | 'groups' | 'entries' | 'rounds';
                  done: number;
                  total?: number;
                };
              }[];
            } | null;
            /** Format: date-time */
            lastCheckedAt: string | null;
            /** Format: date-time */
            lastChangedAt: string | null;
            hasPendingChanges: boolean;
            pendingChanges: {
              added: number;
              changed: number;
              removed: number;
            } | null;
            pipelineOutdated: boolean;
            rebuildRecommended: {
              reason: string;
              /** Format: date-time */
              at: string;
            } | null;
            hasWebSource: boolean;
            hasDatasetSource: boolean;
            sourceUsage: {
              used: number;
              limit: number;
            } | null;
            refreshEnabled: boolean;
            /** @enum {string} */
            refreshFrequency: 'weekly' | 'monthly';
            /** Format: date-time */
            refreshNextRunAt: string | null;
            refreshInFlight: boolean;
            openIssueCount: number;
            instructionCount: number;
            /** Format: date-time */
            createdAt: string;
            /** Format: date-time */
            updatedAt: string;
          };
        };
      };
    };
  };
  buildKnowledgeBase: {
    parameters: {
      query?: never;
      header?: never;
      path: {
        knowledgeBaseId: string;
      };
      cookie?: never;
    };
    requestBody?: never;
    responses: {
      /** @description JobAccepted */
      202: {
        headers: {
          [name: string]: unknown;
        };
        content: {
          'application/json': {
            jobId: string;
          };
        };
      };
    };
  };
  cancelKnowledgeBaseBuild: {
    parameters: {
      query?: never;
      header?: never;
      path: {
        knowledgeBaseId: string;
      };
      cookie?: never;
    };
    requestBody?: never;
    responses: {
      /** @description Default Response */
      200: {
        headers: {
          [name: string]: unknown;
        };
        content: {
          'application/json': {
            cancelled: boolean;
          };
        };
      };
    };
  };
  rebuildEntry: {
    parameters: {
      query?: never;
      header?: never;
      path: {
        knowledgeBaseId: string;
        entryPath: string;
      };
      cookie?: never;
    };
    requestBody?: never;
    responses: {
      /** @description RebuildEntryResponse */
      202: {
        headers: {
          [name: string]: unknown;
        };
        content: {
          'application/json': {
            jobId: string;
            affectedEntries: {
              id: string;
              path: string;
              title: string;
            }[];
          };
        };
      };
    };
  };
  listImports: {
    parameters: {
      query?: {
        cursor?: string;
        limit?: number;
      };
      header?: never;
      path: {
        knowledgeBaseId: string;
      };
      cookie?: never;
    };
    requestBody?: never;
    responses: {
      /** @description Default Response */
      200: {
        headers: {
          [name: string]: unknown;
        };
        content: {
          'application/json': {
            data: {
              /** Format: uuid */
              id: string;
              /** Format: uuid */
              knowledgeBaseId: string;
              name: string | null;
              sizeBytes: number | null;
              /** @enum {string} */
              status: 'uploading' | 'processing' | 'complete' | 'failed';
              /** @enum {string} */
              sourceKind: 'web' | 'file' | 'dataset';
              /** Format: date-time */
              lastCheckedAt: string | null;
              sourceCount: number;
              totalDistillableCount: number;
              distilledCount: number;
              unsupportedCount: number;
              statusDetail: string | null;
              error: string | null;
              /** @description CrawlOptions */
              crawlOptions: {
                includePaths?: string[];
                excludePaths?: string[];
                maxDepth?: number;
                sitemapOnly?: boolean;
                ignoreQueryParameters?: boolean;
                pageLimit?: number;
              } | null;
              /** @description DatasetSourceBinding */
              datasetSource: {
                sanityProjectId: string;
                sanityDatasetId: string;
                query: string;
              } | null;
              /** @description Actor */
              createdBy: {
                id: string | null;
                displayName: string | null;
              } | null;
              /** Format: date-time */
              createdAt: string;
              /** Format: date-time */
              completedAt: string | null;
            }[];
            nextCursor: string | null;
          };
        };
      };
    };
  };
  createImport: {
    parameters: {
      query?: never;
      header?: never;
      path: {
        knowledgeBaseId: string;
      };
      cookie?: never;
    };
    /** @description CreateImportInput */
    requestBody: {
      content: {
        'application/json': {
          /** @enum {string} */
          type: 'text';
          title: string;
          content: string;
          /**
           * @default text/markdown
           * @enum {string}
           */
          contentType?: 'text/markdown' | 'text/plain';
        } | {
          /** Format: uri */
          url: string;
          /** @description CrawlOptions */
          options?: {
            includePaths?: string[];
            excludePaths?: string[];
            maxDepth?: number;
            sitemapOnly?: boolean;
            ignoreQueryParameters?: boolean;
            pageLimit?: number;
          };
          /** @enum {string} */
          type: 'crawl';
        } | {
          sanityProjectId: string;
          sanityDatasetId: string;
          query: string;
          /** @enum {string} */
          type: 'dataset';
        };
      };
    };
    responses: {
      /** @description JobAccepted */
      202: {
        headers: {
          [name: string]: unknown;
        };
        content: {
          'application/json': {
            jobId: string;
          };
        };
      };
    };
  };
  startUpload: {
    parameters: {
      query?: never;
      header?: never;
      path: {
        knowledgeBaseId: string;
      };
      cookie?: never;
    };
    requestBody: {
      content: {
        'application/json': {
          filename: string;
          contentType?: string;
        };
      };
    };
    responses: {
      /** @description Default Response */
      201: {
        headers: {
          [name: string]: unknown;
        };
        content: {
          'application/json': {
            /** Format: uuid */
            importId: string;
            /** Format: uri */
            uploadUrl: string;
          };
        };
      };
    };
  };
  completeUpload: {
    parameters: {
      query?: never;
      header?: never;
      path: {
        knowledgeBaseId: string;
        importId: string;
      };
      cookie?: never;
    };
    requestBody?: never;
    responses: {
      /** @description JobAccepted */
      202: {
        headers: {
          [name: string]: unknown;
        };
        content: {
          'application/json': {
            jobId: string;
          };
        };
      };
    };
  };
  getImport: {
    parameters: {
      query?: never;
      header?: never;
      path: {
        knowledgeBaseId: string;
        importId: string;
      };
      cookie?: never;
    };
    requestBody?: never;
    responses: {
      /** @description Import */
      200: {
        headers: {
          [name: string]: unknown;
        };
        content: {
          'application/json': {
            /** Format: uuid */
            id: string;
            /** Format: uuid */
            knowledgeBaseId: string;
            name: string | null;
            sizeBytes: number | null;
            /** @enum {string} */
            status: 'uploading' | 'processing' | 'complete' | 'failed';
            /** @enum {string} */
            sourceKind: 'web' | 'file' | 'dataset';
            /** Format: date-time */
            lastCheckedAt: string | null;
            sourceCount: number;
            totalDistillableCount: number;
            distilledCount: number;
            unsupportedCount: number;
            statusDetail: string | null;
            error: string | null;
            /** @description CrawlOptions */
            crawlOptions: {
              includePaths?: string[];
              excludePaths?: string[];
              maxDepth?: number;
              sitemapOnly?: boolean;
              ignoreQueryParameters?: boolean;
              pageLimit?: number;
            } | null;
            /** @description DatasetSourceBinding */
            datasetSource: {
              sanityProjectId: string;
              sanityDatasetId: string;
              query: string;
            } | null;
            /** @description Actor */
            createdBy: {
              id: string | null;
              displayName: string | null;
            } | null;
            /** Format: date-time */
            createdAt: string;
            /** Format: date-time */
            completedAt: string | null;
          };
        };
      };
    };
  };
  deleteImport: {
    parameters: {
      query?: never;
      header?: never;
      path: {
        knowledgeBaseId: string;
        importId: string;
      };
      cookie?: never;
    };
    requestBody?: never;
    responses: {
      /** @description Default Response */
      204: {
        headers: {
          [name: string]: unknown;
        };
        content: {
          'application/json': null;
        };
      };
    };
  };
  downloadImport: {
    parameters: {
      query?: never;
      header?: never;
      path: {
        knowledgeBaseId: string;
        importId: string;
      };
      cookie?: never;
    };
    requestBody?: never;
    responses: {
      /** @description Default Response */
      200: {
        headers: {
          [name: string]: unknown;
        };
        content: {
          'application/json': {
            /** Format: uri */
            url: string;
            /** Format: date-time */
            expiresAt: string;
          };
        };
      };
    };
  };
  createInstruction: {
    parameters: {
      query?: never;
      header?: never;
      path: {
        knowledgeBaseId: string;
      };
      cookie?: never;
    };
    /** @description CreateInstructionInput */
    requestBody: {
      content: {
        'application/json': {
          statement: string;
          scopeSourceIds?: string[] | null;
          rebuildPaths?: string[];
          verified?: boolean;
        };
      };
    };
    responses: {
      /** @description CreateInstructionResponse */
      201: {
        headers: {
          [name: string]: unknown;
        };
        content: {
          'application/json': {
            /** @description Instruction */
            instruction: {
              id: string;
              knowledgeBaseId: string;
              /** @enum {string} */
              origin: 'conflict' | 'human';
              /** @enum {string} */
              status: 'active' | 'archived';
              statement: string;
              scopeSourceIds: string[] | null;
              /** Format: date-time */
              archivedAt: string | null;
              archivedReason: string | null;
              sourceIssueId: string | null;
              /** @description Actor */
              createdBy: {
                id: string | null;
                displayName: string | null;
              } | null;
              /** @description Actor */
              updatedBy: {
                id: string | null;
                displayName: string | null;
              } | null;
              /** Format: date-time */
              createdAt: string;
              /** Format: date-time */
              updatedAt: string | null;
            };
            rebuildJobId: string | null;
          };
        };
      };
    };
  };
  deleteInstruction: {
    parameters: {
      query?: never;
      header?: never;
      path: {
        knowledgeBaseId: string;
        instructionId: string;
      };
      cookie?: never;
    };
    requestBody?: never;
    responses: {
      /** @description Default Response */
      204: {
        headers: {
          [name: string]: unknown;
        };
        content: {
          'application/json': null;
        };
      };
    };
  };
  updateInstruction: {
    parameters: {
      query?: never;
      header?: never;
      path: {
        knowledgeBaseId: string;
        instructionId: string;
      };
      cookie?: never;
    };
    /** @description UpdateInstructionInput */
    requestBody: {
      content: {
        'application/json': {
          statement?: string;
          scopeSourceIds?: string[] | null;
        };
      };
    };
    responses: {
      /** @description Instruction */
      200: {
        headers: {
          [name: string]: unknown;
        };
        content: {
          'application/json': {
            id: string;
            knowledgeBaseId: string;
            /** @enum {string} */
            origin: 'conflict' | 'human';
            /** @enum {string} */
            status: 'active' | 'archived';
            statement: string;
            scopeSourceIds: string[] | null;
            /** Format: date-time */
            archivedAt: string | null;
            archivedReason: string | null;
            sourceIssueId: string | null;
            /** @description Actor */
            createdBy: {
              id: string | null;
              displayName: string | null;
            } | null;
            /** @description Actor */
            updatedBy: {
              id: string | null;
              displayName: string | null;
            } | null;
            /** Format: date-time */
            createdAt: string;
            /** Format: date-time */
            updatedAt: string | null;
          };
        };
      };
    };
  };
  applyIssues: {
    parameters: {
      query?: never;
      header?: never;
      path: {
        knowledgeBaseId: string;
      };
      cookie?: never;
    };
    requestBody: {
      content: {
        'application/json': {
          issueIds: string[];
        };
      };
    };
    responses: {
      /** @description JobAccepted */
      202: {
        headers: {
          [name: string]: unknown;
        };
        content: {
          'application/json': {
            jobId: string;
          };
        };
      };
    };
  };
  dismissIssue: {
    parameters: {
      query?: never;
      header?: never;
      path: {
        knowledgeBaseId: string;
        issueId: string;
      };
      cookie?: never;
    };
    requestBody?: never;
    responses: {
      /** @description Issue */
      200: {
        headers: {
          [name: string]: unknown;
        };
        content: {
          'application/json': {
            id: string;
            knowledgeBaseId: string;
            /** @description IssueContent */
            content: {
              /** @enum {string} */
              kind: 'conflict' | 'gap' | 'update_required' | 'add_entry' | 'remove_entry' | 'split_entry' | 'merge_entry';
              /** @enum {string} */
              severity: 'critical' | 'suggestion';
              scopePath: string;
              issue: string;
              suggestedFix: string;
              citedSourceIds?: string[];
              claimKey?: string;
              involvedScopes?: string[];
              currentClaim?: string;
              alternativeClaim?: string;
              /** @enum {string} */
              currentAuthority?: 'primary' | 'secondary' | 'community';
              /** @enum {string} */
              alternativeAuthority?: 'primary' | 'secondary' | 'community';
              /** @enum {string} */
              suggestedResolution?: 'keep_existing' | 'accept_new';
            };
            /** @enum {string} */
            status: 'open' | 'accepted' | 'rejected';
            /** @enum {string|null} */
            resolution: 'keep_existing' | 'accept_new' | null;
            /** @description IssueResolvedBy */
            resolvedBy: {
              id: string;
              /** @enum {string} */
              kind: 'user' | 'robot';
            } | null;
            /** Format: date-time */
            createdAt: string;
            /** Format: date-time */
            resolvedAt: string | null;
          };
        };
      };
    };
  };
  reopenIssue: {
    parameters: {
      query?: never;
      header?: never;
      path: {
        knowledgeBaseId: string;
        issueId: string;
      };
      cookie?: never;
    };
    requestBody?: never;
    responses: {
      /** @description Issue */
      200: {
        headers: {
          [name: string]: unknown;
        };
        content: {
          'application/json': {
            id: string;
            knowledgeBaseId: string;
            /** @description IssueContent */
            content: {
              /** @enum {string} */
              kind: 'conflict' | 'gap' | 'update_required' | 'add_entry' | 'remove_entry' | 'split_entry' | 'merge_entry';
              /** @enum {string} */
              severity: 'critical' | 'suggestion';
              scopePath: string;
              issue: string;
              suggestedFix: string;
              citedSourceIds?: string[];
              claimKey?: string;
              involvedScopes?: string[];
              currentClaim?: string;
              alternativeClaim?: string;
              /** @enum {string} */
              currentAuthority?: 'primary' | 'secondary' | 'community';
              /** @enum {string} */
              alternativeAuthority?: 'primary' | 'secondary' | 'community';
              /** @enum {string} */
              suggestedResolution?: 'keep_existing' | 'accept_new';
            };
            /** @enum {string} */
            status: 'open' | 'accepted' | 'rejected';
            /** @enum {string|null} */
            resolution: 'keep_existing' | 'accept_new' | null;
            /** @description IssueResolvedBy */
            resolvedBy: {
              id: string;
              /** @enum {string} */
              kind: 'user' | 'robot';
            } | null;
            /** Format: date-time */
            createdAt: string;
            /** Format: date-time */
            resolvedAt: string | null;
          };
        };
      };
    };
  };
  resolveIssue: {
    parameters: {
      query?: never;
      header?: never;
      path: {
        knowledgeBaseId: string;
        issueId: string;
      };
      cookie?: never;
    };
    requestBody: {
      content: {
        'application/json': {
          /** @enum {string} */
          resolution: 'keep_existing' | 'accept_new';
        };
      };
    };
    responses: {
      /** @description ResolveIssueResponse */
      200: {
        headers: {
          [name: string]: unknown;
        };
        content: {
          'application/json': {
            /** @description Issue */
            issue: {
              id: string;
              knowledgeBaseId: string;
              /** @description IssueContent */
              content: {
                /** @enum {string} */
                kind: 'conflict' | 'gap' | 'update_required' | 'add_entry' | 'remove_entry' | 'split_entry' | 'merge_entry';
                /** @enum {string} */
                severity: 'critical' | 'suggestion';
                scopePath: string;
                issue: string;
                suggestedFix: string;
                citedSourceIds?: string[];
                claimKey?: string;
                involvedScopes?: string[];
                currentClaim?: string;
                alternativeClaim?: string;
                /** @enum {string} */
                currentAuthority?: 'primary' | 'secondary' | 'community';
                /** @enum {string} */
                alternativeAuthority?: 'primary' | 'secondary' | 'community';
                /** @enum {string} */
                suggestedResolution?: 'keep_existing' | 'accept_new';
              };
              /** @enum {string} */
              status: 'open' | 'accepted' | 'rejected';
              /** @enum {string|null} */
              resolution: 'keep_existing' | 'accept_new' | null;
              /** @description IssueResolvedBy */
              resolvedBy: {
                id: string;
                /** @enum {string} */
                kind: 'user' | 'robot';
              } | null;
              /** Format: date-time */
              createdAt: string;
              /** Format: date-time */
              resolvedAt: string | null;
            };
            jobId: string | null;
          };
        };
      };
    };
  };
  getJob: {
    parameters: {
      query?: never;
      header?: never;
      path: {
        knowledgeBaseId: string;
        jobId: string;
      };
      cookie?: never;
    };
    requestBody?: never;
    responses: {
      /** @description Job */
      200: {
        headers: {
          [name: string]: unknown;
        };
        content: {
          'application/json': {
            id: string;
            /** @enum {string} */
            status: 'pending' | 'queued' | 'running' | 'succeeded' | 'failed' | 'cancelled';
            /** Format: date-time */
            startedAt: string | null;
            /** Format: date-time */
            completedAt: string | null;
            result?: unknown;
            error?: string | null;
          };
        };
      };
    };
  };
  refreshKnowledgeBase: {
    parameters: {
      query?: never;
      header?: never;
      path: {
        knowledgeBaseId: string;
      };
      cookie?: never;
    };
    requestBody?: never;
    responses: {
      /** @description RefreshAccepted */
      202: {
        headers: {
          [name: string]: unknown;
        };
        content: {
          'application/json': {
            jobId: string;
            started: boolean;
          };
        };
      };
    };
  };
  listSources: {
    parameters: {
      query?: {
        cursor?: string;
        limit?: number;
        status?: 'pending' | 'processing' | 'ready' | 'failed' | 'skipped';
        importId?: string;
        ids?: string;
      };
      header?: never;
      path: {
        knowledgeBaseId: string;
      };
      cookie?: never;
    };
    requestBody?: never;
    responses: {
      /** @description Default Response */
      200: {
        headers: {
          [name: string]: unknown;
        };
        content: {
          'application/json': {
            data: {
              /** Format: uuid */
              id: string;
              /** Format: uuid */
              knowledgeBaseId: string;
              filename: string;
              /** @enum {string} */
              kind: 'web' | 'file' | 'dataset';
              sizeBytes: number;
              /** @enum {string} */
              status: 'pending' | 'processing' | 'ready' | 'failed' | 'skipped';
              tldr: string | null;
              topics: string[] | null;
              canonicalUrl: string | null;
              /** Format: date-time */
              fetchedAt: string | null;
              /** Format: date-time */
              distilledAt: string | null;
              /** Format: date-time */
              createdAt: string;
            }[];
            nextCursor: string | null;
          };
        };
      };
    };
  };
  getSource: {
    parameters: {
      query?: never;
      header?: never;
      path: {
        knowledgeBaseId: string;
        sourceId: string;
      };
      cookie?: never;
    };
    requestBody?: never;
    responses: {
      /** @description Source */
      200: {
        headers: {
          [name: string]: unknown;
        };
        content: {
          'application/json': {
            /** Format: uuid */
            id: string;
            /** Format: uuid */
            knowledgeBaseId: string;
            filename: string;
            /** @enum {string} */
            kind: 'web' | 'file' | 'dataset';
            sizeBytes: number;
            /** @enum {string} */
            status: 'pending' | 'processing' | 'ready' | 'failed' | 'skipped';
            tldr: string | null;
            topics: string[] | null;
            canonicalUrl: string | null;
            /** Format: date-time */
            fetchedAt: string | null;
            /** Format: date-time */
            distilledAt: string | null;
            /** Format: date-time */
            createdAt: string;
          };
        };
      };
    };
  };
  deleteSource: {
    parameters: {
      query?: never;
      header?: never;
      path: {
        knowledgeBaseId: string;
        sourceId: string;
      };
      cookie?: never;
    };
    requestBody?: never;
    responses: {
      /** @description Default Response */
      204: {
        headers: {
          [name: string]: unknown;
        };
        content: {
          'application/json': null;
        };
      };
    };
  };
  getSourceContent: {
    parameters: {
      query?: {
        /** @description Output representation. `json` (default) returns the structured resource; `markdown` / `plain` return the rendered, LLM-ready text. */
        format?: 'json' | 'markdown' | 'plain';
        startLine?: number;
        endLine?: number;
      };
      header?: never;
      path: {
        knowledgeBaseId: string;
        sourceId: string;
      };
      cookie?: never;
    };
    requestBody?: never;
    responses: {
      /** @description SourceContent */
      200: {
        headers: {
          [name: string]: unknown;
        };
        content: {
          'application/json': {
            /** Format: uuid */
            sourceId: string;
            content: string;
            totalLines: number;
            slice: {
              start: number;
              end: number;
            };
          };
          'text/markdown': string;
          'text/plain': string;
        };
      };
    };
  };
  saveConversation: {
    parameters: {
      query?: never;
      header?: never;
      path: {
        threadId: string;
      };
      cookie?: never;
    };
    /** @description SaveConversationInput */
    requestBody: {
      content: {
        'application/json': {
          messages: {
            /** @enum {string} */
            role: 'user' | 'assistant' | 'system' | 'tool';
            /** @default null */
            content?: string | null;
            /** @default null */
            toolName?: string | null;
            /**
             * @default null
             * @enum {string|null}
             */
            toolType?: 'call' | 'result' | null;
          }[];
          modelProvider?: string;
          modelId?: string;
          /** @description ConversationTokenUsage */
          tokenUsage?: {
            inputTokens?: number;
            outputTokens?: number;
            totalTokens?: number;
          };
          /** @description ConversationMetadata */
          metadata?: {
            [key: string]: string | string[];
          };
        };
      };
    };
    responses: {
      /** @description Conversation */
      200: {
        headers: {
          [name: string]: unknown;
        };
        content: {
          'application/json': {
            id: string;
            threadId: string;
            /** @description ConversationMetadata */
            metadata: {
              [key: string]: string | string[];
            } | null;
            /** Format: date-time */
            startedAt: string;
            /** Format: date-time */
            messagesUpdatedAt: string;
            messages: {
              /** @enum {string} */
              role: 'user' | 'assistant' | 'system' | 'tool';
              /** @default null */
              content: string | null;
              /** @default null */
              toolName: string | null;
              /**
               * @default null
               * @enum {string|null}
               */
              toolType: 'call' | 'result' | null;
            }[];
            modelProvider: string | null;
            modelId: string | null;
            /** @description ConversationTokenUsage */
            tokenUsage: {
              inputTokens?: number;
              outputTokens?: number;
              totalTokens?: number;
            } | null;
            /** @description ConversationCoreMetrics */
            coreMetrics: {
              successScore?: number;
              /** @enum {string} */
              sentiment?: 'positive' | 'neutral' | 'negative';
              contentGaps?: string[];
            } | null;
            /** Format: date-time */
            classifiedAt: string | null;
            classificationError: string | null;
            /** Format: date-time */
            createdAt: string;
            /** Format: date-time */
            updatedAt: string;
          };
        };
      };
    };
  };
  classifyConversation: {
    parameters: {
      query?: never;
      header?: never;
      path: {
        threadId: string;
      };
      cookie?: never;
    };
    /** @description ClassifyConversationInput */
    requestBody: {
      content: {
        'application/json': {
          coreMetrics?: {
            successScore: number;
            /** @enum {string} */
            sentiment: 'positive' | 'neutral' | 'negative';
            contentGaps: string[];
          };
          classificationError?: string;
        };
      };
    };
    responses: {
      /** @description Conversation */
      200: {
        headers: {
          [name: string]: unknown;
        };
        content: {
          'application/json': {
            id: string;
            threadId: string;
            /** @description ConversationMetadata */
            metadata: {
              [key: string]: string | string[];
            } | null;
            /** Format: date-time */
            startedAt: string;
            /** Format: date-time */
            messagesUpdatedAt: string;
            messages: {
              /** @enum {string} */
              role: 'user' | 'assistant' | 'system' | 'tool';
              /** @default null */
              content: string | null;
              /** @default null */
              toolName: string | null;
              /**
               * @default null
               * @enum {string|null}
               */
              toolType: 'call' | 'result' | null;
            }[];
            modelProvider: string | null;
            modelId: string | null;
            /** @description ConversationTokenUsage */
            tokenUsage: {
              inputTokens?: number;
              outputTokens?: number;
              totalTokens?: number;
            } | null;
            /** @description ConversationCoreMetrics */
            coreMetrics: {
              successScore?: number;
              /** @enum {string} */
              sentiment?: 'positive' | 'neutral' | 'negative';
              contentGaps?: string[];
            } | null;
            /** Format: date-time */
            classifiedAt: string | null;
            classificationError: string | null;
            /** Format: date-time */
            createdAt: string;
            /** Format: date-time */
            updatedAt: string;
          };
        };
      };
    };
  };
}
declare namespace types_d_exports {
  export { ApplyIssuesParams, ApplyIssuesResponse, ClassifyConversationParams, ContextListenOptions, ContextRequestOptions, Conversation, ConversationDoc, CreateFileImportParams, CreateImportParams, CreateInstructionParams, CreateInstructionResponse, CreateKnowledgeBaseParams, DismissIssueResponse, EditInstructionParams, EditKnowledgeBaseParams, Entry, EntryDoc, Import, ImportDetail, ImportDownloadResponse, ImportsResponse, Instruction, InstructionDoc, IssueDoc, Job, JobAccepted, KnowledgeBase, KnowledgeBasesResponse, McpDoc, RebuildEntryResponse, ReopenIssueResponse, RequestOptions$2 as RequestOptions, ResolveIssueParams, ResolveIssueResponse, SaveConversationParams, Source, SourceContentResponse, SourceDetail, SourcesResponse, StagedUpload, possibleStoreRequestOptions };
}
/** Options accepted by every Context method. @beta */
type RequestOptions$2 = {
  signal?: AbortSignal;
  tag?: string;
};
/** @internal */
declare const possibleStoreRequestOptions: readonly ['headers', 'signal', 'tag', 'timeout', 'token'];
/**
 * Request options honored by `context.fetch`.
 *
 * @beta
 */
type ContextRequestOptions = Pick<RequestOptions, (typeof possibleStoreRequestOptions)[number]>;
/**
 * Listener options for `context.listen`.
 *
 * `includeAllVersions` is left out: Context documents are written by the
 * Context API with no drafts or versions, so it would never make a
 * difference.
 *
 * @beta
 */
type ContextListenOptions = Omit<ListenOptions, 'includeAllVersions'> | Omit<ResumableListenOptions, 'includeAllVersions'>;
/**
 * A file import. The client stages the upload, PUTs the bytes straight to
 * storage with a signed URL, and confirms. The Context API never holds the
 * file content.
 * @beta
 */
type CreateFileImportParams = {
  type: 'file';
  /** Same shapes `assets.upload` accepts, minus node streams: the bytes go
   * out through `fetch`, which has no portable stream support. */
  file: Exclude<UploadBody, NodeJS.ReadableStream>;
  filename: string;
  contentType?: string;
};
type KnowledgeBasesPath = '/{apiVersion}/context/knowledge-bases';
type ConversationPath = '/{apiVersion}/context/organizations/{organizationId}/conversations/{threadId}';
type KnowledgeBasePath = '/{apiVersion}/context/knowledge-bases/{knowledgeBaseId}';
type ImportsPath = `${KnowledgeBasePath}/imports`;
type ImportPath = `${KnowledgeBasePath}/imports/{importId}`;
type UploadsPath = `${KnowledgeBasePath}/imports/uploads`;
type EntryRebuildPath = `${KnowledgeBasePath}/entries/{entryPath}/rebuild`;
type SourcesPath = `${KnowledgeBasePath}/sources`;
type SourcePath = `${KnowledgeBasePath}/sources/{sourceId}`;
type SourceContentPath = `${KnowledgeBasePath}/sources/{sourceId}/content`;
type IssuesApplyPath = `${KnowledgeBasePath}/issues/apply`;
type InstructionPath = `${KnowledgeBasePath}/instructions/{instructionId}`;
type JobPath = `${KnowledgeBasePath}/jobs/{jobId}`;
type IssueResolvePath = `${KnowledgeBasePath}/issues/{issueId}/resolve`;
type IssueDismissPath = `${KnowledgeBasePath}/issues/{issueId}/dismiss`;
type IssueReopenPath = `${KnowledgeBasePath}/issues/{issueId}/reopen`;
type InstructionsPath = `${KnowledgeBasePath}/instructions`;
type JsonResponse<T> = T extends {
  content: {
    'application/json': infer R;
  };
} ? R : never;
type JsonBody<T> = T extends {
  requestBody: {
    content: {
      'application/json': infer R;
    };
  };
} ? R : never;
/**
 * A knowledge base: one buildable body of knowledge inside Context.
 * @beta
 */
type KnowledgeBase = JsonResponse<paths[KnowledgeBasePath]['get']['responses']['200']>;
/**
 * Parameters for creating a knowledge base.
 * @beta
 */
type CreateKnowledgeBaseParams = JsonBody<paths[KnowledgeBasesPath]['post']>;
/** @beta */
type EditKnowledgeBaseParams = JsonBody<paths[KnowledgeBasePath]['patch']>;
/**
 * Parameters for importing content. Discriminated on `type`:
 * inline text, a website crawl, or a Sanity dataset bind.
 * @beta
 */
type CreateImportParams = JsonBody<paths[ImportsPath]['post']>;
/**
 * Accepted async work. Poll the job with `jobs.get` until it reaches a
 * terminal state.
 * @beta
 */
type JobAccepted = JsonResponse<paths[`${KnowledgeBasePath}/build`]['post']['responses']['202']>;
/** @beta */
type Job = JsonResponse<paths[JobPath]['get']['responses']['200']>;
/**
 * Accepted entry rebuild: the job to poll plus every entry the rebuild
 * touches.
 * @beta
 */
type RebuildEntryResponse = JsonResponse<paths[EntryRebuildPath]['post']['responses']['202']>;
/** @beta */
type ApplyIssuesParams = JsonBody<paths[IssuesApplyPath]['post']>;
/** @beta */
type ApplyIssuesResponse = JsonResponse<paths[IssuesApplyPath]['post']['responses']['202']>;
/** @beta */
type ResolveIssueParams = JsonBody<paths[IssueResolvePath]['post']>;
/** @beta */
type ResolveIssueResponse = JsonResponse<paths[IssueResolvePath]['post']['responses']['200']>;
/** @beta */
type DismissIssueResponse = JsonResponse<paths[IssueDismissPath]['post']['responses']['200']>;
/** @beta */
type ReopenIssueResponse = JsonResponse<paths[IssueReopenPath]['post']['responses']['200']>;
/** @beta */
type CreateInstructionParams = JsonBody<paths[InstructionsPath]['post']>;
/**
 * A standing instruction, as the instruction endpoints return it.
 * @beta
 */
type Instruction = JsonResponse<paths[InstructionPath]['patch']['responses']['200']>;
/** The created instruction, wrapped the way the create endpoint returns it. @beta */
type CreateInstructionResponse = JsonResponse<paths[InstructionsPath]['post']['responses']['201']>;
/** @beta */
type EditInstructionParams = JsonBody<paths[InstructionPath]['patch']>;
/** @beta */
type KnowledgeBasesResponse = JsonResponse<paths[KnowledgeBasesPath]['get']['responses']['200']>;
/** @beta */
type ImportsResponse = JsonResponse<paths[ImportsPath]['get']['responses']['200']>;
/** @beta */
type Import = ImportsResponse['data'][number];
/** @beta */
type ImportDetail = JsonResponse<paths[ImportPath]['get']['responses']['200']>;
/** @beta */
type ImportDownloadResponse = JsonResponse<paths[`${ImportPath}/download`]['get']['responses']['200']>;
/**
 * The staged half of a file upload: PUT the bytes to `uploadUrl`, then
 * confirm with the complete endpoint. `imports.create({type: 'file'})` does
 * all of this in one call.
 * @beta
 */
type StagedUpload = JsonResponse<paths[UploadsPath]['post']['responses']['201']>;
/** @beta */
type SourcesResponse = JsonResponse<paths[SourcesPath]['get']['responses']['200']>;
/** @beta */
type Source = SourcesResponse['data'][number];
/** @beta */
type SourceDetail = JsonResponse<paths[SourcePath]['get']['responses']['200']>;
/** @beta */
type SourceContentResponse = JsonResponse<paths[SourceContentPath]['get']['responses']['200']>;
/**
 * A recorded conversation: one agent thread's transcript plus the
 * classification recorded on it. Standalone org-level telemetry — dimensions
 * (MCP endpoints, app, the customer's own keys) live in the `metadata` bag.
 * @beta
 */
type Conversation = JsonResponse<paths[ConversationPath]['put']['responses']['200']>;
/**
 * Body for the conversation ingest upsert. Messages replace the stored
 * transcript wholesale; `metadata` and model fields only overwrite when
 * present.
 * @beta
 */
type SaveConversationParams = JsonBody<paths[ConversationPath]['put']>;
/** Exactly one of a verdict (`coreMetrics`) or a failure (`classificationError`). @beta */
type ClassifyConversationParams = JsonBody<paths[ConversationPath]['patch']>;
/**
 * The raw `sanity.context.entry` document shape, as stored in the
 * organization's document store. For typing GROQ reads.
 * @beta
 */
type EntryDoc = components['schemas']['EntryDoc'];
/** @beta */
type IssueDoc = components['schemas']['IssueDoc'];
/** @beta */
type InstructionDoc = components['schemas']['InstructionDoc'];
/**
 * The raw `sanity.context.mcp` document shape (an MCP endpoint
 * configuration), as stored in the organization's document store. For
 * typing GROQ reads.
 * @beta
 */
type McpDoc = components['schemas']['McpDoc'];
/**
 * The metadata view of an entry, as `entries.list` projects it. Bodies stay
 * behind `entries.get` (or a GROQ read through `context.fetch`).
 * @beta
 */
type Entry = Pick<EntryDoc, '_id' | 'path' | 'title' | 'tldr' | 'status'>;
/**
 * The raw `sanity.context.conversation` document shape, as stored in the
 * organization's document store. For typing GROQ reads.
 * @beta
 */
type ConversationDoc = components['schemas']['ConversationDoc'];
type ListOptions$1 = RequestOptions$2 & {
  cursor?: string;
  limit?: number;
};
/**
 * `client.context` — knowledge bases and everything scoped to them.
 *
 * Collection-level management (create, list, get, edit, delete) addresses
 * knowledge bases per call, like `client.projects`. Everything scoped to one
 * knowledge base (imports, builds, issues, entries, ...) operates on the
 * client's configured `resource`, like media libraries:
 *
 * @example Full lifecycle
 * ```ts
 * const created = await client.context.knowledgeBases.create({
 *   organizationId: 'org123',
 *   title: 'Support docs',
 *   description: 'Product docs and troubleshooting guides',
 * })
 *
 * const kb = createClient({
 *   apiVersion: '2026-08-25',
 *   token,
 *   resource: {type: 'knowledge-base', id: created.publicId},
 * })
 *
 * await kb.context.imports.create({type: 'text', title: 'Refund policy', content: refundMd})
 * const {jobId} = await kb.context.build()
 * ```
 *
 * @beta
 */
declare class ContextClient {
  #private;
  constructor(client: SanityClient, httpRequest: HttpRequest);
  /** The knowledge base collection: management addressed per call. */
  knowledgeBases: {
    /** Create a knowledge base. Requires the org-level knowledge-base create grant. */
    create: (params: CreateKnowledgeBaseParams, options?: RequestOptions$2) => Promise<KnowledgeBase>;
    /** List the organization's knowledge bases. */
    list: (params: {
      organizationId: string;
    } & ListOptions$1) => Promise<KnowledgeBasesResponse>;
    /** Fetch a knowledge base by its id. */
    get: (knowledgeBaseId: string, options?: RequestOptions$2) => Promise<KnowledgeBase>;
    /** Edit a knowledge base's configuration. */
    edit: (knowledgeBaseId: string, params: EditKnowledgeBaseParams, options?: RequestOptions$2) => Promise<KnowledgeBase>;
    /** Delete a knowledge base and its generated content. */
    delete: (knowledgeBaseId: string, options?: RequestOptions$2) => Promise<void>;
  };
  /**
   * GROQ over the organization's Context documents (conversation telemetry
   * today; the store holds every Context family and the caller's access
   * decides what a query returns, so filter on `_type`).
   *
   * Requires `context.organizationId` in the client configuration.
   */
  fetch<R = unknown>(query: string, params?: QueryParams, options?: ContextRequestOptions): Promise<R>;
  /**
   * Listen for changes to the organization's Context documents. Mirrors
   * `client.listen(query, params, options)` and emits mutation events by
   * default.
   */
  listen<Opts extends ContextListenOptions | undefined = undefined>(query: string, params?: QueryParams, options?: Opts): Observable<ListenEventFromOptions<SanityDocument, Opts>>;
  /**
   * Conversation telemetry. `threadId` identifies the conversation within
   * the organization — reuse means the same conversation. Beyond the canned
   * `get`, reads go through {@link fetch} and {@link listen} with GROQ
   * (`_type == "sanity.context.conversation"`).
   *
   * Requires `context.organizationId` in the client configuration.
   */
  conversations: {
    /**
     * Record a conversation. Messages replace the stored transcript
     * wholesale; `metadata` and model fields only overwrite when present.
     * Last write per thread wins — retries are safe.
     */
    save: (params: {
      threadId: string;
    } & SaveConversationParams, options?: RequestOptions$2) => Promise<Conversation>;
    /**
     * Record the classification your own model produced for one thread:
     * exactly one of `coreMetrics` (a verdict) or `classificationError`
     * (why classification failed).
     */
    classify: (params: {
      threadId: string;
    } & ClassifyConversationParams, options?: RequestOptions$2) => Promise<Conversation>;
    /**
     * One recorded conversation by its thread id, or `null` when the thread
     * was never recorded. Runs:
     *
     * `*[_type == "sanity.context.conversation" && organizationId == $org && threadId == $threadId][0]`
     *
     * For anything more, use {@link fetch}.
     */
    get: (params: {
      threadId: string;
    }, options?: ContextRequestOptions) => Promise<ConversationDoc | null>;
  };
  /**
   * Build the configured knowledge base. The server waits for pending import
   * processing before assembling, so importing and building back to back is
   * safe. Track the returned job with {@link jobs}.
   */
  build(options?: RequestOptions$2): Promise<JobAccepted>;
  /** Cancel the running build, if any. */
  cancelBuild(options?: RequestOptions$2): Promise<{
    cancelled: boolean;
  }>;
  /** Run an incremental refresh: re-check sources and apply what changed. */
  refresh(options?: RequestOptions$2): Promise<{
    jobId: string;
    started: boolean;
  }>;
  /** Imports: feed content into the configured knowledge base. */
  imports: {
    /**
     * Import content. One entry point, discriminated on `type`: inline
     * `text`, a website `crawl`, a Sanity `dataset` bind, or a `file`
     * upload. Processing queues automatically. The file variant stages the
     * upload, PUTs the bytes to a signed storage URL, and confirms; the
     * bytes never pass through the Context API.
     */
    create: (params: CreateImportParams | CreateFileImportParams, options?: RequestOptions$2) => Promise<JobAccepted>;
    list: (params?: ListOptions$1) => Promise<{
      data: {
        id: string;
        knowledgeBaseId: string;
        name: string | null;
        sizeBytes: number | null;
        status: 'uploading' | 'processing' | 'complete' | 'failed';
        sourceKind: 'web' | 'file' | 'dataset';
        lastCheckedAt: string | null;
        sourceCount: number;
        totalDistillableCount: number;
        distilledCount: number;
        unsupportedCount: number;
        statusDetail: string | null;
        error: string | null;
        crawlOptions: {
          includePaths?: string[];
          excludePaths?: string[];
          maxDepth?: number;
          sitemapOnly?: boolean;
          ignoreQueryParameters?: boolean;
          pageLimit?: number;
        } | null;
        datasetSource: {
          sanityProjectId: string;
          sanityDatasetId: string;
          query: string;
        } | null;
        createdBy: {
          id: string | null;
          displayName: string | null;
        } | null;
        createdAt: string;
        completedAt: string | null;
      }[];
      nextCursor: string | null;
    }>;
    get: (params: {
      importId: string;
    }, options?: RequestOptions$2) => Promise<{
      id: string;
      knowledgeBaseId: string;
      name: string | null;
      sizeBytes: number | null;
      status: 'uploading' | 'processing' | 'complete' | 'failed';
      sourceKind: 'web' | 'file' | 'dataset';
      lastCheckedAt: string | null;
      sourceCount: number;
      totalDistillableCount: number;
      distilledCount: number;
      unsupportedCount: number;
      statusDetail: string | null;
      error: string | null;
      crawlOptions: {
        includePaths?: string[];
        excludePaths?: string[];
        maxDepth?: number;
        sitemapOnly?: boolean;
        ignoreQueryParameters?: boolean;
        pageLimit?: number;
      } | null;
      datasetSource: {
        sanityProjectId: string;
        sanityDatasetId: string;
        query: string;
      } | null;
      createdBy: {
        id: string | null;
        displayName: string | null;
      } | null;
      createdAt: string;
      completedAt: string | null;
    }>;
    /** A short-lived signed URL for the original uploaded bytes. */
    download: (params: {
      importId: string;
    }, options?: RequestOptions$2) => Promise<{
      url: string;
      expiresAt: string;
    }>;
    delete: (params: {
      importId: string;
    }, options?: RequestOptions$2) => Promise<void>;
  };
  /** Jobs: poll async work (builds, imports) to a terminal state. */
  jobs: {
    get: (params: {
      jobId: string;
    }, options?: RequestOptions$2) => Promise<{
      id: string;
      status: 'pending' | 'queued' | 'running' | 'succeeded' | 'failed' | 'cancelled';
      startedAt: string | null;
      completedAt: string | null;
      result?: unknown;
      error?: string | null;
    }>;
  };
  /**
   * Issues: findings from builds awaiting triage. Reads are canned GROQ
   * queries against the organization's document store; for anything more,
   * use {@link fetch}. Reads require `context.organizationId` alongside the
   * knowledge-base `resource` in the client configuration.
   */
  issues: {
    /**
     * Every issue on the knowledge base, oldest first, optionally narrowed
     * to one status. Drains keyset pages internally and resolves with the
     * complete set. Runs:
     *
     * `*[_type == "sanity.context.issue" && knowledgeBaseId == $kb && status == $status] | order(_createdAt asc, _id asc)`
     *
     * (the status clause only when given). For anything more, use {@link fetch}.
     */
    list: (params?: {
      status?: 'open' | 'accepted' | 'rejected';
    }, options?: ContextRequestOptions) => Promise<IssueDoc[]>;
    /**
     * One issue by its document id, or `null` when it does not exist. Runs:
     *
     * `*[_type == "sanity.context.issue" && knowledgeBaseId == $kb && _id == $id][0]`
     *
     * For anything more, use {@link fetch}.
     */
    get: (params: {
      issueId: string;
    }, options?: ContextRequestOptions) => Promise<IssueDoc | null>;
    /** Resolve a conflict issue. Mints the standing instruction, same as the dashboard. */
    resolve: (params: {
      issueId: string;
    } & ResolveIssueParams, options?: RequestOptions$2) => Promise<{
      issue: {
        id: string;
        knowledgeBaseId: string;
        content: {
          kind: 'conflict' | 'gap' | 'update_required' | 'add_entry' | 'remove_entry' | 'split_entry' | 'merge_entry';
          severity: 'critical' | 'suggestion';
          scopePath: string;
          issue: string;
          suggestedFix: string;
          citedSourceIds?: string[];
          claimKey?: string;
          involvedScopes?: string[];
          currentClaim?: string;
          alternativeClaim?: string;
          currentAuthority?: 'primary' | 'secondary' | 'community';
          alternativeAuthority?: 'primary' | 'secondary' | 'community';
          suggestedResolution?: 'keep_existing' | 'accept_new';
        };
        status: 'open' | 'accepted' | 'rejected';
        resolution: 'keep_existing' | 'accept_new' | null;
        resolvedBy: {
          id: string;
          kind: 'user' | 'robot';
        } | null;
        createdAt: string;
        resolvedAt: string | null;
      };
      jobId: string | null;
    }>;
    dismiss: (params: {
      issueId: string;
    }, options?: RequestOptions$2) => Promise<{
      id: string;
      knowledgeBaseId: string;
      content: {
        kind: 'conflict' | 'gap' | 'update_required' | 'add_entry' | 'remove_entry' | 'split_entry' | 'merge_entry';
        severity: 'critical' | 'suggestion';
        scopePath: string;
        issue: string;
        suggestedFix: string;
        citedSourceIds?: string[];
        claimKey?: string;
        involvedScopes?: string[];
        currentClaim?: string;
        alternativeClaim?: string;
        currentAuthority?: 'primary' | 'secondary' | 'community';
        alternativeAuthority?: 'primary' | 'secondary' | 'community';
        suggestedResolution?: 'keep_existing' | 'accept_new';
      };
      status: 'open' | 'accepted' | 'rejected';
      resolution: 'keep_existing' | 'accept_new' | null;
      resolvedBy: {
        id: string;
        kind: 'user' | 'robot';
      } | null;
      createdAt: string;
      resolvedAt: string | null;
    }>;
    reopen: (params: {
      issueId: string;
    }, options?: RequestOptions$2) => Promise<{
      id: string;
      knowledgeBaseId: string;
      content: {
        kind: 'conflict' | 'gap' | 'update_required' | 'add_entry' | 'remove_entry' | 'split_entry' | 'merge_entry';
        severity: 'critical' | 'suggestion';
        scopePath: string;
        issue: string;
        suggestedFix: string;
        citedSourceIds?: string[];
        claimKey?: string;
        involvedScopes?: string[];
        currentClaim?: string;
        alternativeClaim?: string;
        currentAuthority?: 'primary' | 'secondary' | 'community';
        alternativeAuthority?: 'primary' | 'secondary' | 'community';
        suggestedResolution?: 'keep_existing' | 'accept_new';
      };
      status: 'open' | 'accepted' | 'rejected';
      resolution: 'keep_existing' | 'accept_new' | null;
      resolvedBy: {
        id: string;
        kind: 'user' | 'robot';
      } | null;
      createdAt: string;
      resolvedAt: string | null;
    }>;
    /** Apply already-accepted issues to the knowledge base in one batch. */
    apply: (params: ApplyIssuesParams, options?: RequestOptions$2) => Promise<{
      jobId: string;
    }>;
  };
  /** Instructions: standing decisions that steer every build. */
  instructions: {
    create: (params: CreateInstructionParams, options?: RequestOptions$2) => Promise<CreateInstructionResponse>;
    /**
     * Every current-schema instruction on the knowledge base, oldest first.
     * Drains keyset pages internally and resolves with the complete set.
     * Runs:
     *
     * `*[_type == "sanity.context.instruction" && knowledgeBaseId == $kb && schemaVersion == 1] | order(_createdAt asc, _id asc)`
     *
     * For anything more, use {@link fetch}. Requires `context.organizationId`
     * alongside the knowledge-base `resource` in the client configuration.
     */
    list: (options?: ContextRequestOptions) => Promise<InstructionDoc[]>;
    edit: (params: {
      instructionId: string;
    } & EditInstructionParams, options?: RequestOptions$2) => Promise<{
      id: string;
      knowledgeBaseId: string;
      origin: 'conflict' | 'human';
      status: 'active' | 'archived';
      statement: string;
      scopeSourceIds: string[] | null;
      archivedAt: string | null;
      archivedReason: string | null;
      sourceIssueId: string | null;
      createdBy: {
        id: string | null;
        displayName: string | null;
      } | null;
      updatedBy: {
        id: string | null;
        displayName: string | null;
      } | null;
      createdAt: string;
      updatedAt: string | null;
    }>;
    delete: (params: {
      instructionId: string;
    }, options?: RequestOptions$2) => Promise<void>;
  };
  /**
   * Entries: the built outline, one entry per node. Reads are canned GROQ
   * queries against the organization's document store; for anything more,
   * use {@link fetch}. Requires `context.organizationId` alongside the
   * knowledge-base `resource` in the client configuration.
   */
  entries: {
    /**
     * Every entry, path-ordered, as a metadata view (`_id`, `path`,
     * `title`, `tldr`, `status`) with bodies excluded. Drains keyset pages
     * internally and resolves with the complete set. Runs:
     *
     * `*[_type == "sanity.context.entry" && knowledgeBaseId == $kb && path > $after] | order(path asc) [0...200] {_id, path, title, tldr, status}`
     *
     * For bodies, use `entries.get` or {@link fetch}.
     */
    list: (options?: ContextRequestOptions) => Promise<Entry[]>;
    /**
     * One entry with its full body and citations, by outline path (e.g.
     * `billing/refunds`), or `null` when no entry sits at that path. Runs:
     *
     * `*[_type == "sanity.context.entry" && knowledgeBaseId == $kb && path == $path][0]`
     *
     * For anything more, use {@link fetch}.
     */
    get: (params: {
      path: string;
    }, options?: ContextRequestOptions) => Promise<EntryDoc | null>;
    /**
     * Rebuild one entry from its already-placed sources, by outline path.
     * Poll the returned job with {@link jobs}; `affectedEntries` lists every
     * entry the rebuild touches.
     */
    rebuild: (params: {
      path: string;
    }, options?: RequestOptions$2) => Promise<RebuildEntryResponse>;
  };
  /**
   * MCP endpoint configurations, org-owned documents read with canned GROQ
   * queries. Requires `context.organizationId` in the client configuration.
   */
  mcpEndpoints: {
    /**
     * The organization's MCP endpoint configurations, oldest first. Runs:
     *
     * `*[_type == "sanity.context.mcp" && organizationId == $org] | order(_createdAt asc, _id asc) [0...500]`
     *
     * For anything more, use {@link fetch}.
     */
    list: (options?: ContextRequestOptions) => Promise<McpDoc[]>;
    /**
     * One MCP endpoint configuration by its URL name, or `null` when none
     * carries that name. Runs:
     *
     * `*[_type == "sanity.context.mcp" && organizationId == $org && name == $name][0]`
     *
     * For anything more, use {@link fetch}.
     */
    get: (params: {
      name: string;
    }, options?: ContextRequestOptions) => Promise<McpDoc | null>;
  };
  /** Sources: the distilled units builds cite. */
  sources: {
    /**
     * List sources, optionally filtered by `status` or the `importId` they
     * came from. `ids` is a lookup mode: it resolves those exact sources
     * (e.g. from an entry's citations) and overrides `status` and `cursor`.
     */
    list: (params?: {
      status?: Source['status'];
      importId?: string;
      ids?: string[];
    } & ListOptions$1) => Promise<{
      data: {
        id: string;
        knowledgeBaseId: string;
        filename: string;
        kind: 'web' | 'file' | 'dataset';
        sizeBytes: number;
        status: 'pending' | 'processing' | 'ready' | 'failed' | 'skipped';
        tldr: string | null;
        topics: string[] | null;
        canonicalUrl: string | null;
        fetchedAt: string | null;
        distilledAt: string | null;
        createdAt: string;
      }[];
      nextCursor: string | null;
    }>;
    get: (params: {
      sourceId: string;
    }, options?: RequestOptions$2) => Promise<{
      id: string;
      knowledgeBaseId: string;
      filename: string;
      kind: 'web' | 'file' | 'dataset';
      sizeBytes: number;
      status: 'pending' | 'processing' | 'ready' | 'failed' | 'skipped';
      tldr: string | null;
      topics: string[] | null;
      canonicalUrl: string | null;
      fetchedAt: string | null;
      distilledAt: string | null;
      createdAt: string;
    }>;
    /**
     * Distilled source content, optionally a line range: the evidence behind
     * a citation or an issue.
     */
    content: (params: {
      sourceId: string;
      startLine?: number;
      endLine?: number;
    }, options?: RequestOptions$2) => Promise<{
      sourceId: string;
      content: string;
      totalLines: number;
      slice: {
        start: number;
        end: number;
      };
    }>;
    delete: (params: {
      sourceId: string;
    }, options?: RequestOptions$2) => Promise<void>;
  };
}
/**
 * Observable counterpart of {@link ContextClient}. Collection-level
 * methods and the GROQ-backed reads; knowledge-base scoped write
 * operations are promise-based, so use the promise client
 * (`client.context`) for those.
 *
 * @beta
 */
declare class ObservableContextClient {
  #private;
  constructor(client: ObservableSanityClient, httpRequest: HttpRequest);
  /** The knowledge base collection: management addressed per call. */
  knowledgeBases: {
    /** Create a knowledge base. Requires the org-level knowledge-base create grant. */
    create: (params: CreateKnowledgeBaseParams, options?: RequestOptions$2) => Observable<KnowledgeBase>;
    /** List the organization's knowledge bases. */
    list: (params: {
      organizationId: string;
    } & ListOptions$1) => Observable<KnowledgeBasesResponse>;
    /** Fetch a knowledge base by its id. */
    get: (knowledgeBaseId: string, options?: RequestOptions$2) => Observable<KnowledgeBase>;
    /** Edit a knowledge base's configuration. */
    edit: (knowledgeBaseId: string, params: EditKnowledgeBaseParams, options?: RequestOptions$2) => Observable<KnowledgeBase>;
    /** Delete a knowledge base and its generated content. */
    delete: (knowledgeBaseId: string, options?: RequestOptions$2) => Observable<void>;
  };
  /**
   * GROQ over the organization's Context documents (conversation telemetry
   * today; the store holds every Context family and the caller's access
   * decides what a query returns, so filter on `_type`).
   *
   * Requires `context.organizationId` in the client configuration.
   */
  fetch<R = unknown>(query: string, params?: QueryParams, options?: ContextRequestOptions): Observable<R>;
  /**
   * Listen for changes to the organization's Context documents. Mirrors
   * `client.listen(query, params, options)` and emits mutation events by
   * default.
   */
  listen<Opts extends ContextListenOptions | undefined = undefined>(query: string, params?: QueryParams, options?: Opts): Observable<ListenEventFromOptions<SanityDocument, Opts>>;
  /**
   * Conversation telemetry. `threadId` identifies the conversation within
   * the organization — reuse means the same conversation. Beyond the canned
   * `get`, reads go through {@link fetch} and {@link listen} with GROQ
   * (`_type == "sanity.context.conversation"`).
   *
   * Requires `context.organizationId` in the client configuration.
   */
  conversations: {
    /**
     * Record a conversation. Messages replace the stored transcript
     * wholesale; `metadata` and model fields only overwrite when present.
     * Last write per thread wins — retries are safe.
     */
    save: (params: {
      threadId: string;
    } & SaveConversationParams, options?: RequestOptions$2) => Observable<Conversation>;
    /**
     * Record the classification your own model produced for one thread:
     * exactly one of `coreMetrics` (a verdict) or `classificationError`
     * (why classification failed).
     */
    classify: (params: {
      threadId: string;
    } & ClassifyConversationParams, options?: RequestOptions$2) => Observable<Conversation>;
    /**
     * One recorded conversation by its thread id, or `null` when the thread
     * was never recorded. Runs:
     *
     * `*[_type == "sanity.context.conversation" && organizationId == $org && threadId == $threadId][0]`
     *
     * For anything more, use {@link fetch}.
     */
    get: (params: {
      threadId: string;
    }, options?: ContextRequestOptions) => Observable<ConversationDoc | null>;
  };
  /**
   * Entries: the built outline, one entry per node. Reads are canned GROQ
   * queries against the organization's document store; for anything more,
   * use {@link fetch}. Requires `context.organizationId` alongside the
   * knowledge-base `resource` in the client configuration.
   */
  entries: {
    /**
     * Every entry, path-ordered, as a metadata view (`_id`, `path`,
     * `title`, `tldr`, `status`) with bodies excluded. Drains keyset pages
     * internally and emits the complete set. Runs:
     *
     * `*[_type == "sanity.context.entry" && knowledgeBaseId == $kb && path > $after] | order(path asc) [0...200] {_id, path, title, tldr, status}`
     *
     * For bodies, use `entries.get` or {@link fetch}.
     */
    list: (options?: ContextRequestOptions) => Observable<Entry[]>;
    /**
     * One entry with its full body and citations, by outline path (e.g.
     * `billing/refunds`), or `null` when no entry sits at that path. Runs:
     *
     * `*[_type == "sanity.context.entry" && knowledgeBaseId == $kb && path == $path][0]`
     *
     * For anything more, use {@link fetch}.
     */
    get: (params: {
      path: string;
    }, options?: ContextRequestOptions) => Observable<EntryDoc | null>;
    /**
     * Rebuild one entry from its already-placed sources, by outline path.
     * Poll the returned job with the promise client's `jobs`;
     * `affectedEntries` lists every entry the rebuild touches.
     */
    rebuild: (params: {
      path: string;
    }, options?: RequestOptions$2) => Observable<RebuildEntryResponse>;
  };
  /**
   * Issues: findings from builds awaiting triage. Reads are canned GROQ
   * queries against the organization's document store; for anything more,
   * use {@link fetch}. Requires `context.organizationId` alongside the
   * knowledge-base `resource` in the client configuration.
   */
  issues: {
    /**
     * Every issue on the knowledge base, oldest first, optionally narrowed
     * to one status. Drains keyset pages internally and emits the complete
     * set. Runs:
     *
     * `*[_type == "sanity.context.issue" && knowledgeBaseId == $kb && status == $status] | order(_createdAt asc, _id asc)`
     *
     * (the status clause only when given). For anything more, use {@link fetch}.
     */
    list: (params?: {
      status?: 'open' | 'accepted' | 'rejected';
    }, options?: ContextRequestOptions) => Observable<IssueDoc[]>;
    /**
     * One issue by its document id, or `null` when it does not exist. Runs:
     *
     * `*[_type == "sanity.context.issue" && knowledgeBaseId == $kb && _id == $id][0]`
     *
     * For anything more, use {@link fetch}.
     */
    get: (params: {
      issueId: string;
    }, options?: ContextRequestOptions) => Observable<IssueDoc | null>;
  };
  /**
   * Instructions: standing decisions that steer every build. The canned
   * GROQ read; writes are promise-based on `client.context`.
   */
  instructions: {
    /**
     * Every current-schema instruction on the knowledge base, oldest first.
     * Drains keyset pages internally and emits the complete set. Runs:
     *
     * `*[_type == "sanity.context.instruction" && knowledgeBaseId == $kb && schemaVersion == 1] | order(_createdAt asc, _id asc)`
     *
     * For anything more, use {@link fetch}. Requires `context.organizationId`
     * alongside the knowledge-base `resource` in the client configuration.
     */
    list: (options?: ContextRequestOptions) => Observable<InstructionDoc[]>;
  };
  /**
   * MCP endpoint configurations, org-owned documents read with canned GROQ
   * queries. Requires `context.organizationId` in the client configuration.
   */
  mcpEndpoints: {
    /**
     * The organization's MCP endpoint configurations, oldest first. Runs:
     *
     * `*[_type == "sanity.context.mcp" && organizationId == $org] | order(_createdAt asc, _id asc) [0...500]`
     *
     * For anything more, use {@link fetch}.
     */
    list: (options?: ContextRequestOptions) => Observable<McpDoc[]>;
    /**
     * One MCP endpoint configuration by its URL name, or `null` when none
     * carries that name. Runs:
     *
     * `*[_type == "sanity.context.mcp" && organizationId == $org && name == $name][0]`
     *
     * For anything more, use {@link fetch}.
     */
    get: (params: {
      name: string;
    }, options?: ContextRequestOptions) => Observable<McpDoc | null>;
  };
}
/**
 * @public
 */
declare class LiveClient {
  #private;
  constructor(client: SanityClient | ObservableSanityClient);
  /**
   * Requires `apiVersion` to be `2021-03-25` or later.
   */
  events({ includeDrafts, tag: _tag, waitFor }?: {
    includeDrafts?: boolean;
    /**
     * Optional request tag for the listener. Use to identify the request in logs.
     *
     * @defaultValue `undefined`
     */
    tag?: string;
    /**
     * Delays events until after a Sanity Function has processed them and called the callback endpoint.
     * When omitted, events are delivered immediately.
     */
    waitFor?: 'function';
  }): Observable<LiveEvent>;
}
/** @internal */
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;
}
/** @public */
declare class ObservablePatch extends BasePatch {
  #private;
  constructor(selection: PatchSelection, operations?: PatchOperations, client?: ObservableSanityClient);
  /**
   * Clones the patch
   */
  clone(): ObservablePatch;
  /**
   * Commit the patch, returning an observable that produces the first patched document
   *
   * @param options - Options for the mutation operation
   */
  commit<R extends Record<string, Any> = Record<string, Any>>(options: FirstDocumentMutationOptions): Observable<SanityDocument<R>>;
  /**
   * Commit the patch, returning an observable that produces an array of the mutated documents
   *
   * @param options - Options for the mutation operation
   */
  commit<R extends Record<string, Any> = Record<string, Any>>(options: AllDocumentsMutationOptions): Observable<SanityDocument<R>[]>;
  /**
   * Commit the patch, returning an observable that produces a mutation result object
   *
   * @param options - Options for the mutation operation
   */
  commit(options: FirstDocumentIdMutationOptions): Observable<SingleMutationResult>;
  /**
   * Commit the patch, returning an observable that produces a mutation result object
   *
   * @param options - Options for the mutation operation
   */
  commit(options: AllDocumentIdsMutationOptions): Observable<MultipleMutationResult>;
  /**
   * Commit the patch, returning an observable that produces the first patched document
   *
   * @param options - Options for the mutation operation
   */
  commit<R extends Record<string, Any> = Record<string, Any>>(options?: BaseMutationOptions): Observable<SanityDocument<R>>;
}
/** @public */
declare class Patch extends BasePatch {
  #private;
  constructor(selection: PatchSelection, operations?: PatchOperations, client?: SanityClient);
  /**
   * Clones the patch
   */
  clone(): Patch;
  /**
   * Commit the patch, returning a promise that resolves to the first patched document
   *
   * @param options - Options for the mutation operation
   */
  commit<R extends Record<string, Any> = Record<string, Any>>(options: FirstDocumentMutationOptions): Promise<SanityDocument<R>>;
  /**
   * Commit the patch, returning a promise that resolves to an array of the mutated documents
   *
   * @param options - Options for the mutation operation
   */
  commit<R extends Record<string, Any> = Record<string, Any>>(options: AllDocumentsMutationOptions): Promise<SanityDocument<R>[]>;
  /**
   * Commit the patch, returning a promise that resolves to a mutation result object
   *
   * @param options - Options for the mutation operation
   */
  commit(options: FirstDocumentIdMutationOptions): Promise<SingleMutationResult>;
  /**
   * Commit the patch, returning a promise that resolves to a mutation result object
   *
   * @param options - Options for the mutation operation
   */
  commit(options: AllDocumentIdsMutationOptions): Promise<MultipleMutationResult>;
  /**
   * Commit the patch, returning a promise that resolves to the first patched document
   *
   * @param options - Options for the mutation operation
   */
  commit<R extends Record<string, Any> = Record<string, Any>>(options?: BaseMutationOptions): Promise<SanityDocument<R>>;
}
/** @public */
type PatchBuilder = (patch: Patch) => Patch;
/** @public */
type ObservablePatchBuilder = (patch: ObservablePatch) => ObservablePatch;
/** @internal */
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 */
declare class Transaction extends BaseTransaction {
  #private;
  constructor(operations?: Mutation[], client?: SanityClient, transactionId?: string);
  /**
   * Clones the transaction
   */
  clone(): Transaction;
  /**
   * Commit the transaction, returning a promise that resolves to the first mutated document
   *
   * @param options - Options for the mutation operation
   */
  commit<R extends Record<string, Any>>(options: TransactionFirstDocumentMutationOptions): Promise<SanityDocument<R>>;
  /**
   * Commit the transaction, returning a promise that resolves to an array of the mutated documents
   *
   * @param options - Options for the mutation operation
   */
  commit<R extends Record<string, Any>>(options: TransactionAllDocumentsMutationOptions): Promise<SanityDocument<R>[]>;
  /**
   * Commit the transaction, returning a promise that resolves to a mutation result object
   *
   * @param options - Options for the mutation operation
   */
  commit(options: TransactionFirstDocumentIdMutationOptions): Promise<SingleMutationResult>;
  /**
   * Commit the transaction, returning a promise that resolves to a mutation result object
   *
   * @param options - Options for the mutation operation
   */
  commit(options: TransactionAllDocumentIdsMutationOptions): Promise<MultipleMutationResult>;
  /**
   * Commit the transaction, returning a promise that resolves to a mutation result object
   *
   * @param options - Options for the mutation operation
   */
  commit(options?: BaseMutationOptions): Promise<MultipleMutationResult>;
  /**
   * Performs a patch on the given document ID. Can either be a builder function or an object of patch operations.
   * The operation is added to the current transaction, ready to be commited by `commit()`
   *
   * @param documentId - Document ID to perform the patch operation on
   * @param patchOps - Operations to perform, or a builder function
   */
  patch(documentId: string, patchOps?: PatchBuilder | PatchOperations): this;
  /**
   * Performs a patch on the given selection. Can either be a builder function or an object of patch operations.
   *
   * @param selection - An object with `query` and optional `params`, defining which document(s) to patch
   * @param patchOps - Operations to perform, or a builder function
   */
  patch(patch: MutationSelection, patchOps?: PatchBuilder | PatchOperations): this;
  /**
   * Adds the given patch instance to the transaction.
   * The operation is added to the current transaction, ready to be commited by `commit()`
   *
   * @param patch - Patch to execute
   */
  patch(patch: Patch): this;
}
/** @public */
declare class ObservableTransaction extends BaseTransaction {
  #private;
  constructor(operations?: Mutation[], client?: ObservableSanityClient, transactionId?: string);
  /**
   * Clones the transaction
   */
  clone(): ObservableTransaction;
  /**
   * Commit the transaction, returning an observable that produces the first mutated document
   *
   * @param options - Options for the mutation operation
   */
  commit<R extends Record<string, Any>>(options: TransactionFirstDocumentMutationOptions): Observable<SanityDocument<R>>;
  /**
   * Commit the transaction, returning an observable that produces an array of the mutated documents
   *
   * @param options - Options for the mutation operation
   */
  commit<R extends Record<string, Any>>(options: TransactionAllDocumentsMutationOptions): Observable<SanityDocument<R>[]>;
  /**
   * Commit the transaction, returning an observable that produces a mutation result object
   *
   * @param options - Options for the mutation operation
   */
  commit(options: TransactionFirstDocumentIdMutationOptions): Observable<SingleMutationResult>;
  /**
   * Commit the transaction, returning an observable that produces a mutation result object
   *
   * @param options - Options for the mutation operation
   */
  commit(options: TransactionAllDocumentIdsMutationOptions): Observable<MultipleMutationResult>;
  /**
   * Commit the transaction, returning an observable that produces a mutation result object
   *
   * @param options - Options for the mutation operation
   */
  commit(options?: BaseMutationOptions): Observable<MultipleMutationResult>;
  /**
   * Performs a patch on the given document ID. Can either be a builder function or an object of patch operations.
   * The operation is added to the current transaction, ready to be commited by `commit()`
   *
   * @param documentId - Document ID to perform the patch operation on
   * @param patchOps - Operations to perform, or a builder function
   */
  patch(documentId: string, patchOps?: ObservablePatchBuilder | PatchOperations): this;
  /**
   * Adds the given patch instance to the transaction.
   * The operation is added to the current transaction, ready to be commited by `commit()`
   *
   * @param patch - ObservablePatch to execute
   */
  patch(patch: ObservablePatch): this;
}
/** @internal */
declare class ObservableDatasetsClient {
  #private;
  constructor(client: ObservableSanityClient, httpRequest: HttpRequest);
  /**
   * Create a new dataset with the given name
   *
   * @param name - Name of the dataset to create
   * @param options - Options for the dataset, including optional embeddings configuration
   */
  create(name: string, options?: DatasetCreateOptions): Observable<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?: DatasetEditOptions): Observable<DatasetResponse>;
  /**
   * Delete a dataset with the given name
   *
   * @param name - Name of the dataset to delete
   */
  delete(name: string): Observable<{
    deleted: true;
  }>;
  /**
   * Fetch a list of datasets for the configured project
   */
  list(): Observable<DatasetsResponse>;
  /**
   * Get embeddings settings for a dataset
   *
   * @param name - Name of the dataset
   */
  getEmbeddingsSettings(name: string): Observable<EmbeddingsSettings>;
  /**
   * Edit embeddings settings for a dataset
   *
   * @param name - Name of the dataset
   * @param settings - Embeddings settings to apply
   */
  editEmbeddingsSettings(name: string, settings: EmbeddingsSettingsBody): Observable<void>;
}
/** @internal */
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, including optional embeddings configuration
   */
  create(name: string, options?: DatasetCreateOptions): 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?: DatasetEditOptions): 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>;
  /**
   * Get embeddings settings for a dataset
   *
   * @param name - Name of the dataset
   */
  getEmbeddingsSettings(name: string): Promise<EmbeddingsSettings>;
  /**
   * Edit embeddings settings for a dataset
   *
   * @param name - Name of the dataset
   * @param settings - Embeddings settings to apply
   */
  editEmbeddingsSettings(name: string, settings: EmbeddingsSettingsBody): Promise<void>;
}
/** @public */
interface InvokeFunctionEvent {
  /**
   * Payload handed to the function.
   * The function receives it as `event.data`.
   */
  data?: unknown;
}
/** @public */
interface InvokeFunctionRequest {
  event?: InvokeFunctionEvent;
  /**
   * Stack to resolve the function name against.
   * Overrides `stackId` from the client config.
   */
  stackId?: string;
  /**
   * Organization owning the stack.
   */
  organizationId?: string;
  /**
   * Milliseconds to wait for the function to return.
   */
  timeout?: number;
  /** Abort the invocation. */
  signal?: AbortSignal;
}
/** @public */
interface InvokeFunctionOptions {
  /**
   * Wait for the function to finish and resolve with its return value.
   *
   * Defaults to `false`: the invocation is started, the request resolves as soon
   * as it is accepted, and the value is always `undefined`. Only function types
   * that support running inline can be invoked synchronously.
   */
  sync?: boolean;
}
/** @public */
declare class ObservableFunctionsClient {
  #private;
  constructor(client: ObservableSanityClient, httpRequest: HttpRequest);
  /**
   * Invoke a deployed function by its blueprint name.
   *
   * The name is resolved within the stack given by `stackId` on the request or
   * the client config. Starts the invocation and emits `undefined` as soon as
   * it is accepted; pass `{sync: true}` to wait for the function's return value
   * instead.
   *
   * @param functionName - name of the function, as declared in the blueprint
   * @param request - payload and request options
   * @param options - invocation options
   */
  invoke(functionName: string, request?: InvokeFunctionRequest, options?: InvokeFunctionOptions & {
    sync?: false;
  }): Observable<undefined>;
  invoke<R = unknown>(functionName: string, request: InvokeFunctionRequest | undefined, options: InvokeFunctionOptions & {
    sync: true;
  }): Observable<R>;
  invoke<R = unknown>(functionName: string, request?: InvokeFunctionRequest, options?: InvokeFunctionOptions): Observable<R | undefined>;
}
/** @public */
declare class FunctionsClient {
  #private;
  constructor(client: SanityClient, httpRequest: HttpRequest);
  /**
   * Invoke a deployed function by its blueprint name.
   *
   * The name is resolved within the stack given by `stackId` on the request or
   * the client config, which costs one extra request per call. Rejects if the
   * stack has no function by that name, or if the name resolves to a function
   * type that cannot be invoked the way it was asked for.
   *
   * The lookup is scoped to `projectId`, or to `organizationId` when one is set
   * for a stack deployed at organization scope.
   *
   * The invocation is started by default: the promise resolves with `undefined`
   * as soon as the call is accepted, without waiting for the function to run.
   * Pass `{sync: true}` to keep the request open until the function finishes
   * and resolve with its return value — long-running functions may then need an
   * explicit `timeout`. Only `sanity.function.pubsub` functions can be invoked
   * synchronously.
   *
   * @param functionName - name of the function, as declared in the blueprint
   * @param request - payload and request options
   * @param options - invocation options
   */
  invoke(functionName: string, request?: InvokeFunctionRequest, options?: InvokeFunctionOptions & {
    sync?: false;
  }): Promise<undefined>;
  invoke<R = unknown>(functionName: string, request: InvokeFunctionRequest | undefined, options: InvokeFunctionOptions & {
    sync: true;
  }): Promise<R>;
  invoke<R = unknown>(functionName: string, request?: InvokeFunctionRequest, options?: InvokeFunctionOptions): Promise<R | undefined>;
}
/** @internal */
declare class ObservableMediaLibraryVideoClient {
  #private;
  constructor(client: ObservableSanityClient, httpRequest: HttpRequest);
  /**
   * Get video playback information for a media library asset
   *
   * @param assetIdentifier - Asset instance identifier (GDR, video-prefixed ID, or container ID)
   * @param options - Options for transformations and expiration
   */
  getPlaybackInfo(assetIdentifier: MediaLibraryAssetInstanceIdentifier, options?: MediaLibraryPlaybackInfoOptions): Observable<VideoPlaybackInfo>;
}
/** @internal */
declare class MediaLibraryVideoClient {
  #private;
  constructor(client: SanityClient, httpRequest: HttpRequest);
  /**
   * Get video playback information for a media library asset
   *
   * @param assetIdentifier - Asset instance identifier (GDR, video-prefixed ID, or container ID)
   * @param options - Options for transformations and expiration
   */
  getPlaybackInfo(assetIdentifier: MediaLibraryAssetInstanceIdentifier, options?: MediaLibraryPlaybackInfoOptions): Promise<VideoPlaybackInfo>;
}
type ListOptions = {
  includeMembers?: boolean;
  includeFeatures?: boolean;
  organizationId?: string;
  onlyExplicitMembership?: boolean;
};
type OmittedProjectFields<T extends ListOptions | undefined> = (T extends {
  includeMembers: false;
} ? 'members' : never) | (T extends {
  includeFeatures: false;
} ? 'features' : never);
/** @internal */
declare class ObservableProjectsClient {
  #private;
  constructor(client: ObservableSanityClient, httpRequest: HttpRequest);
  /**
   * Fetch a list of projects the authenticated user has access to.
   *
   * @param options - Options for the list request
   *   - `includeMembers` - Whether to include members in the response (default: true)
   *   - `includeFeatures` - Whether to include features in the response (default: true)
   *   - `organizationId` - ID of the organization to fetch projects for
   *   - `onlyExplicitMembership` - Whether to include only projects with explicit membership (default: false)
   */
  list<T extends ListOptions>(options?: T): Observable<Omit<SanityProject, OmittedProjectFields<T>>[]>;
  /**
   * Fetch a project by project ID
   *
   * @param projectId - ID of the project to fetch
   */
  getById(projectId: string): Observable<SanityProject>;
}
/** @internal */
declare class ProjectsClient {
  #private;
  constructor(client: SanityClient, httpRequest: HttpRequest);
  /**
   * Fetch a list of projects the authenticated user has access to.
   *
   * @param options - Options for the list request
   *   - `includeMembers` - Whether to include members in the response (default: true)
   *   - `includeFeatures` - Whether to include features in the response (default: true)
   *   - `organizationId` - ID of the organization to fetch projects for
   *   - `onlyExplicitMembership` - Whether to include only projects with explicit membership (default: false)
   */
  list<T extends ListOptions>(options?: T): Promise<Omit<SanityProject, OmittedProjectFields<T>>[]>;
  /**
   * Fetch a project by project ID
   *
   * @param projectId - ID of the project to fetch
   */
  getById(projectId: string): Promise<SanityProject>;
}
/** @public */
declare class ObservableReleasesClient {
  #private;
  constructor(client: ObservableSanityClient, httpRequest: HttpRequest);
  /**
   * @public
   *
   * Retrieve a release by id.
   *
   * @category Releases
   *
   * @param params - Release action parameters:
   *   - `releaseId` - The id of the release to retrieve.
   * @param options - Additional query options including abort signal and query tag.
   * @returns An observable that resolves to the release document {@link ReleaseDocument}.
   *
   * @example Retrieving a release by id
   * ```ts
   * client.observable.releases.get({releaseId: 'my-release'}).pipe(
   *   tap((release) => console.log(release)),
   *   // {
   *   //   _id: '_.releases.my-release',
   *   //   name: 'my-release'
   *   //   _type: 'system.release',
   *   //   metadata: {releaseType: 'asap'},
   *   //   _createdAt: '2021-01-01T00:00:00.000Z',
   *   //   ...
   *   // }
   * ).subscribe()
   * ```
   */
  get({ releaseId }: {
    releaseId: string;
  }, options?: {
    signal?: AbortSignal;
    tag?: string;
  }): Observable<ReleaseDocument | undefined>;
  /**
   * @public
   *
   * Creates a new release under the given id, with metadata.
   *
   * @remarks
   * * If no releaseId is provided, a release id will be generated.
   * * If no metadata is provided, then an `undecided` releaseType will be used.
   *
   * @category Releases
   *
   * @param params - Release action parameters:
   *   - `releaseId` - The id of the release to create.
   *   - `metadata` - The metadata to associate with the release {@link ReleaseDocument}.
   * @param options - Additional action options.
   * @returns An observable that resolves to the `transactionId` and the release id and metadata.
   *
   * @example Creating a release with a custom id and metadata
   * ```ts
   * const releaseId = 'my-release'
   * const metadata: ReleaseDocument['metadata'] = {
   *   releaseType: 'asap',
   * }
   *
   * client.observable.releases.create({releaseId, metadata}).pipe(
   *   tap(({transactionId, releaseId, metadata}) => console.log(transactionId, releaseId, metadata)),
   *   // {
   *   //   transactionId: 'transaction-id',
   *   //   releaseId: 'my-release',
   *   //   metadata: {releaseType: 'asap'},
   *   // }
   * ).subscribe()
   * ```
   *
   * @example Creating a release with generated id and metadata
   * ```ts
   * client.observable.releases.create().pipe(
   *   tap(({metadata}) => console.log(metadata)),
   *   // {
   *   //   metadata: {releaseType: 'undecided'},
   *   // }
   * ).subscribe()
   * ```
   *
   * @example Creating a release using a custom transaction id
   * ```ts
   * client.observable.releases.create({transactionId: 'my-transaction-id'}).pipe(
   *   tap(({transactionId, metadata}) => console.log(transactionId, metadata)),
   *   // {
   *   //   transactionId: 'my-transaction-id',
   *   //   metadata: {releaseType: 'undecided'},
   *   // }
   * ).subscribe()
   * ```
   */
  create(options: BaseActionOptions): Observable<SingleActionResult & {
    releaseId: string;
    metadata: ReleaseDocument['metadata'];
  }>;
  create(release: {
    releaseId?: string;
    metadata?: Partial<ReleaseDocument['metadata']>;
  }, options?: BaseActionOptions): Observable<SingleActionResult & {
    releaseId: string;
    metadata: ReleaseDocument['metadata'];
  }>;
  /**
   * @public
   *
   * Edits an existing release, updating the metadata.
   *
   * @category Releases
   *
   * @param params - Release action parameters:
   *   - `releaseId` - The id of the release to edit.
   *   - `patch` - The patch operation to apply on the release metadata {@link PatchMutationOperation}.
   * @param options - Additional action options.
   * @returns An observable that resolves to the `transactionId`.
   */
  edit({ releaseId, patch }: {
    releaseId: string;
    patch: PatchOperations;
  }, options?: BaseActionOptions): Observable<SingleActionResult>;
  /**
   * @public
   *
   * Publishes all documents in a release at once. For larger releases the effect of the publish
   * will be visible immediately when querying but the removal of the `versions.<releasesId>.*`
   * documents and creation of the corresponding published documents with the new content may
   * take some time.
   *
   * During this period both the source and target documents are locked and cannot be
   * modified through any other means.
   *
   * @category Releases
   *
   * @param params - Release action parameters:
   *   - `releaseId` - The id of the release to publish.
   * @param options - Additional action options.
   * @returns An observable that resolves to the `transactionId`.
   */
  publish({ releaseId }: {
    releaseId: string;
  }, options?: BaseActionOptions): Observable<SingleActionResult>;
  /**
   * @public
   *
   * An archive action removes an active release. The documents that comprise the release
   * are deleted and therefore no longer queryable.
   *
   * While the documents remain in retention the last version can still be accessed using document history endpoint.
   *
   * @category Releases
   *
   * @param params - Release action parameters:
   *   - `releaseId` - The id of the release to archive.
   * @param options - Additional action options.
   * @returns An observable that resolves to the `transactionId`.
   */
  archive({ releaseId }: {
    releaseId: string;
  }, options?: BaseActionOptions): Observable<SingleActionResult>;
  /**
   * @public
   *
   * An unarchive action restores an archived release and all documents
   * with the content they had just prior to archiving.
   *
   * @category Releases
   *
   * @param params - Release action parameters:
   *   - `releaseId` - The id of the release to unarchive.
   * @param options - Additional action options.
   * @returns An observable that resolves to the `transactionId`.
   */
  unarchive({ releaseId }: {
    releaseId: string;
  }, options?: BaseActionOptions): Observable<SingleActionResult>;
  /**
   * @public
   *
   * A schedule action queues a release for publishing at the given future time.
   * The release is locked such that no documents in the release can be modified and
   * no documents that it references can be deleted as this would make the publish fail.
   * At the given time, the same logic as for the publish action is triggered.
   *
   * @category Releases
   *
   * @param params - Release action parameters:
   *   - `releaseId` - The id of the release to schedule.
   *   - `publishAt` - The serialised date and time to publish the release. If the `publishAt` is in the past, the release will be published immediately.
   * @param options - Additional action options.
   * @returns An observable that resolves to the `transactionId`.
   */
  schedule({ releaseId, publishAt }: {
    releaseId: string;
    publishAt: string;
  }, options?: BaseActionOptions): Observable<SingleActionResult>;
  /**
   * @public
   *
   * An unschedule action stops a release from being published.
   * The documents in the release are considered unlocked and can be edited again.
   * This may fail if another release is scheduled to be published after this one and
   * has a reference to a document created by this one.
   *
   * @category Releases
   *
   * @param params - Release action parameters:
   *   - `releaseId` - The id of the release to unschedule.
   * @param options - Additional action options.
   * @returns An observable that resolves to the `transactionId`.
   */
  unschedule({ releaseId }: {
    releaseId: string;
  }, options?: BaseActionOptions): Observable<SingleActionResult>;
  /**
   * @public
   *
   * A delete action removes a published or archived release.
   * The backing system document will be removed from the dataset.
   *
   * @category Releases
   *
   * @param params - Release action parameters:
   *   - `releaseId` - The id of the release to delete.
   * @param options - Additional action options.
   * @returns An observable that resolves to the `transactionId`.
   */
  delete({ releaseId }: {
    releaseId: string;
  }, options?: BaseActionOptions): Observable<SingleActionResult>;
  /**
   * @public
   *
   * Fetch the documents in a release by release id.
   *
   * @category Releases
   *
   * @param params - Release action parameters:
   *   - `releaseId` - The id of the release to fetch documents for.
   * @param options - Additional mutation options {@link BaseMutationOptions}.
   * @returns An observable that resolves to the documents in the release.
   */
  fetchDocuments({ releaseId }: {
    releaseId: string;
  }, options?: BaseMutationOptions): Observable<RawQueryResponse<SanityDocument[]>>;
}
/** @public */
declare class ReleasesClient {
  #private;
  constructor(client: SanityClient, httpRequest: HttpRequest);
  /**
   * @public
   *
   * Retrieve a release by id.
   *
   * @category Releases
   *
   * @param params - Release action parameters:
   *   - `releaseId` - The id of the release to retrieve.
   * @param options - Additional query options including abort signal and query tag.
   * @returns A promise that resolves to the release document {@link ReleaseDocument}.
   *
   * @example Retrieving a release by id
   * ```ts
   * const release = await client.releases.get({releaseId: 'my-release'})
   * console.log(release)
   * // {
   * //   _id: '_.releases.my-release',
   * //   name: 'my-release'
   * //   _type: 'system.release',
   * //   metadata: {releaseType: 'asap'},
   * //   _createdAt: '2021-01-01T00:00:00.000Z',
   * //   ...
   * // }
   * ```
   */
  get({ releaseId }: {
    releaseId: string;
  }, options?: {
    signal?: AbortSignal;
    tag?: string;
  }): Promise<ReleaseDocument | undefined>;
  /**
   * @public
   *
   * Creates a new release under the given id, with metadata.
   *
   * @remarks
   * * If no releaseId is provided, a release id will be generated.
   * * If no metadata is provided, then an `undecided` releaseType will be used.
   *
   * @category Releases
   *
   * @param params - Release action parameters:
   *   - `releaseId` - The id of the release to create.
   *   - `metadata` - The metadata to associate with the release {@link ReleaseDocument}.
   * @param options - Additional action options.
   * @returns A promise that resolves to the `transactionId` and the release id and metadata.
   *
   * @example Creating a release with a custom id and metadata
   * ```ts
   * const releaseId = 'my-release'
   * const releaseMetadata: ReleaseDocument['metadata'] = {
   *   releaseType: 'asap',
   * }
   *
   * const result =
   *   await client.releases.create({releaseId, metadata: releaseMetadata})
   * console.log(result)
   * // {
   * //   transactionId: 'transaction-id',
   * //   releaseId: 'my-release',
   * //   metadata: {releaseType: 'asap'},
   * // }
   * ```
   *
   * @example Creating a release with generated id and metadata
   * ```ts
   * const {metadata} = await client.releases.create()
   * console.log(metadata.releaseType) // 'undecided'
   * ```
   *
   * @example Creating a release with a custom transaction id
   * ```ts
   * const {transactionId, metadata} = await client.releases.create({transactionId: 'my-transaction-id'})
   * console.log(metadata.releaseType) // 'undecided'
   * console.log(transactionId) // 'my-transaction-id'
   * ```
   */
  create(options: BaseActionOptions): Promise<SingleActionResult & {
    releaseId: string;
    metadata: ReleaseDocument['metadata'];
  }>;
  create(release: {
    releaseId?: string;
    metadata?: Partial<ReleaseDocument['metadata']>;
  }, options?: BaseActionOptions): Promise<SingleActionResult & {
    releaseId: string;
    metadata: ReleaseDocument['metadata'];
  }>;
  /**
   * @public
   *
   * Edits an existing release, updating the metadata.
   *
   * @category Releases
   *
   * @param params - Release action parameters:
   *   - `releaseId` - The id of the release to edit.
   *   - `patch` - The patch operation to apply on the release metadata {@link PatchMutationOperation}.
   * @param options - Additional action options.
   * @returns A promise that resolves to the `transactionId`.
   */
  edit({ releaseId, patch }: {
    releaseId: string;
    patch: PatchOperations;
  }, options?: BaseActionOptions): Promise<SingleActionResult>;
  /**
   * @public
   *
   * Publishes all documents in a release at once. For larger releases the effect of the publish
   * will be visible immediately when querying but the removal of the `versions.<releasesId>.*`
   * documents and creation of the corresponding published documents with the new content may
   * take some time.
   *
   * During this period both the source and target documents are locked and cannot be
   * modified through any other means.
   *
   * @category Releases
   *
   * @param params - Release action parameters:
   *   - `releaseId` - The id of the release to publish.
   * @param options - Additional action options.
   * @returns A promise that resolves to the `transactionId`.
   */
  publish({ releaseId }: {
    releaseId: string;
  }, options?: BaseActionOptions): Promise<SingleActionResult>;
  /**
   * @public
   *
   * An archive action removes an active release. The documents that comprise the release
   * are deleted and therefore no longer queryable.
   *
   * While the documents remain in retention the last version can still be accessed using document history endpoint.
   *
   * @category Releases
   *
   * @param params - Release action parameters:
   *   - `releaseId` - The id of the release to archive.
   * @param options - Additional action options.
   * @returns A promise that resolves to the `transactionId`.
   */
  archive({ releaseId }: {
    releaseId: string;
  }, options?: BaseActionOptions): Promise<SingleActionResult>;
  /**
   * @public
   *
   * An unarchive action restores an archived release and all documents
   * with the content they had just prior to archiving.
   *
   * @category Releases
   *
   * @param params - Release action parameters:
   *   - `releaseId` - The id of the release to unarchive.
   * @param options - Additional action options.
   * @returns A promise that resolves to the `transactionId`.
   */
  unarchive({ releaseId }: {
    releaseId: string;
  }, options?: BaseActionOptions): Promise<SingleActionResult>;
  /**
   * @public
   *
   * A schedule action queues a release for publishing at the given future time.
   * The release is locked such that no documents in the release can be modified and
   * no documents that it references can be deleted as this would make the publish fail.
   * At the given time, the same logic as for the publish action is triggered.
   *
   * @category Releases
   *
   * @param params - Release action parameters:
   *   - `releaseId` - The id of the release to schedule.
   *   - `publishAt` - The serialised date and time to publish the release. If the `publishAt` is in the past, the release will be published immediately.
   * @param options - Additional action options.
   * @returns A promise that resolves to the `transactionId`.
   */
  schedule({ releaseId, publishAt }: {
    releaseId: string;
    publishAt: string;
  }, options?: BaseActionOptions): Promise<SingleActionResult>;
  /**
   * @public
   *
   * An unschedule action stops a release from being published.
   * The documents in the release are considered unlocked and can be edited again.
   * This may fail if another release is scheduled to be published after this one and
   * has a reference to a document created by this one.
   *
   * @category Releases
   *
   * @param params - Release action parameters:
   *   - `releaseId` - The id of the release to unschedule.
   * @param options - Additional action options.
   * @returns A promise that resolves to the `transactionId`.
   */
  unschedule({ releaseId }: {
    releaseId: string;
  }, options?: BaseActionOptions): Promise<SingleActionResult>;
  /**
   * @public
   *
   * A delete action removes a published or archived release.
   * The backing system document will be removed from the dataset.
   *
   * @category Releases
   *
   * @param params - Release action parameters:
   *   - `releaseId` - The id of the release to delete.
   * @param options - Additional action options.
   * @returns A promise that resolves to the `transactionId`.
   */
  delete({ releaseId }: {
    releaseId: string;
  }, options?: BaseActionOptions): Promise<SingleActionResult>;
  /**
   * @public
   *
   * Fetch the documents in a release by release id.
   *
   * @category Releases
   *
   * @param params - Release action parameters:
   *   - `releaseId` - The id of the release to fetch documents for.
   * @param options - Additional mutation options {@link BaseMutationOptions}.
   * @returns A promise that resolves to the documents in the release.
   */
  fetchDocuments({ releaseId }: {
    releaseId: string;
  }, options?: BaseMutationOptions): Promise<RawQueryResponse<SanityDocument[]>>;
}
/** @public */
declare class ObservableUsersClient {
  #private;
  constructor(client: ObservableSanityClient, httpRequest: HttpRequest);
  /**
   * Fetch a user by user ID
   *
   * @param id - User ID of the user to fetch. If `me` is provided, a minimal response including the users role is returned.
   */
  getById<T extends string>(id: T): Observable<T extends 'me' ? CurrentSanityUser : SanityUser>;
}
/** @public */
declare class UsersClient {
  #private;
  constructor(client: SanityClient, httpRequest: HttpRequest);
  /**
   * Fetch a user by user ID
   *
   * @param id - User ID of the user to fetch. If `me` is provided, a minimal response including the users role is returned.
   */
  getById<T extends string>(id: T): Promise<T extends 'me' ? CurrentSanityUser : SanityUser>;
}
/** @public */
declare class ObservableSanityClient {
  #private;
  assets: ObservableAssetsClient;
  datasets: ObservableDatasetsClient;
  live: LiveClient;
  mediaLibrary: {
    video: ObservableMediaLibraryVideoClient;
  };
  projects: ObservableProjectsClient;
  users: ObservableUsersClient;
  agent: {
    action: ObservableAgentsActionClient;
  };
  collaboration: {
    /** @alpha */
    comments: ObservableCollaborationCommentsClient;
  };
  functions: ObservableFunctionsClient;
  releases: ObservableReleasesClient;
  /** @beta */
  context: ObservableContextClient;
  /**
   * Instance properties
   */
  listen: typeof _listen;
  constructor(httpRequest: HttpRequest, config?: ClientConfig);
  /**
   * Clone the client - returns a new instance
   */
  clone(): ObservableSanityClient;
  /**
   * Returns the current client configuration
   */
  config(): InitializedClientConfig;
  /**
   * Reconfigure the client. Note that this _mutates_ the current client.
   */
  config(newConfig?: Partial<ClientConfig>): this;
  /**
   * Clone the client with a new (partial) configuration.
   *
   * @param newConfig - New client configuration properties, shallowly merged with existing configuration
   */
  withConfig(newConfig?: Partial<ClientConfig>): ObservableSanityClient;
  /**
   * Perform a GROQ-query against the configured dataset.
   *
   * @param query - GROQ-query to perform
   */
  fetch<R = Any, Q extends QueryWithoutParams = QueryWithoutParams, const G extends string = string>(query: G, params?: Q | QueryWithoutParams): Observable<ClientReturn<G, R>>;
  /**
   * Perform a GROQ-query against the configured dataset.
   *
   * @param query - GROQ-query to perform
   * @param params - Optional query parameters
   * @param options - Optional request options
   */
  fetch<R = Any, Q extends QueryWithoutParams | QueryParams = QueryParams, const G extends string = string>(query: G, params: Q extends QueryWithoutParams ? QueryWithoutParams : Q, options?: FilteredResponseQueryOptions): Observable<ClientReturn<G, R>>;
  /**
   * Perform a GROQ-query against the configured dataset.
   *
   * @param query - GROQ-query to perform
   * @param params - Optional query parameters
   * @param options - Request options
   */
  fetch<R = Any, Q extends QueryWithoutParams | QueryParams = QueryParams, const G extends string = string>(query: string, params: Q extends QueryWithoutParams ? QueryWithoutParams : Q, options: UnfilteredResponseQueryOptions): Observable<RawQueryResponse<ClientReturn<G, R>>>;
  /**
   * Perform a GROQ-query against the configured dataset.
   *
   * @param query - GROQ-query to perform
   * @param params - Optional query parameters
   * @param options - Request options
   */
  fetch<R = Any, Q extends QueryWithoutParams | QueryParams = QueryParams, const G extends string = string>(query: G, params: Q extends QueryWithoutParams ? QueryWithoutParams : Q, options: UnfilteredResponseWithoutQuery): Observable<RawQuerylessQueryResponse<ClientReturn<G, R>>>;
  /**
   * Fetch a single document with the given ID.
   *
   * @param id - Document ID to fetch
   * @param options - Request options
   */
  getDocument<R extends Record<string, Any> = Record<string, Any>>(id: string, options: {
    signal?: AbortSignal;
    tag?: string;
    releaseId?: string;
    includeAllVersions: true;
  }): Observable<SanityDocument<R>[]>;
  /**
   * Fetch a single document with the given ID.
   *
   * @param id - Document ID to fetch
   * @param options - Request options
   */
  getDocument<R extends Record<string, Any> = Record<string, Any>>(id: string, options?: {
    signal?: AbortSignal;
    tag?: string;
    releaseId?: string;
    includeAllVersions?: false;
  }): Observable<SanityDocument<R> | undefined>;
  /**
   * Fetch multiple documents in one request.
   * Should be used sparingly - performing a query is usually a better option.
   * The order/position of documents is preserved based on the original array of IDs.
   * If any of the documents are missing, they will be replaced by a `null` entry in the returned array
   *
   * @param ids - Document IDs to fetch
   * @param options - Request options
   */
  getDocuments<R extends Record<string, Any> = Record<string, Any>>(ids: string[], options?: {
    tag?: string;
  }): Observable<(SanityDocument<R> | null)[]>;
  /**
   * Convenient and bandwidth efficient method of checking wether a set of document IDs exists.
   * Returns a set of the IDs that exist.
   *
   * @param ids - Document IDs to check
   * @param options - Request options
   */
  documentsExists(ids: string[], options?: {
    signal?: AbortSignal;
    tag?: string;
  }): Observable<Set<string>>;
  /**
   * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.
   * Returns an observable that resolves to the created document.
   *
   * @param document - Document to create
   * @param options - Mutation options
   */
  create<R extends Record<string, Any> = Record<string, Any>>(document: SanityDocumentStub<R>, options: FirstDocumentMutationOptions): Observable<SanityDocument<R>>;
  /**
   * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.
   * Returns an observable that resolves to an array containing the created document.
   *
   * @param document - Document to create
   * @param options - Mutation options
   */
  create<R extends Record<string, Any> = Record<string, Any>>(document: SanityDocumentStub<R>, options: AllDocumentsMutationOptions): Observable<SanityDocument<R>[]>;
  /**
   * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.
   * Returns an observable that resolves to a mutation result object containing the ID of the created document.
   *
   * @param document - Document to create
   * @param options - Mutation options
   */
  create<R extends Record<string, Any> = Record<string, Any>>(document: SanityDocumentStub<R>, options: FirstDocumentIdMutationOptions): Observable<SingleMutationResult>;
  /**
   * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.
   * Returns an observable that resolves to a mutation result object containing the ID of the created document.
   *
   * @param document - Document to create
   * @param options - Mutation options
   */
  create<R extends Record<string, Any> = Record<string, Any>>(document: SanityDocumentStub<R>, options: AllDocumentIdsMutationOptions): Observable<MultipleMutationResult>;
  /**
   * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.
   * Returns an observable that resolves to the created document.
   *
   * @param document - Document to create
   * @param options - Mutation options
   */
  create<R extends Record<string, Any> = Record<string, Any>>(document: SanityDocumentStub<R>, options?: BaseMutationOptions): Observable<SanityDocument<R>>;
  /**
   * Create a document if no document with the same ID already exists.
   * Returns an observable that resolves to the created document.
   *
   * @param document - Document to create
   * @param options - Mutation options
   */
  createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(document: IdentifiedSanityDocumentStub<R>, options: FirstDocumentMutationOptions): Observable<SanityDocument<R>>;
  /**
   * Create a document if no document with the same ID already exists.
   * Returns an observable that resolves to an array containing the created document.
   *
   * @param document - Document to create
   * @param options - Mutation options
   */
  createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(document: IdentifiedSanityDocumentStub<R>, options: AllDocumentsMutationOptions): Observable<SanityDocument<R>[]>;
  /**
   * Create a document if no document with the same ID already exists.
   * Returns an observable that resolves to a mutation result object containing the ID of the created document.
   *
   * @param document - Document to create
   * @param options - Mutation options
   */
  createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(document: IdentifiedSanityDocumentStub<R>, options: FirstDocumentIdMutationOptions): Observable<SingleMutationResult>;
  /**
   * Create a document if no document with the same ID already exists.
   * Returns an observable that resolves to a mutation result object containing the ID of the created document.
   *
   * @param document - Document to create
   * @param options - Mutation options
   */
  createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(document: IdentifiedSanityDocumentStub<R>, options: AllDocumentIdsMutationOptions): Observable<MultipleMutationResult>;
  /**
   * Create a document if no document with the same ID already exists.
   * Returns an observable that resolves to the created document.
   *
   * @param document - Document to create
   * @param options - Mutation options
   */
  createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(document: IdentifiedSanityDocumentStub<R>, options?: BaseMutationOptions): Observable<SanityDocument<R>>;
  /**
   * Create a document if it does not exist, or replace a document with the same document ID
   * Returns an observable that resolves to the created document.
   *
   * @param document - Document to either create or replace
   * @param options - Mutation options
   */
  createOrReplace<R extends Record<string, Any> = Record<string, Any>>(document: IdentifiedSanityDocumentStub<R>, options: FirstDocumentMutationOptions): Observable<SanityDocument<R>>;
  /**
   * Create a document if it does not exist, or replace a document with the same document ID
   * Returns an observable that resolves to an array containing the created document.
   *
   * @param document - Document to either create or replace
   * @param options - Mutation options
   */
  createOrReplace<R extends Record<string, Any> = Record<string, Any>>(document: IdentifiedSanityDocumentStub<R>, options: AllDocumentsMutationOptions): Observable<SanityDocument<R>[]>;
  /**
   * Create a document if it does not exist, or replace a document with the same document ID
   * Returns an observable that resolves to a mutation result object containing the ID of the created document.
   *
   * @param document - Document to either create or replace
   * @param options - Mutation options
   */
  createOrReplace<R extends Record<string, Any> = Record<string, Any>>(document: IdentifiedSanityDocumentStub<R>, options: FirstDocumentIdMutationOptions): Observable<SingleMutationResult>;
  /**
   * Create a document if it does not exist, or replace a document with the same document ID
   * Returns an observable that resolves to a mutation result object containing the created document ID.
   *
   * @param document - Document to either create or replace
   * @param options - Mutation options
   */
  createOrReplace<R extends Record<string, Any> = Record<string, Any>>(document: IdentifiedSanityDocumentStub<R>, options: AllDocumentIdsMutationOptions): Observable<MultipleMutationResult>;
  /**
   * Create a document if it does not exist, or replace a document with the same document ID
   * Returns an observable that resolves to the created document.
   *
   * @param document - Document to either create or replace
   * @param options - Mutation options
   */
  createOrReplace<R extends Record<string, Any> = Record<string, Any>>(document: IdentifiedSanityDocumentStub<R>, options?: BaseMutationOptions): Observable<SanityDocument<R>>;
  /**
   * @public
   *
   * Creates a new version of a published document.
   *
   * @remarks
   * * Requires a document with a `_type` property.
   * * Creating a version with no `releaseId` will create a new draft version of the published document.
   * * If the `document._id` is defined, it should be a draft or release version ID that matches the version ID generated from `publishedId` and `releaseId`.
   * * If the `document._id` is not defined, it will be generated from `publishedId` and `releaseId`.
   * * To create a version of an unpublished document, use the `client.create` method.
   *
   * @category Versions
   *
   * @param params - Version action parameters:
   *   - `document` - The document to create as a new version (must include `_type`).
   *   - `publishedId` - The ID of the published document being versioned.
   *   - `releaseId` - The ID of the release to create the version for.
   * @param options - Additional action options.
   * @returns an observable that resolves to the `transactionId`.
   *
   * @example Creating a new version of a published document with a generated version ID
   * ```ts
   * client.observable.createVersion({
   *   // The document does not need to include an `_id` property since it will be generated from `publishedId` and `releaseId`
   *   document: {_type: 'myDocument', title: 'My Document'},
   *   publishedId: 'myDocument',
   *   releaseId: 'myRelease',
   * })
   *
   * // The following document will be created:
   * // {
   * //   _id: 'versions.myRelease.myDocument',
   * //   _type: 'myDocument',
   * //   title: 'My Document',
   * // }
   * ```
   *
   * @example Creating a new version of a published document with a specified version ID
   * ```ts
   * client.observable.createVersion({
   *   document: {_type: 'myDocument', _id: 'versions.myRelease.myDocument', title: 'My Document'},
   *   // `publishedId` and `releaseId` are not required since `document._id` has been specified
   * })
   *
   * // The following document will be created:
   * // {
   * //   _id: 'versions.myRelease.myDocument',
   * //   _type: 'myDocument',
   * //   title: 'My Document',
   * // }
   * ```
   *
   * @example Creating a new draft version of a published document
   * ```ts
   * client.observable.createVersion({
   *   document: {_type: 'myDocument', title: 'My Document'},
   *   publishedId: 'myDocument',
   * })
   *
   * // The following document will be created:
   * // {
   * //   _id: 'drafts.myDocument',
   * //   _type: 'myDocument',
   * //   title: 'My Document',
   * // }
   * ```
   */
  createVersion<R extends Record<string, Any>>(args: {
    document: SanityDocumentStub<R>;
    publishedId: string;
    releaseId?: string;
  }, options?: BaseActionOptions): Observable<SingleActionResult | MultipleActionResult>;
  createVersion<R extends Record<string, Any>>(args: {
    document: IdentifiedSanityDocumentStub<R>;
    publishedId?: string;
    releaseId?: string;
  }, options?: BaseActionOptions): Observable<SingleActionResult | MultipleActionResult>;
  createVersion(args: {
    baseId: string;
    releaseId?: string;
    publishedId: string;
    ifBaseRevisionId?: string;
  }, options?: BaseActionOptions): Observable<SingleActionResult | MultipleActionResult>;
  /**
   * Deletes a document with the given document ID.
   * Returns an observable that resolves to the deleted document.
   *
   * @param id - Document ID to delete
   * @param options - Options for the mutation
   */
  delete<R extends Record<string, Any> = Record<string, Any>>(id: string, options: FirstDocumentMutationOptions): Observable<SanityDocument<R>>;
  /**
   * Deletes a document with the given document ID.
   * Returns an observable that resolves to an array containing the deleted document.
   *
   * @param id - Document ID to delete
   * @param options - Options for the mutation
   */
  delete<R extends Record<string, Any> = Record<string, Any>>(id: string, options: AllDocumentsMutationOptions): Observable<SanityDocument<R>[]>;
  /**
   * Deletes a document with the given document ID.
   * Returns an observable that resolves to a mutation result object containing the deleted document ID.
   *
   * @param id - Document ID to delete
   * @param options - Options for the mutation
   */
  delete(id: string, options: FirstDocumentIdMutationOptions): Observable<SingleMutationResult>;
  /**
   * Deletes a document with the given document ID.
   * Returns an observable that resolves to a mutation result object containing the deleted document ID.
   *
   * @param id - Document ID to delete
   * @param options - Options for the mutation
   */
  delete(id: string, options: AllDocumentIdsMutationOptions): Observable<MultipleMutationResult>;
  /**
   * Deletes a document with the given document ID.
   * Returns an observable that resolves to a mutation result object containing the deleted document ID.
   *
   * @param id - Document ID to delete
   * @param options - Options for the mutation
   */
  delete(id: string, options?: BaseMutationOptions): Observable<MultipleMutationResult>;
  /**
   * Deletes one or more documents matching the given query or document ID.
   * Returns an observable that resolves to first deleted document.
   *
   * @param selection - An object with either an `id` or `query` key defining what to delete
   * @param options - Options for the mutation
   */
  delete<R extends Record<string, Any> = Record<string, Any>>(selection: MutationSelection, options: FirstDocumentMutationOptions): Observable<SanityDocument<R>>;
  /**
   * Deletes one or more documents matching the given query or document ID.
   * Returns an observable that resolves to an array containing the deleted documents.
   *
   * @param selection - An object with either an `id` or `query` key defining what to delete
   * @param options - Options for the mutation
   */
  delete<R extends Record<string, Any> = Record<string, Any>>(selection: MutationSelection, options: AllDocumentsMutationOptions): Observable<SanityDocument<R>[]>;
  /**
   * Deletes one or more documents matching the given query or document ID.
   * Returns an observable that resolves to a mutation result object containing the ID of the first deleted document.
   *
   * @param selection - An object with either an `id` or `query` key defining what to delete
   * @param options - Options for the mutation
   */
  delete(selection: MutationSelection, options: FirstDocumentIdMutationOptions): Observable<SingleMutationResult>;
  /**
   * Deletes one or more documents matching the given query or document ID.
   * Returns an observable that resolves to a mutation result object containing the document IDs that were deleted.
   *
   * @param selection - An object with either an `id` or `query` key defining what to delete
   * @param options - Options for the mutation
   */
  delete(selection: MutationSelection, options: AllDocumentIdsMutationOptions): Observable<MultipleMutationResult>;
  /**
   * Deletes one or more documents matching the given query or document ID.
   * Returns an observable that resolves to a mutation result object containing the document IDs that were deleted.
   *
   * @param selection - An object with either an `id` or `query` key defining what to delete
   * @param options - Options for the mutation
   */
  delete(selection: MutationSelection, options?: BaseMutationOptions): Observable<MultipleMutationResult>;
  /**
   * @public
   *
   * Deletes the draft or release version of a document.
   *
   * @remarks
   * * Discarding a version with no `releaseId` will discard the draft version of the published document.
   * * If the draft or release version does not exist, any error will throw.
   *
   * @param params - Version action parameters:
   *   - `releaseId` - The ID of the release to discard the document from.
   *   - `publishedId` - The published ID of the document to discard.
   * @param purge - if `true` the document history is also discarded.
   * @param options - Additional action options.
   * @returns an observable that resolves to the `transactionId`.
   *
   * @example Discarding a release version of a document
   * ```ts
   * client.observable.discardVersion({publishedId: 'myDocument', releaseId: 'myRelease'})
   * // The document with the ID `versions.myRelease.myDocument` will be discarded.
   * ```
   *
   * @example Discarding a draft version of a document
   * ```ts
   * client.observable.discardVersion({publishedId: 'myDocument'})
   * // The document with the ID `drafts.myDocument` will be discarded.
   * ```
   */
  discardVersion({ releaseId, publishedId }: {
    releaseId?: string;
    publishedId: string;
  }, purge?: boolean, options?: BaseActionOptions): Observable<SingleActionResult | MultipleActionResult>;
  /**
   * @public
   *
   * Replaces an existing version document.
   *
   * @remarks
   * * Requires a document with a `_type` property.
   * * If the `document._id` is defined, it should be a draft or release version ID that matches the version ID generated from `publishedId` and `releaseId`.
   * * If the `document._id` is not defined, it will be generated from `publishedId` and `releaseId`.
   * * Replacing a version with no `releaseId` will replace the draft version of the published document.
   * * At least one of the **version** or **published** documents must exist.
   *
   * @param params - Version action parameters:
   *   - `document` - The new document to replace the version with.
   *   - `releaseId` - The ID of the release where the document version is replaced.
   *   - `publishedId` - The ID of the published document to replace.
   * @param options - Additional action options.
   * @returns an observable that resolves to the `transactionId`.
   *
   * @example Replacing a release version of a published document with a generated version ID
   * ```ts
   * client.observable.replaceVersion({
   *   document: {_type: 'myDocument', title: 'My Document'},
   *   publishedId: 'myDocument',
   *   releaseId: 'myRelease',
   * })
   *
   * // The following document will be patched:
   * // {
   * //   _id: 'versions.myRelease.myDocument',
   * //   _type: 'myDocument',
   * //   title: 'My Document',
   * // }
   * ```
   *
   * @example Replacing a release version of a published document with a specified version ID
   * ```ts
   * client.observable.replaceVersion({
   *   document: {_type: 'myDocument', _id: 'versions.myRelease.myDocument', title: 'My Document'},
   *   // `publishedId` and `releaseId` are not required since `document._id` has been specified
   * })
   *
   * // The following document will be patched:
   * // {
   * //   _id: 'versions.myRelease.myDocument',
   * //   _type: 'myDocument',
   * //   title: 'My Document',
   * // }
   * ```
   *
   * @example Replacing a draft version of a published document
   * ```ts
   * client.observable.replaceVersion({
   *   document: {_type: 'myDocument', title: 'My Document'},
   *   publishedId: 'myDocument',
   * })
   *
   * // The following document will be patched:
   * // {
   * //   _id: 'drafts.myDocument',
   * //   _type: 'myDocument',
   * //   title: 'My Document',
   * // }
   * ```
   */
  replaceVersion<R extends Record<string, Any>>(args: {
    document: SanityDocumentStub<R>;
    publishedId: string;
    releaseId?: string;
  }, options?: BaseActionOptions): Observable<SingleActionResult | MultipleActionResult>;
  replaceVersion<R extends Record<string, Any>>(args: {
    document: IdentifiedSanityDocumentStub<R>;
    publishedId?: string;
    releaseId?: string;
  }, options?: BaseActionOptions): Observable<SingleActionResult | MultipleActionResult>;
  /**
   * @public
   *
   * Used to indicate when a document within a release should be unpublished when
   * the release is run.
   *
   * @remarks
   * * If the published document does not exist, an error will be thrown.
   *
   * @param params - Version action parameters:
   *   - `releaseId` - The ID of the release to unpublish the document from.
   *   - `publishedId` - The published ID of the document to unpublish.
   * @param options - Additional action options.
   * @returns an observable that resolves to the `transactionId`.
   *
   * @example Unpublishing a release version of a published document
   * ```ts
   * client.observable.unpublishVersion({publishedId: 'myDocument', releaseId: 'myRelease'})
   * // The document with the ID `versions.myRelease.myDocument` will be unpublished. when `myRelease` is run.
   * ```
   */
  unpublishVersion({ releaseId, publishedId }: {
    releaseId: string;
    publishedId: string;
  }, options?: BaseActionOptions): Observable<SingleActionResult | MultipleActionResult>;
  /**
   * Perform mutation operations against the configured dataset
   * Returns an observable that resolves to the first mutated document.
   *
   * @param operations - Mutation operations to execute
   * @param options - Mutation options
   */
  mutate<R extends Record<string, Any> = Record<string, Any>>(operations: Mutation<R>[] | ObservablePatch | ObservableTransaction, options: FirstDocumentMutationOptions): Observable<SanityDocument<R>>;
  /**
   * Perform mutation operations against the configured dataset.
   * Returns an observable that resolves to an array of the mutated documents.
   *
   * @param operations - Mutation operations to execute
   * @param options - Mutation options
   */
  mutate<R extends Record<string, Any> = Record<string, Any>>(operations: Mutation<R>[] | ObservablePatch | ObservableTransaction, options: AllDocumentsMutationOptions): Observable<SanityDocument<R>[]>;
  /**
   * Perform mutation operations against the configured dataset
   * Returns an observable that resolves to a mutation result object containing the document ID of the first mutated document.
   *
   * @param operations - Mutation operations to execute
   * @param options - Mutation options
   */
  mutate<R extends Record<string, Any> = Record<string, Any>>(operations: Mutation<R>[] | ObservablePatch | ObservableTransaction, options: FirstDocumentIdMutationOptions): Observable<SingleMutationResult>;
  /**
   * Perform mutation operations against the configured dataset
   * Returns an observable that resolves to a mutation result object containing the mutated document IDs.
   *
   * @param operations - Mutation operations to execute
   * @param options - Mutation options
   */
  mutate<R extends Record<string, Any> = Record<string, Any>>(operations: Mutation<R>[] | ObservablePatch | ObservableTransaction, options: AllDocumentIdsMutationOptions): Observable<MultipleMutationResult>;
  /**
   * Perform mutation operations against the configured dataset
   * Returns an observable that resolves to a mutation result object containing the mutated document IDs.
   *
   * @param operations - Mutation operations to execute
   * @param options - Mutation options
   */
  mutate<R extends Record<string, Any> = Record<string, Any>>(operations: Mutation<R>[] | ObservablePatch | ObservableTransaction, options?: BaseMutationOptions): Observable<MultipleMutationResult>;
  /**
   * Create a new buildable patch of operations to perform
   *
   * @param documentId - Document ID to patch
   * @param operations - Optional object of patch operations to initialize the patch instance with
   * @returns Patch instance - call `.commit()` to perform the operations defined
   */
  patch(documentId: string, operations?: PatchOperations): ObservablePatch;
  /**
   * Create a new buildable patch of operations to perform
   *
   * @param documentIds - Array of document IDs to patch
   * @param operations - Optional object of patch operations to initialize the patch instance with
   * @returns Patch instance - call `.commit()` to perform the operations defined
   */
  patch(documentIds: string[], operations?: PatchOperations): ObservablePatch;
  /**
   * Create a new buildable patch of operations to perform
   *
   * @param selection - An object with `query` and optional `params`, defining which document(s) to patch
   * @param operations - Optional object of patch operations to initialize the patch instance with
   * @returns Patch instance - call `.commit()` to perform the operations defined
   */
  patch(selection: MutationSelection, operations?: PatchOperations): ObservablePatch;
  /**
   * Create a new transaction of mutations
   *
   * @param operations - Optional array of mutation operations to initialize the transaction instance with
   */
  transaction<R extends Record<string, Any> = Record<string, Any>>(operations?: Mutation<R>[]): ObservableTransaction;
  /**
   * Perform action operations against the configured dataset
   *
   * @param operations - Action operation(s) to execute
   * @param options - Action options
   */
  action(operations: Action | Action[], options?: BaseActionOptions): Observable<SingleActionResult | MultipleActionResult>;
  /**
   * Perform an HTTP request against the Sanity API
   *
   * @param options - Request options
   */
  request<R = Any>(options: RawRequestOptions): Observable<R>;
  /**
   * Get a Sanity API URL for the URI provided
   *
   * @param uri - URI/path to build URL for
   * @param canUseCdn - Whether or not to allow using the API CDN for this route
   */
  getUrl(uri: string, canUseCdn?: boolean): string;
  /**
   * Get a Sanity API URL for the data operation and path provided
   *
   * @param operation - Data operation (eg `query`, `mutate`, `listen` or similar)
   * @param path - Path to append after the operation
   */
  getDataUrl(operation: string, path?: string): string;
}
/** @public */
declare class SanityClient {
  #private;
  assets: AssetsClient;
  datasets: DatasetsClient;
  live: LiveClient;
  mediaLibrary: {
    video: MediaLibraryVideoClient;
  };
  projects: ProjectsClient;
  users: UsersClient;
  agent: {
    action: AgentActionsClient;
  };
  collaboration: {
    /** @alpha */
    comments: CollaborationCommentsClient;
  };
  functions: FunctionsClient;
  releases: ReleasesClient;
  /** @beta */
  context: ContextClient;
  /**
   * Observable version of the Sanity client, with the same configuration as the promise-based one
   */
  observable: ObservableSanityClient;
  /**
   * Instance properties
   */
  listen: typeof _listen;
  constructor(httpRequest: HttpRequest, config?: ClientConfig);
  /**
   * Clone the client - returns a new instance
   */
  clone(): SanityClient;
  /**
   * Returns the current client configuration
   */
  config(): InitializedClientConfig;
  /**
   * Reconfigure the client. Note that this _mutates_ the current client.
   */
  config(newConfig?: Partial<ClientConfig>): this;
  /**
   * Clone the client with a new (partial) configuration.
   *
   * @param newConfig - New client configuration properties, shallowly merged with existing configuration
   */
  withConfig(newConfig?: Partial<ClientConfig>): SanityClient;
  /**
   * Perform a GROQ-query against the configured dataset.
   *
   * @param query - GROQ-query to perform
   */
  fetch<R = Any, Q extends QueryWithoutParams = QueryWithoutParams, const G extends string = string>(query: G, params?: Q | QueryWithoutParams): Promise<ClientReturn<G, R>>;
  /**
   * Perform a GROQ-query against the configured dataset.
   *
   * @param query - GROQ-query to perform
   * @param params - Optional query parameters
   * @param options - Optional request options
   */
  fetch<R = Any, Q extends QueryWithoutParams | QueryParams = QueryParams, const G extends string = string>(query: G, params: Q extends QueryWithoutParams ? QueryWithoutParams : Q, options?: FilteredResponseQueryOptions): Promise<ClientReturn<G, R>>;
  /**
   * Perform a GROQ-query against the configured dataset.
   *
   * @param query - GROQ-query to perform
   * @param params - Optional query parameters
   * @param options - Request options
   */
  fetch<R = Any, Q extends QueryWithoutParams | QueryParams = QueryParams, const G extends string = string>(query: G, params: Q extends QueryWithoutParams ? QueryWithoutParams : Q, options: UnfilteredResponseQueryOptions): Promise<RawQueryResponse<ClientReturn<G, R>>>;
  /**
   * Perform a GROQ-query against the configured dataset.
   *
   * @param query - GROQ-query to perform
   * @param params - Optional query parameters
   * @param options - Request options
   */
  fetch<R = Any, Q extends QueryWithoutParams | QueryParams = QueryParams, const G extends string = string>(query: G, params: Q extends QueryWithoutParams ? QueryWithoutParams : Q, options: UnfilteredResponseWithoutQuery): Promise<RawQuerylessQueryResponse<ClientReturn<G, R>>>;
  /**
   * Fetch a single document with the given ID.
   *
   * @param id - Document ID to fetch
   * @param options - Request options
   */
  getDocument<R extends Record<string, Any> = Record<string, Any>>(id: string, options: {
    signal?: AbortSignal;
    tag?: string;
    releaseId?: string;
    includeAllVersions: true;
  }): Promise<SanityDocument<R>[]>;
  /**
   * Fetch a single document with the given ID.
   *
   * @param id - Document ID to fetch
   * @param options - Request options
   */
  getDocument<R extends Record<string, Any> = Record<string, Any>>(id: string, options?: {
    signal?: AbortSignal;
    tag?: string;
    releaseId?: string;
    includeAllVersions?: false;
  }): Promise<SanityDocument<R> | undefined>;
  /**
   * Fetch multiple documents in one request.
   * Should be used sparingly - performing a query is usually a better option.
   * The order/position of documents is preserved based on the original array of IDs.
   * If any of the documents are missing, they will be replaced by a `null` entry in the returned array
   *
   * @param ids - Document IDs to fetch
   * @param options - Request options
   */
  getDocuments<R extends Record<string, Any> = Record<string, Any>>(ids: string[], options?: {
    signal?: AbortSignal;
    tag?: string;
  }): Promise<(SanityDocument<R> | null)[]>;
  /**
   * Convenient and bandwidth efficient method of checking wether a set of document IDs exists.
   * Returns a set of the IDs that exist.
   *
   * @param ids - Document IDs to check
   * @param options - Request options
   */
  documentsExists(ids: string[], options?: {
    signal?: AbortSignal;
    tag?: string;
  }): Promise<Set<string>>;
  /**
   * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.
   * Returns a promise that resolves to the created document.
   *
   * @param document - Document to create
   * @param options - Mutation options
   */
  create<R extends Record<string, Any> = Record<string, Any>>(document: SanityDocumentStub<R>, options: FirstDocumentMutationOptions): Promise<SanityDocument<R>>;
  /**
   * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.
   * Returns a promise that resolves to an array containing the created document.
   *
   * @param document - Document to create
   * @param options - Mutation options
   */
  create<R extends Record<string, Any> = Record<string, Any>>(document: SanityDocumentStub<R>, options: AllDocumentsMutationOptions): Promise<SanityDocument<R>[]>;
  /**
   * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.
   * Returns a promise that resolves to a mutation result object containing the ID of the created document.
   *
   * @param document - Document to create
   * @param options - Mutation options
   */
  create<R extends Record<string, Any> = Record<string, Any>>(document: SanityDocumentStub<R>, options: FirstDocumentIdMutationOptions): Promise<SingleMutationResult>;
  /**
   * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.
   * Returns a promise that resolves to a mutation result object containing the ID of the created document.
   *
   * @param document - Document to create
   * @param options - Mutation options
   */
  create<R extends Record<string, Any> = Record<string, Any>>(document: SanityDocumentStub<R>, options: AllDocumentIdsMutationOptions): Promise<MultipleMutationResult>;
  /**
   * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.
   * Returns a promise that resolves to the created document.
   *
   * @param document - Document to create
   * @param options - Mutation options
   */
  create<R extends Record<string, Any> = Record<string, Any>>(document: SanityDocumentStub<R>, options?: BaseMutationOptions): Promise<SanityDocument<R>>;
  /**
   * Create a document if no document with the same ID already exists.
   * Returns a promise that resolves to the created document.
   *
   * @param document - Document to create
   * @param options - Mutation options
   */
  createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(document: IdentifiedSanityDocumentStub<R>, options: FirstDocumentMutationOptions): Promise<SanityDocument<R>>;
  /**
   * Create a document if no document with the same ID already exists.
   * Returns a promise that resolves to an array containing the created document.
   *
   * @param document - Document to create
   * @param options - Mutation options
   */
  createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(document: IdentifiedSanityDocumentStub<R>, options: AllDocumentsMutationOptions): Promise<SanityDocument<R>[]>;
  /**
   * Create a document if no document with the same ID already exists.
   * Returns a promise that resolves to a mutation result object containing the ID of the created document.
   *
   * @param document - Document to create
   * @param options - Mutation options
   */
  createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(document: IdentifiedSanityDocumentStub<R>, options: FirstDocumentIdMutationOptions): Promise<SingleMutationResult>;
  /**
   * Create a document if no document with the same ID already exists.
   * Returns a promise that resolves to a mutation result object containing the ID of the created document.
   *
   * @param document - Document to create
   * @param options - Mutation options
   */
  createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(document: IdentifiedSanityDocumentStub<R>, options: AllDocumentIdsMutationOptions): Promise<MultipleMutationResult>;
  /**
   * Create a document if no document with the same ID already exists.
   * Returns a promise that resolves to the created document.
   *
   * @param document - Document to create
   * @param options - Mutation options
   */
  createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(document: IdentifiedSanityDocumentStub<R>, options?: BaseMutationOptions): Promise<SanityDocument<R>>;
  /**
   * Create a document if it does not exist, or replace a document with the same document ID
   * Returns a promise that resolves to the created document.
   *
   * @param document - Document to either create or replace
   * @param options - Mutation options
   */
  createOrReplace<R extends Record<string, Any> = Record<string, Any>>(document: IdentifiedSanityDocumentStub<R>, options: FirstDocumentMutationOptions): Promise<SanityDocument<R>>;
  /**
   * Create a document if it does not exist, or replace a document with the same document ID
   * Returns a promise that resolves to an array containing the created document.
   *
   * @param document - Document to either create or replace
   * @param options - Mutation options
   */
  createOrReplace<R extends Record<string, Any> = Record<string, Any>>(document: IdentifiedSanityDocumentStub<R>, options: AllDocumentsMutationOptions): Promise<SanityDocument<R>[]>;
  /**
   * Create a document if it does not exist, or replace a document with the same document ID
   * Returns a promise that resolves to a mutation result object containing the ID of the created document.
   *
   * @param document - Document to either create or replace
   * @param options - Mutation options
   */
  createOrReplace<R extends Record<string, Any> = Record<string, Any>>(document: IdentifiedSanityDocumentStub<R>, options: FirstDocumentIdMutationOptions): Promise<SingleMutationResult>;
  /**
   * Create a document if it does not exist, or replace a document with the same document ID
   * Returns a promise that resolves to a mutation result object containing the created document ID.
   *
   * @param document - Document to either create or replace
   * @param options - Mutation options
   */
  createOrReplace<R extends Record<string, Any> = Record<string, Any>>(document: IdentifiedSanityDocumentStub<R>, options: AllDocumentIdsMutationOptions): Promise<MultipleMutationResult>;
  /**
   * Create a document if it does not exist, or replace a document with the same document ID
   * Returns a promise that resolves to the created document.
   *
   * @param document - Document to either create or replace
   * @param options - Mutation options
   */
  createOrReplace<R extends Record<string, Any> = Record<string, Any>>(document: IdentifiedSanityDocumentStub<R>, options?: BaseMutationOptions): Promise<SanityDocument<R>>;
  /**
   * @public
   *
   * Creates a new version of a published document.
   *
   * @remarks
   * * The preferred approach is to use `baseId` to refer to the existing published document, but it is also possible to provide a complete `document` instead.
   * * If `document` is provided, it must have a `_type` property.
   * * Creating a version with no `releaseId` will create a new draft version of the published document.
   * * If the `document._id` is defined, it should be a draft or release version ID that matches the version ID generated from `publishedId` and `releaseId`.
   * * If the `document._id` is not defined, it will be generated from `publishedId` and `releaseId`.
   * * To create a version of an unpublished document, use the `client.create` method.
   *
   * @category Versions
   *
   * @param params - Version action parameters:
   *   - `baseId` - The ID of the published document from which to create a new version from.
   *   - `ifBaseRevisionId` - If `baseId` is provided, this ensures the `baseId`'s revision Id is as expected before creating the new version from it.
   *   - `document` - The document to create as a new version (must include `_type`).
   *   - `publishedId` - The ID of the published document being versioned.
   *   - `releaseId` - The ID of the release to create the version for.
   * @param options - Additional action options.
   * @returns A promise that resolves to the `transactionId`.
   *
   * @example Creating a new version of a published document
   * ```ts
   * const transactionId = await client.createVersion({
   *   baseId: 'myDocument',
   *   publishedId: 'myDocument',
   *   releaseId: 'myRelease',
   * })
   *
   * // The following document will be created:
   * // {
   * //   _id: 'versions.myRelease.myDocument',
   * //   _type: 'myDocument',
   * //   title: 'My Document',
   * // }
   * ```
   *
   *
   * @example Creating a new draft version of a published document
   * ```ts
   * const transactionId = await client.createVersion({
   *   baseId: 'myDocument',
   *   publishedId: 'myDocument',
   * })
   *
   * // The following document will be created:
   * // {
   * //   _id: 'drafts.myDocument',
   * //   _type: 'myDocument',
   * //   title: 'My Document',
   * // }
   * ```
   */
  createVersion<R extends Record<string, Any>>(args: {
    document: SanityDocumentStub<R>;
    publishedId: string;
    releaseId?: string;
  }, options?: BaseActionOptions): Promise<SingleActionResult | MultipleActionResult>;
  createVersion<R extends Record<string, Any>>(args: {
    document: IdentifiedSanityDocumentStub<R>;
    publishedId?: string;
    releaseId?: string;
  }, options?: BaseActionOptions): Promise<SingleActionResult | MultipleActionResult>;
  createVersion(args: {
    publishedId: string;
    baseId: string;
    releaseId?: string;
    ifBaseRevisionId?: string;
  }, options?: BaseActionOptions): Promise<SingleActionResult | MultipleActionResult>;
  /**
   * Deletes a document with the given document ID.
   * Returns a promise that resolves to the deleted document.
   *
   * @param id - Document ID to delete
   * @param options - Options for the mutation
   */
  delete<R extends Record<string, Any> = Record<string, Any>>(id: string, options: FirstDocumentMutationOptions): Promise<SanityDocument<R>>;
  /**
   * Deletes a document with the given document ID.
   * Returns a promise that resolves to an array containing the deleted document.
   *
   * @param id - Document ID to delete
   * @param options - Options for the mutation
   */
  delete<R extends Record<string, Any> = Record<string, Any>>(id: string, options: AllDocumentsMutationOptions): Promise<SanityDocument<R>[]>;
  /**
   * Deletes a document with the given document ID.
   * Returns a promise that resolves to a mutation result object containing the deleted document ID.
   *
   * @param id - Document ID to delete
   * @param options - Options for the mutation
   */
  delete(id: string, options: FirstDocumentIdMutationOptions): Promise<SingleMutationResult>;
  /**
   * Deletes a document with the given document ID.
   * Returns a promise that resolves to a mutation result object containing the deleted document ID.
   *
   * @param id - Document ID to delete
   * @param options - Options for the mutation
   */
  delete(id: string, options: AllDocumentIdsMutationOptions): Promise<MultipleMutationResult>;
  /**
   * Deletes a document with the given document ID.
   * Returns a promise that resolves to a mutation result object containing the deleted document ID.
   *
   * @param id - Document ID to delete
   * @param options - Options for the mutation
   */
  delete(id: string, options?: BaseMutationOptions): Promise<MultipleMutationResult>;
  /**
   * Deletes one or more documents matching the given query or document ID.
   * Returns a promise that resolves to first deleted document.
   *
   * @param selection - An object with either an `id` or `query` key defining what to delete
   * @param options - Options for the mutation
   */
  delete<R extends Record<string, Any> = Record<string, Any>>(selection: MutationSelection, options: FirstDocumentMutationOptions): Promise<SanityDocument<R>>;
  /**
   * Deletes one or more documents matching the given query or document ID.
   * Returns a promise that resolves to an array containing the deleted documents.
   *
   * @param selection - An object with either an `id` or `query` key defining what to delete
   * @param options - Options for the mutation
   */
  delete<R extends Record<string, Any> = Record<string, Any>>(selection: MutationSelection, options: AllDocumentsMutationOptions): Promise<SanityDocument<R>[]>;
  /**
   * Deletes one or more documents matching the given query or document ID.
   * Returns a promise that resolves to a mutation result object containing the ID of the first deleted document.
   *
   * @param selection - An object with either an `id` or `query` key defining what to delete
   * @param options - Options for the mutation
   */
  delete(selection: MutationSelection, options: FirstDocumentIdMutationOptions): Promise<SingleMutationResult>;
  /**
   * Deletes one or more documents matching the given query or document ID.
   * Returns a promise that resolves to a mutation result object containing the document IDs that were deleted.
   *
   * @param selection - An object with either an `id` or `query` key defining what to delete
   * @param options - Options for the mutation
   */
  delete(selection: MutationSelection, options: AllDocumentIdsMutationOptions): Promise<MultipleMutationResult>;
  /**
   * Deletes one or more documents matching the given query or document ID.
   * Returns a promise that resolves to a mutation result object containing the document IDs that were deleted.
   *
   * @param selection - An object with either an `id` or `query` key defining what to delete
   * @param options - Options for the mutation
   */
  delete(selection: MutationSelection, options?: BaseMutationOptions): Promise<MultipleMutationResult>;
  /**
   * @public
   *
   * Deletes the draft or release version of a document.
   *
   * @remarks
   * * Discarding a version with no `releaseId` will discard the draft version of the published document.
   * * If the draft or release version does not exist, any error will throw.
   *
   * @param params - Version action parameters:
   *   - `releaseId` - The ID of the release to discard the document from.
   *   - `publishedId` - The published ID of the document to discard.
   * @param purge - if `true` the document history is also discarded.
   * @param options - Additional action options.
   * @returns a promise that resolves to the `transactionId`.
   *
   * @example Discarding a release version of a document
   * ```ts
   * client.discardVersion({publishedId: 'myDocument', releaseId: 'myRelease'})
   * // The document with the ID `versions.myRelease.myDocument` will be discarded.
   * ```
   *
   * @example Discarding a draft version of a document
   * ```ts
   * client.discardVersion({publishedId: 'myDocument'})
   * // The document with the ID `drafts.myDocument` will be discarded.
   * ```
   */
  discardVersion({ releaseId, publishedId }: {
    releaseId?: string;
    publishedId: string;
  }, purge?: boolean, options?: BaseActionOptions): Promise<SingleActionResult | MultipleActionResult>;
  /**
   * @public
   *
   * Replaces an existing version document.
   *
   * @remarks
   * * Requires a document with a `_type` property.
   * * If the `document._id` is defined, it should be a draft or release version ID that matches the version ID generated from `publishedId` and `releaseId`.
   * * If the `document._id` is not defined, it will be generated from `publishedId` and `releaseId`.
   * * Replacing a version with no `releaseId` will replace the draft version of the published document.
   * * At least one of the **version** or **published** documents must exist.
   *
   * @param params - Version action parameters:
   *   - `document` - The new document to replace the version with.
   *   - `releaseId` - The ID of the release where the document version is replaced.
   *   - `publishedId` - The ID of the published document to replace.
   * @param options - Additional action options.
   * @returns a promise that resolves to the `transactionId`.
   *
   * @example Replacing a release version of a published document with a generated version ID
   * ```ts
   * await client.replaceVersion({
   *   document: {_type: 'myDocument', title: 'My Document'},
   *   publishedId: 'myDocument',
   *   releaseId: 'myRelease',
   * })
   *
   * // The following document will be patched:
   * // {
   * //   _id: 'versions.myRelease.myDocument',
   * //   _type: 'myDocument',
   * //   title: 'My Document',
   * // }
   * ```
   *
   * @example Replacing a release version of a published document with a specified version ID
   * ```ts
   * await client.replaceVersion({
   *   document: {_type: 'myDocument', _id: 'versions.myRelease.myDocument', title: 'My Document'},
   *   // `publishedId` and `releaseId` are not required since `document._id` has been specified
   * })
   *
   * // The following document will be patched:
   * // {
   * //   _id: 'versions.myRelease.myDocument',
   * //   _type: 'myDocument',
   * //   title: 'My Document',
   * // }
   * ```
   *
   * @example Replacing a draft version of a published document
   * ```ts
   * await client.replaceVersion({
   *   document: {_type: 'myDocument', title: 'My Document'},
   *   publishedId: 'myDocument',
   * })
   *
   * // The following document will be patched:
   * // {
   * //   _id: 'drafts.myDocument',
   * //   _type: 'myDocument',
   * //   title: 'My Document',
   * // }
   * ```
   */
  replaceVersion<R extends Record<string, Any>>(args: {
    document: SanityDocumentStub<R>;
    publishedId: string;
    releaseId?: string;
  }, options?: BaseActionOptions): Promise<SingleActionResult | MultipleActionResult>;
  replaceVersion<R extends Record<string, Any>>(args: {
    document: IdentifiedSanityDocumentStub<R>;
    publishedId?: string;
    releaseId?: string;
  }, options?: BaseActionOptions): Promise<SingleActionResult | MultipleActionResult>;
  /**
   * @public
   *
   * Used to indicate when a document within a release should be unpublished when
   * the release is run.
   *
   * @remarks
   * * If the published document does not exist, an error will be thrown.
   *
   * @param params - Version action parameters:
   *   - `releaseId` - The ID of the release to unpublish the document from.
   *   - `publishedId` - The published ID of the document to unpublish.
   * @param options - Additional action options.
   * @returns a promise that resolves to the `transactionId`.
   *
   * @example Unpublishing a release version of a published document
   * ```ts
   * await client.unpublishVersion({publishedId: 'myDocument', releaseId: 'myRelease'})
   * // The document with the ID `versions.myRelease.myDocument` will be unpublished. when `myRelease` is run.
   * ```
   */
  unpublishVersion({ releaseId, publishedId }: {
    releaseId: string;
    publishedId: string;
  }, options?: BaseActionOptions): Promise<SingleActionResult | MultipleActionResult>;
  /**
   * Perform mutation operations against the configured dataset
   * Returns a promise that resolves to the first mutated document.
   *
   * @param operations - Mutation operations to execute
   * @param options - Mutation options
   */
  mutate<R extends Record<string, Any> = Record<string, Any>>(operations: Mutation<R>[] | Patch | Transaction, options: FirstDocumentMutationOptions): Promise<SanityDocument<R>>;
  /**
   * Perform mutation operations against the configured dataset.
   * Returns a promise that resolves to an array of the mutated documents.
   *
   * @param operations - Mutation operations to execute
   * @param options - Mutation options
   */
  mutate<R extends Record<string, Any> = Record<string, Any>>(operations: Mutation<R>[] | Patch | Transaction, options: AllDocumentsMutationOptions): Promise<SanityDocument<R>[]>;
  /**
   * Perform mutation operations against the configured dataset
   * Returns a promise that resolves to a mutation result object containing the document ID of the first mutated document.
   *
   * @param operations - Mutation operations to execute
   * @param options - Mutation options
   */
  mutate<R extends Record<string, Any> = Record<string, Any>>(operations: Mutation<R>[] | Patch | Transaction, options: FirstDocumentIdMutationOptions): Promise<SingleMutationResult>;
  /**
   * Perform mutation operations against the configured dataset
   * Returns a promise that resolves to a mutation result object containing the mutated document IDs.
   *
   * @param operations - Mutation operations to execute
   * @param options - Mutation options
   */
  mutate<R extends Record<string, Any> = Record<string, Any>>(operations: Mutation<R>[] | Patch | Transaction, options: AllDocumentIdsMutationOptions): Promise<MultipleMutationResult>;
  /**
   * Perform mutation operations against the configured dataset
   * Returns a promise that resolves to a mutation result object containing the mutated document IDs.
   *
   * @param operations - Mutation operations to execute
   * @param options - Mutation options
   */
  mutate<R extends Record<string, Any> = Record<string, Any>>(operations: Mutation<R>[] | Patch | Transaction, options?: BaseMutationOptions): Promise<MultipleMutationResult>;
  /**
   * Create a new buildable patch of operations to perform
   *
   * @param documentId - Document ID to patch
   * @param operations - Optional object of patch operations to initialize the patch instance with
   * @returns Patch instance - call `.commit()` to perform the operations defined
   */
  patch(documentId: string, operations?: PatchOperations): Patch;
  /**
   * Create a new buildable patch of operations to perform
   *
   * @param documentIds - Array of document IDs to patch
   * @param operations - Optional object of patch operations to initialize the patch instance with
   * @returns Patch instance - call `.commit()` to perform the operations defined
   */
  patch(documentIds: string[], operations?: PatchOperations): Patch;
  /**
   * Create a new buildable patch of operations to perform
   *
   * @param selection - An object with `query` and optional `params`, defining which document(s) to patch
   * @param operations - Optional object of patch operations to initialize the patch instance with
   * @returns Patch instance - call `.commit()` to perform the operations defined
   */
  patch(selection: MutationSelection, operations?: PatchOperations): Patch;
  /**
   * Create a new transaction of mutations
   *
   * @param operations - Optional array of mutation operations to initialize the transaction instance with
   */
  transaction<R extends Record<string, Any> = Record<string, Any>>(operations?: Mutation<R>[]): Transaction;
  /**
   * Perform action operations against the configured dataset
   * Returns a promise that resolves to the transaction result
   *
   * @param operations - Action operation(s) to execute
   * @param options - Action options
   */
  action(operations: Action | Action[], options?: BaseActionOptions): Promise<SingleActionResult | MultipleActionResult>;
  /**
   * Perform a request against the Sanity API
   * NOTE: Only use this for Sanity API endpoints, not for your own APIs!
   *
   * @param options - Request options
   * @returns Promise resolving to the response body
   */
  request<R = Any>(options: RawRequestOptions): Promise<R>;
  /**
   * Perform an HTTP request a `/data` sub-endpoint
   * NOTE: Considered internal, thus marked as deprecated. Use `request` instead.
   *
   * @deprecated - Use `request()` or your own HTTP library instead
   * @param endpoint - Endpoint to hit (mutate, query etc)
   * @param body - Request body
   * @param options - Request options
   * @internal
   */
  dataRequest(endpoint: string, body: unknown, options?: BaseMutationOptions): Promise<Any>;
  /**
   * Get a Sanity API URL for the URI provided
   *
   * @param uri - URI/path to build URL for
   * @param canUseCdn - Whether or not to allow using the API CDN for this route
   */
  getUrl(uri: string, canUseCdn?: boolean): string;
  /**
   * Get a Sanity API URL for the data operation and path provided
   *
   * @param operation - Data operation (eg `query`, `mutate`, `listen` or similar)
   * @param path - Path to append after the operation
   */
  getDataUrl(operation: string, path?: string): string;
}
/**  @beta */
type GenerateOperation = 'set' | 'append' | 'mixed';
/**  @beta */
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 the following will generate an image into the provided asset:
   * * `target: {path: ['image', 'asset'] }`
   * * `target: {path: 'image', include: ['asset'] }`
   *
   * Image generation can be combined with regular content targets:
   * * `target: [{path: ['image', 'asset'] }, {include: ['title', 'description']}]`
   *
   * Since Generate happens in a single LLM pass, the image will be contextually related to other generated content.
   * @see AgentActionRequestBase#conditionalPaths
   */
  target?: GenerateTarget | GenerateTarget[];
}
/**  @beta */
interface GenerateTargetInclude extends AgentActionTargetInclude {
  /**
   * Sets the operation for this path, and all its children.
   * This overrides any operation set parents or the root target.
   * @see #GenerateTarget.operation
   * @see #include
   */
  operation?: GenerateOperation;
  /**
   * By default, all children up to `target.maxPathDepth` are included.
   *
   * When `include` is specified, only segments explicitly listed will be included.
   *
   * Fields or array items not on the include list, are implicitly excluded.
   */
  include?: (AgentActionPathSegment | GenerateTargetInclude)[];
}
/**  @beta */
interface GenerateTarget extends AgentActionTarget {
  /**
   * Sets the default operation for all paths in the target.
   * Generate runs in `'mixed'` operation mode by default:
   * Changes are set in all non-array fields, and append to all array fields.
   *
   * ### Operation types
   * - `'set'` – an *overwriting* operation, and replaces the full field value.
   * - `'append'`:
   *    – array fields: appends new items to the end of the array,
   *    - string fields: '"existing content" "new content"'
   *    - text fields: '"existing content"\\n"new content"'
   *    - number fields: existing + new
   *    - other field types not mentioned will set instead (dates, url)
   * - `'mixed'` – (default) sets non-array fields, and appends to array fields
   *
   * The default operation can be overridden on a per-path basis using `include`.
   *
   * Nested fields inherit the operation specified by their parent and falls back to the
   * top level target operation if not otherwise specified.
   *
   * Use `include` to change the `operation` of individual fields or items.
   *
   * #### Appending in the middle of arrays
   * `target: {path: ['array'], operation: 'append'}` will append the output of the instruction to the end of the array.
   *
   * To insert in the middle of the array, use `target: {path: ['array', {_key: 'appendAfterKey'}], operation: 'append'}`.
   * Here, the output of the instruction will be appended after the array item with key `'appendAfterKey'`.
   *
   * @see #AgentActionTargetInclude.operation
   * @see #include
   * @see #AgentActionTargetInclude.include
   * @see #AgentActionSchema.forcePublishedWrite
   */
  operation?: GenerateOperation;
  /**
   * By default, all children up to `target.maxPathDepth` are included.
   *
   * When `include` is specified, only segments explicitly listed will be included.
   *
   * Fields or array items not on the include list, are implicitly excluded.
   */
  include?: (AgentActionPathSegment | GenerateTargetInclude)[];
}
/**  @beta */
type GenerateTargetDocument<T extends Record<string, Any> = Record<string, Any>> = {
  operation: 'edit';
  /**
   * @see #AgentActionSchema.forcePublishedWrite
   */
  _id: string;
} | {
  operation: 'create';
  /**
   * @see #AgentActionSchema.forcePublishedWrite
   */
  _id?: string;
  _type: string;
  initialValues?: T;
} | {
  operation: 'createIfNotExists';
  /**
   * @see #AgentActionSchema.forcePublishedWrite
   */
  _id: string;
  _type: string;
  initialValues?: T;
} | {
  operation: 'createOrReplace';
  /**
   * @see #AgentActionSchema.forcePublishedWrite
   */
  _id: string;
  _type: string;
  initialValues?: T;
};
/**
 * Instruction for an existing document.
 * @beta
 */
interface GenerateExistingDocumentRequest {
  /**
   * @see #AgentActionSchema.forcePublishedWrite
   */
  documentId: string;
  targetDocument?: never;
}
/**
 * Instruction to create a new document
 * @beta
 */
interface GenerateTargetDocumentRequest<T extends Record<string, Any> = Record<string, Any>> {
  /**
   * @see #AgentActionSchema.forcePublishedWrite
   */
  targetDocument: GenerateTargetDocument<T>;
  documentId?: never;
}
/** @beta */
type GenerateSyncInstruction<T extends Record<string, Any> = Record<string, Any>> = (GenerateExistingDocumentRequest | GenerateTargetDocumentRequest<T>) & GenerateRequestBase & AgentActionSync;
/** @beta */
type GenerateAsyncInstruction<T extends Record<string, Any> = Record<string, Any>> = (GenerateExistingDocumentRequest | GenerateTargetDocumentRequest<T>) & GenerateRequestBase & AgentActionAsync;
/** @beta */
type GenerateInstruction<T extends Record<string, Any> = Record<string, Any>> = GenerateSyncInstruction<T> | GenerateAsyncInstruction<T>;
/**
 * Low-level requester returned by `defineRequester(...).observable`.
 * Surfaces as `client.config().requester` and as the named `requester`
 * export.
 *
 * Defined locally rather than imported from `http/request` so api-extractor
 * inlines it into the bundled `.d.ts` instead of emitting a relative import
 * that doesn't survive into `dist/` ([#1290][]).
 *
 * [#1290]: https://github.com/sanity-io/client/issues/1290
 *
 * @public
 */
type Requester = (options: Any) => Observable<unknown>;
/**
 * Used to tag types that is set to `any` as a temporary measure, but should be replaced with proper typings in the future
 * @internal
 */
type Any = any;
declare global {
  interface File {}
}
/** @public */
type UploadBody = File | Blob | Buffer | NodeJS.ReadableStream;
/** @public */
interface RequestOptions {
  timeout?: number;
  token?: string;
  tag?: string;
  headers?: Record<string, string>;
  method?: string;
  query?: Any;
  body?: Any;
  signal?: AbortSignal;
}
/**
 * The fully resolved request passed to a {@link RequestHandler}.
 *
 * @public
 */
type RequestHandlerOptions = RequestOptions$1;
/**
 * Intercepts a client request around the normal HTTP pipeline.
 *
 * Call `next(request)` to execute the request. It resolves to the parsed
 * response body and rejects with the same errors the client normally exposes,
 * including {@link ClientError} and {@link ServerError}. A handler can modify
 * the request, retry it by calling `next` again, or return a synthetic body.
 *
 * Browser asset uploads and server-sent event connections do not use this handler.
 *
 * @public
 */
type RequestHandler = (request: RequestHandlerOptions, next: (request: RequestHandlerOptions) => Promise<unknown>) => Promise<unknown>;
/**
 * @public
 * @deprecated – The `r`-prefix is not required, use `string` instead
 */
type ReleaseId = `r${string}`;
/**
 * @deprecated use 'drafts' instead
 */
type DeprecatedPreviewDrafts = 'previewDrafts';
/** @public */
type StackablePerspective = 'published' | 'drafts' | (string & {});
/** @public */
type ClientPerspective = DeprecatedPreviewDrafts | 'published' | 'drafts' | 'raw' | StackablePerspective[];
/**
 * @public
 * @beta
 */
type ClientVariantConditions = Record<string, string>;
/**
 * @public
 * @beta
 */
type ClientVariant = ClientVariantConditions | string;
type ClientConfigResource = {
  type: 'canvas';
  id: string;
} | {
  type: 'knowledge-base';
  id: string;
} | {
  type: 'media-library';
  id: string;
} | {
  type: 'dataset';
  id: string;
} | {
  type: 'dashboard';
  id: string;
};
/** @public */
interface ClientConfig {
  projectId?: string;
  dataset?: string;
  /** @defaultValue true */
  useCdn?: boolean;
  token?: string;
  /**
   * Configure the client to work with a specific Sanity resource (Media Library, Canvas, etc.)
   * @remarks
   * This allows the client to interact with resources beyond traditional project datasets.
   * When configured, methods like `fetch()`, `assets.upload()`, and mutations will operate on the specified resource.
   * @example
   * ```ts
   * createClient({
   *   resource: {
   *     type: 'media-library',
   *     id: 'your-media-library-id'
   *   }
   * })
   * ```
   */
  resource?: ClientConfigResource;
  /**
   * @deprecated Use `resource` instead
   * @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;
  /**
   * @beta
   */
  variant?: ClientVariant;
  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;
  /**
   * Route requests through an HTTP(S) proxy. Node.js only. Can be replaced
   * on an existing client via `client.config({proxy})` or
   * `client.withConfig({proxy})`. For environment-driven proxying, set
   * `HTTP_PROXY`/`HTTPS_PROXY`/`NO_PROXY` before the process starts.
   */
  proxy?: string;
  /**
   * Optional request tag prefix for all request tags
   */
  requestTagPrefix?: string;
  /**
   * Intercepts requests after the client has resolved their URL, headers, and
   * transport options. The handler wraps the normal client pipeline, so errors
   * from `next` are already converted to {@link ClientError} or
   * {@link ServerError}.
   *
   * A handler supplied through `withConfig()` replaces the current handler.
   * To compose handlers, read the current handler from `client.config()` and
   * call it from the replacement.
   *
   * Browser asset uploads and server-sent event connections are not intercepted.
   */
  requestHandler?: RequestHandler;
  /**
   * 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;
  /**
   * Ignore specific warning messages from the client.
   *
   * @remarks
   * - String values perform substring matching (not exact matching) against warning messages
   * - RegExp values are tested against the full warning message
   * - Array values allow multiple patterns to be specified
   *
   * @example
   * ```typescript
   * // Ignore warnings containing "experimental"
   * ignoreWarnings: 'experimental'
   *
   * // Ignore multiple warning types
   * ignoreWarnings: ['experimental', 'deprecated']
   *
   * // Use regex for exact matching
   * ignoreWarnings: /^This is an experimental API version$/
   *
   * // Mix strings and regex patterns
   * ignoreWarnings: ['rate limit', /^deprecated/i]
   * ```
   */
  ignoreWarnings?: string | RegExp | Array<string | RegExp>;
  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;
  /**
   * Resolves the fetch implementation every request (including EventSource
   * connections) goes through. Defaults to the environment entry point's
   * fetch — the Node entry supplies get-it's undici-backed fetch (resolved
   * via the entry point instead of a direct import so `get-it/node`/`undici`
   * stays out of the browser bundle), the browser entry leaves it unset (the
   * global fetch IS the environment's fetch there). Receives the explicit
   * `proxy` config, when set, as its argument.
   *
   * Supplying it in the client config replaces the transport wholesale —
   * custom fetch variants, alternative undici configurations, or a mock
   * (the test suite injects `get-it/mock` this way).
   *
   * Returns get-it's minimal `FetchFunction` contract rather than the full
   * `typeof fetch` — that is what the environments actually provide, and
   * every consumer (the transport, the EventSource fetch resolver) only
   * needs that subset.
   *
   * @internal
   */
  resolveFetch?: (proxyUrl?: string) => FetchFunction;
  /**
   * 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;
  /**
   * Lineage token for recursion control
   */
  lineage?: string;
  /**
   * ID of the blueprints stack that `functions.invoke()` resolves function
   * names against. Function names are unique within a stack
   */
  stackId?: string;
  /**
   * ID of the organization owning the blueprints stack
   */
  organizationId?: string;
  /**
   * Organization-scoped configuration for collaboration APIs.
   *
   * Currently this is used by `collaboration.comments` methods.
   *
   * @alpha
   */
  collaboration?: {
    organizationId?: string;
  };
  /**
   * Organization-scoped configuration for Context APIs.
   *
   * Currently this is used by `context.insights` methods.
   *
   * @beta
   */
  context?: {
    organizationId?: string;
  };
}
/** @public */
interface InitializedClientConfig extends ClientConfig {
  apiHost: string;
  apiVersion: string;
  useProjectHostname: boolean;
  useCdn: boolean;
  /**
   * @deprecated Internal, don't use
   */
  isDefaultApi: boolean;
  /**
   * @deprecated Internal, don't use
   */
  url: string;
  /**
   * @deprecated Internal, don't use
   */
  cdnUrl: string;
  /**
   * The fully initialized stega config, can be used to check if stega is enabled
   */
  stega: InitializedStegaConfig;
  /**
   * The resolved low-level requester for this client. Always populated by
   * `createClient` so internal paths (e.g. the asset upload event stream) can
   * reach the underlying transport.
   *
   * @internal
   */
  requester: Requester;
  /**
   * Default headers to include with all requests
   *
   * @remarks request-specific headers will override any default headers with the same name.
   */
  headers?: Record<string, string>;
}
/** @public */
type AssetMetadataType = 'location' | 'exif' | 'image' | 'palette' | 'lqip' | 'blurhash' | 'thumbhash' | 'none';
/** @public */
interface UploadClientConfig {
  /**
   * Optional request tag for the upload
   */
  tag?: string;
  /**
   * Whether or not to preserve the original filename (default: true)
   */
  preserveFilename?: boolean;
  /**
   * Filename for this file (optional)
   */
  filename?: string;
  /**
   * Milliseconds to wait before timing the request out.
   *
   * Unlike other requests, uploads have NO timeout unless one is explicitly
   * set here — uploads can legitimately be slow, so timing out is opt-in.
   */
  timeout?: number;
  /**
   * Mime type of the file
   */
  contentType?: string;
  /**
   * Array of metadata parts to extract from asset
   */
  extract?: AssetMetadataType[];
  /**
   * Optional freeform label for the asset. Generally not used.
   */
  label?: string;
  /**
   * Optional title for the asset
   */
  title?: string;
  /**
   * Optional description for the asset
   */
  description?: string;
  /**
   * The credit to person(s) and/or organization(s) required by the supplier of the asset to be used when published
   */
  creditLine?: string;
  /**
   * Source data (when the asset is from an external service)
   */
  source?: {
    /**
     * The (u)id of the asset within the source, i.e. 'i-f323r1E'
     */
    id: string;
    /**
     * The name of the source, i.e. 'unsplash'
     */
    name: string;
    /**
     * A url to where to find the asset, or get more info about it in the source
     */
    url?: string;
  };
}
/** @internal */
interface SanityReference {
  _ref: string;
}
/** @internal */
type SanityDocument<T extends Record<string, Any> = Record<string, Any>> = { [P in keyof T]: T[P]; } & {
  _id: string;
  _rev: string;
  _type: string;
  _createdAt: string;
  _updatedAt: string;
  /**
   * Present when `perspective` is set to `previewDrafts`
   */
  _originalId?: string;
};
/** @internal */
interface SanityAssetDocument extends SanityDocument {
  url: string;
  path: string;
  size: number;
  assetId: string;
  mimeType: string;
  sha1hash: string;
  extension: string;
  uploadId?: string;
  originalFilename?: string;
}
/** @internal */
interface SanityImagePalette {
  background: string;
  foreground: string;
  population: number;
  title: string;
}
/** @internal */
interface SanityImageAssetDocument extends SanityAssetDocument {
  metadata: {
    _type: 'sanity.imageMetadata';
    hasAlpha: boolean;
    isOpaque: boolean;
    lqip?: string;
    blurHash?: string;
    thumbHash?: string;
    dimensions: {
      _type: 'sanity.imageDimensions';
      aspectRatio: number;
      height: number;
      width: number;
    };
    palette?: {
      _type: 'sanity.imagePalette';
      darkMuted?: SanityImagePalette;
      darkVibrant?: SanityImagePalette;
      dominant?: SanityImagePalette;
      lightMuted?: SanityImagePalette;
      lightVibrant?: SanityImagePalette;
      muted?: SanityImagePalette;
      vibrant?: SanityImagePalette;
    };
    image?: {
      _type: 'sanity.imageExifTags';
      [key: string]: Any;
    };
    exif?: {
      _type: 'sanity.imageExifMetadata';
      [key: string]: Any;
    };
  };
}
/** @public */
interface ErrorProps {
  message: string;
  response: Any;
  statusCode: number;
  responseBody: Any;
  traceId?: string;
  details: Any;
}
/**
 * The internal HTTP request abstraction used by the client. Resolves directly
 * to the parsed response body as a Promise — middleware-level transport
 * details (status codes, headers, progress events) are not exposed. The
 * observable client surface wraps this in an Observable; the promise surface
 * uses it directly.
 *
 * The body is typed as `unknown`; consumers narrow at their own boundary.
 *
 * @internal
 */
type HttpRequest = {
  (options: Any, requestHandler?: RequestHandler): Promise<unknown>;
};
/**
 * Target URL for a request. Exactly one of `url` or the deprecated `uri` alias
 * must be given.
 *
 * @internal
 */
type RequestUrlOptions = {
  url: string;
  uri?: never;
} | {
  /**
   * @deprecated Use `url` instead. Support for `uri` will be removed in a future version.
   */
  uri: string;
  url?: never;
};
/** @internal */
type RequestObservableOptions = RequestUrlOptions & Omit<RequestOptions, 'url'> & {
  canUseCdn?: boolean;
  useCdn?: boolean;
  tag?: string;
  returnQuery?: boolean;
  resultSourceMap?: boolean | 'withKeyArraySelector';
  perspective?: ClientPerspective;
  /**
   * @beta
   */
  variant?: ClientVariant;
  lastLiveEventId?: string;
  cacheMode?: 'noStale';
};
/** @public */
interface UploadProgressEvent {
  type: 'progress';
  stage: 'upload' | 'download';
  percent: number;
  total?: number;
  loaded?: number;
  lengthComputable: boolean;
}
/** @public */
interface UploadResponseEvent<T = unknown> {
  type: 'response';
  body: T;
}
/**
 * Events emitted by `client.assets.upload()` when called via the observable
 * API. Progress events are best-effort — they're only emitted when the
 * environment supports tracking upload/download bytes (e.g. browsers via
 * `XMLHttpRequest`). Other runtimes only emit the terminal `response` event.
 *
 * @public
 */
type UploadEvent<T = unknown> = UploadResponseEvent<T> | UploadProgressEvent;
/** @internal */
interface AuthProvider {
  name: string;
  title: string;
  url: string;
}
/** @internal */
type AuthProviderResponse = {
  providers: AuthProvider[];
};
/** @public */
type DatasetAclMode = 'public' | 'private' | 'custom';
/** @public */
type DatasetCreateOptions = {
  aclMode?: DatasetAclMode;
  description?: string;
  embeddings?: {
    enabled: boolean;
    projection?: string;
  };
};
/** @public */
type DatasetEditOptions = {
  aclMode?: DatasetAclMode;
  description?: string;
};
/** @public */
type EmbeddingsSettings = {
  enabled: boolean;
  projection?: string;
  status: string;
};
/** @public */
type EmbeddingsSettingsBody = {
  enabled: boolean;
  projection?: string;
};
/** @public */
type DatasetResponse = {
  datasetName: string;
  aclMode: DatasetAclMode;
  description: string;
};
/** @public */
type DatasetsResponse = {
  name: string;
  aclMode: DatasetAclMode;
  description: string;
  createdAt: string;
  createdByUserId: string;
  addonFor: string | null;
  datasetProfile: string;
  features: string[];
  tags: {
    name: string;
    title: string;
  }[];
}[];
/** @public */
interface SanityProjectMember {
  id: string;
  role: string;
  isRobot: boolean;
  isCurrentUser: boolean;
}
/** @public */
interface SanityProject {
  id: string;
  displayName: string;
  /**
   * @deprecated Use the `/user-applications` endpoint instead, which lists all deployed studios/applications
   * @see https://www.sanity.io/help/studio-host-user-applications
   */
  studioHost: string | null;
  organizationId: string | null;
  isBlocked: boolean;
  isDisabled: boolean;
  isDisabledByUser: boolean;
  createdAt: string;
  pendingInvites?: number;
  maxRetentionDays?: number;
  members: SanityProjectMember[];
  features: string[];
  metadata: {
    cliInitializedAt?: string;
    color?: string;
    /**
     * @deprecated Use the `/user-applications` endpoint instead, which lists all deployed studios/applications
     * @see https://www.sanity.io/help/studio-host-user-applications
     */
    externalStudioHost?: string;
  };
}
/** @public */
interface SanityUser {
  id: string;
  projectId: string;
  displayName: string;
  familyName: string | null;
  givenName: string | null;
  middleName: string | null;
  imageUrl: string | null;
  createdAt: string;
  updatedAt: string;
  isCurrentUser: boolean;
}
/** @public */
interface CurrentSanityUser {
  id: string;
  name: string;
  email: string;
  profileImage: string | null;
  role: string;
  provider: string;
}
/** @public */
type SanityDocumentStub<T extends Record<string, Any> = Record<string, Any>> = { [P in keyof T]: T[P]; } & {
  _type: string;
};
/** @public */
type IdentifiedSanityDocumentStub<T extends Record<string, Any> = Record<string, Any>> = { [P in keyof T]: T[P]; } & {
  _id: string;
} & SanityDocumentStub;
/** @internal */
type InsertPatch = {
  before: string;
  items: Any[];
} | {
  after: string;
  items: Any[];
} | {
  replace: string;
  items: Any[];
};
/** @internal */
interface PatchOperations {
  set?: {
    [key: string]: Any;
  };
  setIfMissing?: {
    [key: string]: Any;
  };
  diffMatchPatch?: {
    [key: string]: Any;
  };
  unset?: string[];
  inc?: {
    [key: string]: number;
  };
  dec?: {
    [key: string]: number;
  };
  insert?: InsertPatch;
  ifRevisionID?: string;
}
/** @public */
interface QueryParams {
  [key: string]: any;
  /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
  body?: never;
  /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
  cache?: 'next' extends keyof RequestInit ? never : any;
  /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
  filterResponse?: never;
  /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
  headers?: never;
  /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
  method?: never;
  /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
  next?: 'next' extends keyof RequestInit ? never : any;
  /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
  perspective?: never;
  /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
  variant?: never;
  /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
  query?: never;
  /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
  resultSourceMap?: never;
  /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
  returnQuery?: never;
  /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
  signal?: never;
  /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
  stega?: never;
  /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
  tag?: never;
  /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
  timeout?: never;
  /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
  token?: never;
  /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
  useCdn?: never;
  /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
  lastLiveEventId?: never;
  /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
  cacheMode?: never;
}
/**
 * This type can be used with `client.fetch` to indicate that the query has no GROQ parameters.
 * @public
 */
type QueryWithoutParams = Record<string, never> | undefined;
/** @internal */
type MutationSelectionQueryParams = {
  [key: string]: Any;
};
/** @internal */
type MutationSelection = {
  query: string;
  params?: MutationSelectionQueryParams;
} | {
  id: string | string[];
};
/** @internal */
type PatchSelection = string | string[] | MutationSelection;
/** @internal */
type PatchMutationOperation = PatchOperations & MutationSelection;
/** @public */
type Mutation<R extends Record<string, Any> = Record<string, Any>> = {
  create: SanityDocumentStub<R>;
} | {
  createOrReplace: IdentifiedSanityDocumentStub<R>;
} | {
  createIfNotExists: IdentifiedSanityDocumentStub<R>;
} | {
  delete: MutationSelection;
} | {
  patch: PatchMutationOperation;
};
/** @public */
type ReleaseAction = CreateReleaseAction | EditReleaseAction | PublishReleaseAction | ArchiveReleaseAction | UnarchiveReleaseAction | ScheduleReleaseAction | UnscheduleReleaseAction | DeleteReleaseAction | ImportReleaseAction;
/**
 * @public
 * @beta
 */
type VariantDefinitionAction = CreateVariantDefinitionAction | EditVariantDefinitionAction | DeleteVariantDefinitionAction;
/** @public */
type VersionAction = CreateVersionAction | DiscardVersionAction | ReplaceVersionAction | UnpublishVersionAction;
/**
 * @public
 * @beta
 */
type VariantAction = CreateVariantAction | EditVariantAction | DeleteVariantAction | PublishVariantAction | UnpublishVariantAction;
/** @public */
type Action = CreateAction | ReplaceDraftAction | EditAction | DeleteAction | DiscardAction | PublishAction | UnpublishAction | VersionAction | VariantAction | ReleaseAction | VariantDefinitionAction;
/** @public */
type ImportReleaseAction = {
  actionType: 'sanity.action.release.import';
  attributes: IdentifiedSanityDocumentStub;
  releaseId: string;
  ifExists: 'fail' | 'ignore' | 'replace';
} | {
  actionType: 'sanity.action.release.import';
  document: IdentifiedSanityDocumentStub;
  releaseId: string;
  ifExists: 'fail' | 'ignore' | 'replace';
};
/**
 * Creates a new release under the given id, with metadata.
 *
 * @public
 */
interface CreateReleaseAction {
  actionType: 'sanity.action.release.create';
  releaseId: string;
  metadata?: Partial<ReleaseDocument['metadata']>;
}
/**
 * Edits an existing release, updating the metadata.
 *
 * @public
 */
interface EditReleaseAction {
  actionType: 'sanity.action.release.edit';
  releaseId: string;
  patch: PatchOperations;
}
/**
 * Publishes all documents in a release at once.
 *
 * @public
 */
interface PublishReleaseAction {
  actionType: 'sanity.action.release.publish';
  releaseId: string;
}
/**
 * Archives an `active` release, and deletes all the release documents.
 *
 * @public
 */
interface ArchiveReleaseAction {
  actionType: 'sanity.action.release.archive';
  releaseId: string;
}
/**
 * Unarchived an `archived` release, and restores all the release documents.
 *
 * @public
 */
interface UnarchiveReleaseAction {
  actionType: 'sanity.action.release.unarchive';
  releaseId: string;
}
/**
 * Queues release for publishing at the given future time.
 *
 * @public
 */
interface ScheduleReleaseAction {
  actionType: 'sanity.action.release.schedule';
  releaseId: string;
  publishAt: string;
}
/**
 * Unschedules a `scheduled` release, stopping it from being published.
 *
 * @public
 */
interface UnscheduleReleaseAction {
  actionType: 'sanity.action.release.unschedule';
  releaseId: string;
}
/**
 * Deletes a `archived` or `published` release, and all the release documents versions.
 *
 * @public
 */
interface DeleteReleaseAction {
  actionType: 'sanity.action.release.delete';
  releaseId: string;
}
/**
 * Creates a new version of an existing document.
 *
 * If the `document` is provided, the version is created from the document
 * attached to the release as given by `document._id`
 *
 * If the `baseId` and `versionId` are provided, the version is created from the base document
 * and the version is attached to the release as given by `publishedId` and `versionId`
 *
 * @public
 */
type CreateVersionAction = {
  actionType: 'sanity.action.document.version.create';
  publishedId: string;
} & ({
  document: IdentifiedSanityDocumentStub;
} | {
  baseId: string;
  versionId: string;
  ifBaseRevisionId?: string;
});
/**
 * Delete a version of a document.
 *
 * @public
 */
interface DiscardVersionAction {
  actionType: 'sanity.action.document.version.discard';
  versionId: string;
  purge?: boolean;
}
/**
 * Replace an existing version of a document.
 *
 * @public
 */
interface ReplaceVersionAction {
  actionType: 'sanity.action.document.version.replace';
  document: IdentifiedSanityDocumentStub;
}
/**
 * Identify that a version of a document should be unpublished when
 * the release that version is contained within is published.
 *
 * @public
 */
interface UnpublishVersionAction {
  actionType: 'sanity.action.document.version.unpublish';
  versionId: string;
  publishedId: string;
}
/**
 * Creates a variant of a document, either by supplying the full document
 * content, or the base ID of a document to copy.
 *
 * @public
 * @beta
 */
type CreateVariantAction = {
  actionType: 'sanity.action.document.variant.create';
  /**
   * ID of the document group to create a variant in. Must be a published
   * document ID, without a `drafts.` or `versions.` prefix.
   */
  publishedId: string;
  /**
   * Name of the variant definition this document belongs to, as in
   * `_.variants.{variantName}`. Must be a bare name, not a full document ID.
   */
  variantId: string;
  /**
   * Source bundle: `'drafts'`, or a release id.
   *
   * Defaults to the published bundle.
   */
  bundleId?: 'drafts' | (string & {});
} & ({
  /**
   * The full document content. Requires a `_type` property.
   */
  document: SanityDocumentStub;
  baseId?: never;
  ifBaseRevisionId?: never;
} | {
  /**
   * ID of an existing document to copy the content from.
   */
  baseId: string;
  /**
   * When set, the action fails unless the current revision of the base
   * document matches this value.
   */
  ifBaseRevisionId?: string;
  document?: never;
});
/**
 * Modifies a variant version of a document by applying a patch.
 *
 * If no such variant document exists it is first created, by copying the
 * variant's published sibling, or the published document if the variant was
 * never published.
 *
 * @public
 * @beta
 */
interface EditVariantAction {
  actionType: 'sanity.action.document.variant.edit';
  /**
   * ID of the document group the variant belongs to. Must be a published
   * document ID, without a `drafts.` or `versions.` prefix.
   */
  publishedId: string;
  /**
   * Name of the variant definition this document belongs to, as in
   * `_.variants.{variantName}`. Must be a bare name, not a full document ID.
   */
  variantId: string;
  /**
   * Source bundle: `'drafts'`, or a release id.
   *
   * Defaults to the published bundle.
   */
  bundleId?: 'drafts' | (string & {});
  /**
   * Patch operations to apply.
   */
  patch: PatchOperations;
}
/**
 * Deletes a variant of a document.
 *
 * @public
 * @beta
 */
interface DeleteVariantAction {
  actionType: 'sanity.action.document.variant.delete';
  /**
   * ID of the document group the variant belongs to. Must be a published
   * document ID, without a `drafts.` or `versions.` prefix.
   */
  publishedId: string;
  /**
   * Name of the variant definition this document belongs to, as in
   * `_.variants.{variantName}`. Must be a bare name, not a full document ID.
   */
  variantId: string;
  /**
   * Source bundle: `'drafts'`, or a release id.
   *
   * Defaults to the published bundle.
   */
  bundleId?: 'drafts' | (string & {});
  /**
   * Delete document history.
   */
  purge?: boolean;
}
/**
 * Publishes a variant version of a document, replacing the published variant
 * and removing the source variant document.
 *
 * @public
 * @beta
 */
interface PublishVariantAction {
  actionType: 'sanity.action.document.variant.publish';
  /**
   * ID of the document group the variant belongs to. Must be a published
   * document ID, without a `drafts.` or `versions.` prefix.
   */
  publishedId: string;
  /**
   * Name of the variant definition this document belongs to, as in
   * `_.variants.{variantName}`. Must be a bare name, not a full document ID.
   */
  variantId: string;
  /**
   * Bundle to publish from: `'drafts'`, or a release id.
   */
  bundleId: 'drafts' | (string & {});
  /**
   * When set, publishing fails unless the current revision of the source
   * variant document matches this value.
   */
  ifVersionRevisionId?: string;
  /**
   * When set, publishing fails unless the current revision of the published
   * variant document matches this value.
   */
  ifPublishedVariantRevisionId?: string;
}
/**
 * Unpublishes a variant version of a document.
 *
 * By default the published variant is removed and preserved as a draft
 * variant. When a release id is given as the `bundleId`, the deletion is
 * instead staged in that release, and takes effect when it is published.
 *
 * @public
 * @beta
 */
interface UnpublishVariantAction {
  actionType: 'sanity.action.document.variant.unpublish';
  /**
   * ID of the document group the variant belongs to. Must be a published
   * document ID, without a `drafts.` or `versions.` prefix.
   */
  publishedId: string;
  /**
   * Name of the variant definition this document belongs to, as in
   * `_.variants.{variantName}`. Must be a bare name, not a full document ID.
   */
  variantId: string;
  /**
   * The content release in which to stage the unpublish.
   *
   * By default, the currently published document is unpublished immediately.
   */
  bundleId?: string;
}
/**
 * Creates a new `system.variant` definition document.
 *
 * @public
 * @beta
 */
interface CreateVariantDefinitionAction {
  actionType: 'sanity.action.variant.definition.create';
  /**
   * Name of the variant definition to create, as in
   * `_.variants.{variantName}`. Must be a bare name, not a full document ID.
   */
  variantId: string;
  /**
   * Conditions used to select this variant.
   */
  conditions?: ClientVariantConditions;
  /**
   * Selection priority. Higher values are preferred when multiple variants
   * match.
   *
   * Defaults to `0`.
   */
  priority?: number;
  metadata?: Record<string, Any>;
}
/**
 * Edits an existing variant definition.
 *
 * @public
 * @beta
 */
interface EditVariantDefinitionAction {
  actionType: 'sanity.action.variant.definition.edit';
  /**
   * Name of the variant definition to edit, as in `_.variants.{variantName}`.
   * Must be a bare name, not a full document ID.
   */
  variantId: string;
  /**
   * Patch operations to apply.
   */
  patch: PatchOperations;
  /**
   * When set, the action fails unless the current revision of the variant
   * definition matches this value.
   */
  ifRevisionId?: string;
}
/**
 * Deletes a variant definition.
 *
 * Deletion fails if any document holds a strong reference to this variant.
 *
 * @public
 * @beta
 */
interface DeleteVariantDefinitionAction {
  actionType: 'sanity.action.variant.definition.delete';
  /**
   * Name of the variant definition to delete, as in
   * `_.variants.{variantName}`. Must be a bare name, not a full document ID.
   */
  variantId: string;
  /**
   * When set, the action fails unless the current revision of the variant
   * definition matches this value.
   */
  ifRevisionId?: 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
 */
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';
};
/**
 * Replaces an existing draft document.
 * At least one of the draft or published versions of the document must exist.
 *
 * @public
 * @deprecated Use {@link ReplaceVersionAction} instead
 */
type ReplaceDraftAction = {
  actionType: 'sanity.action.document.replaceDraft';
  /**
   * Published document ID to create draft from, if draft does not exist
   */
  publishedId: string;
  /**
   * Document to create if it does not already exist. Requires `_id` and `_type` properties.
   */
  attributes: IdentifiedSanityDocumentStub;
};
/**
 * 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
 */
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;
};
/**
 * 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
 */
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;
};
/**
 * 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
 */
type DiscardAction = {
  actionType: 'sanity.action.document.discard';
  /**
   * Draft document ID to delete
   */
  draftId: string;
  /**
   * Delete document history
   */
  purge?: boolean;
};
/**
 * Publishes a draft document.
 * If a published version of the document already exists this is replaced by the current draft document.
 * In either case the draft document is deleted.
 * The optional revision id parameters can be used for optimistic locking to ensure
 * that the draft and/or published versions of the document have not been changed by another client.
 *
 * @public
 */
type PublishAction = {
  actionType: 'sanity.action.document.publish';
  /**
   * Draft document ID to publish
   */
  draftId: string;
  /**
   * Draft revision ID to match
   */
  ifDraftRevisionId?: string;
  /**
   * Published document ID to replace
   */
  publishedId: string;
  /**
   * Published revision ID to match
   */
  ifPublishedRevisionId?: string;
};
/**
 * Retract a published document.
 * If there is no draft version then this is created from the published version.
 * In either case the published version is deleted.
 *
 * @public
 */
type UnpublishAction = {
  actionType: 'sanity.action.document.unpublish';
  /**
   * Draft document ID to replace the published document with
   */
  draftId: string;
  /**
   * Published document ID to delete
   */
  publishedId: string;
};
/**
 * A mutation was performed. Note that when updating multiple documents in a transaction,
 * each document affected will get a separate mutation event.
 *
 * @public
 */
type MutationEvent<R extends Record<string, Any> = Record<string, Any>> = {
  type: 'mutation';
  /**
   * The ID of the document that was affected
   */
  documentId: string;
  /**
   * A unique ID for this event
   */
  eventId: string;
  /**
   * The user ID of the user that performed the mutation
   */
  identity: string;
  /**
   * An array of mutations that were performed. Note that this can differ slightly from the
   * mutations sent to the server, as the server may perform some mutations automatically.
   */
  mutations: Mutation[];
  /**
   * The revision ID of the document before the mutation was performed
   */
  previousRev?: string;
  /**
   * The revision ID of the document after the mutation was performed
   */
  resultRev?: string;
  /**
   * The document as it looked after the mutation was performed. This is only included if
   * the listener was configured with `includeResult: true`.
   */
  result?: SanityDocument<R>;
  /**
   * The document as it looked before the mutation was performed. This is only included if
   * the listener was configured with `includePreviousRevision: true`.
   */
  previous?: SanityDocument<R> | null;
  /**
   * The effects of the mutation, if the listener was configured with `effectFormat: 'mendoza'`.
   * Object with `apply` and `revert` arrays, see {@link https://github.com/sanity-io/mendoza}.
   */
  effects?: {
    apply: unknown[];
    revert: unknown[];
  };
  /**
   * A timestamp for when the mutation was performed
   */
  timestamp: string;
  /**
   * The transaction ID for the mutation
   */
  transactionId: string;
  /**
   * The type of transition the document went through.
   *
   * - `update` means the document was previously part of the subscribed set of documents,
   *   and still is.
   * - `appear` means the document was not previously part of the subscribed set of documents,
   *   but is now. This can happen both on create or if updating to a state where it now matches
   *   the filter provided to the listener.
   * - `disappear` means the document was previously part of the subscribed set of documents,
   *   but is no longer. This can happen both on delete or if updating to a state where it no
   *   longer matches the filter provided to the listener.
   */
  transition: 'update' | 'appear' | 'disappear';
  /**
   * Whether the change that triggered this event is visible to queries (query) or only to
   * subsequent transactions (transaction). The listener client can specify a preferred visibility
   * through the `visibility` parameter on the listener, but this is only on a best-effort basis,
   * and may yet not be accurate.
   */
  visibility: 'query' | 'transaction';
  /**
   * The total number of events that will be sent for this transaction.
   * Note that this may differ from the amount of _documents_ affected by the transaction, as this
   * number only includes the documents that matches the given filter.
   *
   * This can be useful if you need to perform changes to all matched documents atomically,
   * eg you would wait for `transactionTotalEvents` events with the same `transactionId` before
   * applying the changes locally.
   */
  transactionTotalEvents: number;
  /**
   * The index of this event within the transaction. Note that events may be delivered out of order,
   * and that the index is zero-based.
   */
  transactionCurrentEvent: number;
};
/**
 * 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
 */
type ChannelErrorEvent = {
  type: 'channelError';
  message: string;
};
/**
 * 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
 */
type DisconnectEvent = {
  type: 'disconnect';
  reason: string;
};
/**
 * The listener has been disconnected, and a reconnect attempt is scheduled.
 *
 * @public
 */
type ReconnectEvent = {
  type: 'reconnect';
};
/**
 * The listener connection has been established
 * note: it's usually a better option to use the 'welcome' event
 * @public
 */
type OpenEvent = {
  type: 'open';
};
/**
 * Emitted when the listener connection has been successfully established
 * and is ready to receive events.
 *
 * If the listener was created with `enableResume: true` and resume support
 * is available, the `welcome` event will only be emitted on the initial
 * connection. On subsequent reconnects, a `welcomeback` event will be
 * emitted instead, followed by any events that were missed while the
 * connection was disconnected.
 *
 * @public
 */
type WelcomeEvent = {
  type: 'welcome';
  listenerName: string;
};
/**
 * Emitted when the listener reconnects and successfully resumes from
 * its previous position.
 *
 * Even if the listener is created with `enableResume: true`, resume support
 * may not be available. In that case, a reconnect will emit `welcome`
 * instead of `welcomeback`.
 *
 * If resumability is unavailable, even listeners created with `enableResume: true` may still
 * emit `welcome` when reconnected. Subscribers should therefore treat `welcome` after a reconnect
 * the same way they would otherwise treat a `reset` event.
 *
 * @public
 */
type WelcomeBackEvent = {
  type: 'welcomeback';
  listenerName: string;
};
/**
 * The listener can't be resumed or otherwise need to reset its local state
 *
 * If resumability is unavailable, even listeners created with `enableResume: true` may still
 * emit `welcome` when reconnected. Subscribers should therefore treat `welcome` after a reconnect
 * the same way they would otherwise treat a `reset` event.
 *
 * @public
 */
type ResetEvent = {
  type: 'reset';
};
/** @public */
type ListenEvent<R extends Record<string, Any> = Record<string, Any>> = MutationEvent<R> | ReconnectEvent | WelcomeBackEvent | ResetEvent | WelcomeEvent | OpenEvent;
/** @public */
type ListenEventName =
/** A mutation was performed */
'mutation' |
/** The listener has been (re)established */
'welcome' |
/** The listener has been disconnected, and a reconnect attempt is scheduled */
'reconnect' |
/**
 * The listener connection has been established
 * note: it's usually a better option to use the 'welcome' event
 */
'open';
/** @public */
type ResumableListenEventNames = ListenEventName |
/** The listener has reconnected and successfully resumed from where it left off */
'welcomeback' |
/** The listener can't be resumed or otherwise need to reset its local state */
'reset';
/** @public */
type ListenParams = {
  [key: string]: Any;
};
/** @public */
interface ListenOptions {
  /**
   * Whether or not to include the resulting document in addition to the mutations performed.
   * If you do not need the actual document, set this to `false` to reduce bandwidth usage.
   * The result will be available on the `.result` property of the events.
   * @defaultValue `true`
   */
  includeResult?: boolean;
  /**
   * Whether or not to include the mutations that was performed.
   * If you do not need the mutations, set this to `false` to reduce bandwidth usage.
   * @defaultValue `true`
   */
  includeMutations?: boolean;
  /**
   * Whether or not to include the document as it looked before the mutation event.
   * The previous revision will be available on the `.previous` property of the events,
   * and may be `null` in the case of a new document.
   * @defaultValue `false`
   */
  includePreviousRevision?: boolean;
  includeAllVersions?: boolean;
  /**
   * Whether events should be sent as soon as a transaction has been committed (`transaction`, default),
   * or only after they are available for queries (query). Note that this is on a best-effort basis,
   * and listeners with `query` may in certain cases (notably with deferred transactions) receive events
   * that are not yet visible to queries.
   *
   * @defaultValue `'transaction'`
   */
  visibility?: 'transaction' | 'query';
  /**
   * Array of event names to include in the observable. By default, only mutation events are included.
   * Note: `welcomeback` and `reset` events requires `enableResume: true`
   * @defaultValue `['mutation']`
   */
  events?: ListenEventName[];
  /**
   * Format of "effects", eg the resulting changes of a mutation.
   * Currently only `mendoza` is supported, and (if set) will include `apply` and `revert` arrays
   * in the mutation events under the `effects` property.
   *
   * See {@link https://github.com/sanity-io/mendoza | The mendoza docs} for more info
   *
   * @defaultValue `undefined`
   */
  effectFormat?: 'mendoza';
  /**
   * Optional request tag for the listener. Use to identify the request in logs.
   *
   * @defaultValue `undefined`
   */
  tag?: string;
  /**
   * If this is enabled, the client will normally resume events upon reconnect
   * When if enabling this, you should also add the `reset` to the events array and handle the case where the backend is unable to resume.
   * @beta
   * @defaultValue `false`
   */
  enableResume?: boolean;
}
/** @public */
interface ResumableListenOptions extends Omit<ListenOptions, 'events' | 'enableResume'> {
  /**
   * If this is enabled, the client will normally resume events upon reconnect
   * Note that you should also subscribe to `reset`-events and handle the case where the backend is unable to resume
   * @beta
   * @defaultValue `false`
   */
  enableResume: true;
  /**
   * Array of event names to include in the observable. By default, only mutation events are included.
   *
   * @defaultValue `['mutation']`
   */
  events?: ResumableListenEventNames[];
}
/** @public */
interface ResponseQueryOptions extends RequestOptions {
  perspective?: ClientPerspective;
  /**
   * @beta
   */
  variant?: ClientVariant;
  resultSourceMap?: boolean | 'withKeyArraySelector';
  returnQuery?: boolean;
  useCdn?: boolean;
  stega?: boolean | StegaConfig;
  cache?: 'next' extends keyof RequestInit ? RequestInit['cache'] : never;
  next?: ('next' extends keyof RequestInit ? RequestInit : never)['next'];
  lastLiveEventId?: string | string[] | null;
  /**
   * When set to `noStale`, APICDN will not return a cached response if the content is stale.
   * Tradeoff between latency and freshness of content.
   *
   * Only to be used with live content queries and when useCdn is true.
   */
  cacheMode?: 'noStale';
}
/** @public */
interface FilteredResponseQueryOptions extends ResponseQueryOptions {
  filterResponse?: true;
}
/** @public */
interface UnfilteredResponseQueryOptions extends ResponseQueryOptions {
  filterResponse: false;
  /**
   * When `filterResponse` is `false`, `returnQuery` also defaults to `true` for
   * backwards compatibility (on the client side, not from the content lake API).
   * Can also explicitly be set to `true`.
   */
  returnQuery?: true;
}
/**
 * When using `filterResponse: false`, but you do not wish to receive back the query from
 * the content lake API.
 *
 * @public
 */
interface UnfilteredResponseWithoutQuery extends ResponseQueryOptions {
  filterResponse: false;
  returnQuery: false;
}
/** @public */
type QueryOptions = FilteredResponseQueryOptions | UnfilteredResponseQueryOptions | UnfilteredResponseWithoutQuery;
/** @public */
interface RawQueryResponse<R> {
  query: string;
  ms: number;
  result: R;
  resultSourceMap?: ContentSourceMap;
  /** Requires `apiVersion` to be `2021-03-25` or later. */
  syncTags?: SyncTag[];
}
/** @public */
type RawQuerylessQueryResponse<R> = Omit<RawQueryResponse<R>, 'query'>;
/** @internal */
type BaseMutationOptions = RequestOptions & {
  visibility?: 'sync' | 'async' | 'deferred';
  returnDocuments?: boolean;
  returnFirst?: boolean;
  dryRun?: boolean;
  autoGenerateArrayKeys?: boolean;
  skipCrossDatasetReferenceValidation?: boolean;
  transactionId?: string;
};
/** @internal */
type FirstDocumentMutationOptions = BaseMutationOptions & {
  returnFirst?: true;
  returnDocuments?: true;
};
/** @internal */
type FirstDocumentIdMutationOptions = BaseMutationOptions & {
  returnFirst?: true;
  returnDocuments: false;
};
/** @internal */
type AllDocumentsMutationOptions = BaseMutationOptions & {
  returnFirst: false;
  returnDocuments?: true;
};
/** @internal */
type MutationOperation = 'create' | 'delete' | 'update' | 'none';
/** @internal */
interface SingleMutationResult {
  transactionId: string;
  documentId: string;
  results: {
    id: string;
    operation: MutationOperation;
  }[];
}
/** @internal */
interface MultipleMutationResult {
  transactionId: string;
  documentIds: string[];
  results: {
    id: string;
    operation: MutationOperation;
  }[];
}
/** @internal */
type AllDocumentIdsMutationOptions = BaseMutationOptions & {
  returnFirst: false;
  returnDocuments: false;
};
/** @internal */
type AttributeSet = {
  [key: string]: Any;
};
/** @internal */
type TransactionFirstDocumentMutationOptions = BaseMutationOptions & {
  returnFirst: true;
  returnDocuments: true;
};
/** @internal */
type TransactionFirstDocumentIdMutationOptions = BaseMutationOptions & {
  returnFirst: true;
  returnDocuments?: false;
};
/** @internal */
type TransactionAllDocumentsMutationOptions = BaseMutationOptions & {
  returnFirst?: false;
  returnDocuments: true;
};
/** @internal */
type TransactionAllDocumentIdsMutationOptions = BaseMutationOptions & {
  returnFirst?: false;
  returnDocuments?: false;
};
/** @internal */
type TransactionMutationOptions = TransactionFirstDocumentMutationOptions | TransactionFirstDocumentIdMutationOptions | TransactionAllDocumentsMutationOptions | TransactionAllDocumentIdsMutationOptions;
/** @internal */
type BaseActionOptions = RequestOptions & {
  transactionId?: string;
  skipCrossDatasetReferenceValidation?: boolean;
  dryRun?: boolean;
};
/** @internal */
interface SingleActionResult {
  transactionId: string;
}
/** @internal */
interface MultipleActionResult {
  transactionId: string;
}
/** @internal */
type RawRequestOptions = RequestUrlOptions & {
  method?: string;
  token?: string;
  /** @deprecated has no effect — response parsing is driven by the response `content-type` */
  json?: boolean;
  tag?: string;
  useGlobalApi?: boolean;
  withCredentials?: boolean;
  query?: {
    [key: string]: string | string[];
  };
  headers?: {
    [key: string]: string;
  };
  timeout?: number;
  body?: Any;
  maxRedirects?: number;
  /** Max retries for this request; `0` disables retries. Overrides the client-level maximum in both directions. */
  maxRetries?: number;
  signal?: AbortSignal;
};
/** @internal */
interface ApiError {
  error: string;
  message: string;
  statusCode: number;
}
/** @internal */
interface MutationError {
  type: 'mutationError';
  description: string;
  items?: MutationErrorItem[];
}
/**
 * Returned from the Content Lake API when a query is malformed, usually with a start
 * and end column to indicate where the error occurred, but not always. Can we used to
 * provide a more structured error message to the user.
 *
 * This will be located under the response `error` property.
 *
 * @public
 */
interface QueryParseError {
  type: 'queryParseError';
  description: string;
  start?: number;
  end?: number;
  query?: string;
}
/** @internal */
interface MutationErrorItem {
  error: {
    type: string;
    description: string;
    value?: unknown;
  };
}
/** @internal */
interface ActionError {
  type: 'actionError';
  description: string;
  items?: ActionErrorItem[];
}
/** @internal */
interface ActionErrorItem {
  error: {
    type: string;
    description: string;
    value?: unknown;
  };
  index: number;
}
/** @internal */
type PartialExcept<T, K extends keyof T> = Pick<T, K> & Partial<Omit<T, K>>;
/** @beta */
type ReleaseState = 'active' | 'archiving' | 'unarchiving' | 'archived' | 'published' | 'publishing' | 'scheduled' | 'scheduling';
/** @internal */
type ReleaseType = 'asap' | 'scheduled' | 'undecided';
/** @public */
type ReleaseCardinality = 'many' | 'one' | undefined;
/** @internal */
interface ReleaseDocument extends SanityDocument {
  /**
   * typically
   * `_.releases.<name>`
   */
  _id: string;
  /**
   * where a release has _id `_.releases.foo`, the name is `foo`
   */
  name: string;
  _type: 'system.release';
  _createdAt: string;
  _updatedAt: string;
  _rev: string;
  state: ReleaseState;
  error?: {
    message: string;
  };
  finalDocumentStates?: {
    /** Document ID */
    id: string;
  }[];
  /**
   * If defined, it takes precedence over the intendedPublishAt, the state should be 'scheduled'
   */
  publishAt?: string;
  /**
   * If defined, it provides the time the release was actually published
   */
  publishedAt?: string;
  metadata: {
    title?: string;
    description?: string;
    intendedPublishAt?: string;
    releaseType: ReleaseType;
    cardinality?: ReleaseCardinality;
  };
}
/** @internal */
type EditableReleaseDocument = Omit<PartialExcept<ReleaseDocument, '_id'>, 'metadata' | '_type'> & {
  _id: string;
  metadata: Partial<ReleaseDocument['metadata']>;
};
/**
 * DocumentValueSource is a path to a value within a document
 * @public
 */
interface ContentSourceMapDocumentValueSource {
  type: 'documentValue';
  document: number;
  path: number;
}
/**
 * When a value is not from a source, its a literal
 * @public
 */
interface ContentSourceMapLiteralSource {
  type: 'literal';
}
/**
 * When a field source is unknown
 * @public
 */
interface ContentSourceMapUnknownSource {
  type: 'unknown';
}
/** @public */
type ContentSourceMapSource = ContentSourceMapDocumentValueSource | ContentSourceMapLiteralSource | ContentSourceMapUnknownSource;
/**
 * 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
 */
interface ContentSourceMapValueMapping {
  type: 'value';
  source: ContentSourceMapSource;
}
/** @public */
type ContentSourceMapMapping = ContentSourceMapValueMapping;
/** @public */
type ContentSourceMapMappings = Record<string, ContentSourceMapMapping>;
/** @public */
interface ContentSourceMapDocumentBase {
  _id: string;
  _type: string;
}
/** @public */
interface ContentSourceMapDocument extends ContentSourceMapDocumentBase {
  _projectId?: undefined;
  _dataset?: undefined;
}
/** @public */
interface ContentSourceMapRemoteDocument extends ContentSourceMapDocumentBase {
  _projectId: string;
  _dataset: string;
}
/** @public */
type ContentSourceMapDocuments = (ContentSourceMapDocument | ContentSourceMapRemoteDocument)[];
/** @public */
type ContentSourceMapPaths = string[];
/** @public */
interface ContentSourceMap {
  mappings: ContentSourceMapMappings;
  documents: ContentSourceMapDocuments;
  paths: ContentSourceMapPaths;
}
/** @public */
type SyncTag = `s1:${string}`;
/** @public */
interface LiveEventRestart {
  type: 'restart';
  id: string;
}
/** @public */
interface LiveEventReconnect {
  type: 'reconnect';
}
/** @public */
interface LiveEventMessage {
  type: 'message';
  id: string;
  tags: SyncTag[];
}
/** @public */
interface LiveEventWelcome {
  type: 'welcome';
}
/**
 * The `id` field is the position at which the connection was rejected or closed.
 * The `reason` field will specify why the connection rejected/closed.
 * @public
 */
interface LiveEventGoAway {
  type: 'goaway';
  id: string;
  reason: string;
}
/** @public */
type LiveEvent = LiveEventRestart | LiveEventReconnect | LiveEventMessage | LiveEventWelcome | LiveEventGoAway;
/** @public */
interface SanityQueries {}
/** @public */
type ClientReturn<GroqString extends string, Fallback = Any> = GroqString extends keyof SanityQueries ? SanityQueries[GroqString] : Fallback;
/**
 * A string constant containing the experimental API version warning message.
 * Use this with the `ignoreWarnings` option to suppress warnings when using experimental API versions.
 *
 * @example
 * ```typescript
 * import { createClient, EXPERIMENTAL_API_WARNING } from '@sanity/client'
 *
 * const client = createClient({
 *   projectId: 'your-project-id',
 *   dataset: 'production',
 *   apiVersion: 'vX', // experimental version
 *   ignoreWarnings: EXPERIMENTAL_API_WARNING
 * })
 * ```
 *
 * @public
 */
declare const EXPERIMENTAL_API_WARNING = "This is an experimental API version";
/**
 * Fit / resize modes accepted for thumbnail params.
 * @public
 */
type FitMode = 'preserve' | 'stretch' | 'crop' | 'smartcrop' | 'pad';
/**
 * Allowed still image formats (thumbnail + storyboard).
 * @public
 */
type StillImageFormat = 'jpg' | 'png' | 'webp';
/**
 * Allowed animated image formats.
 * @public
 */
type AnimatedImageFormat = 'gif' | 'webp';
/**
 * Thumbnail rendition (single frame) options.
 * @public
 */
interface ThumbnailTransformOptions {
  /** Pixel width of the thumbnail frame. */
  width?: number;
  /** Pixel height of the thumbnail frame. */
  height?: number;
  /** Timestamp (seconds) from which to grab the frame. */
  time?: number;
  /** Resize / fit mode applied to the extracted frame. */
  fit?: FitMode;
  /** Output image format. */
  format?: StillImageFormat;
}
/**
 * Animated preview rendition options (e.g. GIF / animated WebP).
 * @public
 */
interface AnimatedTransformOptions {
  /** Pixel width of the animated output. Max 640 px. */
  width?: number;
  /** Pixel height of the animated output. Max 640 px. */
  height?: number;
  /** Start time in seconds (inclusive). */
  start?: number;
  /** End time in seconds. */
  end?: number;
  /** Frames per second (1–30). */
  fps?: number;
  /** Output animated format. */
  format?: AnimatedImageFormat;
}
/**
 * Storyboard (contact sheet) options.
 * @public
 */
interface StoryboardTransformOptions {
  /** Output image format for the storyboard. */
  format?: StillImageFormat;
}
/**
 * Video-specific playback transformation option groups.
 * Only explicitly provided values are serialized into query parameters.
 * @public
 */
interface MediaLibraryVideoPlaybackTransformations {
  /** Static thumbnail (single frame) options. */
  thumbnail?: ThumbnailTransformOptions;
  /** Animated preview options (GIF / animated WebP). */
  animated?: AnimatedTransformOptions;
  /** Storyboard (contact sheet) options. */
  storyboard?: StoryboardTransformOptions;
}
/**
 * Options for requesting playback info (URLs + optional tokens) for a Media Library video asset.
 *
 * Removed: generic fallback parameters (width, height, fit, format). Supply per‑transformation values instead.
 * Animated transformations intentionally exclude any fit option (not supported by Mux).
 *
 * includeTokens is a client-side flag (not sent to the server) controlling whether
 * returned tokens should be appended to URLs when consumed.
 * @public
 */
interface MediaLibraryPlaybackInfoOptions {
  /** Explicit per-video transformation options (thumbnail, animated, storyboard). */
  transformations?: MediaLibraryVideoPlaybackTransformations;
  /** Expiration hint for secured/signed URLs (string or number, number will be stringified). */
  expiration?: string | number;
}
/** @public */
interface VideoPlaybackInfoItemPublic {
  url: string;
}
/** @public */
interface VideoPlaybackInfoItemSigned extends VideoPlaybackInfoItemPublic {
  token: string;
}
/** @public */
type VideoPlaybackInfoItem = VideoPlaybackInfoItemPublic | VideoPlaybackInfoItemSigned;
/** @public */
interface VideoRenditionInfoPublic {
  /** URL to the MP4 rendition (redirects to CDN) */
  url: string;
  /** Resolution identifier, e.g. "1080p", "480p", "270p" */
  resolution: '1080p' | '480p' | '270p' | (string & {});
}
/** @public */
interface VideoRenditionInfoSigned extends VideoRenditionInfoPublic {
  /** Authentication token for signed playback */
  token: string;
  /** Token expiration time in ISO 8601 format */
  expiresAt: string;
}
/** @public */
type VideoRenditionInfo = VideoRenditionInfoPublic | VideoRenditionInfoSigned;
/** @public */
interface VideoSubtitleInfoPublic {
  /** Subtitle track identifier */
  trackId: string;
  /** ISO 639-1 language code */
  languageCode: string;
  /** URL to the subtitle file */
  url: string;
  /** Whether this track contains closed captions */
  closedCaptions: boolean;
}
/** @public */
interface VideoSubtitleInfoSigned extends VideoSubtitleInfoPublic {
  /** Authentication token for signed playback */
  token: string;
  /** Token expiration time in ISO 8601 format */
  expiresAt: string;
}
/** @public */
type VideoSubtitleInfo = VideoSubtitleInfoPublic | VideoSubtitleInfoSigned;
/** @public */
interface VideoPlaybackInfo<T extends VideoPlaybackInfoItem = VideoPlaybackInfoItem, R extends VideoRenditionInfo = T extends VideoPlaybackInfoItemSigned ? VideoRenditionInfoSigned : VideoRenditionInfo, S extends VideoSubtitleInfo = T extends VideoPlaybackInfoItemSigned ? VideoSubtitleInfoSigned : VideoSubtitleInfo> {
  id: string;
  thumbnail: T;
  animated: T;
  storyboard: T;
  stream: T;
  duration: number;
  aspectRatio: number;
  renditions?: R[];
  subtitles?: S[];
}
/** @public */
type VideoPlaybackInfoSigned = VideoPlaybackInfo<VideoPlaybackInfoItemSigned>;
/** @public */
type VideoPlaybackInfoPublic = VideoPlaybackInfo<VideoPlaybackInfoItemPublic>;
/** @public */
interface VideoPlaybackTokens {
  stream?: string;
  thumbnail?: string;
  storyboard?: string;
  animated?: string;
}
/** @public */
type MediaLibraryAssetInstanceIdentifier = string | SanityReference;
/**
 * A single tracked version of a Media Library asset - one uploaded instance,
 * referencing the underlying (Content Lake shaped) asset document it wraps.
 *
 * @public
 */
interface MediaLibraryAssetVersion {
  _key: string;
  _type: 'sanity.asset.version';
  title?: string;
  instance: SanityReference;
}
/**
 * The document returned by the Media Library upload endpoint
 * (`POST /media-libraries/:id/upload`).
 *
 * This is _not_ the same shape as {@link SanityAssetDocument} /
 * {@link SanityImageAssetDocument}: a Media Library asset is a `sanity.asset`
 * document that tracks one or more uploaded versions, each pointing at its
 * own underlying Content Lake asset document via `currentVersion`/`versions`.
 *
 * Modelled directly on an observed API response. Fields whose full shape has
 * not been confirmed (`parent`, `rootDirectory`, `aspects`) are typed loosely
 * on purpose - widen them once their shape is confirmed.
 *
 * @public
 */
interface MediaLibraryAssetDocument {
  _id: string;
  _type: 'sanity.asset';
  assetType: string;
  title?: string;
  cdnAccessPolicy?: string;
  currentVersion: SanityReference;
  versions: MediaLibraryAssetVersion[];
  aspects?: Record<string, Any>;
  parent?: SanityReference | null;
  rootDirectory?: Any;
}
/**
 * @internal - it may have breaking changes in any release
 */
declare function validateApiPerspective(perspective: unknown): asserts perspective is ClientPerspective;
/**
 * Thrown when the EventSource connection could not be established, or was rejected by the server.
 * Transient failures (network drops, 5xx, 408, 429) are reconnected internally and emitted as
 * `reconnect` events; a permanent rejection (any other 4xx, eg an expired token) errors the
 * stream with this class so consumers can react — check `status` for the rejection code.
 *
 * @public
 */
declare class ConnectionFailedError extends Error {
  readonly name = "ConnectionFailedError";
  /**
   * HTTP status code of the rejected connection attempt, if known.
   * Only set when the EventSource implementation exposes it — the `eventsource`
   * package used by the client does (as `code` on its error events), while
   * native EventSource implementations (browser and Node.js) do not.
   */
  readonly status?: number;
  constructor(message?: string, options?: ErrorOptions & {
    status?: number;
  });
}
/**
 * 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
 */
declare class DisconnectError extends Error {
  readonly name = "DisconnectError";
  readonly reason?: string;
  constructor(message: string, reason?: string, options?: ErrorOptions);
}
/**
 * The server sent a `channelError` message. Usually indicative of a bad or malformed request
 *
 * @public
 */
declare class ChannelError extends Error {
  readonly name = "ChannelError";
  readonly data?: unknown;
  constructor(message: string, data: unknown);
}
/**
 * The server sent an `error`-event to tell the client that an unexpected error has happened.
 *
 * @public
 */
declare class MessageError extends Error {
  readonly name = "MessageError";
  readonly data?: unknown;
  constructor(message: string, data: unknown, options?: ErrorOptions);
}
/**
 * An error occurred while parsing the message sent by the server as JSON. Should normally not happen.
 *
 * @public
 */
declare class MessageParseError extends Error {
  readonly name = "MessageParseError";
}
/**
 * @public
 */
interface ServerSentEvent<Name extends string> {
  type: Name;
  id?: string;
  data?: unknown;
}
/**
 * @internal
 */
type EventSourceEvent<Name extends string> = ServerSentEvent<Name>;
/**
 * @internal
 */
type EventSourceInstance = InstanceType<EventSourceConstructor>;
/**
 * 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
 */
declare function connectEventSource<EventName extends string>(initEventSource: () => EventSourceInstance | Observable<EventSourceInstance>, events: EventName[]): Observable<EventSourceEvent<EventName>>;
/**
 * Shared properties for HTTP errors (eg both ClientError and ServerError)
 * Use `isHttpError` for type narrowing and accessing response properties.
 *
 * @public
 */
interface HttpError {
  statusCode: number;
  message: string;
  response: {
    body: unknown;
    url: string;
    method: string;
    headers: Record<string, string>;
    statusCode: number;
    statusMessage: string | null;
  };
}
/**
 * Checks if the provided error is an HTTP error.
 *
 * @param error - The error to check.
 * @returns `true` if the error is an HTTP error, `false` otherwise.
 * @public
 */
declare function isHttpError(error: unknown): error is HttpError;
/** @public */
declare class ClientError extends Error {
  response: ErrorProps['response'];
  statusCode: ErrorProps['statusCode'];
  responseBody: ErrorProps['responseBody'];
  traceId: ErrorProps['traceId'];
  details: ErrorProps['details'];
  constructor(res: Any, tag?: string);
}
/** @public */
declare class ServerError extends Error {
  response: ErrorProps['response'];
  statusCode: ErrorProps['statusCode'];
  responseBody: ErrorProps['responseBody'];
  traceId: ErrorProps['traceId'];
  details: ErrorProps['details'];
  constructor(res: Any);
}
/** @internal */
declare function isQueryParseError(error: object): error is QueryParseError;
/**
 * 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
 */
declare function formatQueryParseError(error: QueryParseError, tag?: string | null, traceId?: string): string;
/** @public */
declare class CorsOriginError extends Error {
  projectId?: string;
  addOriginUrl?: URL;
  constructor({ projectId, credentials }?: {
    projectId?: string;
    credentials?: boolean;
  });
}
/** @public */
declare const requester: Requester;
/**
 * @remarks
 * As of API version `v2025-02-19`, the default perspective used by the client has changed from `raw` to `published`. {@link https://www.sanity.io/changelog/676aaa9d-2da6-44fb-abe5-580f28047c10|Changelog}
 * @public
 */
declare const createClient: (config: ClientConfig) => SanityClient;
/**
 * @public
 * @deprecated Use the named export `createClient` instead of the `default` export
 */
declare const deprecatedCreateClient: (config: ClientConfig) => SanityClient;
export { Action, ActionError, ActionErrorItem, type AgentActionParam, type AgentActionParams, type AgentActionPath, type AgentActionPathSegment, type AgentActionTarget, AllDocumentIdsMutationOptions, AllDocumentsMutationOptions, AnimatedImageFormat, AnimatedTransformOptions, Any, ApiError, ArchiveReleaseAction, AssetMetadataType, type AssetsClient, AttributeSet, AuthProvider, AuthProviderResponse, BaseActionOptions, BaseMutationOptions, BasePatch, BaseTransaction, ChannelError, ChannelErrorEvent, ClientConfig, ClientError, ClientPerspective, ClientReturn, ClientVariant, ClientVariantConditions, type CollaborationCommentCreate, type CollaborationCommentDocument, type CollaborationCommentFieldValue, type CollaborationCommentMessage, type CollaborationCommentPortableTextBlock, type CollaborationCommentRange, type CollaborationCommentReactionShortName, type CollaborationCommentSelection, type CollaborationCommentStatus, type CollaborationCommentTarget, type CollaborationCommentUpdate, type CollaborationCommentsClient, type CollaborationCommentsListenOptions, type CollaborationCommentsRequestOptions, type CollaborationCommentsWriteOptions, ConnectionFailedError, type ConstantAgentActionParam, ContentSourceMap, ContentSourceMapDocument, ContentSourceMapDocumentBase, ContentSourceMapDocumentValueSource, ContentSourceMapDocuments, ContentSourceMapLiteralSource, ContentSourceMapMapping, ContentSourceMapMappings, type ContentSourceMapParsedPath, type ContentSourceMapParsedPathKeyedSegment, ContentSourceMapPaths, ContentSourceMapRemoteDocument, ContentSourceMapSource, ContentSourceMapUnknownSource, ContentSourceMapValueMapping, types_d_exports as Context, CorsOriginError, CreateAction, CreateReleaseAction, CreateVariantAction, CreateVariantDefinitionAction, CreateVersionAction, CurrentSanityUser, DatasetAclMode, DatasetCreateOptions, DatasetEditOptions, DatasetResponse, type DatasetsClient, DatasetsResponse, DeleteAction, DeleteReleaseAction, DeleteVariantAction, DeleteVariantDefinitionAction, DiscardAction, DiscardVersionAction, DisconnectError, DisconnectEvent, type DocumentAgentActionParam, EXPERIMENTAL_API_WARNING, EditAction, EditReleaseAction, EditVariantAction, EditVariantDefinitionAction, EditableReleaseDocument, EmbeddingsSettings, EmbeddingsSettingsBody, ErrorProps, type EventSourceEvent, type EventSourceInstance, type FieldAgentActionParam, type FilterDefault, FilteredResponseQueryOptions, FirstDocumentIdMutationOptions, FirstDocumentMutationOptions, FitMode, type GenerateInstruction, type GenerateOperation, type GenerateTarget, type GenerateTargetDocument, type GenerateTargetInclude, type GroqAgentActionParam, type HttpError, HttpRequest, IdentifiedSanityDocumentStub, type ImageDescriptionOperation, ImportReleaseAction, InitializedClientConfig, type InitializedStegaConfig, InsertPatch, type InvokeFunctionEvent, type InvokeFunctionOptions, type InvokeFunctionRequest, ListenEvent, ListenEventName, ListenOptions, ListenParams, type LiveClient, LiveEvent, LiveEventGoAway, LiveEventMessage, LiveEventReconnect, LiveEventRestart, LiveEventWelcome, type Logger, MediaLibraryAssetDocument, MediaLibraryAssetInstanceIdentifier, MediaLibraryAssetVersion, MediaLibraryPlaybackInfoOptions, type MediaLibraryVideoClient, MediaLibraryVideoPlaybackTransformations, MessageError, MessageParseError, MultipleActionResult, MultipleMutationResult, Mutation, MutationError, MutationErrorItem, MutationEvent, MutationOperation, MutationSelection, MutationSelectionQueryParams, type ObservableAssetsClient, type ObservableCollaborationCommentsClient, type ObservableDatasetsClient, type ObservableMediaLibraryVideoClient, ObservablePatch, ObservablePatchBuilder, type ObservableProjectsClient, ObservableSanityClient, ObservableTransaction, type ObservableUsersClient, OpenEvent, PartialExcept, Patch, PatchBuilder, type PatchDocument, PatchMutationOperation, type PatchOperation, PatchOperations, PatchSelection, type PatchTarget, type ProjectsClient, type PromptRequest, PublishAction, PublishReleaseAction, PublishVariantAction, QueryOptions, QueryParams, QueryParseError, QueryWithoutParams, RawQueryResponse, RawQuerylessQueryResponse, RawRequestOptions, ReconnectEvent, ReleaseAction, ReleaseCardinality, ReleaseDocument, ReleaseId, ReleaseState, ReleaseType, ReplaceDraftAction, ReplaceVersionAction, RequestHandler, RequestHandlerOptions, RequestObservableOptions, RequestOptions, RequestUrlOptions, Requester, ResetEvent, type ResolveStudioUrl, ResponseQueryOptions, ResumableListenEventNames, ResumableListenOptions, SanityAssetDocument, SanityClient, SanityDocument, SanityDocumentStub, SanityImageAssetDocument, SanityImagePalette, SanityProject, SanityProjectMember, SanityQueries, SanityReference, SanityUser, ScheduleReleaseAction, ServerError, type ServerSentEvent, SingleActionResult, SingleMutationResult, StackablePerspective, type StegaConfig, type StegaConfigRequiredKeys, StillImageFormat, StoryboardTransformOptions, type StudioBaseRoute, type StudioBaseUrl, type StudioUrl, SyncTag, ThumbnailTransformOptions, type TimeoutErrorLike, Transaction, TransactionAllDocumentIdsMutationOptions, TransactionAllDocumentsMutationOptions, TransactionFirstDocumentIdMutationOptions, TransactionFirstDocumentMutationOptions, TransactionMutationOptions, type TransformDocument, type TransformOperation, type TransformTarget, type TransformTargetDocument, type TransformTargetInclude, type TranslateDocument, type TranslateTarget, type TranslateTargetInclude, UnarchiveReleaseAction, UnfilteredResponseQueryOptions, UnfilteredResponseWithoutQuery, UnpublishAction, UnpublishVariantAction, UnpublishVersionAction, UnscheduleReleaseAction, UploadBody, UploadClientConfig, UploadEvent, UploadProgressEvent, UploadResponseEvent, type UsersClient, VariantAction, VariantDefinitionAction, VersionAction, VideoPlaybackInfo, VideoPlaybackInfoItem, VideoPlaybackInfoItemPublic, VideoPlaybackInfoItemSigned, VideoPlaybackInfoPublic, VideoPlaybackInfoSigned, VideoPlaybackTokens, VideoRenditionInfo, VideoRenditionInfoPublic, VideoRenditionInfoSigned, VideoSubtitleInfo, VideoSubtitleInfoPublic, VideoSubtitleInfoSigned, WelcomeBackEvent, WelcomeEvent, type _listen, connectEventSource, createClient, deprecatedCreateClient as default, formatQueryParseError, isHttpError, isQueryParseError, isTimeoutError, requester, validateApiPerspective };
//# sourceMappingURL=index.node.d.ts.map