@sanity/client 7.13.2 → 7.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +66 -4
- package/dist/_chunks-cjs/config.cjs +21 -8
- package/dist/_chunks-cjs/config.cjs.map +1 -1
- package/dist/_chunks-es/config.js +21 -8
- package/dist/_chunks-es/config.js.map +1 -1
- package/dist/index.browser.cjs +40 -18
- package/dist/index.browser.cjs.map +1 -1
- package/dist/index.browser.d.cts +22 -1
- package/dist/index.browser.d.ts +22 -1
- package/dist/index.browser.js +40 -18
- package/dist/index.browser.js.map +1 -1
- package/dist/index.cjs +20 -11
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +22 -1
- package/dist/index.d.ts +22 -1
- package/dist/index.js +20 -11
- package/dist/index.js.map +1 -1
- package/dist/stega.browser.d.cts +22 -1
- package/dist/stega.browser.d.ts +22 -1
- package/dist/stega.d.cts +22 -1
- package/dist/stega.d.ts +22 -1
- package/package.json +2 -2
- package/src/assets/AssetsClient.ts +25 -11
- package/src/config.ts +10 -2
- package/src/data/dataMethods.ts +12 -6
- package/src/mediaLibrary/MediaLibraryVideoClient.ts +3 -1
- package/src/types.ts +23 -1
- package/src/validators.ts +22 -6
- package/src/warnings.ts +5 -0
- package/umd/sanityClient.js +40 -18
- package/umd/sanityClient.min.js +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.browser.js","sources":["../src/util/codeFrame.ts","../src/http/errors.ts","../src/http/request.ts","../src/generateHelpUrl.ts","../src/validators.ts","../src/types.ts","../src/util/once.ts","../src/warnings.ts","../src/config.ts","../src/data/eventsource.ts","../src/util/getSelection.ts","../src/data/patch.ts","../src/data/transaction.ts","../src/http/requestOptions.ts","../src/data/encodeQueryString.ts","../src/data/dataMethods.ts","../src/agent/actions/generate.ts","../src/agent/actions/patch.ts","../src/agent/actions/prompt.ts","../src/agent/actions/transform.ts","../src/agent/actions/translate.ts","../src/agent/actions/AgentActionsClient.ts","../src/assets/AssetsClient.ts","../src/util/defaults.ts","../src/util/pick.ts","../src/data/eventsourcePolyfill.ts","../src/data/reconnectOnConnectionFailure.ts","../src/data/listen.ts","../src/util/shareReplayLatest.ts","../src/data/live.ts","../src/datasets/DatasetsClient.ts","../src/mediaLibrary/MediaLibraryVideoClient.ts","../src/projects/ProjectsClient.ts","../src/util/createVersionId.ts","../src/releases/createRelease.ts","../src/releases/ReleasesClient.ts","../src/users/UsersClient.ts","../src/SanityClient.ts","../src/defineCreateClient.ts","../src/defineDeprecatedCreateClient.ts","../src/http/browserMiddleware.ts","../src/index.browser.ts"],"sourcesContent":["/**\n * Inlined, modified version of the `codeFrameColumns` function from `@babel/code-frame`.\n * MIT-licensed - https://github.com/babel/babel/blob/main/LICENSE\n * Copyright (c) 2014-present Sebastian McKenzie and other contributors.\n */\ntype Location = {\n column: number\n line: number\n}\n\ntype NodeLocation = {\n start: Location\n end?: Location\n}\n\ntype GroqLocation = {\n start: number\n end?: number\n}\n\n/**\n * RegExp to test for newlines.\n */\n\nconst NEWLINE = /\\r\\n|[\\n\\r\\u2028\\u2029]/\n\n/**\n * Extract what lines should be marked and highlighted.\n */\n\ntype MarkerLines = Record<number, true | [number, number]>\n\n/**\n * Highlight a code frame with the given location and message.\n *\n * @param query - The query to be highlighted.\n * @param location - The location of the error in the code/query.\n * @param message - Message to be displayed inline (if possible) next to the highlighted\n * location in the code. If it can't be positioned inline, it will be placed above the\n * code frame.\n * @returns The highlighted code frame.\n */\nexport function codeFrame(query: string, location: GroqLocation, message?: string): string {\n const lines = query.split(NEWLINE)\n const loc = {\n start: columnToLine(location.start, lines),\n end: location.end ? columnToLine(location.end, lines) : undefined,\n }\n\n const {start, end, markerLines} = getMarkerLines(loc, lines)\n\n const numberMaxWidth = `${end}`.length\n\n return query\n .split(NEWLINE, end)\n .slice(start, end)\n .map((line, index) => {\n const number = start + 1 + index\n const paddedNumber = ` ${number}`.slice(-numberMaxWidth)\n const gutter = ` ${paddedNumber} |`\n const hasMarker = markerLines[number]\n const lastMarkerLine = !markerLines[number + 1]\n if (!hasMarker) {\n return ` ${gutter}${line.length > 0 ? ` ${line}` : ''}`\n }\n\n let markerLine = ''\n if (Array.isArray(hasMarker)) {\n const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\\t]/g, ' ')\n const numberOfMarkers = hasMarker[1] || 1\n\n markerLine = [\n '\\n ',\n gutter.replace(/\\d/g, ' '),\n ' ',\n markerSpacing,\n '^'.repeat(numberOfMarkers),\n ].join('')\n\n if (lastMarkerLine && message) {\n markerLine += ' ' + message\n }\n }\n return ['>', gutter, line.length > 0 ? ` ${line}` : '', markerLine].join('')\n })\n .join('\\n')\n}\n\nfunction getMarkerLines(\n loc: NodeLocation,\n source: Array<string>,\n): {\n start: number\n end: number\n markerLines: MarkerLines\n} {\n const startLoc: Location = {...loc.start}\n const endLoc: Location = {...startLoc, ...loc.end}\n const linesAbove = 2\n const linesBelow = 3\n const startLine = startLoc.line ?? -1\n const startColumn = startLoc.column ?? 0\n const endLine = endLoc.line\n const endColumn = endLoc.column\n\n let start = Math.max(startLine - (linesAbove + 1), 0)\n let end = Math.min(source.length, endLine + linesBelow)\n\n if (startLine === -1) {\n start = 0\n }\n\n if (endLine === -1) {\n end = source.length\n }\n\n const lineDiff = endLine - startLine\n const markerLines: MarkerLines = {}\n\n if (lineDiff) {\n for (let i = 0; i <= lineDiff; i++) {\n const lineNumber = i + startLine\n\n if (!startColumn) {\n markerLines[lineNumber] = true\n } else if (i === 0) {\n const sourceLength = source[lineNumber - 1].length\n\n markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1]\n } else if (i === lineDiff) {\n markerLines[lineNumber] = [0, endColumn]\n } else {\n const sourceLength = source[lineNumber - i].length\n\n markerLines[lineNumber] = [0, sourceLength]\n }\n }\n } else {\n if (startColumn === endColumn) {\n if (startColumn) {\n markerLines[startLine] = [startColumn, 0]\n } else {\n markerLines[startLine] = true\n }\n } else {\n markerLines[startLine] = [startColumn, endColumn - startColumn]\n }\n }\n\n return {start, end, markerLines}\n}\n\nfunction columnToLine(column: number, lines: string[]): Location {\n let offset = 0\n\n for (let i = 0; i < lines.length; i++) {\n const lineLength = lines[i].length + 1 // assume '\\n' after each line\n\n if (offset + lineLength > column) {\n return {\n line: i + 1, // 1-based line\n column: column - offset, // 0-based column\n }\n }\n\n offset += lineLength\n }\n\n // Fallback: beyond last line\n return {\n line: lines.length,\n column: lines[lines.length - 1]?.length ?? 0,\n }\n}\n","import type {HttpContext} from 'get-it'\n\nimport type {ActionError, Any, ErrorProps, MutationError, QueryParseError} from '../types'\nimport {codeFrame} from '../util/codeFrame'\nimport {isRecord} from '../util/isRecord'\n\nconst MAX_ITEMS_IN_ERROR_MESSAGE = 5\n\n/**\n * Shared properties for HTTP errors (eg both ClientError and ServerError)\n * Use `isHttpError` for type narrowing and accessing response properties.\n *\n * @public\n */\nexport interface HttpError {\n statusCode: number\n message: string\n response: {\n body: unknown\n url: string\n method: string\n headers: Record<string, string>\n statusCode: number\n statusMessage: string | null\n }\n}\n\n/**\n * Checks if the provided error is an HTTP error.\n *\n * @param error - The error to check.\n * @returns `true` if the error is an HTTP error, `false` otherwise.\n * @public\n */\nexport function isHttpError(error: unknown): error is HttpError {\n if (!isRecord(error)) {\n return false\n }\n\n const response = error.response\n if (\n typeof error.statusCode !== 'number' ||\n typeof error.message !== 'string' ||\n !isRecord(response)\n ) {\n return false\n }\n\n if (\n typeof response.body === 'undefined' ||\n typeof response.url !== 'string' ||\n typeof response.method !== 'string' ||\n typeof response.headers !== 'object' ||\n typeof response.statusCode !== 'number'\n ) {\n return false\n }\n\n return true\n}\n\n/** @public */\nexport class ClientError extends Error {\n response: ErrorProps['response']\n statusCode: ErrorProps['statusCode'] = 400\n responseBody: ErrorProps['responseBody']\n details: ErrorProps['details']\n\n constructor(res: Any, context?: HttpContext) {\n const props = extractErrorProps(res, context)\n super(props.message)\n Object.assign(this, props)\n }\n}\n\n/** @public */\nexport class ServerError extends Error {\n response: ErrorProps['response']\n statusCode: ErrorProps['statusCode'] = 500\n responseBody: ErrorProps['responseBody']\n details: ErrorProps['details']\n\n constructor(res: Any) {\n const props = extractErrorProps(res)\n super(props.message)\n Object.assign(this, props)\n }\n}\n\nfunction extractErrorProps(res: Any, context?: HttpContext): ErrorProps {\n const body = res.body\n const props = {\n response: res,\n statusCode: res.statusCode,\n responseBody: stringifyBody(body, res),\n message: '',\n details: undefined as Any,\n }\n\n // Fall back early if we didn't get a JSON object returned as expected\n if (!isRecord(body)) {\n props.message = httpErrorMessage(res, body)\n return props\n }\n\n const error = body.error\n\n // API/Boom style errors ({statusCode, error, message})\n if (typeof error === 'string' && typeof body.message === 'string') {\n props.message = `${error} - ${body.message}`\n return props\n }\n\n // Content Lake errors with a `error` prop being an object\n if (typeof error !== 'object' || error === null) {\n if (typeof error === 'string') {\n props.message = error\n } else if (typeof body.message === 'string') {\n props.message = body.message\n } else {\n props.message = httpErrorMessage(res, body)\n }\n return props\n }\n\n // Mutation errors (specifically)\n if (isMutationError(error) || isActionError(error)) {\n const allItems = error.items || []\n const items = allItems\n .slice(0, MAX_ITEMS_IN_ERROR_MESSAGE)\n .map((item) => item.error?.description)\n .filter(Boolean)\n let itemsStr = items.length ? `:\\n- ${items.join('\\n- ')}` : ''\n if (allItems.length > MAX_ITEMS_IN_ERROR_MESSAGE) {\n itemsStr += `\\n...and ${allItems.length - MAX_ITEMS_IN_ERROR_MESSAGE} more`\n }\n props.message = `${error.description}${itemsStr}`\n props.details = body.error\n return props\n }\n\n // Query parse errors\n if (isQueryParseError(error)) {\n const tag = context?.options?.query?.tag\n props.message = formatQueryParseError(error, tag)\n props.details = body.error\n return props\n }\n\n if ('description' in error && typeof error.description === 'string') {\n // Query/database errors ({error: {description, other, arb, props}})\n props.message = error.description\n props.details = error\n return props\n }\n\n // Other, more arbitrary errors\n props.message = httpErrorMessage(res, body)\n return props\n}\n\nfunction isMutationError(error: object): error is MutationError {\n return (\n 'type' in error &&\n error.type === 'mutationError' &&\n 'description' in error &&\n typeof error.description === 'string'\n )\n}\n\nfunction isActionError(error: object): error is ActionError {\n return (\n 'type' in error &&\n error.type === 'actionError' &&\n 'description' in error &&\n typeof error.description === 'string'\n )\n}\n\n/** @internal */\nexport function isQueryParseError(error: object): error is QueryParseError {\n return (\n isRecord(error) &&\n error.type === 'queryParseError' &&\n typeof error.query === 'string' &&\n typeof error.start === 'number' &&\n typeof error.end === 'number'\n )\n}\n\n/**\n * Formats a GROQ query parse error into a human-readable string.\n *\n * @param error - The error object containing details about the parse error.\n * @param tag - An optional tag to include in the error message.\n * @returns A formatted error message string.\n * @public\n */\nexport function formatQueryParseError(error: QueryParseError, tag?: string | null) {\n const {query, start, end, description} = error\n\n if (!query || typeof start === 'undefined') {\n return `GROQ query parse error: ${description}`\n }\n\n const withTag = tag ? `\\n\\nTag: ${tag}` : ''\n const framed = codeFrame(query, {start, end}, description)\n\n return `GROQ query parse error:\\n${framed}${withTag}`\n}\n\nfunction httpErrorMessage(res: Any, body: unknown) {\n const details = typeof body === 'string' ? ` (${sliceWithEllipsis(body, 100)})` : ''\n const statusMessage = res.statusMessage ? ` ${res.statusMessage}` : ''\n return `${res.method}-request to ${res.url} resulted in HTTP ${res.statusCode}${statusMessage}${details}`\n}\n\nfunction stringifyBody(body: Any, res: Any) {\n const contentType = (res.headers['content-type'] || '').toLowerCase()\n const isJson = contentType.indexOf('application/json') !== -1\n return isJson ? JSON.stringify(body, null, 2) : body\n}\n\nfunction sliceWithEllipsis(str: string, max: number) {\n return str.length > max ? `${str.slice(0, max)}…` : str\n}\n\n/** @public */\nexport class CorsOriginError extends Error {\n projectId: string\n addOriginUrl?: URL\n\n constructor({projectId}: {projectId: string}) {\n super('CorsOriginError')\n this.name = 'CorsOriginError'\n this.projectId = projectId\n\n const url = new URL(`https://sanity.io/manage/project/${projectId}/api`)\n if (typeof location !== 'undefined') {\n const {origin} = location\n url.searchParams.set('cors', 'add')\n url.searchParams.set('origin', origin)\n this.addOriginUrl = url\n this.message = `The current origin is not allowed to connect to the Live Content API. Add it here: ${url}`\n } else {\n this.message = `The current origin is not allowed to connect to the Live Content API. Change your configuration here: ${url}`\n }\n }\n}\n","import {getIt, type HttpContext, type Middlewares, type Requester} from 'get-it'\nimport {jsonRequest, jsonResponse, observable, progress, retry} from 'get-it/middleware'\nimport {Observable} from 'rxjs'\n\nimport type {Any} from '../types'\nimport {ClientError, ServerError} from './errors'\n\nconst httpError = {\n onResponse: (res: Any, context: HttpContext) => {\n if (res.statusCode >= 500) {\n throw new ServerError(res)\n } else if (res.statusCode >= 400) {\n throw new ClientError(res, context)\n }\n\n return res\n },\n}\n\nfunction printWarnings(config: {ignoreWarnings?: string | RegExp | Array<string | RegExp>} = {}) {\n const seen: Record<string, boolean> = {}\n\n // Helper function to check if a warning should be ignored\n const shouldIgnoreWarning = (message: string): boolean => {\n if (config.ignoreWarnings === undefined) return false\n\n const patterns = Array.isArray(config.ignoreWarnings)\n ? config.ignoreWarnings\n : [config.ignoreWarnings]\n\n return patterns.some((pattern) => {\n if (typeof pattern === 'string') {\n return message.includes(pattern)\n } else if (pattern instanceof RegExp) {\n return pattern.test(message)\n }\n return false\n })\n }\n\n return {\n onResponse: (res: Any) => {\n const warn = res.headers['x-sanity-warning']\n const warnings = Array.isArray(warn) ? warn : [warn]\n for (const msg of warnings) {\n if (!msg || seen[msg]) continue\n\n // Skip warnings that match ignore patterns\n if (shouldIgnoreWarning(msg)) {\n continue\n }\n\n seen[msg] = true\n console.warn(msg) // eslint-disable-line no-console\n }\n return res\n },\n }\n}\n\ntype HttpRequestConfig = {\n ignoreWarnings?: string | RegExp | Array<string | RegExp>\n}\n\n/** @internal */\nexport function defineHttpRequest(\n envMiddleware: Middlewares,\n config: HttpRequestConfig = {},\n): Requester {\n return getIt([\n retry({shouldRetry}),\n ...envMiddleware,\n printWarnings(config),\n jsonRequest(),\n jsonResponse(),\n progress(),\n httpError,\n observable({implementation: Observable}),\n ])\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction shouldRetry(err: any, attempt: number, options: any) {\n // Allow opting out of retries\n if (options.maxRetries === 0) return false\n\n // By default `retry.shouldRetry` doesn't retry on server errors so we add our own logic.\n\n const isSafe = options.method === 'GET' || options.method === 'HEAD'\n const uri = options.uri || options.url\n const isQuery = uri.startsWith('/data/query')\n const isRetriableResponse =\n err.response &&\n (err.response.statusCode === 429 ||\n err.response.statusCode === 502 ||\n err.response.statusCode === 503)\n\n // We retry the following errors:\n // - 429 means that the request was rate limited. It's a bit difficult\n // to know exactly how long it makes sense to wait and/or how many\n // attempts we should retry, but the backoff should alleviate the\n // additional load.\n // - 502/503 can occur when certain components struggle to talk to their\n // upstream dependencies. This is most likely a temporary problem\n // and retrying makes sense.\n\n if ((isSafe || isQuery) && isRetriableResponse) return true\n\n return retry.shouldRetry(err, attempt, options)\n}\n","const BASE_URL = 'https://www.sanity.io/help/'\n\nexport function generateHelpUrl(slug: string) {\n return BASE_URL + slug\n}\n","import type {Any, InitializedClientConfig, SanityDocumentStub} from './types'\n\nconst VALID_ASSET_TYPES = ['image', 'file']\nconst VALID_INSERT_LOCATIONS = ['before', 'after', 'replace']\n\nexport const dataset = (name: string) => {\n if (!/^(~[a-z0-9]{1}[-\\w]{0,63}|[a-z0-9]{1}[-\\w]{0,63})$/.test(name)) {\n throw new Error(\n 'Datasets can only contain lowercase characters, numbers, underscores and dashes, and start with tilde, and be maximum 64 characters',\n )\n }\n}\n\nexport const projectId = (id: string) => {\n if (!/^[-a-z0-9]+$/i.test(id)) {\n throw new Error('`projectId` can only contain only a-z, 0-9 and dashes')\n }\n}\n\nexport const validateAssetType = (type: string) => {\n if (VALID_ASSET_TYPES.indexOf(type) === -1) {\n throw new Error(`Invalid asset type: ${type}. Must be one of ${VALID_ASSET_TYPES.join(', ')}`)\n }\n}\n\nexport const validateObject = (op: string, val: Any) => {\n if (val === null || typeof val !== 'object' || Array.isArray(val)) {\n throw new Error(`${op}() takes an object of properties`)\n }\n}\n\nexport const validateDocumentId = (op: string, id: string) => {\n if (typeof id !== 'string' || !/^[a-z0-9_][a-z0-9_.-]{0,127}$/i.test(id) || id.includes('..')) {\n throw new Error(`${op}(): \"${id}\" is not a valid document ID`)\n }\n}\n\nexport const requireDocumentId = (op: string, doc: Record<string, Any>) => {\n if (!doc._id) {\n throw new Error(`${op}() requires that the document contains an ID (\"_id\" property)`)\n }\n\n validateDocumentId(op, doc._id)\n}\n\nexport const validateDocumentType = (op: string, type: string) => {\n if (typeof type !== 'string') {\n throw new Error(`\\`${op}()\\`: \\`${type}\\` is not a valid document type`)\n }\n}\n\nexport const requireDocumentType = (op: string, doc: Record<string, Any>) => {\n if (!doc._type) {\n throw new Error(`\\`${op}()\\` requires that the document contains a type (\\`_type\\` property)`)\n }\n\n validateDocumentType(op, doc._type)\n}\n\nexport const validateVersionIdMatch = (builtVersionId: string, document: SanityDocumentStub) => {\n if (document._id && document._id !== builtVersionId) {\n throw new Error(\n `The provided document ID (\\`${document._id}\\`) does not match the generated version ID (\\`${builtVersionId}\\`)`,\n )\n }\n}\n\nexport const validateInsert = (at: string, selector: string, items: Any[]) => {\n const signature = 'insert(at, selector, items)'\n if (VALID_INSERT_LOCATIONS.indexOf(at) === -1) {\n const valid = VALID_INSERT_LOCATIONS.map((loc) => `\"${loc}\"`).join(', ')\n throw new Error(`${signature} takes an \"at\"-argument which is one of: ${valid}`)\n }\n\n if (typeof selector !== 'string') {\n throw new Error(`${signature} takes a \"selector\"-argument which must be a string`)\n }\n\n if (!Array.isArray(items)) {\n throw new Error(`${signature} takes an \"items\"-argument which must be an array`)\n }\n}\n\nexport const hasDataset = (config: InitializedClientConfig): string => {\n if (!config.dataset) {\n throw new Error('`dataset` must be provided to perform queries')\n }\n\n return config.dataset || ''\n}\n\nexport const requestTag = (tag: string) => {\n if (typeof tag !== 'string' || !/^[a-z0-9._-]{1,75}$/i.test(tag)) {\n throw new Error(\n `Tag can only contain alphanumeric characters, underscores, dashes and dots, and be between one and 75 characters long.`,\n )\n }\n\n return tag\n}\n\nexport const resourceConfig = (config: InitializedClientConfig): void => {\n if (!config['~experimental_resource']) {\n throw new Error('`resource` must be provided to perform resource queries')\n }\n const {type, id} = config['~experimental_resource']\n\n switch (type) {\n case 'dataset': {\n const segments = id.split('.')\n if (segments.length !== 2) {\n throw new Error('Dataset resource ID must be in the format \"project.dataset\"')\n }\n return\n }\n case 'dashboard':\n case 'media-library':\n case 'canvas': {\n return\n }\n default:\n // @ts-expect-error - handle all supported resource types\n throw new Error(`Unsupported resource type: ${type.toString()}`)\n }\n}\n\nexport const resourceGuard = (service: string, config: InitializedClientConfig): void => {\n if (config['~experimental_resource']) {\n throw new Error(`\\`${service}\\` does not support resource-based operations`)\n }\n}\n","// deno-lint-ignore-file no-empty-interface\n/* eslint-disable @typescript-eslint/no-empty-object-type */\n\nimport type {Requester} from 'get-it'\n\nimport type {InitializedStegaConfig, StegaConfig} from './stega/types'\n\n/**\n * Used to tag types that is set to `any` as a temporary measure, but should be replaced with proper typings in the future\n * @internal\n */\nexport type Any = any // eslint-disable-line @typescript-eslint/no-explicit-any\n\ndeclare global {\n // Declare empty stub interfaces for environments where \"dom\" lib is not included\n interface File {}\n}\n\n/** @public */\nexport type UploadBody = File | Blob | Buffer | NodeJS.ReadableStream\n\n/** @public */\nexport interface RequestOptions {\n timeout?: number\n token?: string\n tag?: string\n headers?: Record<string, string>\n method?: string\n query?: Any\n body?: Any\n signal?: AbortSignal\n}\n\n/**\n * @public\n * @deprecated – The `r`-prefix is not required, use `string` instead\n */\nexport type ReleaseId = `r${string}`\n\n/**\n * @deprecated use 'drafts' instead\n */\ntype DeprecatedPreviewDrafts = 'previewDrafts'\n\n/** @public */\nexport type StackablePerspective = ('published' | 'drafts' | string) & {}\n\n/** @public */\nexport type ClientPerspective =\n | DeprecatedPreviewDrafts\n | 'published'\n | 'drafts'\n | 'raw'\n | StackablePerspective[]\n\ntype ClientConfigResource =\n | {\n type: 'canvas'\n id: string\n }\n | {\n type: 'media-library'\n id: string\n }\n | {\n type: 'dataset'\n id: string\n }\n | {\n type: 'dashboard'\n id: string\n }\n\n/** @public */\nexport interface ClientConfig {\n projectId?: string\n dataset?: string\n /** @defaultValue true */\n useCdn?: boolean\n token?: string\n\n /** @internal */\n '~experimental_resource'?: ClientConfigResource\n\n /**\n * What perspective to use for the client. See {@link https://www.sanity.io/docs/perspectives|perspective documentation}\n * @remarks\n * 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}\n * @defaultValue 'published'\n */\n perspective?: ClientPerspective\n apiHost?: string\n\n /**\n @remarks\n * 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}\n */\n apiVersion?: string\n proxy?: string\n\n /**\n * Optional request tag prefix for all request tags\n */\n requestTagPrefix?: string\n\n /**\n * Optional default headers to include with all requests\n *\n * @remarks request-specific headers will override any default headers with the same name.\n */\n headers?: Record<string, string>\n\n ignoreBrowserTokenWarning?: boolean\n /**\n * Ignore specific warning messages from the client.\n *\n * @remarks\n * - String values perform substring matching (not exact matching) against warning messages\n * - RegExp values are tested against the full warning message\n * - Array values allow multiple patterns to be specified\n *\n * @example\n * ```typescript\n * // Ignore warnings containing \"experimental\"\n * ignoreWarnings: 'experimental'\n *\n * // Ignore multiple warning types\n * ignoreWarnings: ['experimental', 'deprecated']\n *\n * // Use regex for exact matching\n * ignoreWarnings: /^This is an experimental API version$/\n *\n * // Mix strings and regex patterns\n * ignoreWarnings: ['rate limit', /^deprecated/i]\n * ```\n */\n ignoreWarnings?: string | RegExp | Array<string | RegExp>\n withCredentials?: boolean\n allowReconfigure?: boolean\n timeout?: number\n\n /** Number of retries for requests. Defaults to 5. */\n maxRetries?: number\n\n /**\n * The amount of time, in milliseconds, to wait before retrying, given an attemptNumber (starting at 0).\n *\n * Defaults to exponential back-off, starting at 100ms, doubling for each attempt, together with random\n * jitter between 0 and 100 milliseconds. More specifically the following algorithm is used:\n *\n * Delay = 100 * 2^attemptNumber + randomNumberBetween0and100\n */\n retryDelay?: (attemptNumber: number) => number\n\n /**\n * @deprecated Don't use\n */\n useProjectHostname?: boolean\n\n /**\n * @deprecated Don't use\n */\n requester?: Requester\n\n /**\n * Adds a `resultSourceMap` key to the API response, with the type `ContentSourceMap`\n */\n resultSourceMap?: boolean | 'withKeyArraySelector'\n /**\n *@deprecated set `cache` and `next` options on `client.fetch` instead\n */\n fetch?:\n | {\n cache?: ResponseQueryOptions['cache']\n next?: ResponseQueryOptions['next']\n }\n | boolean\n /**\n * Options for how, if enabled, Content Source Maps are encoded into query results using steganography\n */\n stega?: StegaConfig | boolean\n /**\n * Lineage token for recursion control\n */\n lineage?: string\n}\n\n/** @public */\nexport interface InitializedClientConfig extends ClientConfig {\n // These are required in the initialized config\n apiHost: string\n apiVersion: string\n useProjectHostname: boolean\n useCdn: boolean\n // These are added by the initConfig function\n /**\n * @deprecated Internal, don't use\n */\n isDefaultApi: boolean\n /**\n * @deprecated Internal, don't use\n */\n url: string\n /**\n * @deprecated Internal, don't use\n */\n cdnUrl: string\n /**\n * The fully initialized stega config, can be used to check if stega is enabled\n */\n stega: InitializedStegaConfig\n /**\n * Default headers to include with all requests\n *\n * @remarks request-specific headers will override any default headers with the same name.\n */\n headers?: Record<string, string>\n}\n\n/** @public */\nexport type AssetMetadataType =\n | 'location'\n | 'exif'\n | 'image'\n | 'palette'\n | 'lqip'\n | 'blurhash'\n | 'none'\n\n/** @public */\nexport interface UploadClientConfig {\n /**\n * Optional request tag for the upload\n */\n tag?: string\n\n /**\n * Whether or not to preserve the original filename (default: true)\n */\n preserveFilename?: boolean\n\n /**\n * Filename for this file (optional)\n */\n filename?: string\n\n /**\n * Milliseconds to wait before timing the request out\n */\n timeout?: number\n\n /**\n * Mime type of the file\n */\n contentType?: string\n\n /**\n * Array of metadata parts to extract from asset\n */\n extract?: AssetMetadataType[]\n\n /**\n * Optional freeform label for the asset. Generally not used.\n */\n label?: string\n\n /**\n * Optional title for the asset\n */\n title?: string\n\n /**\n * Optional description for the asset\n */\n description?: string\n\n /**\n * The credit to person(s) and/or organization(s) required by the supplier of the asset to be used when published\n */\n creditLine?: string\n\n /**\n * Source data (when the asset is from an external service)\n */\n source?: {\n /**\n * The (u)id of the asset within the source, i.e. 'i-f323r1E'\n */\n id: string\n\n /**\n * The name of the source, i.e. 'unsplash'\n */\n name: string\n\n /**\n * A url to where to find the asset, or get more info about it in the source\n */\n url?: string\n }\n}\n\n/** @internal */\nexport interface SanityReference {\n _ref: string\n}\n\n/** @internal */\nexport type SanityDocument<T extends Record<string, Any> = Record<string, Any>> = {\n [P in keyof T]: T[P]\n} & {\n _id: string\n _rev: string\n _type: string\n _createdAt: string\n _updatedAt: string\n /**\n * Present when `perspective` is set to `previewDrafts`\n */\n _originalId?: string\n}\n\n/** @internal */\nexport interface SanityAssetDocument extends SanityDocument {\n url: string\n path: string\n size: number\n assetId: string\n mimeType: string\n sha1hash: string\n extension: string\n uploadId?: string\n originalFilename?: string\n}\n\n/** @internal */\nexport interface SanityImagePalette {\n background: string\n foreground: string\n population: number\n title: string\n}\n\n/** @internal */\nexport interface SanityImageAssetDocument extends SanityAssetDocument {\n metadata: {\n _type: 'sanity.imageMetadata'\n hasAlpha: boolean\n isOpaque: boolean\n lqip?: string\n blurHash?: string\n dimensions: {\n _type: 'sanity.imageDimensions'\n aspectRatio: number\n height: number\n width: number\n }\n palette?: {\n _type: 'sanity.imagePalette'\n darkMuted?: SanityImagePalette\n darkVibrant?: SanityImagePalette\n dominant?: SanityImagePalette\n lightMuted?: SanityImagePalette\n lightVibrant?: SanityImagePalette\n muted?: SanityImagePalette\n vibrant?: SanityImagePalette\n }\n image?: {\n _type: 'sanity.imageExifTags'\n [key: string]: Any\n }\n exif?: {\n _type: 'sanity.imageExifMetadata'\n [key: string]: Any\n }\n }\n}\n\n/** @public */\nexport interface ErrorProps {\n message: string\n response: Any\n statusCode: number\n responseBody: Any\n details: Any\n}\n\n/** @public */\nexport type HttpRequest = {\n (options: RequestOptions, requester: Requester): ReturnType<Requester>\n}\n\n/** @internal */\nexport interface RequestObservableOptions extends Omit<RequestOptions, 'url'> {\n url?: string\n uri?: string\n canUseCdn?: boolean\n useCdn?: boolean\n tag?: string\n returnQuery?: boolean\n resultSourceMap?: boolean | 'withKeyArraySelector'\n perspective?: ClientPerspective\n lastLiveEventId?: string\n cacheMode?: 'noStale'\n}\n\n/** @public */\nexport interface ProgressEvent {\n type: 'progress'\n stage: 'upload' | 'download'\n percent: number\n total?: number\n loaded?: number\n lengthComputable: boolean\n}\n\n/** @public */\nexport interface ResponseEvent<T = unknown> {\n type: 'response'\n body: T\n url: string\n method: string\n statusCode: number\n statusMessage?: string\n headers: Record<string, string>\n}\n\n/** @public */\nexport type HttpRequestEvent<T = unknown> = ResponseEvent<T> | ProgressEvent\n\n/** @internal */\nexport interface AuthProvider {\n name: string\n title: string\n url: string\n}\n\n/** @internal */\nexport type AuthProviderResponse = {providers: AuthProvider[]}\n\n/** @public */\nexport type DatasetAclMode = 'public' | 'private' | 'custom'\n\n/** @public */\nexport type DatasetResponse = {datasetName: string; aclMode: DatasetAclMode}\n/** @public */\nexport type DatasetsResponse = {\n name: string\n aclMode: DatasetAclMode\n createdAt: string\n createdByUserId: string\n addonFor: string | null\n datasetProfile: string\n features: string[]\n tags: string[]\n}[]\n\n/** @public */\nexport interface SanityProjectMember {\n id: string\n role: string\n isRobot: boolean\n isCurrentUser: boolean\n}\n\n/** @public */\nexport interface SanityProject {\n id: string\n displayName: string\n /**\n * @deprecated Use the `/user-applications` endpoint instead, which lists all deployed studios/applications\n * @see https://www.sanity.io/help/studio-host-user-applications\n */\n studioHost: string | null\n organizationId: string | null\n isBlocked: boolean\n isDisabled: boolean\n isDisabledByUser: boolean\n createdAt: string\n pendingInvites?: number\n maxRetentionDays?: number\n members: SanityProjectMember[]\n metadata: {\n cliInitializedAt?: string\n color?: string\n /**\n * @deprecated Use the `/user-applications` endpoint instead, which lists all deployed studios/applications\n * @see https://www.sanity.io/help/studio-host-user-applications\n */\n externalStudioHost?: string\n }\n}\n\n/** @public */\nexport interface SanityUser {\n id: string\n projectId: string\n displayName: string\n familyName: string | null\n givenName: string | null\n middleName: string | null\n imageUrl: string | null\n createdAt: string\n updatedAt: string\n isCurrentUser: boolean\n}\n\n/** @public */\nexport interface CurrentSanityUser {\n id: string\n name: string\n email: string\n profileImage: string | null\n role: string\n provider: string\n}\n\n/** @public */\nexport type SanityDocumentStub<T extends Record<string, Any> = Record<string, Any>> = {\n [P in keyof T]: T[P]\n} & {\n _type: string\n}\n\n/** @public */\nexport type IdentifiedSanityDocumentStub<T extends Record<string, Any> = Record<string, Any>> = {\n [P in keyof T]: T[P]\n} & {\n _id: string\n} & SanityDocumentStub\n\n/** @internal */\nexport type InsertPatch =\n | {before: string; items: Any[]}\n | {after: string; items: Any[]}\n | {replace: string; items: Any[]}\n\n// Note: this is actually incorrect/invalid, but implemented as-is for backwards compatibility\n/** @internal */\nexport interface PatchOperations {\n set?: {[key: string]: Any}\n setIfMissing?: {[key: string]: Any}\n diffMatchPatch?: {[key: string]: Any}\n unset?: string[]\n inc?: {[key: string]: number}\n dec?: {[key: string]: number}\n insert?: InsertPatch\n ifRevisionID?: string\n}\n\n/** @public */\nexport interface QueryParams {\n /* eslint-disable @typescript-eslint/no-explicit-any */\n [key: string]: any\n /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */\n body?: never\n /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */\n cache?: 'next' extends keyof RequestInit ? never : any\n /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */\n filterResponse?: never\n /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */\n headers?: never\n /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */\n method?: never\n /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */\n next?: 'next' extends keyof RequestInit ? never : any\n /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */\n perspective?: never\n /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */\n query?: never\n /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */\n resultSourceMap?: never\n /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */\n returnQuery?: never\n /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */\n signal?: never\n /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */\n stega?: never\n /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */\n tag?: never\n /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */\n timeout?: never\n /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */\n token?: never\n /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */\n useCdn?: never\n /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */\n lastLiveEventId?: never\n /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */\n cacheMode?: never\n /* eslint-enable @typescript-eslint/no-explicit-any */\n}\n\n/**\n * This type can be used with `client.fetch` to indicate that the query has no GROQ parameters.\n * @public\n */\nexport type QueryWithoutParams = Record<string, never> | undefined\n\n/** @internal */\nexport type MutationSelectionQueryParams = {[key: string]: Any}\n/** @internal */\nexport type MutationSelection =\n | {query: string; params?: MutationSelectionQueryParams}\n | {id: string | string[]}\n/** @internal */\nexport type PatchSelection = string | string[] | MutationSelection\n/** @internal */\nexport type PatchMutationOperation = PatchOperations & MutationSelection\n\n/** @public */\nexport type Mutation<R extends Record<string, Any> = Record<string, Any>> =\n | {create: SanityDocumentStub<R>}\n | {createOrReplace: IdentifiedSanityDocumentStub<R>}\n | {createIfNotExists: IdentifiedSanityDocumentStub<R>}\n | {delete: MutationSelection}\n | {patch: PatchMutationOperation}\n\n/** @public */\nexport type ReleaseAction =\n | CreateReleaseAction\n | EditReleaseAction\n | PublishReleaseAction\n | ArchiveReleaseAction\n | UnarchiveReleaseAction\n | ScheduleReleaseAction\n | UnscheduleReleaseAction\n | DeleteReleaseAction\n | ImportReleaseAction\n\n/** @public */\nexport type VersionAction =\n | CreateVersionAction\n | DiscardVersionAction\n | ReplaceVersionAction\n | UnpublishVersionAction\n\n/** @public */\nexport type Action =\n | CreateAction\n | ReplaceDraftAction\n | EditAction\n | DeleteAction\n | DiscardAction\n | PublishAction\n | UnpublishAction\n | VersionAction\n | ReleaseAction\n\n/** @public */\nexport type ImportReleaseAction =\n | {\n actionType: 'sanity.action.release.import'\n attributes: IdentifiedSanityDocumentStub\n releaseId: string\n ifExists: 'fail' | 'ignore' | 'replace'\n }\n | {\n actionType: 'sanity.action.release.import'\n document: IdentifiedSanityDocumentStub\n releaseId: string\n ifExists: 'fail' | 'ignore' | 'replace'\n }\n\n/**\n * Creates a new release under the given id, with metadata.\n *\n * @public\n */\nexport interface CreateReleaseAction {\n actionType: 'sanity.action.release.create'\n releaseId: string\n metadata?: Partial<ReleaseDocument['metadata']>\n}\n\n/**\n * Edits an existing release, updating the metadata.\n *\n * @public\n */\nexport interface EditReleaseAction {\n actionType: 'sanity.action.release.edit'\n releaseId: string\n patch: PatchOperations\n}\n\n/**\n * Publishes all documents in a release at once.\n *\n * @public\n */\nexport interface PublishReleaseAction {\n actionType: 'sanity.action.release.publish'\n releaseId: string\n}\n\n/**\n * Archives an `active` release, and deletes all the release documents.\n *\n * @public\n */\nexport interface ArchiveReleaseAction {\n actionType: 'sanity.action.release.archive'\n releaseId: string\n}\n\n/**\n * Unarchived an `archived` release, and restores all the release documents.\n *\n * @public\n */\nexport interface UnarchiveReleaseAction {\n actionType: 'sanity.action.release.unarchive'\n releaseId: string\n}\n\n/**\n * Queues release for publishing at the given future time.\n *\n * @public\n */\nexport interface ScheduleReleaseAction {\n actionType: 'sanity.action.release.schedule'\n releaseId: string\n publishAt: string\n}\n\n/**\n * Unschedules a `scheduled` release, stopping it from being published.\n *\n * @public\n */\nexport interface UnscheduleReleaseAction {\n actionType: 'sanity.action.release.unschedule'\n releaseId: string\n}\n\n/**\n * Deletes a `archived` or `published` release, and all the release documents versions.\n *\n * @public\n */\nexport interface DeleteReleaseAction {\n actionType: 'sanity.action.release.delete'\n releaseId: string\n}\n\n/**\n * Creates a new version of an existing document.\n *\n * If the `document` is provided, the version is created from the document\n * attached to the release as given by `document._id`\n *\n * If the `baseId` and `versionId` are provided, the version is created from the base document\n * and the version is attached to the release as given by `publishedId` and `versionId`\n *\n * @public\n */\nexport type CreateVersionAction = {\n actionType: 'sanity.action.document.version.create'\n publishedId: string\n} & (\n | {\n document: IdentifiedSanityDocumentStub\n }\n | {\n baseId: string\n versionId: string\n ifBaseRevisionId?: string\n }\n)\n\n/**\n * Delete a version of a document.\n *\n * @public\n */\nexport interface DiscardVersionAction {\n actionType: 'sanity.action.document.version.discard'\n versionId: string\n purge?: boolean\n}\n\n/**\n * Replace an existing version of a document.\n *\n * @public\n */\nexport interface ReplaceVersionAction {\n actionType: 'sanity.action.document.version.replace'\n document: IdentifiedSanityDocumentStub\n}\n\n/**\n * Identify that a version of a document should be unpublished when\n * the release that version is contained within is published.\n *\n * @public\n */\nexport interface UnpublishVersionAction {\n actionType: 'sanity.action.document.version.unpublish'\n versionId: string\n publishedId: string\n}\n\n/**\n * Creates a new draft document. The published version of the document must not already exist.\n * If the draft version of the document already exists the action will fail by default, but\n * this can be adjusted to instead leave the existing document in place.\n *\n * @public\n */\nexport type CreateAction = {\n actionType: 'sanity.action.document.create'\n\n /**\n * ID of the published document to create a draft for.\n */\n publishedId: string\n\n /**\n * Document to create. Requires a `_type` property.\n */\n attributes: IdentifiedSanityDocumentStub\n\n /**\n * ifExists controls what to do if the draft already exists\n */\n ifExists: 'fail' | 'ignore'\n}\n\n/**\n * Replaces an existing draft document.\n * At least one of the draft or published versions of the document must exist.\n *\n * @public\n * @deprecated Use {@link ReplaceVersionAction} instead\n */\nexport type ReplaceDraftAction = {\n actionType: 'sanity.action.document.replaceDraft'\n\n /**\n * Published document ID to create draft from, if draft does not exist\n */\n publishedId: string\n\n /**\n * Document to create if it does not already exist. Requires `_id` and `_type` properties.\n */\n attributes: IdentifiedSanityDocumentStub\n}\n\n/**\n * Modifies an existing draft document.\n * It applies the given patch to the document referenced by draftId.\n * If there is no such document then one is created using the current state of the published version and then that is updated accordingly.\n *\n * @public\n */\nexport type EditAction = {\n actionType: 'sanity.action.document.edit'\n\n /**\n * Draft document ID to edit\n */\n draftId: string\n\n /**\n * Published document ID to create draft from, if draft does not exist\n */\n publishedId: string\n\n /**\n * Patch operations to apply\n */\n patch: PatchOperations\n}\n\n/**\n * Deletes the published version of a document and optionally some (likely all known) draft versions.\n * If any draft version exists that is not specified for deletion this is an error.\n * If the purge flag is set then the document history is also deleted.\n *\n * @public\n */\nexport type DeleteAction = {\n actionType: 'sanity.action.document.delete'\n\n /**\n * Published document ID to delete\n */\n publishedId: string\n\n /**\n * Draft document ID to delete\n */\n includeDrafts: string[]\n\n /**\n * Delete document history\n */\n purge?: boolean\n}\n\n/**\n * Delete the draft version of a document.\n * It is an error if it does not exist. If the purge flag is set, the document history is also deleted.\n *\n * @public\n * @deprecated Use {@link DiscardVersionAction} instead\n */\nexport type DiscardAction = {\n actionType: 'sanity.action.document.discard'\n\n /**\n * Draft document ID to delete\n */\n draftId: string\n\n /**\n * Delete document history\n */\n purge?: boolean\n}\n\n/**\n * Publishes a draft document.\n * If a published version of the document already exists this is replaced by the current draft document.\n * In either case the draft document is deleted.\n * The optional revision id parameters can be used for optimistic locking to ensure\n * that the draft and/or published versions of the document have not been changed by another client.\n *\n * @public\n */\nexport type PublishAction = {\n actionType: 'sanity.action.document.publish'\n\n /**\n * Draft document ID to publish\n */\n draftId: string\n\n /**\n * Draft revision ID to match\n */\n ifDraftRevisionId?: string\n\n /**\n * Published document ID to replace\n */\n publishedId: string\n\n /**\n * Published revision ID to match\n */\n ifPublishedRevisionId?: string\n}\n\n/**\n * Retract a published document.\n * If there is no draft version then this is created from the published version.\n * In either case the published version is deleted.\n *\n * @public\n */\nexport type UnpublishAction = {\n actionType: 'sanity.action.document.unpublish'\n\n /**\n * Draft document ID to replace the published document with\n */\n draftId: string\n\n /**\n * Published document ID to delete\n */\n publishedId: string\n}\n\n/**\n * A mutation was performed. Note that when updating multiple documents in a transaction,\n * each document affected will get a separate mutation event.\n *\n * @public\n */\nexport type MutationEvent<R extends Record<string, Any> = Record<string, Any>> = {\n type: 'mutation'\n\n /**\n * The ID of the document that was affected\n */\n documentId: string\n\n /**\n * A unique ID for this event\n */\n eventId: string\n\n /**\n * The user ID of the user that performed the mutation\n */\n identity: string\n\n /**\n * An array of mutations that were performed. Note that this can differ slightly from the\n * mutations sent to the server, as the server may perform some mutations automatically.\n */\n mutations: Mutation[]\n\n /**\n * The revision ID of the document before the mutation was performed\n */\n previousRev?: string\n\n /**\n * The revision ID of the document after the mutation was performed\n */\n resultRev?: string\n\n /**\n * The document as it looked after the mutation was performed. This is only included if\n * the listener was configured with `includeResult: true`.\n */\n result?: SanityDocument<R>\n\n /**\n * The document as it looked before the mutation was performed. This is only included if\n * the listener was configured with `includePreviousRevision: true`.\n */\n previous?: SanityDocument<R> | null\n\n /**\n * The effects of the mutation, if the listener was configured with `effectFormat: 'mendoza'`.\n * Object with `apply` and `revert` arrays, see {@link https://github.com/sanity-io/mendoza}.\n */\n effects?: {apply: unknown[]; revert: unknown[]}\n\n /**\n * A timestamp for when the mutation was performed\n */\n timestamp: string\n\n /**\n * The transaction ID for the mutation\n */\n transactionId: string\n\n /**\n * The type of transition the document went through.\n *\n * - `update` means the document was previously part of the subscribed set of documents,\n * and still is.\n * - `appear` means the document was not previously part of the subscribed set of documents,\n * but is now. This can happen both on create or if updating to a state where it now matches\n * the filter provided to the listener.\n * - `disappear` means the document was previously part of the subscribed set of documents,\n * but is no longer. This can happen both on delete or if updating to a state where it no\n * longer matches the filter provided to the listener.\n */\n transition: 'update' | 'appear' | 'disappear'\n\n /**\n * Whether the change that triggered this event is visible to queries (query) or only to\n * subsequent transactions (transaction). The listener client can specify a preferred visibility\n * through the `visibility` parameter on the listener, but this is only on a best-effort basis,\n * and may yet not be accurate.\n */\n visibility: 'query' | 'transaction'\n\n /**\n * The total number of events that will be sent for this transaction.\n * Note that this may differ from the amount of _documents_ affected by the transaction, as this\n * number only includes the documents that matches the given filter.\n *\n * This can be useful if you need to perform changes to all matched documents atomically,\n * eg you would wait for `transactionTotalEvents` events with the same `transactionId` before\n * applying the changes locally.\n */\n transactionTotalEvents: number\n\n /**\n * The index of this event within the transaction. Note that events may be delivered out of order,\n * and that the index is zero-based.\n */\n transactionCurrentEvent: number\n}\n\n/**\n * An error occurred. This is different from a network-level error (which will be emitted as 'error').\n * Possible causes are things such as malformed filters, non-existant datasets or similar.\n *\n * @public\n */\nexport type ChannelErrorEvent = {\n type: 'channelError'\n message: string\n}\n\n/**\n * The listener has been told to explicitly disconnect and not reconnect.\n * This is a rare situation, but may occur if the API knows reconnect attempts will fail,\n * eg in the case of a deleted dataset, a blocked project or similar events.\n *\n * Note that this is not treated as an error on the observable, but will complete the observable.\n *\n * @public\n */\nexport type DisconnectEvent = {\n type: 'disconnect'\n reason: string\n}\n\n/**\n * The listener has been disconnected, and a reconnect attempt is scheduled.\n *\n * @public\n */\nexport type ReconnectEvent = {\n type: 'reconnect'\n}\n\n/**\n * The listener connection has been established\n * note: it's usually a better option to use the 'welcome' event\n * @public\n */\nexport type OpenEvent = {\n type: 'open'\n}\n\n/**\n * The listener has been established, and will start receiving events.\n * Note that this is also emitted upon _reconnection_.\n *\n * @public\n */\nexport type WelcomeEvent = {\n type: 'welcome'\n listenerName: string\n}\n\n/** @public */\nexport type ListenEvent<R extends Record<string, Any>> =\n | MutationEvent<R>\n | ReconnectEvent\n | WelcomeEvent\n | OpenEvent\n\n/** @public */\nexport type ListenEventName =\n /** A mutation was performed */\n | 'mutation'\n /** The listener has been (re)established */\n | 'welcome'\n /** The listener has been disconnected, and a reconnect attempt is scheduled */\n | 'reconnect'\n /**\n * The listener connection has been established\n * note: it's usually a better option to use the 'welcome' event\n */\n | 'open'\n\n/** @public */\nexport type ListenParams = {[key: string]: Any}\n\n/** @public */\nexport interface ListenOptions {\n /**\n * Whether or not to include the resulting document in addition to the mutations performed.\n * If you do not need the actual document, set this to `false` to reduce bandwidth usage.\n * The result will be available on the `.result` property of the events.\n * @defaultValue `true`\n */\n includeResult?: boolean\n\n /**\n * Whether or not to include the mutations that was performed.\n * If you do not need the mutations, set this to `false` to reduce bandwidth usage.\n * @defaultValue `true`\n */\n includeMutations?: boolean\n\n /**\n * Whether or not to include the document as it looked before the mutation event.\n * The previous revision will be available on the `.previous` property of the events,\n * and may be `null` in the case of a new document.\n * @defaultValue `false`\n */\n includePreviousRevision?: boolean\n\n /*\n * Whether to include events for drafts and versions. As of API Version >= v2025-02-19, only events\n * for published documents will be included by default (see {@link https://www.sanity.io/changelog/676aaa9d-2da6-44fb-abe5-580f28047c10|Changelog})\n * If you need events from drafts and versions, set this to `true`.\n * Note: Keep in mind that additional document variants may be introduced in the future, so it's\n * recommended to respond to events in a way that's tolerant of potential future variants, e.g. by\n * explicitly checking whether the event is for a draft or a version.\n * @defaultValue `false`\n */\n includeAllVersions?: boolean\n\n /**\n * Whether events should be sent as soon as a transaction has been committed (`transaction`, default),\n * or only after they are available for queries (query). Note that this is on a best-effort basis,\n * and listeners with `query` may in certain cases (notably with deferred transactions) receive events\n * that are not yet visible to queries.\n *\n * @defaultValue `'transaction'`\n */\n visibility?: 'transaction' | 'query'\n\n /**\n * Array of event names to include in the observable. By default, only mutation events are included.\n *\n * @defaultValue `['mutation']`\n */\n events?: ListenEventName[]\n\n /**\n * Format of \"effects\", eg the resulting changes of a mutation.\n * Currently only `mendoza` is supported, and (if set) will include `apply` and `revert` arrays\n * in the mutation events under the `effects` property.\n *\n * See {@link https://github.com/sanity-io/mendoza | The mendoza docs} for more info\n *\n * @defaultValue `undefined`\n */\n effectFormat?: 'mendoza'\n\n /**\n * Optional request tag for the listener. Use to identify the request in logs.\n *\n * @defaultValue `undefined`\n */\n tag?: string\n}\n\n/** @public */\nexport interface ResponseQueryOptions extends RequestOptions {\n perspective?: ClientPerspective\n resultSourceMap?: boolean | 'withKeyArraySelector'\n returnQuery?: boolean\n useCdn?: boolean\n stega?: boolean | StegaConfig\n // The `cache` and `next` options are specific to the Next.js App Router integration\n cache?: 'next' extends keyof RequestInit ? RequestInit['cache'] : never\n next?: ('next' extends keyof RequestInit ? RequestInit : never)['next']\n lastLiveEventId?: string | string[] | null\n\n /**\n * When set to `noStale`, APICDN will not return a cached response if the content is stale.\n * Tradeoff between latency and freshness of content.\n *\n * Only to be used with live content queries and when useCdn is true.\n */\n cacheMode?: 'noStale'\n}\n\n/** @public */\nexport interface FilteredResponseQueryOptions extends ResponseQueryOptions {\n filterResponse?: true\n}\n\n/** @public */\nexport interface UnfilteredResponseQueryOptions extends ResponseQueryOptions {\n filterResponse: false\n\n /**\n * When `filterResponse` is `false`, `returnQuery` also defaults to `true` for\n * backwards compatibility (on the client side, not from the content lake API).\n * Can also explicitly be set to `true`.\n */\n returnQuery?: true\n}\n\n/**\n * When using `filterResponse: false`, but you do not wish to receive back the query from\n * the content lake API.\n *\n * @public\n */\nexport interface UnfilteredResponseWithoutQuery extends ResponseQueryOptions {\n filterResponse: false\n returnQuery: false\n}\n\n/** @public */\nexport type QueryOptions =\n | FilteredResponseQueryOptions\n | UnfilteredResponseQueryOptions\n | UnfilteredResponseWithoutQuery\n\n/** @public */\nexport interface RawQueryResponse<R> {\n query: string\n ms: number\n result: R\n resultSourceMap?: ContentSourceMap\n /** Requires `apiVersion` to be `2021-03-25` or later. */\n syncTags?: SyncTag[]\n}\n\n/** @public */\nexport type RawQuerylessQueryResponse<R> = Omit<RawQueryResponse<R>, 'query'>\n\n/** @internal */\nexport type BaseMutationOptions = RequestOptions & {\n visibility?: 'sync' | 'async' | 'deferred'\n returnDocuments?: boolean\n returnFirst?: boolean\n dryRun?: boolean\n autoGenerateArrayKeys?: boolean\n skipCrossDatasetReferenceValidation?: boolean\n transactionId?: string\n}\n\n/** @internal */\nexport type FirstDocumentMutationOptions = BaseMutationOptions & {\n returnFirst?: true\n returnDocuments?: true\n}\n\n/** @internal */\nexport type FirstDocumentIdMutationOptions = BaseMutationOptions & {\n returnFirst?: true\n returnDocuments: false\n}\n\n/** @internal */\nexport type AllDocumentsMutationOptions = BaseMutationOptions & {\n returnFirst: false\n returnDocuments?: true\n}\n\n/** @internal */\nexport type MutationOperation = 'create' | 'delete' | 'update' | 'none'\n\n/** @internal */\nexport interface SingleMutationResult {\n transactionId: string\n documentId: string\n results: {id: string; operation: MutationOperation}[]\n}\n\n/** @internal */\nexport interface MultipleMutationResult {\n transactionId: string\n documentIds: string[]\n results: {id: string; operation: MutationOperation}[]\n}\n\n/** @internal */\nexport type AllDocumentIdsMutationOptions = BaseMutationOptions & {\n returnFirst: false\n returnDocuments: false\n}\n\n/** @internal */\nexport type AttributeSet = {[key: string]: Any}\n\n/** @internal */\nexport type TransactionFirstDocumentMutationOptions = BaseMutationOptions & {\n returnFirst: true\n returnDocuments: true\n}\n\n/** @internal */\nexport type TransactionFirstDocumentIdMutationOptions = BaseMutationOptions & {\n returnFirst: true\n returnDocuments?: false\n}\n\n/** @internal */\nexport type TransactionAllDocumentsMutationOptions = BaseMutationOptions & {\n returnFirst?: false\n returnDocuments: true\n}\n\n/** @internal */\nexport type TransactionAllDocumentIdsMutationOptions = BaseMutationOptions & {\n returnFirst?: false\n returnDocuments?: false\n}\n\n/** @internal */\nexport type TransactionMutationOptions =\n | TransactionFirstDocumentMutationOptions\n | TransactionFirstDocumentIdMutationOptions\n | TransactionAllDocumentsMutationOptions\n | TransactionAllDocumentIdsMutationOptions\n\n/** @internal */\nexport type BaseActionOptions = RequestOptions & {\n transactionId?: string\n skipCrossDatasetReferenceValidation?: boolean\n dryRun?: boolean\n}\n\n/** @internal */\nexport interface SingleActionResult {\n transactionId: string\n}\n\n/** @internal */\nexport interface MultipleActionResult {\n transactionId: string\n}\n\n/** @internal */\nexport interface RawRequestOptions {\n url?: string\n uri?: string\n method?: string\n token?: string\n json?: boolean\n tag?: string\n useGlobalApi?: boolean\n withCredentials?: boolean\n query?: {[key: string]: string | string[]}\n headers?: {[key: string]: string}\n timeout?: number\n proxy?: string\n body?: Any\n maxRedirects?: number\n signal?: AbortSignal\n}\n\n/** @internal */\nexport interface ApiError {\n error: string\n message: string\n statusCode: number\n}\n\n/** @internal */\nexport interface MutationError {\n type: 'mutationError'\n description: string\n items?: MutationErrorItem[]\n}\n\n/**\n * Returned from the Content Lake API when a query is malformed, usually with a start\n * and end column to indicate where the error occurred, but not always. Can we used to\n * provide a more structured error message to the user.\n *\n * This will be located under the response `error` property.\n *\n * @public\n */\nexport interface QueryParseError {\n type: 'queryParseError'\n description: string\n start?: number\n end?: number\n query?: string\n}\n\n/** @internal */\nexport interface MutationErrorItem {\n error: {\n type: string\n description: string\n value?: unknown\n }\n}\n\n/** @internal */\nexport interface ActionError {\n type: 'actionError'\n description: string\n items?: ActionErrorItem[]\n}\n\n/** @internal */\nexport interface ActionErrorItem {\n error: {\n type: string\n description: string\n value?: unknown\n }\n index: number\n}\n\n/** @internal */\nexport type PartialExcept<T, K extends keyof T> = Pick<T, K> & Partial<Omit<T, K>>\n\n/** @beta */\nexport type ReleaseState =\n | 'active'\n | 'archiving'\n | 'unarchiving'\n | 'archived'\n | 'published'\n | 'publishing'\n | 'scheduled'\n | 'scheduling'\n\n/** @internal */\nexport type ReleaseType = 'asap' | 'scheduled' | 'undecided'\n\n/** @public */\nexport type ReleaseCardinality = 'many' | 'one' | undefined\n\n/** @internal */\nexport interface ReleaseDocument extends SanityDocument {\n /**\n * typically\n * `_.releases.<name>`\n */\n _id: string\n /**\n * where a release has _id `_.releases.foo`, the name is `foo`\n */\n name: string\n _type: 'system.release'\n _createdAt: string\n _updatedAt: string\n _rev: string\n state: ReleaseState\n error?: {\n message: string\n }\n finalDocumentStates?: {\n /** Document ID */\n id: string\n }[]\n /**\n * If defined, it takes precedence over the intendedPublishAt, the state should be 'scheduled'\n */\n publishAt?: string\n /**\n * If defined, it provides the time the release was actually published\n */\n publishedAt?: string\n metadata: {\n title?: string\n description?: string\n intendedPublishAt?: string\n releaseType: ReleaseType\n cardinality?: ReleaseCardinality\n }\n}\n\n/** @internal */\nexport type EditableReleaseDocument = Omit<\n PartialExcept<ReleaseDocument, '_id'>,\n 'metadata' | '_type'\n> & {\n _id: string\n metadata: Partial<ReleaseDocument['metadata']>\n}\n\n/**\n * DocumentValueSource is a path to a value within a document\n * @public\n */\nexport interface ContentSourceMapDocumentValueSource {\n type: 'documentValue'\n // index location of the document\n document: number\n // index location of the path\n path: number\n}\n/**\n * When a value is not from a source, its a literal\n * @public\n */\nexport interface ContentSourceMapLiteralSource {\n type: 'literal'\n}\n/**\n * When a field source is unknown\n * @public\n */\nexport interface ContentSourceMapUnknownSource {\n type: 'unknown'\n}\n/** @public */\nexport type ContentSourceMapSource =\n | ContentSourceMapDocumentValueSource\n | ContentSourceMapLiteralSource\n | ContentSourceMapUnknownSource\n/**\n * ValueMapping is a mapping when for value that is from a single source value\n * It may refer to a field within a document or a literal value\n * @public\n */\nexport interface ContentSourceMapValueMapping {\n type: 'value'\n // source of the value\n source: ContentSourceMapSource\n}\n/** @public */\nexport type ContentSourceMapMapping = ContentSourceMapValueMapping\n\n/** @public */\nexport type ContentSourceMapMappings = Record<string, ContentSourceMapMapping>\n\n/** @public */\nexport interface ContentSourceMapDocumentBase {\n _id: string\n _type: string\n}\n\n/** @public */\nexport interface ContentSourceMapDocument extends ContentSourceMapDocumentBase {\n _projectId?: undefined\n _dataset?: undefined\n}\n\n/** @public */\nexport interface ContentSourceMapRemoteDocument extends ContentSourceMapDocumentBase {\n _projectId: string\n _dataset: string\n}\n\n/** @public */\nexport type ContentSourceMapDocuments = (\n | ContentSourceMapDocument\n | ContentSourceMapRemoteDocument\n)[]\n\n/** @public */\nexport type ContentSourceMapPaths = string[]\n\n/** @public */\nexport interface ContentSourceMap {\n mappings: ContentSourceMapMappings\n documents: ContentSourceMapDocuments\n paths: ContentSourceMapPaths\n}\n\n/** @public */\nexport type SyncTag = `s1:${string}`\n/** @public */\nexport interface LiveEventRestart {\n type: 'restart'\n id: string\n}\n/** @public */\nexport interface LiveEventReconnect {\n type: 'reconnect'\n}\n/** @public */\nexport interface LiveEventMessage {\n type: 'message'\n id: string\n tags: SyncTag[]\n}\n/** @public */\nexport interface LiveEventWelcome {\n type: 'welcome'\n}\n/**\n * The `id` field is the position at which the connection was rejected or closed.\n * The `reason` field will specify why the connection rejected/closed.\n * @public\n */\nexport interface LiveEventGoAway {\n type: 'goaway'\n id: string\n reason: string\n}\n/** @public */\nexport type LiveEvent =\n | LiveEventRestart\n | LiveEventReconnect\n | LiveEventMessage\n | LiveEventWelcome\n | LiveEventGoAway\n\n/** @public */\nexport interface SanityQueries {}\n\n/** @public */\nexport type ClientReturn<\n GroqString extends string,\n Fallback = Any,\n> = GroqString extends keyof SanityQueries ? SanityQueries[GroqString] : Fallback\n\nexport type {\n AgentActionParam,\n AgentActionParams,\n AgentActionPath,\n AgentActionPathSegment,\n AgentActionTarget,\n ConstantAgentActionParam,\n DocumentAgentActionParam,\n FieldAgentActionParam,\n GroqAgentActionParam,\n} from './agent/actions/commonTypes'\nexport type {\n GenerateInstruction,\n GenerateOperation,\n GenerateTarget,\n GenerateTargetDocument,\n GenerateTargetInclude,\n} from './agent/actions/generate'\nexport type {PatchDocument, PatchOperation, PatchTarget} from './agent/actions/patch'\nexport type {PromptRequest} from './agent/actions/prompt'\nexport type {\n ImageDescriptionOperation,\n TransformDocument,\n TransformOperation,\n TransformTarget,\n TransformTargetDocument,\n TransformTargetInclude,\n} from './agent/actions/transform'\nexport type {\n TranslateDocument,\n TranslateTarget,\n TranslateTargetInclude,\n} from './agent/actions/translate'\nexport type {\n ContentSourceMapParsedPath,\n ContentSourceMapParsedPathKeyedSegment,\n FilterDefault,\n InitializedStegaConfig,\n Logger,\n ResolveStudioUrl,\n StegaConfig,\n StegaConfigRequiredKeys,\n StudioBaseRoute,\n StudioBaseUrl,\n StudioUrl,\n} from './stega/types'\n\n/**\n * A string constant containing the experimental API version warning message.\n * Use this with the `ignoreWarnings` option to suppress warnings when using experimental API versions.\n *\n * @example\n * ```typescript\n * import { createClient, EXPERIMENTAL_API_WARNING } from '@sanity/client'\n *\n * const client = createClient({\n * projectId: 'your-project-id',\n * dataset: 'production',\n * apiVersion: 'vX', // experimental version\n * ignoreWarnings: EXPERIMENTAL_API_WARNING\n * })\n * ```\n *\n * @public\n */\nexport const EXPERIMENTAL_API_WARNING = 'This is an experimental API version'\n\n// Media Libraries types\n/**\n * Fit / resize modes accepted for thumbnail params.\n * @public\n */\nexport type FitMode = 'preserve' | 'stretch' | 'crop' | 'smartcrop' | 'pad'\n\n/**\n * Allowed still image formats (thumbnail + storyboard).\n * @public\n */\nexport type StillImageFormat = 'jpg' | 'png' | 'webp'\n\n/**\n * Allowed animated image formats.\n * @public\n */\nexport type AnimatedImageFormat = 'gif' | 'webp'\n\n/**\n * Thumbnail rendition (single frame) options.\n * @public\n */\nexport interface ThumbnailTransformOptions {\n /** Pixel width of the thumbnail frame. */\n width?: number\n /** Pixel height of the thumbnail frame. */\n height?: number\n /** Timestamp (seconds) from which to grab the frame. */\n time?: number\n /** Resize / fit mode applied to the extracted frame. */\n fit?: FitMode\n /** Output image format. */\n format?: StillImageFormat\n}\n\n/**\n * Animated preview rendition options (e.g. GIF / animated WebP).\n * @public\n */\nexport interface AnimatedTransformOptions {\n /** Pixel width of the animated output. Max 640 px. */\n width?: number\n /** Pixel height of the animated output. Max 640 px. */\n height?: number\n /** Start time in seconds (inclusive). */\n start?: number\n /** End time in seconds. */\n end?: number\n /** Frames per second (1–30). */\n fps?: number\n /** Output animated format. */\n format?: AnimatedImageFormat\n}\n\n/**\n * Storyboard (contact sheet) options.\n * @public\n */\nexport interface StoryboardTransformOptions {\n /** Output image format for the storyboard. */\n format?: StillImageFormat\n}\n\n/**\n * Video-specific playback transformation option groups.\n * Only explicitly provided values are serialized into query parameters.\n * @public\n */\nexport interface MediaLibraryVideoPlaybackTransformations {\n /** Static thumbnail (single frame) options. */\n thumbnail?: ThumbnailTransformOptions\n /** Animated preview options (GIF / animated WebP). */\n animated?: AnimatedTransformOptions\n /** Storyboard (contact sheet) options. */\n storyboard?: StoryboardTransformOptions\n}\n\n/**\n * Options for requesting playback info (URLs + optional tokens) for a Media Library video asset.\n *\n * Removed: generic fallback parameters (width, height, fit, format). Supply per‑transformation values instead.\n * Animated transformations intentionally exclude any fit option (not supported by Mux).\n *\n * includeTokens is a client-side flag (not sent to the server) controlling whether\n * returned tokens should be appended to URLs when consumed.\n * @public\n */\nexport interface MediaLibraryPlaybackInfoOptions {\n /** Explicit per-video transformation options (thumbnail, animated, storyboard). */\n transformations?: MediaLibraryVideoPlaybackTransformations\n /** Expiration hint for secured/signed URLs (string or number, number will be stringified). */\n expiration?: string | number\n}\n\n/** @public */\nexport interface VideoPlaybackInfoItemPublic {\n url: string\n}\n\n/** @public */\nexport interface VideoPlaybackInfoItemSigned extends VideoPlaybackInfoItemPublic {\n token: string\n}\n\n/** @public */\nexport type VideoPlaybackInfoItem = VideoPlaybackInfoItemPublic | VideoPlaybackInfoItemSigned\n\n/** @public */\nexport interface VideoPlaybackInfo<T extends VideoPlaybackInfoItem = VideoPlaybackInfoItem> {\n id: string\n thumbnail: T\n animated: T\n storyboard: T\n stream: T\n duration: number\n aspectRatio: number\n}\n\n/** @public */\nexport type VideoPlaybackInfoSigned = VideoPlaybackInfo<VideoPlaybackInfoItemSigned>\n\n/** @public */\nexport type VideoPlaybackInfoPublic = VideoPlaybackInfo<VideoPlaybackInfoItemPublic>\n\n/** @public */\nexport interface VideoPlaybackTokens {\n stream?: string\n thumbnail?: string\n storyboard?: string\n animated?: string\n}\n\n/** @public */\nexport type MediaLibraryAssetInstanceIdentifier = string | SanityReference\n","import type {Any} from '../types'\n\nexport function once(fn: Any) {\n let didCall = false\n let returnValue: Any\n return (...args: Any[]) => {\n if (didCall) {\n return returnValue\n }\n returnValue = fn(...args)\n didCall = true\n return returnValue\n }\n}\n","import {generateHelpUrl} from './generateHelpUrl'\nimport {type Any} from './types'\nimport {once} from './util/once'\n\nconst createWarningPrinter = (message: string[]) =>\n // eslint-disable-next-line no-console\n once((...args: Any[]) => console.warn(message.join(' '), ...args))\n\nexport const printCdnAndWithCredentialsWarning = createWarningPrinter([\n `Because you set \\`withCredentials\\` to true, we will override your \\`useCdn\\``,\n `setting to be false since (cookie-based) credentials are never set on the CDN`,\n])\n\nexport const printCdnWarning = createWarningPrinter([\n `Since you haven't set a value for \\`useCdn\\`, we will deliver content using our`,\n `global, edge-cached API-CDN. If you wish to have content delivered faster, set`,\n `\\`useCdn: false\\` to use the Live API. Note: You may incur higher costs using the live API.`,\n])\n\nexport const printCdnPreviewDraftsWarning = createWarningPrinter([\n `The Sanity client is configured with the \\`perspective\\` set to \\`drafts\\` or \\`previewDrafts\\`, which doesn't support the API-CDN.`,\n `The Live API will be used instead. Set \\`useCdn: false\\` in your configuration to hide this warning.`,\n])\n\nexport const printPreviewDraftsDeprecationWarning = createWarningPrinter([\n `The \\`previewDrafts\\` perspective has been renamed to \\`drafts\\` and will be removed in a future API version`,\n])\n\nexport const printBrowserTokenWarning = createWarningPrinter([\n 'You have configured Sanity client to use a token in the browser. This may cause unintentional security issues.',\n `See ${generateHelpUrl(\n 'js-client-browser-token',\n )} for more information and how to hide this warning.`,\n])\n\nexport const printCredentialedTokenWarning = createWarningPrinter([\n 'You have configured Sanity client to use a token, but also provided `withCredentials: true`.',\n 'This is no longer supported - only token will be used - remove `withCredentials: true`.',\n])\n\nexport const printNoApiVersionSpecifiedWarning = createWarningPrinter([\n 'Using the Sanity client without specifying an API version is deprecated.',\n `See ${generateHelpUrl('js-client-api-version')}`,\n])\n\nexport const printNoDefaultExport = createWarningPrinter([\n 'The default export of @sanity/client has been deprecated. Use the named export `createClient` instead.',\n])\n\nexport const printCreateVersionWithBaseIdWarning = createWarningPrinter([\n 'You have called `createVersion()` with a defined `document`. The recommended approach is to provide a `baseId` and `releaseId` instead.',\n])\n","import {generateHelpUrl} from './generateHelpUrl'\nimport type {ClientConfig, ClientPerspective, InitializedClientConfig} from './types'\nimport * as validate from './validators'\nimport * as warnings from './warnings'\n\nconst defaultCdnHost = 'apicdn.sanity.io'\nexport const defaultConfig = {\n apiHost: 'https://api.sanity.io',\n apiVersion: '1',\n useProjectHostname: true,\n stega: {enabled: false},\n} satisfies ClientConfig\n\nconst LOCALHOSTS = ['localhost', '127.0.0.1', '0.0.0.0']\nconst isLocal = (host: string) => LOCALHOSTS.indexOf(host) !== -1\n\nfunction validateApiVersion(apiVersion: string) {\n if (apiVersion === '1' || apiVersion === 'X') {\n return\n }\n\n const apiDate = new Date(apiVersion)\n const apiVersionValid =\n /^\\d{4}-\\d{2}-\\d{2}$/.test(apiVersion) && apiDate instanceof Date && apiDate.getTime() > 0\n\n if (!apiVersionValid) {\n throw new Error('Invalid API version string, expected `1` or date in format `YYYY-MM-DD`')\n }\n}\n\n/**\n * @internal - it may have breaking changes in any release\n */\nexport function validateApiPerspective(\n perspective: unknown,\n): asserts perspective is ClientPerspective {\n if (Array.isArray(perspective) && perspective.length > 1 && perspective.includes('raw')) {\n throw new TypeError(\n `Invalid API perspective value: \"raw\". The raw-perspective can not be combined with other perspectives`,\n )\n }\n}\n\nexport const initConfig = (\n config: Partial<ClientConfig>,\n prevConfig: Partial<ClientConfig>,\n): InitializedClientConfig => {\n const specifiedConfig = {\n ...prevConfig,\n ...config,\n stega: {\n ...(typeof prevConfig.stega === 'boolean'\n ? {enabled: prevConfig.stega}\n : prevConfig.stega || defaultConfig.stega),\n ...(typeof config.stega === 'boolean' ? {enabled: config.stega} : config.stega || {}),\n },\n }\n if (!specifiedConfig.apiVersion) {\n warnings.printNoApiVersionSpecifiedWarning()\n }\n\n const newConfig = {\n ...defaultConfig,\n ...specifiedConfig,\n } as InitializedClientConfig\n const projectBased = newConfig.useProjectHostname && !newConfig['~experimental_resource']\n\n if (typeof Promise === 'undefined') {\n const helpUrl = generateHelpUrl('js-client-promise-polyfill')\n throw new Error(`No native Promise-implementation found, polyfill needed - see ${helpUrl}`)\n }\n\n if (projectBased && !newConfig.projectId) {\n throw new Error('Configuration must contain `projectId`')\n }\n\n if (newConfig['~experimental_resource']) {\n validate.resourceConfig(newConfig)\n }\n\n if (typeof newConfig.perspective !== 'undefined') {\n validateApiPerspective(newConfig.perspective)\n }\n\n if ('encodeSourceMap' in newConfig) {\n throw new Error(\n `It looks like you're using options meant for '@sanity/preview-kit/client'. 'encodeSourceMap' is not supported in '@sanity/client'. Did you mean 'stega.enabled'?`,\n )\n }\n if ('encodeSourceMapAtPath' in newConfig) {\n throw new Error(\n `It looks like you're using options meant for '@sanity/preview-kit/client'. 'encodeSourceMapAtPath' is not supported in '@sanity/client'. Did you mean 'stega.filter'?`,\n )\n }\n if (typeof newConfig.stega.enabled !== 'boolean') {\n throw new Error(`stega.enabled must be a boolean, received ${newConfig.stega.enabled}`)\n }\n if (newConfig.stega.enabled && newConfig.stega.studioUrl === undefined) {\n throw new Error(`stega.studioUrl must be defined when stega.enabled is true`)\n }\n if (\n newConfig.stega.enabled &&\n typeof newConfig.stega.studioUrl !== 'string' &&\n typeof newConfig.stega.studioUrl !== 'function'\n ) {\n throw new Error(\n `stega.studioUrl must be a string or a function, received ${newConfig.stega.studioUrl}`,\n )\n }\n\n const isBrowser = typeof window !== 'undefined' && window.location && window.location.hostname\n const isLocalhost = isBrowser && isLocal(window.location.hostname)\n\n const hasToken = Boolean(newConfig.token)\n if (newConfig.withCredentials && hasToken) {\n warnings.printCredentialedTokenWarning()\n newConfig.withCredentials = false\n }\n\n if (isBrowser && isLocalhost && hasToken && newConfig.ignoreBrowserTokenWarning !== true) {\n warnings.printBrowserTokenWarning()\n } else if (typeof newConfig.useCdn === 'undefined') {\n warnings.printCdnWarning()\n }\n\n if (projectBased) {\n validate.projectId(newConfig.projectId!)\n }\n\n if (newConfig.dataset) {\n validate.dataset(newConfig.dataset)\n }\n\n if ('requestTagPrefix' in newConfig) {\n // Allow setting and unsetting request tag prefix\n newConfig.requestTagPrefix = newConfig.requestTagPrefix\n ? validate.requestTag(newConfig.requestTagPrefix).replace(/\\.+$/, '')\n : undefined\n }\n\n newConfig.apiVersion = `${newConfig.apiVersion}`.replace(/^v/, '')\n newConfig.isDefaultApi = newConfig.apiHost === defaultConfig.apiHost\n\n if (newConfig.useCdn === true && newConfig.withCredentials) {\n warnings.printCdnAndWithCredentialsWarning()\n }\n\n // If `useCdn` is undefined, we treat it as `true`\n newConfig.useCdn = newConfig.useCdn !== false && !newConfig.withCredentials\n\n validateApiVersion(newConfig.apiVersion)\n\n const hostParts = newConfig.apiHost.split('://', 2)\n const protocol = hostParts[0]\n const host = hostParts[1]\n const cdnHost = newConfig.isDefaultApi ? defaultCdnHost : host\n\n if (projectBased) {\n newConfig.url = `${protocol}://${newConfig.projectId}.${host}/v${newConfig.apiVersion}`\n newConfig.cdnUrl = `${protocol}://${newConfig.projectId}.${cdnHost}/v${newConfig.apiVersion}`\n } else {\n newConfig.url = `${newConfig.apiHost}/v${newConfig.apiVersion}`\n newConfig.cdnUrl = newConfig.url\n }\n\n return newConfig\n}\n","import {defer, isObservable, mergeMap, Observable, of} from 'rxjs'\n\nimport {formatQueryParseError, isQueryParseError} from '../http/errors'\nimport {type Any} from '../types'\n\n/**\n * @public\n * Thrown if the EventSource connection could not be established.\n * Note that ConnectionFailedErrors are rare, and disconnects will normally be handled by the EventSource instance itself and emitted as `reconnect` events.\n */\nexport class ConnectionFailedError extends Error {\n readonly name = 'ConnectionFailedError'\n}\n\n/**\n * The listener has been told to explicitly disconnect.\n * This is a rare situation, but may occur if the API knows reconnect attempts will fail,\n * eg in the case of a deleted dataset, a blocked project or similar events.\n * @public\n */\nexport class DisconnectError extends Error {\n readonly name = 'DisconnectError'\n readonly reason?: string\n constructor(message: string, reason?: string, options: ErrorOptions = {}) {\n super(message, options)\n this.reason = reason\n }\n}\n\n/**\n * @public\n * The server sent a `channelError` message. Usually indicative of a bad or malformed request\n */\nexport class ChannelError extends Error {\n readonly name = 'ChannelError'\n readonly data?: unknown\n constructor(message: string, data: unknown) {\n super(message)\n this.data = data\n }\n}\n\n/**\n * @public\n * The server sent an `error`-event to tell the client that an unexpected error has happened.\n */\nexport class MessageError extends Error {\n readonly name = 'MessageError'\n readonly data?: unknown\n constructor(message: string, data: unknown, options: ErrorOptions = {}) {\n super(message, options)\n this.data = data\n }\n}\n\n/**\n * @public\n * An error occurred while parsing the message sent by the server as JSON. Should normally not happen.\n */\nexport class MessageParseError extends Error {\n readonly name = 'MessageParseError'\n}\n\n/**\n * @public\n */\nexport interface ServerSentEvent<Name extends string> {\n type: Name\n id?: string\n data?: unknown\n}\n\n// Always listen for these events, no matter what\nconst REQUIRED_EVENTS = ['channelError', 'disconnect']\n\n/**\n * @internal\n */\nexport type EventSourceEvent<Name extends string> = ServerSentEvent<Name>\n\n/**\n * @internal\n */\nexport type EventSourceInstance = InstanceType<typeof globalThis.EventSource>\n\n/**\n * Sanity API specific EventSource handler shared between the listen and live APIs\n *\n * Since the `EventSource` API is not provided by all environments, this function enables custom initialization of the EventSource instance\n * for runtimes that requires polyfilling or custom setup logic (e.g. custom HTTP headers)\n * via the passed `initEventSource` function which must return an EventSource instance.\n *\n * Possible errors to be thrown on the returned observable are:\n * - {@link MessageError}\n * - {@link MessageParseError}\n * - {@link ChannelError}\n * - {@link DisconnectError}\n * - {@link ConnectionFailedError}\n *\n * @param initEventSource - A function that returns an EventSource instance or an Observable that resolves to an EventSource instance\n * @param events - an array of named events from the API to listen for.\n *\n * @internal\n */\nexport function connectEventSource<EventName extends string>(\n initEventSource: () => EventSourceInstance | Observable<EventSourceInstance>,\n events: EventName[],\n) {\n return defer(() => {\n const es = initEventSource()\n return isObservable(es) ? es : of(es)\n }).pipe(mergeMap((es) => connectWithESInstance(es, events))) as Observable<\n ServerSentEvent<EventName>\n >\n}\n\n/**\n * Provides an observable from the passed EventSource instance, subscribing to the passed list of names of events types to listen for\n * Handles connection logic, adding/removing event listeners, payload parsing, error propagation, etc.\n *\n * @param es - The EventSource instance\n * @param events - List of event names to listen for\n */\nfunction connectWithESInstance<EventTypeName extends string>(\n es: EventSourceInstance,\n events: EventTypeName[],\n) {\n return new Observable<EventSourceEvent<EventTypeName>>((observer) => {\n const emitOpen = (events as string[]).includes('open')\n const emitReconnect = (events as string[]).includes('reconnect')\n\n // EventSource will emit a regular Event if it fails to connect, however the API may also emit an `error` MessageEvent\n // So we need to handle both cases\n function onError(evt: MessageEvent | Event) {\n // If the event has a `data` property, then it`s a MessageEvent emitted by the API and we should forward the error\n if ('data' in evt) {\n const [parseError, event] = parseEvent(evt as MessageEvent)\n observer.error(\n parseError\n ? new MessageParseError('Unable to parse EventSource error message', {cause: event})\n : new MessageError((event?.data as {message: string}).message, event),\n )\n return\n }\n\n // We should never be in a disconnected state. By default, EventSource will reconnect\n // automatically, but in some cases (like when a laptop lid is closed), it will trigger onError\n // if it can't reconnect.\n // see https://html.spec.whatwg.org/multipage/server-sent-events.html#sse-processing-model\n if (es.readyState === es.CLOSED) {\n // In these cases we'll signal to consumers (via the error path) that a retry/reconnect is needed.\n observer.error(new ConnectionFailedError('EventSource connection failed'))\n } else if (emitReconnect) {\n observer.next({type: 'reconnect' as EventTypeName})\n }\n }\n\n function onOpen() {\n // The open event of the EventSource API is fired when a connection with an event source is opened.\n observer.next({type: 'open' as EventTypeName})\n }\n\n function onMessage(message: MessageEvent) {\n const [parseError, event] = parseEvent(message)\n if (parseError) {\n observer.error(\n new MessageParseError('Unable to parse EventSource message', {cause: parseError}),\n )\n return\n }\n if (message.type === 'channelError') {\n // An error occurred. This is different from a network-level error (which will be emitted as 'error').\n // Possible causes are things such as malformed filters, non-existant datasets\n // or similar.\n const tag = new URL(es.url).searchParams.get('tag')\n observer.error(new ChannelError(extractErrorMessage(event?.data, tag), event.data))\n return\n }\n if (message.type === 'disconnect') {\n // The listener has been told to explicitly disconnect and not reconnect.\n // This is a rare situation, but may occur if the API knows reconnect attempts will fail,\n // eg in the case of a deleted dataset, a blocked project or similar events.\n observer.error(\n new DisconnectError(\n `Server disconnected client: ${\n (event.data as {reason?: string})?.reason || 'unknown error'\n }`,\n ),\n )\n return\n }\n observer.next({\n type: message.type as EventTypeName,\n id: message.lastEventId,\n ...(event.data ? {data: event.data} : {}),\n })\n }\n\n es.addEventListener('error', onError)\n\n if (emitOpen) {\n es.addEventListener('open', onOpen)\n }\n\n // Make sure we have a unique list of events types to avoid listening multiple times,\n const cleanedEvents = [...new Set([...REQUIRED_EVENTS, ...events])]\n // filter out events that are handled separately\n .filter((type) => type !== 'error' && type !== 'open' && type !== 'reconnect')\n\n cleanedEvents.forEach((type: string) => es.addEventListener(type, onMessage))\n\n return () => {\n es.removeEventListener('error', onError)\n if (emitOpen) {\n es.removeEventListener('open', onOpen)\n }\n cleanedEvents.forEach((type: string) => es.removeEventListener(type, onMessage))\n es.close()\n }\n })\n}\n\nfunction parseEvent(\n message: MessageEvent,\n): [null, {type: string; id: string; data?: unknown}] | [Error, null] {\n try {\n const data = typeof message.data === 'string' && JSON.parse(message.data)\n return [\n null,\n {\n type: message.type,\n id: message.lastEventId,\n ...(isEmptyObject(data) ? {} : {data}),\n },\n ]\n } catch (err) {\n return [err as Error, null]\n }\n}\n\nfunction extractErrorMessage(err: Any, tag?: string | null) {\n const error = err.error\n\n if (!error) {\n return err.message || 'Unknown listener error'\n }\n\n if (isQueryParseError(error)) {\n return formatQueryParseError(error, tag)\n }\n\n if (error.description) {\n return error.description\n }\n\n return typeof error === 'string' ? error : JSON.stringify(error, null, 2)\n}\n\nfunction isEmptyObject(data: object) {\n for (const _ in data) {\n return false\n }\n return true\n}\n","import type {MutationSelection} from '../types'\n\nexport function getSelection(sel: unknown): MutationSelection {\n if (typeof sel === 'string') {\n return {id: sel}\n }\n\n if (Array.isArray(sel)) {\n return {query: '*[_id in $ids]', params: {ids: sel}}\n }\n\n if (typeof sel === 'object' && sel !== null && 'query' in sel && typeof sel.query === 'string') {\n return 'params' in sel && typeof sel.params === 'object' && sel.params !== null\n ? {query: sel.query, params: sel.params}\n : {query: sel.query}\n }\n\n const selectionOpts = [\n '* Document ID (<docId>)',\n '* Array of document IDs',\n '* Object containing `query`',\n ].join('\\n')\n\n throw new Error(`Unknown selection - must be one of:\\n\\n${selectionOpts}`)\n}\n","import {type Observable} from 'rxjs'\n\nimport type {ObservableSanityClient, SanityClient} from '../SanityClient'\nimport type {\n AllDocumentIdsMutationOptions,\n AllDocumentsMutationOptions,\n Any,\n AttributeSet,\n BaseMutationOptions,\n FirstDocumentIdMutationOptions,\n FirstDocumentMutationOptions,\n MultipleMutationResult,\n PatchMutationOperation,\n PatchOperations,\n PatchSelection,\n SanityDocument,\n SingleMutationResult,\n} from '../types'\nimport {getSelection} from '../util/getSelection'\nimport {validateInsert, validateObject} from '../validators'\n\n/** @internal */\nexport class BasePatch {\n protected selection: PatchSelection\n protected operations: PatchOperations\n constructor(selection: PatchSelection, operations: PatchOperations = {}) {\n this.selection = selection\n this.operations = operations\n }\n\n /**\n * Sets the given attributes to the document. Does NOT merge objects.\n * The operation is added to the current patch, ready to be commited by `commit()`\n *\n * @param attrs - Attributes to set. To set a deep attribute, use JSONMatch, eg: \\{\"nested.prop\": \"value\"\\}\n */\n set(attrs: AttributeSet): this {\n return this._assign('set', attrs)\n }\n\n /**\n * Sets the given attributes to the document if they are not currently set. Does NOT merge objects.\n * The operation is added to the current patch, ready to be commited by `commit()`\n *\n * @param attrs - Attributes to set. To set a deep attribute, use JSONMatch, eg: \\{\"nested.prop\": \"value\"\\}\n */\n setIfMissing(attrs: AttributeSet): this {\n return this._assign('setIfMissing', attrs)\n }\n\n /**\n * Performs a \"diff-match-patch\" operation on the string attributes provided.\n * The operation is added to the current patch, ready to be commited by `commit()`\n *\n * @param attrs - Attributes to perform operation on. To set a deep attribute, use JSONMatch, eg: \\{\"nested.prop\": \"dmp\"\\}\n */\n diffMatchPatch(attrs: AttributeSet): this {\n validateObject('diffMatchPatch', attrs)\n return this._assign('diffMatchPatch', attrs)\n }\n\n /**\n * Unsets the attribute paths provided.\n * The operation is added to the current patch, ready to be commited by `commit()`\n *\n * @param attrs - Attribute paths to unset.\n */\n unset(attrs: string[]): this {\n if (!Array.isArray(attrs)) {\n throw new Error('unset(attrs) takes an array of attributes to unset, non-array given')\n }\n\n this.operations = Object.assign({}, this.operations, {unset: attrs})\n return this\n }\n\n /**\n * 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.\n *\n * @param attrs - Object of attribute paths to increment, values representing the number to increment by.\n */\n inc(attrs: {[key: string]: number}): this {\n return this._assign('inc', attrs)\n }\n\n /**\n * 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.\n *\n * @param attrs - Object of attribute paths to decrement, values representing the number to decrement by.\n */\n dec(attrs: {[key: string]: number}): this {\n return this._assign('dec', attrs)\n }\n\n /**\n * Provides methods for modifying arrays, by inserting, appending and replacing elements via a JSONPath expression.\n *\n * @param at - Location to insert at, relative to the given selector, or 'replace' the matched path\n * @param selector - JSONPath expression, eg `comments[-1]` or `blocks[_key==\"abc123\"]`\n * @param items - Array of items to insert/replace\n */\n insert(at: 'before' | 'after' | 'replace', selector: string, items: Any[]): this {\n validateInsert(at, selector, items)\n return this._assign('insert', {[at]: selector, items})\n }\n\n /**\n * Append the given items to the array at the given JSONPath\n *\n * @param selector - Attribute/path to append to, eg `comments` or `person.hobbies`\n * @param items - Array of items to append to the array\n */\n append(selector: string, items: Any[]): this {\n return this.insert('after', `${selector}[-1]`, items)\n }\n\n /**\n * Prepend the given items to the array at the given JSONPath\n *\n * @param selector - Attribute/path to prepend to, eg `comments` or `person.hobbies`\n * @param items - Array of items to prepend to the array\n */\n prepend(selector: string, items: Any[]): this {\n return this.insert('before', `${selector}[0]`, items)\n }\n\n /**\n * Change the contents of an array by removing existing elements and/or adding new elements.\n *\n * @param selector - Attribute or JSONPath expression for array\n * @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\n * @param deleteCount - An integer indicating the number of old array elements to remove.\n * @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.\n */\n splice(selector: string, start: number, deleteCount?: number, items?: Any[]): this {\n // Negative indexes doesn't mean the same in Sanity as they do in JS;\n // -1 means \"actually at the end of the array\", which allows inserting\n // at the end of the array without knowing its length. We therefore have\n // to substract negative indexes by one to match JS. If you want Sanity-\n // behaviour, just use `insert('replace', selector, items)` directly\n const delAll = typeof deleteCount === 'undefined' || deleteCount === -1\n const startIndex = start < 0 ? start - 1 : start\n const delCount = delAll ? -1 : Math.max(0, start + deleteCount)\n const delRange = startIndex < 0 && delCount >= 0 ? '' : delCount\n const rangeSelector = `${selector}[${startIndex}:${delRange}]`\n return this.insert('replace', rangeSelector, items || [])\n }\n\n /**\n * Adds a revision clause, preventing the document from being patched if the `_rev` property does not match the given value\n *\n * @param rev - Revision to lock the patch to\n */\n ifRevisionId(rev: string): this {\n this.operations.ifRevisionID = rev\n return this\n }\n\n /**\n * Return a plain JSON representation of the patch\n */\n serialize(): PatchMutationOperation {\n return {...getSelection(this.selection), ...this.operations}\n }\n\n /**\n * Return a plain JSON representation of the patch\n */\n toJSON(): PatchMutationOperation {\n return this.serialize()\n }\n\n /**\n * Clears the patch of all operations\n */\n reset(): this {\n this.operations = {}\n return this\n }\n\n protected _assign(op: keyof PatchOperations, props: Any, merge = true): this {\n validateObject(op, props)\n this.operations = Object.assign({}, this.operations, {\n [op]: Object.assign({}, (merge && this.operations[op]) || {}, props),\n })\n return this\n }\n\n protected _set(op: keyof PatchOperations, props: Any): this {\n return this._assign(op, props, false)\n }\n}\n\n/** @public */\nexport class ObservablePatch extends BasePatch {\n #client?: ObservableSanityClient\n\n constructor(\n selection: PatchSelection,\n operations?: PatchOperations,\n client?: ObservableSanityClient,\n ) {\n super(selection, operations)\n this.#client = client\n }\n\n /**\n * Clones the patch\n */\n clone(): ObservablePatch {\n return new ObservablePatch(this.selection, {...this.operations}, this.#client)\n }\n\n /**\n * Commit the patch, returning an observable that produces the first patched document\n *\n * @param options - Options for the mutation operation\n */\n commit<R extends Record<string, Any> = Record<string, Any>>(\n options: FirstDocumentMutationOptions,\n ): Observable<SanityDocument<R>>\n /**\n * Commit the patch, returning an observable that produces an array of the mutated documents\n *\n * @param options - Options for the mutation operation\n */\n commit<R extends Record<string, Any> = Record<string, Any>>(\n options: AllDocumentsMutationOptions,\n ): Observable<SanityDocument<R>[]>\n /**\n * Commit the patch, returning an observable that produces a mutation result object\n *\n * @param options - Options for the mutation operation\n */\n commit(options: FirstDocumentIdMutationOptions): Observable<SingleMutationResult>\n /**\n * Commit the patch, returning an observable that produces a mutation result object\n *\n * @param options - Options for the mutation operation\n */\n commit(options: AllDocumentIdsMutationOptions): Observable<MultipleMutationResult>\n /**\n * Commit the patch, returning an observable that produces the first patched document\n *\n * @param options - Options for the mutation operation\n */\n commit<R extends Record<string, Any> = Record<string, Any>>(\n options?: BaseMutationOptions,\n ): Observable<SanityDocument<R>>\n commit<R extends Record<string, Any> = Record<string, Any>>(\n options?:\n | FirstDocumentMutationOptions\n | AllDocumentsMutationOptions\n | FirstDocumentIdMutationOptions\n | AllDocumentIdsMutationOptions\n | BaseMutationOptions,\n ): Observable<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n if (!this.#client) {\n throw new Error(\n 'No `client` passed to patch, either provide one or pass the ' +\n 'patch to a clients `mutate()` method',\n )\n }\n\n const returnFirst = typeof this.selection === 'string'\n const opts = Object.assign({returnFirst, returnDocuments: true}, options)\n return this.#client.mutate<R>({patch: this.serialize()} as Any, opts)\n }\n}\n\n/** @public */\nexport class Patch extends BasePatch {\n #client?: SanityClient\n constructor(selection: PatchSelection, operations?: PatchOperations, client?: SanityClient) {\n super(selection, operations)\n this.#client = client\n }\n\n /**\n * Clones the patch\n */\n clone(): Patch {\n return new Patch(this.selection, {...this.operations}, this.#client)\n }\n\n /**\n * Commit the patch, returning a promise that resolves to the first patched document\n *\n * @param options - Options for the mutation operation\n */\n commit<R extends Record<string, Any> = Record<string, Any>>(\n options: FirstDocumentMutationOptions,\n ): Promise<SanityDocument<R>>\n /**\n * Commit the patch, returning a promise that resolves to an array of the mutated documents\n *\n * @param options - Options for the mutation operation\n */\n commit<R extends Record<string, Any> = Record<string, Any>>(\n options: AllDocumentsMutationOptions,\n ): Promise<SanityDocument<R>[]>\n /**\n * Commit the patch, returning a promise that resolves to a mutation result object\n *\n * @param options - Options for the mutation operation\n */\n commit(options: FirstDocumentIdMutationOptions): Promise<SingleMutationResult>\n /**\n * Commit the patch, returning a promise that resolves to a mutation result object\n *\n * @param options - Options for the mutation operation\n */\n commit(options: AllDocumentIdsMutationOptions): Promise<MultipleMutationResult>\n /**\n * Commit the patch, returning a promise that resolves to the first patched document\n *\n * @param options - Options for the mutation operation\n */\n commit<R extends Record<string, Any> = Record<string, Any>>(\n options?: BaseMutationOptions,\n ): Promise<SanityDocument<R>>\n commit<R extends Record<string, Any> = Record<string, Any>>(\n options?:\n | FirstDocumentMutationOptions\n | AllDocumentsMutationOptions\n | FirstDocumentIdMutationOptions\n | AllDocumentIdsMutationOptions\n | BaseMutationOptions,\n ): Promise<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n if (!this.#client) {\n throw new Error(\n 'No `client` passed to patch, either provide one or pass the ' +\n 'patch to a clients `mutate()` method',\n )\n }\n\n const returnFirst = typeof this.selection === 'string'\n const opts = Object.assign({returnFirst, returnDocuments: true}, options)\n return this.#client.mutate<R>({patch: this.serialize()} as Any, opts)\n }\n}\n","import type {Observable} from 'rxjs'\n\nimport type {ObservableSanityClient, SanityClient} from '../SanityClient'\nimport type {\n Any,\n BaseMutationOptions,\n IdentifiedSanityDocumentStub,\n MultipleMutationResult,\n Mutation,\n MutationSelection,\n PatchOperations,\n SanityDocument,\n SanityDocumentStub,\n SingleMutationResult,\n TransactionAllDocumentIdsMutationOptions,\n TransactionAllDocumentsMutationOptions,\n TransactionFirstDocumentIdMutationOptions,\n TransactionFirstDocumentMutationOptions,\n} from '../types'\nimport * as validators from '../validators'\nimport {ObservablePatch, Patch} from './patch'\n\n/** @public */\nexport type PatchBuilder = (patch: Patch) => Patch\n/** @public */\nexport type ObservablePatchBuilder = (patch: ObservablePatch) => ObservablePatch\n\nconst defaultMutateOptions = {returnDocuments: false}\n\n/** @internal */\nexport class BaseTransaction {\n protected operations: Mutation[]\n protected trxId?: string\n constructor(operations: Mutation[] = [], transactionId?: string) {\n this.operations = operations\n this.trxId = transactionId\n }\n /**\n * 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.\n * The operation is added to the current transaction, ready to be commited by `commit()`\n *\n * @param doc - Document to create. Requires a `_type` property.\n */\n create<R extends Record<string, Any> = Record<string, Any>>(doc: SanityDocumentStub<R>): this {\n validators.validateObject('create', doc)\n return this._add({create: doc})\n }\n\n /**\n * Creates a new Sanity document. If a document with the same `_id` already exists, the create operation will be ignored.\n * The operation is added to the current transaction, ready to be commited by `commit()`\n *\n * @param doc - Document to create if it does not already exist. Requires `_id` and `_type` properties.\n */\n createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(\n doc: IdentifiedSanityDocumentStub<R>,\n ): this {\n const op = 'createIfNotExists'\n validators.validateObject(op, doc)\n validators.requireDocumentId(op, doc)\n return this._add({[op]: doc})\n }\n\n /**\n * Creates a new Sanity document, or replaces an existing one if the same `_id` is already used.\n * The operation is added to the current transaction, ready to be commited by `commit()`\n *\n * @param doc - Document to create or replace. Requires `_id` and `_type` properties.\n */\n createOrReplace<R extends Record<string, Any> = Record<string, Any>>(\n doc: IdentifiedSanityDocumentStub<R>,\n ): this {\n const op = 'createOrReplace'\n validators.validateObject(op, doc)\n validators.requireDocumentId(op, doc)\n return this._add({[op]: doc})\n }\n\n /**\n * Deletes the document with the given document ID\n * The operation is added to the current transaction, ready to be commited by `commit()`\n *\n * @param documentId - Document ID to delete\n */\n delete(documentId: string): this {\n validators.validateDocumentId('delete', documentId)\n return this._add({delete: {id: documentId}})\n }\n\n /**\n * Gets the current transaction ID, if any\n */\n transactionId(): string | undefined\n /**\n * Set the ID of this transaction.\n *\n * @param id - Transaction ID\n */\n transactionId(id: string): this\n transactionId(id?: string): this | string | undefined {\n if (!id) {\n return this.trxId\n }\n\n this.trxId = id\n return this\n }\n\n /**\n * Return a plain JSON representation of the transaction\n */\n serialize(): Mutation[] {\n return [...this.operations]\n }\n\n /**\n * Return a plain JSON representation of the transaction\n */\n toJSON(): Mutation[] {\n return this.serialize()\n }\n\n /**\n * Clears the transaction of all operations\n */\n reset(): this {\n this.operations = []\n return this\n }\n\n protected _add(mut: Mutation): this {\n this.operations.push(mut)\n return this\n }\n}\n\n/** @public */\nexport class Transaction extends BaseTransaction {\n #client?: SanityClient\n constructor(operations?: Mutation[], client?: SanityClient, transactionId?: string) {\n super(operations, transactionId)\n this.#client = client\n }\n\n /**\n * Clones the transaction\n */\n clone(): Transaction {\n return new Transaction([...this.operations], this.#client, this.trxId)\n }\n\n /**\n * Commit the transaction, returning a promise that resolves to the first mutated document\n *\n * @param options - Options for the mutation operation\n */\n commit<R extends Record<string, Any>>(\n options: TransactionFirstDocumentMutationOptions,\n ): Promise<SanityDocument<R>>\n /**\n * Commit the transaction, returning a promise that resolves to an array of the mutated documents\n *\n * @param options - Options for the mutation operation\n */\n commit<R extends Record<string, Any>>(\n options: TransactionAllDocumentsMutationOptions,\n ): Promise<SanityDocument<R>[]>\n /**\n * Commit the transaction, returning a promise that resolves to a mutation result object\n *\n * @param options - Options for the mutation operation\n */\n commit(options: TransactionFirstDocumentIdMutationOptions): Promise<SingleMutationResult>\n /**\n * Commit the transaction, returning a promise that resolves to a mutation result object\n *\n * @param options - Options for the mutation operation\n */\n commit(options: TransactionAllDocumentIdsMutationOptions): Promise<MultipleMutationResult>\n /**\n * Commit the transaction, returning a promise that resolves to a mutation result object\n *\n * @param options - Options for the mutation operation\n */\n commit(options?: BaseMutationOptions): Promise<MultipleMutationResult>\n commit<R extends Record<string, Any> = Record<string, Any>>(\n options?:\n | TransactionFirstDocumentMutationOptions\n | TransactionAllDocumentsMutationOptions\n | TransactionFirstDocumentIdMutationOptions\n | TransactionAllDocumentIdsMutationOptions\n | BaseMutationOptions,\n ): Promise<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n if (!this.#client) {\n throw new Error(\n 'No `client` passed to transaction, either provide one or pass the ' +\n 'transaction to a clients `mutate()` method',\n )\n }\n\n return this.#client.mutate<R>(\n this.serialize() as Any,\n Object.assign({transactionId: this.trxId}, defaultMutateOptions, options || {}),\n )\n }\n\n /**\n * Performs a patch on the given document ID. Can either be a builder function or an object of patch operations.\n * The operation is added to the current transaction, ready to be commited by `commit()`\n *\n * @param documentId - Document ID to perform the patch operation on\n * @param patchOps - Operations to perform, or a builder function\n */\n patch(documentId: string, patchOps?: PatchBuilder | PatchOperations): this\n /**\n * Performs a patch on the given selection. Can either be a builder function or an object of patch operations.\n *\n * @param selection - An object with `query` and optional `params`, defining which document(s) to patch\n * @param patchOps - Operations to perform, or a builder function\n */\n patch(patch: MutationSelection, patchOps?: PatchBuilder | PatchOperations): this\n /**\n * Adds the given patch instance to the transaction.\n * The operation is added to the current transaction, ready to be commited by `commit()`\n *\n * @param patch - Patch to execute\n */\n patch(patch: Patch): this\n patch(\n patchOrDocumentId: Patch | MutationSelection | string,\n patchOps?: PatchBuilder | PatchOperations,\n ): this {\n const isBuilder = typeof patchOps === 'function'\n const isPatch = typeof patchOrDocumentId !== 'string' && patchOrDocumentId instanceof Patch\n const isMutationSelection =\n typeof patchOrDocumentId === 'object' &&\n ('query' in patchOrDocumentId || 'id' in patchOrDocumentId)\n\n // transaction.patch(client.patch('documentId').inc({visits: 1}))\n if (isPatch) {\n return this._add({patch: patchOrDocumentId.serialize()})\n }\n\n // patch => patch.inc({visits: 1}).set({foo: 'bar'})\n if (isBuilder) {\n const patch = patchOps(new Patch(patchOrDocumentId, {}, this.#client))\n if (!(patch instanceof Patch)) {\n throw new Error('function passed to `patch()` must return the patch')\n }\n\n return this._add({patch: patch.serialize()})\n }\n\n /*\n * transaction.patch(\n * {query: \"*[_type == 'person' && points >= $threshold]\", params: { threshold: 100 }},\n * {dec: { points: 100 }, inc: { bonuses: 1 }}\n * )\n */\n if (isMutationSelection) {\n const patch = new Patch(patchOrDocumentId, patchOps || {}, this.#client)\n return this._add({patch: patch.serialize()})\n }\n\n return this._add({patch: {id: patchOrDocumentId, ...patchOps}})\n }\n}\n\n/** @public */\nexport class ObservableTransaction extends BaseTransaction {\n #client?: ObservableSanityClient\n constructor(operations?: Mutation[], client?: ObservableSanityClient, transactionId?: string) {\n super(operations, transactionId)\n this.#client = client\n }\n\n /**\n * Clones the transaction\n */\n clone(): ObservableTransaction {\n return new ObservableTransaction([...this.operations], this.#client, this.trxId)\n }\n\n /**\n * Commit the transaction, returning an observable that produces the first mutated document\n *\n * @param options - Options for the mutation operation\n */\n commit<R extends Record<string, Any>>(\n options: TransactionFirstDocumentMutationOptions,\n ): Observable<SanityDocument<R>>\n /**\n * Commit the transaction, returning an observable that produces an array of the mutated documents\n *\n * @param options - Options for the mutation operation\n */\n commit<R extends Record<string, Any>>(\n options: TransactionAllDocumentsMutationOptions,\n ): Observable<SanityDocument<R>[]>\n /**\n * Commit the transaction, returning an observable that produces a mutation result object\n *\n * @param options - Options for the mutation operation\n */\n commit(options: TransactionFirstDocumentIdMutationOptions): Observable<SingleMutationResult>\n /**\n * Commit the transaction, returning an observable that produces a mutation result object\n *\n * @param options - Options for the mutation operation\n */\n commit(options: TransactionAllDocumentIdsMutationOptions): Observable<MultipleMutationResult>\n /**\n * Commit the transaction, returning an observable that produces a mutation result object\n *\n * @param options - Options for the mutation operation\n */\n commit(options?: BaseMutationOptions): Observable<MultipleMutationResult>\n commit<R extends Record<string, Any> = Record<string, Any>>(\n options?:\n | TransactionFirstDocumentMutationOptions\n | TransactionAllDocumentsMutationOptions\n | TransactionFirstDocumentIdMutationOptions\n | TransactionAllDocumentIdsMutationOptions\n | BaseMutationOptions,\n ): Observable<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n if (!this.#client) {\n throw new Error(\n 'No `client` passed to transaction, either provide one or pass the ' +\n 'transaction to a clients `mutate()` method',\n )\n }\n\n return this.#client.mutate<R>(\n this.serialize() as Any,\n Object.assign({transactionId: this.trxId}, defaultMutateOptions, options || {}),\n )\n }\n\n /**\n * Performs a patch on the given document ID. Can either be a builder function or an object of patch operations.\n * The operation is added to the current transaction, ready to be commited by `commit()`\n *\n * @param documentId - Document ID to perform the patch operation on\n * @param patchOps - Operations to perform, or a builder function\n */\n patch(documentId: string, patchOps?: ObservablePatchBuilder | PatchOperations): this\n /**\n * Adds the given patch instance to the transaction.\n * The operation is added to the current transaction, ready to be commited by `commit()`\n *\n * @param patch - ObservablePatch to execute\n */\n patch(patch: ObservablePatch): this\n patch(\n patchOrDocumentId: ObservablePatch | string,\n patchOps?: ObservablePatchBuilder | PatchOperations,\n ): this {\n const isBuilder = typeof patchOps === 'function'\n const isPatch =\n typeof patchOrDocumentId !== 'string' && patchOrDocumentId instanceof ObservablePatch\n\n // transaction.patch(client.patch('documentId').inc({visits: 1}))\n if (isPatch) {\n return this._add({patch: patchOrDocumentId.serialize()})\n }\n\n // patch => patch.inc({visits: 1}).set({foo: 'bar'})\n if (isBuilder) {\n const patch = patchOps(new ObservablePatch(patchOrDocumentId, {}, this.#client))\n if (!(patch instanceof ObservablePatch)) {\n throw new Error('function passed to `patch()` must return the patch')\n }\n\n return this._add({patch: patch.serialize()})\n }\n\n return this._add({patch: {id: patchOrDocumentId, ...patchOps}})\n }\n}\n","import type {RequestOptions} from 'get-it'\n\nimport type {Any} from '../types'\n\nconst projectHeader = 'X-Sanity-Project-ID'\n\nexport function requestOptions(config: Any, overrides: Any = {}): Omit<RequestOptions, 'url'> {\n const headers: Any = {}\n\n if (config.headers) {\n Object.assign(headers, config.headers)\n }\n\n const token = overrides.token || config.token\n if (token) {\n headers.Authorization = `Bearer ${token}`\n }\n\n if (!overrides.useGlobalApi && !config.useProjectHostname && config.projectId) {\n headers[projectHeader] = config.projectId\n }\n\n const withCredentials = Boolean(\n typeof overrides.withCredentials === 'undefined'\n ? config.withCredentials\n : overrides.withCredentials,\n )\n\n const timeout = typeof overrides.timeout === 'undefined' ? config.timeout : overrides.timeout\n return Object.assign({}, overrides, {\n headers: Object.assign({}, headers, overrides.headers || {}),\n timeout: typeof timeout === 'undefined' ? 5 * 60 * 1000 : timeout,\n proxy: overrides.proxy || config.proxy,\n json: true,\n withCredentials,\n fetch:\n typeof overrides.fetch === 'object' && typeof config.fetch === 'object'\n ? {...config.fetch, ...overrides.fetch}\n : overrides.fetch || config.fetch,\n })\n}\n","import type {Any, ListenParams, QueryParams} from '../types'\n\nexport const encodeQueryString = ({\n query,\n params = {},\n options = {},\n}: {\n query: string\n params?: ListenParams | QueryParams\n options?: Any\n}) => {\n const searchParams = new URLSearchParams()\n // We generally want tag at the start of the query string\n const {tag, includeMutations, returnQuery, ...opts} = options\n // We're using `append` instead of `set` to support React Native: https://github.com/facebook/react-native/blob/1982c4722fcc51aa87e34cf562672ee4aff540f1/packages/react-native/Libraries/Blob/URL.js#L86-L88\n if (tag) searchParams.append('tag', tag)\n searchParams.append('query', query)\n\n // Iterate params, the keys are prefixed with `$` and their values JSON stringified\n for (const [key, value] of Object.entries(params)) {\n if (value !== undefined) searchParams.append(`$${key}`, JSON.stringify(value))\n }\n // Options are passed as-is\n for (const [key, value] of Object.entries(opts)) {\n // Skip falsy values\n if (value) searchParams.append(key, `${value}`)\n }\n\n // `returnQuery` is default `true`, so needs an explicit `false` handling\n if (returnQuery === false) searchParams.append('returnQuery', 'false')\n\n // `includeMutations` is default `true`, so needs an explicit `false` handling\n if (includeMutations === false) searchParams.append('includeMutations', 'false')\n\n return `?${searchParams}`\n}\n","import {getDraftId, getVersionFromId, getVersionId, isDraftId} from '@sanity/client/csm'\nimport {from, type MonoTypeOperatorFunction, Observable} from 'rxjs'\nimport {combineLatestWith, filter, map} from 'rxjs/operators'\n\nimport {validateApiPerspective} from '../config'\nimport {requestOptions} from '../http/requestOptions'\nimport type {ObservableSanityClient, SanityClient} from '../SanityClient'\nimport {stegaClean} from '../stega/stegaClean'\nimport type {\n Action,\n AllDocumentIdsMutationOptions,\n AllDocumentsMutationOptions,\n Any,\n BaseActionOptions,\n BaseMutationOptions,\n CreateVersionAction,\n DiscardVersionAction,\n FirstDocumentIdMutationOptions,\n FirstDocumentMutationOptions,\n HttpRequest,\n HttpRequestEvent,\n IdentifiedSanityDocumentStub,\n InitializedClientConfig,\n InitializedStegaConfig,\n MultipleActionResult,\n MultipleMutationResult,\n Mutation,\n MutationSelection,\n QueryOptions,\n RawQueryResponse,\n ReplaceVersionAction,\n RequestObservableOptions,\n RequestOptions,\n SanityDocument,\n SingleActionResult,\n SingleMutationResult,\n UnpublishVersionAction,\n} from '../types'\nimport {getSelection} from '../util/getSelection'\nimport * as validate from '../validators'\nimport * as validators from '../validators'\nimport {\n printCdnPreviewDraftsWarning,\n printCreateVersionWithBaseIdWarning,\n printPreviewDraftsDeprecationWarning,\n} from '../warnings'\nimport {encodeQueryString} from './encodeQueryString'\nimport {ObservablePatch, Patch} from './patch'\nimport {ObservableTransaction, Transaction} from './transaction'\n\ntype Client = SanityClient | ObservableSanityClient\n\nconst excludeFalsey = (param: Any, defValue: Any) => {\n const value = typeof param === 'undefined' ? defValue : param\n return param === false ? undefined : value\n}\n\nconst getMutationQuery = (options: BaseMutationOptions = {}) => {\n return {\n dryRun: options.dryRun,\n returnIds: true,\n returnDocuments: excludeFalsey(options.returnDocuments, true),\n visibility: options.visibility || 'sync',\n autoGenerateArrayKeys: options.autoGenerateArrayKeys,\n skipCrossDatasetReferenceValidation: options.skipCrossDatasetReferenceValidation,\n }\n}\n\nconst isResponse = (event: Any) => event.type === 'response'\nconst getBody = (event: Any) => event.body\n\nconst indexBy = (docs: Any[], attr: Any) =>\n docs.reduce((indexed, doc) => {\n indexed[attr(doc)] = doc\n return indexed\n }, Object.create(null))\n\nconst getQuerySizeLimit = 11264\n\n/** @internal */\nexport function _fetch<R, Q>(\n client: Client,\n httpRequest: HttpRequest,\n _stega: InitializedStegaConfig,\n query: string,\n _params: Q = {} as Q,\n options: QueryOptions = {},\n): Observable<RawQueryResponse<R> | R> {\n const stega =\n 'stega' in options\n ? {\n ...(_stega || {}),\n ...(typeof options.stega === 'boolean' ? {enabled: options.stega} : options.stega || {}),\n }\n : _stega\n const params = stega.enabled ? stegaClean(_params) : _params\n const mapResponse =\n options.filterResponse === false ? (res: Any) => res : (res: Any) => res.result\n\n const {cache, next, ...opts} = {\n // Opt out of setting a `signal` on an internal `fetch` if one isn't provided.\n // This is necessary in React Server Components to avoid opting out of Request Memoization.\n useAbortSignal: typeof options.signal !== 'undefined',\n // Set `resultSourceMap' when stega is enabled, as it's required for encoding.\n resultSourceMap: stega.enabled ? 'withKeyArraySelector' : options.resultSourceMap,\n ...options,\n // Default to not returning the query, unless `filterResponse` is `false`,\n // or `returnQuery` is explicitly set. `true` is the default in Content Lake, so skip if truthy\n returnQuery: options.filterResponse === false && options.returnQuery !== false,\n }\n const reqOpts =\n typeof cache !== 'undefined' || typeof next !== 'undefined'\n ? {...opts, fetch: {cache, next}}\n : opts\n\n const $request = _dataRequest(client, httpRequest, 'query', {query, params}, reqOpts)\n return stega.enabled\n ? $request.pipe(\n combineLatestWith(\n from(\n import('../stega/stegaEncodeSourceMap').then(\n ({stegaEncodeSourceMap}) => stegaEncodeSourceMap,\n ),\n ),\n ),\n map(\n ([res, stegaEncodeSourceMap]: [\n Any,\n (typeof import('../stega/stegaEncodeSourceMap'))['stegaEncodeSourceMap'],\n ]) => {\n const result = stegaEncodeSourceMap(res.result, res.resultSourceMap, stega)\n return mapResponse({...res, result})\n },\n ),\n )\n : $request.pipe(map(mapResponse))\n}\n\n/** @internal */\nexport function _getDocument<R extends Record<string, Any>>(\n client: Client,\n httpRequest: HttpRequest,\n id: string,\n opts: {signal?: AbortSignal; tag?: string; releaseId?: string; includeAllVersions: true},\n): Observable<SanityDocument<R>[]>\n/** @internal */\nexport function _getDocument<R extends Record<string, Any>>(\n client: Client,\n httpRequest: HttpRequest,\n id: string,\n opts?: {signal?: AbortSignal; tag?: string; releaseId?: string; includeAllVersions?: false},\n): Observable<SanityDocument<R> | undefined>\n/** @internal */\nexport function _getDocument<R extends Record<string, Any>>(\n client: Client,\n httpRequest: HttpRequest,\n id: string,\n opts: {signal?: AbortSignal; tag?: string; releaseId?: string; includeAllVersions?: boolean} = {},\n): Observable<SanityDocument<R> | undefined | SanityDocument<R>[]> {\n const getDocId = () => {\n if (!opts.releaseId) {\n return id\n }\n\n const versionId = getVersionFromId(id)\n if (!versionId) {\n if (isDraftId(id)) {\n throw new Error(\n `The document ID (\\`${id}\\`) is a draft, but \\`options.releaseId\\` is set as \\`${opts.releaseId}\\``,\n )\n }\n\n return getVersionId(id, opts.releaseId)\n }\n\n if (versionId !== opts.releaseId) {\n throw new Error(\n `The document ID (\\`${id}\\`) is already a version of \\`${versionId}\\` release, but this does not match the provided \\`options.releaseId\\` (\\`${opts.releaseId}\\`)`,\n )\n }\n\n return id\n }\n const docId = getDocId()\n\n const options = {\n uri: _getDataUrl(client, 'doc', docId),\n json: true,\n tag: opts.tag,\n signal: opts.signal,\n query:\n opts.includeAllVersions !== undefined\n ? {includeAllVersions: opts.includeAllVersions}\n : undefined,\n }\n return _requestObservable<SanityDocument<R> | undefined | SanityDocument<R>[]>(\n client,\n httpRequest,\n options,\n ).pipe(\n filter(isResponse),\n map((event) => {\n const documents = event.body.documents\n if (!documents) {\n return opts.includeAllVersions ? [] : undefined\n }\n return opts.includeAllVersions ? documents : documents[0]\n }),\n )\n}\n\n/** @internal */\nexport function _getDocuments<R extends Record<string, Any>>(\n client: Client,\n httpRequest: HttpRequest,\n ids: string[],\n opts: {signal?: AbortSignal; tag?: string} = {},\n): Observable<(SanityDocument<R> | null)[]> {\n const options = {\n uri: _getDataUrl(client, 'doc', ids.join(',')),\n json: true,\n tag: opts.tag,\n signal: opts.signal,\n }\n return _requestObservable<(SanityDocument<R> | null)[]>(client, httpRequest, options).pipe(\n filter(isResponse),\n map((event: Any) => {\n const indexed = indexBy(event.body.documents || [], (doc: Any) => doc._id)\n return ids.map((id) => indexed[id] || null)\n }),\n )\n}\n\n/** @internal */\nexport function _getReleaseDocuments<R extends Record<string, Any>>(\n client: ObservableSanityClient | SanityClient,\n httpRequest: HttpRequest,\n releaseId: string,\n opts: BaseMutationOptions = {},\n): Observable<RawQueryResponse<SanityDocument<R>[]>> {\n return _dataRequest(\n client,\n httpRequest,\n 'query',\n {\n query: '*[sanity::partOfRelease($releaseId)]',\n params: {\n releaseId,\n },\n },\n opts,\n )\n}\n\n/** @internal */\nexport function _createIfNotExists<R extends Record<string, Any>>(\n client: Client,\n httpRequest: HttpRequest,\n doc: IdentifiedSanityDocumentStub<R>,\n options?:\n | AllDocumentIdsMutationOptions\n | AllDocumentsMutationOptions\n | BaseMutationOptions\n | FirstDocumentIdMutationOptions\n | FirstDocumentMutationOptions,\n): Observable<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n> {\n validators.requireDocumentId('createIfNotExists', doc)\n return _create<R>(client, httpRequest, doc, 'createIfNotExists', options)\n}\n\n/** @internal */\nexport function _createOrReplace<R extends Record<string, Any>>(\n client: Client,\n httpRequest: HttpRequest,\n doc: IdentifiedSanityDocumentStub<R>,\n options?:\n | AllDocumentIdsMutationOptions\n | AllDocumentsMutationOptions\n | BaseMutationOptions\n | FirstDocumentIdMutationOptions\n | FirstDocumentMutationOptions,\n): Observable<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n> {\n validators.requireDocumentId('createOrReplace', doc)\n return _create<R>(client, httpRequest, doc, 'createOrReplace', options)\n}\n\n/** @internal */\nexport function _createVersion<R extends Record<string, Any>>(\n client: ObservableSanityClient | SanityClient,\n httpRequest: HttpRequest,\n doc: IdentifiedSanityDocumentStub<R>,\n publishedId: string,\n options?: BaseActionOptions,\n): Observable<SingleActionResult> {\n validators.requireDocumentId('createVersion', doc)\n validators.requireDocumentType('createVersion', doc)\n printCreateVersionWithBaseIdWarning()\n\n const createVersionAction: CreateVersionAction = {\n actionType: 'sanity.action.document.version.create',\n publishedId,\n document: doc,\n }\n\n return _action(client, httpRequest, createVersionAction, options)\n}\n\n/** @internal */\nexport function _createVersionFromBase(\n client: ObservableSanityClient | SanityClient,\n httpRequest: HttpRequest,\n publishedId?: string,\n baseId?: string,\n releaseId?: string,\n ifBaseRevisionId?: string,\n options?: BaseActionOptions,\n): Observable<SingleActionResult> {\n if (!baseId) {\n throw new Error('`createVersion()` requires `baseId` when no `document` is provided')\n }\n\n if (!publishedId) {\n throw new Error('`createVersion()` requires `publishedId` when `baseId` is provided')\n }\n\n validators.validateDocumentId('createVersion', baseId)\n validators.validateDocumentId('createVersion', publishedId)\n\n const createVersionAction: CreateVersionAction = {\n actionType: 'sanity.action.document.version.create',\n publishedId,\n baseId,\n versionId: releaseId ? getVersionId(publishedId, releaseId) : getDraftId(publishedId),\n ifBaseRevisionId,\n }\n\n return _action(client, httpRequest, createVersionAction, options)\n}\n\n/** @internal */\nexport function _delete<R extends Record<string, Any>>(\n client: Client,\n httpRequest: HttpRequest,\n selection: string | MutationSelection,\n options?:\n | AllDocumentIdsMutationOptions\n | AllDocumentsMutationOptions\n | BaseMutationOptions\n | FirstDocumentIdMutationOptions\n | FirstDocumentMutationOptions,\n): Observable<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n> {\n return _dataRequest(\n client,\n httpRequest,\n 'mutate',\n {mutations: [{delete: getSelection(selection)}]},\n options,\n )\n}\n\n/** @internal */\nexport function _discardVersion(\n client: ObservableSanityClient | SanityClient,\n httpRequest: HttpRequest,\n versionId: string,\n purge: boolean = false,\n options?: BaseActionOptions,\n): Observable<SingleActionResult> {\n const discardVersionAction: DiscardVersionAction = {\n actionType: 'sanity.action.document.version.discard',\n versionId,\n purge,\n }\n\n return _action(client, httpRequest, discardVersionAction, options)\n}\n\n/** @internal */\nexport function _replaceVersion<R extends Record<string, Any>>(\n client: ObservableSanityClient | SanityClient,\n httpRequest: HttpRequest,\n doc: IdentifiedSanityDocumentStub<R>,\n options?: BaseActionOptions,\n): Observable<SingleActionResult> {\n validators.requireDocumentId('replaceVersion', doc)\n validators.requireDocumentType('replaceVersion', doc)\n\n const replaceVersionAction: ReplaceVersionAction = {\n actionType: 'sanity.action.document.version.replace',\n document: doc,\n }\n\n return _action(client, httpRequest, replaceVersionAction, options)\n}\n\n/** @internal */\nexport function _unpublishVersion(\n client: ObservableSanityClient | SanityClient,\n httpRequest: HttpRequest,\n versionId: string,\n publishedId: string,\n options?: BaseActionOptions,\n): Observable<SingleActionResult> {\n const unpublishVersionAction: UnpublishVersionAction = {\n actionType: 'sanity.action.document.version.unpublish',\n versionId,\n publishedId,\n }\n\n return _action(client, httpRequest, unpublishVersionAction, options)\n}\n\n/** @internal */\nexport function _mutate<R extends Record<string, Any>>(\n client: Client,\n httpRequest: HttpRequest,\n mutations: Mutation<R>[] | Patch | ObservablePatch | Transaction | ObservableTransaction,\n options?:\n | AllDocumentIdsMutationOptions\n | AllDocumentsMutationOptions\n | BaseMutationOptions\n | FirstDocumentIdMutationOptions\n | FirstDocumentMutationOptions,\n): Observable<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n> {\n let mut: Mutation | Mutation[]\n if (mutations instanceof Patch || mutations instanceof ObservablePatch) {\n mut = {patch: mutations.serialize()}\n } else if (mutations instanceof Transaction || mutations instanceof ObservableTransaction) {\n mut = mutations.serialize()\n } else {\n mut = mutations\n }\n\n const muts = Array.isArray(mut) ? mut : [mut]\n const transactionId = (options && options.transactionId) || undefined\n return _dataRequest(client, httpRequest, 'mutate', {mutations: muts, transactionId}, options)\n}\n\n/**\n * @internal\n */\nexport function _action(\n client: Client,\n httpRequest: HttpRequest,\n actions: Action | Action[],\n options?: BaseActionOptions,\n): Observable<SingleActionResult | MultipleActionResult> {\n const acts = Array.isArray(actions) ? actions : [actions]\n const transactionId = (options && options.transactionId) || undefined\n const skipCrossDatasetReferenceValidation =\n (options && options.skipCrossDatasetReferenceValidation) || undefined\n const dryRun = (options && options.dryRun) || undefined\n\n return _dataRequest(\n client,\n httpRequest,\n 'actions',\n {actions: acts, transactionId, skipCrossDatasetReferenceValidation, dryRun},\n options,\n )\n}\n\n/**\n * @internal\n */\nexport function _dataRequest(\n client: Client,\n httpRequest: HttpRequest,\n endpoint: string,\n body: Any,\n options: Any = {},\n): Any {\n const isMutation = endpoint === 'mutate'\n const isAction = endpoint === 'actions'\n const isQuery = endpoint === 'query'\n\n // Check if the query string is within a configured threshold,\n // in which case we can use GET. Otherwise, use POST.\n const strQuery = isMutation || isAction ? '' : encodeQueryString(body)\n const useGet = !isMutation && !isAction && strQuery.length < getQuerySizeLimit\n const stringQuery = useGet ? strQuery : ''\n const returnFirst = options.returnFirst\n const {timeout, token, tag, headers, returnQuery, lastLiveEventId, cacheMode} = options\n\n const uri = _getDataUrl(client, endpoint, stringQuery)\n\n const reqOptions = {\n method: useGet ? 'GET' : 'POST',\n uri: uri,\n json: true,\n body: useGet ? undefined : body,\n query: isMutation && getMutationQuery(options),\n timeout,\n headers,\n token,\n tag,\n returnQuery,\n perspective: options.perspective,\n resultSourceMap: options.resultSourceMap,\n lastLiveEventId: Array.isArray(lastLiveEventId) ? lastLiveEventId[0] : lastLiveEventId,\n cacheMode: cacheMode,\n canUseCdn: isQuery,\n signal: options.signal,\n fetch: options.fetch,\n useAbortSignal: options.useAbortSignal,\n useCdn: options.useCdn,\n }\n\n return _requestObservable(client, httpRequest, reqOptions).pipe(\n filter(isResponse),\n map(getBody),\n map((res) => {\n if (!isMutation) {\n return res\n }\n\n // Should we return documents?\n const results = res.results || []\n if (options.returnDocuments) {\n return returnFirst\n ? results[0] && results[0].document\n : results.map((mut: Any) => mut.document)\n }\n\n // Return a reduced subset\n const key = returnFirst ? 'documentId' : 'documentIds'\n const ids = returnFirst ? results[0] && results[0].id : results.map((mut: Any) => mut.id)\n return {\n transactionId: res.transactionId,\n results: results,\n [key]: ids,\n }\n }),\n )\n}\n\n/**\n * @internal\n */\nexport function _create<R extends Record<string, Any>>(\n client: Client,\n httpRequest: HttpRequest,\n doc: Any,\n op: Any,\n options: Any = {},\n): Observable<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n> {\n const mutation = {[op]: doc}\n const opts = Object.assign({returnFirst: true, returnDocuments: true}, options)\n return _dataRequest(client, httpRequest, 'mutate', {mutations: [mutation]}, opts)\n}\n\nconst hasDataConfig = (client: Client) =>\n (client.config().dataset !== undefined && client.config().projectId !== undefined) ||\n client.config()['~experimental_resource'] !== undefined\n\nconst isQuery = (client: Client, uri: string) =>\n hasDataConfig(client) && uri.startsWith(_getDataUrl(client, 'query'))\n\nconst isMutate = (client: Client, uri: string) =>\n hasDataConfig(client) && uri.startsWith(_getDataUrl(client, 'mutate'))\n\nconst isDoc = (client: Client, uri: string) =>\n hasDataConfig(client) && uri.startsWith(_getDataUrl(client, 'doc', ''))\n\nconst isListener = (client: Client, uri: string) =>\n hasDataConfig(client) && uri.startsWith(_getDataUrl(client, 'listen'))\n\nconst isHistory = (client: Client, uri: string) =>\n hasDataConfig(client) && uri.startsWith(_getDataUrl(client, 'history', ''))\n\nconst isData = (client: Client, uri: string) =>\n uri.startsWith('/data/') ||\n isQuery(client, uri) ||\n isMutate(client, uri) ||\n isDoc(client, uri) ||\n isListener(client, uri) ||\n isHistory(client, uri)\n\n/**\n * @internal\n */\nexport function _requestObservable<R>(\n client: Client,\n httpRequest: HttpRequest,\n options: RequestObservableOptions,\n): Observable<HttpRequestEvent<R>> {\n const uri = options.url || (options.uri as string)\n const config = client.config()\n\n // If the `canUseCdn`-option is not set we detect it automatically based on the method + URL.\n // Only the /data endpoint is currently available through API-CDN.\n const canUseCdn =\n typeof options.canUseCdn === 'undefined'\n ? ['GET', 'HEAD'].indexOf(options.method || 'GET') >= 0 && isData(client, uri)\n : options.canUseCdn\n\n let useCdn = (options.useCdn ?? config.useCdn) && canUseCdn\n\n const tag =\n options.tag && config.requestTagPrefix\n ? [config.requestTagPrefix, options.tag].join('.')\n : options.tag || config.requestTagPrefix\n\n if (tag && options.tag !== null) {\n options.query = {tag: validate.requestTag(tag), ...options.query}\n }\n\n // GROQ query-only parameters\n if (['GET', 'HEAD', 'POST'].indexOf(options.method || 'GET') >= 0 && isQuery(client, uri)) {\n const resultSourceMap = options.resultSourceMap ?? config.resultSourceMap\n if (resultSourceMap !== undefined && resultSourceMap !== false) {\n options.query = {resultSourceMap, ...options.query}\n }\n const perspectiveOption = options.perspective || config.perspective\n if (typeof perspectiveOption !== 'undefined') {\n if (perspectiveOption === 'previewDrafts') {\n printPreviewDraftsDeprecationWarning()\n }\n validateApiPerspective(perspectiveOption)\n options.query = {\n perspective: Array.isArray(perspectiveOption)\n ? perspectiveOption.join(',')\n : perspectiveOption,\n ...options.query,\n }\n // If the perspective is set to `drafts` or multiple perspectives we can't use the CDN, the API will throw\n if (\n ((Array.isArray(perspectiveOption) && perspectiveOption.length > 0) ||\n // previewDrafts was renamed to drafts, but keep for backwards compat\n perspectiveOption === 'previewDrafts' ||\n perspectiveOption === 'drafts') &&\n useCdn\n ) {\n useCdn = false\n printCdnPreviewDraftsWarning()\n }\n }\n\n if (options.lastLiveEventId) {\n options.query = {...options.query, lastLiveEventId: options.lastLiveEventId}\n }\n\n if (options.returnQuery === false) {\n options.query = {returnQuery: 'false', ...options.query}\n }\n\n if (useCdn && options.cacheMode == 'noStale') {\n options.query = {cacheMode: 'noStale', ...options.query}\n }\n }\n\n const reqOptions = requestOptions(\n config,\n Object.assign({}, options, {\n url: _getUrl(client, uri, useCdn),\n }),\n ) as RequestOptions\n\n const request = new Observable<HttpRequestEvent<R>>((subscriber) =>\n httpRequest(reqOptions, config.requester!).subscribe(subscriber),\n )\n\n return options.signal ? request.pipe(_withAbortSignal(options.signal)) : request\n}\n\n/**\n * @internal\n */\nexport function _request<R>(client: Client, httpRequest: HttpRequest, options: Any): Observable<R> {\n const observable = _requestObservable<R>(client, httpRequest, options).pipe(\n filter((event: Any) => event.type === 'response'),\n map((event: Any) => event.body),\n )\n\n return observable\n}\n\n/**\n * @internal\n */\nexport function _getDataUrl(client: Client, operation: string, path?: string): string {\n const config = client.config()\n if (config['~experimental_resource']) {\n validators.resourceConfig(config)\n const resourceBase = resourceDataBase(config)\n const uri = path !== undefined ? `${operation}/${path}` : operation\n return `${resourceBase}/${uri}`.replace(/\\/($|\\?)/, '$1')\n }\n const catalog = validators.hasDataset(config)\n const baseUri = `/${operation}/${catalog}`\n const uri = path !== undefined ? `${baseUri}/${path}` : baseUri\n return `/data${uri}`.replace(/\\/($|\\?)/, '$1')\n}\n\n/**\n * @internal\n */\nexport function _getUrl(client: Client, uri: string, canUseCdn = false): string {\n const {url, cdnUrl} = client.config()\n const base = canUseCdn ? cdnUrl : url\n return `${base}/${uri.replace(/^\\//, '')}`\n}\n\n/**\n * @internal\n */\nfunction _withAbortSignal<T>(signal: AbortSignal): MonoTypeOperatorFunction<T> {\n return (input) => {\n return new Observable((observer) => {\n const abort = () => observer.error(_createAbortError(signal))\n\n if (signal && signal.aborted) {\n abort()\n return\n }\n const subscription = input.subscribe(observer)\n signal.addEventListener('abort', abort)\n return () => {\n signal.removeEventListener('abort', abort)\n subscription.unsubscribe()\n }\n })\n }\n}\n// DOMException is supported on most modern browsers and Node.js 18+.\n// @see https://developer.mozilla.org/en-US/docs/Web/API/DOMException#browser_compatibility\nconst isDomExceptionSupported = Boolean(globalThis.DOMException)\n\n/**\n * @internal\n * @param signal - The abort signal to use.\n * Original source copied from https://github.com/sindresorhus/ky/blob/740732c78aad97e9aec199e9871bdbf0ae29b805/source/errors/DOMException.ts\n * TODO: When targeting Node.js 18, use `signal.throwIfAborted()` (https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/throwIfAborted)\n */\nfunction _createAbortError(signal?: AbortSignal) {\n /*\n NOTE: Use DomException with AbortError name as specified in MDN docs (https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort)\n > When abort() is called, the fetch() promise rejects with an Error of type DOMException, with name AbortError.\n */\n if (isDomExceptionSupported) {\n return new DOMException(signal?.reason ?? 'The operation was aborted.', 'AbortError')\n }\n\n // DOMException not supported. Fall back to use of error and override name.\n const error = new Error(signal?.reason ?? 'The operation was aborted.')\n error.name = 'AbortError'\n\n return error\n}\n\nconst resourceDataBase = (config: InitializedClientConfig): string => {\n if (!config['~experimental_resource']) {\n throw new Error('`resource` must be provided to perform resource queries')\n }\n const {type, id} = config['~experimental_resource']\n\n switch (type) {\n case 'dataset': {\n const segments = id.split('.')\n if (segments.length !== 2) {\n throw new Error('Dataset ID must be in the format \"project.dataset\"')\n }\n return `/projects/${segments[0]}/datasets/${segments[1]}`\n }\n case 'canvas': {\n return `/canvases/${id}`\n }\n case 'media-library': {\n return `/media-libraries/${id}`\n }\n case 'dashboard': {\n return `/dashboards/${id}`\n }\n default:\n // @ts-expect-error - handle all supported resource types\n throw new Error(`Unsupported resource type: ${type.toString()}`)\n }\n}\n","import {type Observable} from 'rxjs'\n\nimport {_request} from '../../data/dataMethods'\nimport type {ObservableSanityClient, SanityClient} from '../../SanityClient'\nimport type {AgentActionParams, Any, HttpRequest, IdentifiedSanityDocumentStub} from '../../types'\nimport {hasDataset} from '../../validators'\nimport type {\n AgentActionAsync,\n AgentActionPathSegment,\n AgentActionRequestBase,\n AgentActionSync,\n AgentActionTarget,\n AgentActionTargetInclude,\n} from './commonTypes'\n\n/** @beta */\nexport type GenerateOperation = 'set' | 'append' | 'mixed'\n\n/** @beta */\nexport interface GenerateRequestBase extends AgentActionRequestBase {\n /** schemaId as reported by sanity deploy / sanity schema store */\n schemaId: string\n /**\n * Instruct the LLM how it should generate content. Be as specific and detailed as needed.\n *\n * The LLM only has access to information in the instruction, plus the target schema.\n *\n * String template with support for $variable from `instructionParams`.\n * */\n instruction: string\n /**\n * param values for the string template, keys are the variable name, ie if the template has \"$variable\", one key must be \"variable\"\n *\n * ### Examples\n *\n * #### Constant\n *\n * ##### Shorthand\n * ```ts\n * client.agent.action.generate({\n * schemaId,\n * documentId,\n * instruction: 'Give the following topic:\\n $topic \\n ---\\nGenerate the full article.',\n * instructionParams: {\n * topic: 'Grapefruit'\n * },\n * })\n * ```\n * ##### Object-form\n *\n * ```ts\n * client.agent.action.generate({\n * schemaId,\n * documentId,\n * instruction: 'Give the following topic:\\n $topic \\n ---\\nGenerate the full article.',\n * instructionParams: {\n * topic: {\n * type: 'constant',\n * value: 'Grapefruit'\n * },\n * },\n * })\n * ```\n * #### Field\n * ```ts\n * client.agent.action.generate({\n * schemaId,\n * documentId,\n * instruction: 'Give the following field value:\\n $pte \\n ---\\nGenerate keywords.',\n * instructionParams: {\n * pte: {\n * type: 'field',\n * path: ['pteField'],\n * },\n * },\n * target: {path: 'keywords' }\n * })\n * ```\n * #### Document\n * ```ts\n * client.agent.action.generate({\n * schemaId,\n * documentId,\n * instruction: 'Give the following document value:\\n $document \\n ---\\nGenerate keywords.',\n * instructionParams: {\n * document: {\n * type: 'document',\n * },\n * },\n * target: {path: 'keywords' }\n * })\n * ```\n *\n * #### GROQ\n * ```ts\n * client.agent.action.generate({\n * schemaId,\n * documentId,\n * instruction: 'Give the following list of titles:\\n $list \\n ---\\nGenerate a similar title.',\n * instructionParams: {\n * list: {\n * type: 'groq',\n * query: '* [_type==$type].title',\n * params: {type: 'article'}\n * },\n * },\n * target: {path: 'title' }\n * })\n * ```\n * */\n instructionParams?: AgentActionParams\n\n /**\n * Target defines which parts of the document will be affected by the instruction.\n * It can be an array, so multiple parts of the document can be separately configured in detail.\n *\n * Omitting target implies that the document itself is the root.\n *\n * Notes:\n * - instruction can only affect fields up to `maxPathDepth`\n * - when multiple targets are provided, they will be coalesced into a single target sharing a common target root.\n * It is therefor an error to provide conflicting include/exclude across targets (ie, include title in one, and exclude it in another)\n *\n * ## Generating images\n *\n * Generate will generate images the same was as AI Assist, for images that have been configured using\n * [AI Assist schema options](https://github.com/sanity-io/assist/tree/main/plugin#image-generation).\n *\n * To generate images _without_ changing the schema, directly target an image asset path.\n *\n * For example, all the following will generate an image into the provided asset:\n * * `target: {path: ['image', 'asset'] }`\n * * `target: {path: 'image', include: ['asset'] }`\n *\n * Image generation can be combined with regular content targets:\n * * `target: [{path: ['image', 'asset'] }, {include: ['title', 'description']}]`\n *\n * Since Generate happens in a single LLM pass, the image will be contextually related to other generated content.\n * @see AgentActionRequestBase#conditionalPaths\n */\n target?: GenerateTarget | GenerateTarget[]\n}\n\n/** @beta */\nexport interface GenerateTargetInclude extends AgentActionTargetInclude {\n /**\n * Sets the operation for this path, and all its children.\n * This overrides any operation set parents or the root target.\n * @see #GenerateTarget.operation\n * @see #include\n */\n operation?: GenerateOperation\n\n /**\n * By default, all children up to `target.maxPathDepth` are included.\n *\n * When `include` is specified, only segments explicitly listed will be included.\n *\n * Fields or array items not on the include list, are implicitly excluded.\n */\n include?: (AgentActionPathSegment | GenerateTargetInclude)[]\n}\n\n/** @beta */\nexport interface GenerateTarget extends AgentActionTarget {\n /**\n * Sets the default operation for all paths in the target.\n * Generate runs in `'mixed'` operation mode by default:\n * Changes are set in all non-array fields, and append to all array fields.\n *\n * ### Operation types\n * - `'set'` – an *overwriting* operation, and replaces the full field value.\n * - `'append'`:\n * – array fields: appends new items to the end of the array,\n * - string fields: '\"existing content\" \"new content\"'\n * - text fields: '\"existing content\"\\\\n\"new content\"'\n * - number fields: existing + new\n * - other field types not mentioned will set instead (dates, url)\n * - `'mixed'` – (default) sets non-array fields, and appends to array fields\n *\n * The default operation can be overridden on a per-path basis using `include`.\n *\n * Nested fields inherit the operation specified by their parent and falls back to the\n * top level target operation if not otherwise specified.\n *\n * Use `include` to change the `operation` of individual fields or items.\n *\n * #### Appending in the middle of arrays\n * `target: {path: ['array'], operation: 'append'}` will append the output of the instruction to the end of the array.\n *\n * To insert in the middle of the array, use `target: {path: ['array', {_key: 'appendAfterKey'}], operation: 'append'}`.\n * Here, the output of the instruction will be appended after the array item with key `'appendAfterKey'`.\n *\n * @see #AgentActionTargetInclude.operation\n * @see #include\n * @see #AgentActionTargetInclude.include\n * @see #AgentActionSchema.forcePublishedWrite\n */\n operation?: GenerateOperation\n\n /**\n * By default, all children up to `target.maxPathDepth` are included.\n *\n * When `include` is specified, only segments explicitly listed will be included.\n *\n * Fields or array items not on the include list, are implicitly excluded.\n */\n include?: (AgentActionPathSegment | GenerateTargetInclude)[]\n}\n\n/** @beta */\nexport type GenerateTargetDocument<T extends Record<string, Any> = Record<string, Any>> =\n | {\n operation: 'edit'\n /**\n * @see #AgentActionSchema.forcePublishedWrite\n */\n _id: string\n }\n | {\n operation: 'create'\n /**\n * @see #AgentActionSchema.forcePublishedWrite\n */\n _id?: string\n _type: string\n initialValues?: T\n }\n | {\n operation: 'createIfNotExists'\n /**\n * @see #AgentActionSchema.forcePublishedWrite\n */\n _id: string\n _type: string\n initialValues?: T\n }\n | {\n operation: 'createOrReplace'\n /**\n * @see #AgentActionSchema.forcePublishedWrite\n */\n _id: string\n _type: string\n initialValues?: T\n }\n\n/**\n * Instruction for an existing document.\n * @beta\n */\ninterface GenerateExistingDocumentRequest {\n /**\n * @see #AgentActionSchema.forcePublishedWrite\n */\n documentId: string\n targetDocument?: never\n}\n\n/**\n * Instruction to create a new document\n * @beta\n */\ninterface GenerateTargetDocumentRequest<T extends Record<string, Any> = Record<string, Any>> {\n /**\n * @see #AgentActionSchema.forcePublishedWrite\n */\n targetDocument: GenerateTargetDocument<T>\n documentId?: never\n}\n\n/** @beta */\nexport type GenerateSyncInstruction<T extends Record<string, Any> = Record<string, Any>> = (\n | GenerateExistingDocumentRequest\n | GenerateTargetDocumentRequest<T>\n) &\n GenerateRequestBase &\n AgentActionSync\n\n/** @beta */\nexport type GenerateAsyncInstruction<T extends Record<string, Any> = Record<string, Any>> = (\n | GenerateExistingDocumentRequest\n | GenerateTargetDocumentRequest<T>\n) &\n GenerateRequestBase &\n AgentActionAsync\n\n/** @beta */\nexport type GenerateInstruction<T extends Record<string, Any> = Record<string, Any>> =\n | GenerateSyncInstruction<T>\n | GenerateAsyncInstruction<T>\n\nexport function _generate<DocumentShape extends Record<string, Any>>(\n client: SanityClient | ObservableSanityClient,\n httpRequest: HttpRequest,\n request: GenerateInstruction<DocumentShape>,\n): Observable<\n (typeof request)['async'] extends true\n ? {_id: string}\n : IdentifiedSanityDocumentStub & DocumentShape\n> {\n const dataset = hasDataset(client.config())\n return _request(client, httpRequest, {\n method: 'POST',\n uri: `/agent/action/generate/${dataset}`,\n body: request,\n })\n}\n","import {type Observable} from 'rxjs'\n\nimport {_request} from '../../data/dataMethods'\nimport type {ObservableSanityClient, SanityClient} from '../../SanityClient'\nimport type {\n AgentActionPath,\n AgentActionPathSegment,\n Any,\n GenerateTargetDocument,\n HttpRequest,\n IdentifiedSanityDocumentStub,\n} from '../../types'\nimport {hasDataset} from '../../validators'\nimport type {AgentActionAsync, AgentActionSchema, AgentActionSync} from './commonTypes'\n\n/** @beta */\nexport type PatchOperation = 'set' | 'append' | 'mixed' | 'unset'\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyNonNullable = Exclude<any, null | undefined>\n\n/** @beta */\nexport interface PatchRequestBase extends AgentActionSchema {\n /**\n * Target defines which parts of the document will be affected by the instruction.\n * It can be an array, so multiple parts of the document can be separately configured in detail.\n *\n * Omitting target implies that the document itself is the root.\n *\n * Notes:\n * - instruction can only affect fields up to `maxPathDepth`\n * - when multiple targets are provided, they will be coalesced into a single target sharing a common target root.\n * It is therefore an error to provide conflicting include/exclude across targets (ie, include title in one, and exclude it in another)\n *\n * @see AgentActionRequestBase#conditionalPaths\n */\n target: PatchTarget | PatchTarget[]\n}\n\n/** @beta */\nexport type PatchTarget = {\n /**\n * Determines how the target path will be patched.\n *\n * ### Operation types\n * - `'set'` – an *overwriting* operation: sets the full field value for primitive targets, and merges the provided value with existing values for objects\n * - `'append'`:\n * – array fields: appends new items to the end of the array,\n * - string fields: '\"existing content\" \"new content\"'\n * - text fields: '\"existing content\"\\\\n\"new content\"'\n * - number fields: existing + new\n * - other field types not mentioned will set instead (dates, url)\n * - `'mixed'` – sets non-array fields, and appends to array fields\n * - `'unset'` – removes whatever value is on the target path\n *\n * All operations except unset requires a `value`.\n *\n * #### Appending in the middle of arrays\n * To append to an array, use the 'append' operation, and provide an array value with one or more array items.\n *\n * `target: {path: ['array'], operation: 'append', value: [{_type: 'item' _key: 'a'}]}` will append the items in the value to the existing array.\n *\n * To insert in the middle of the array, use `target: {path: ['array', {_key: 'appendAfterKey'}], operation: 'append', value: [{_type: 'item' _key: 'a'}]}`.\n * Here, `{_type: 'item' _key: 'a'}` will be appended after the array item with key `'appendAfterKey'`\n *\n * It is optional to provide a _key for inserted array items; if one isn't provided, it will be generated.\n */\n operation: PatchOperation\n\n path: AgentActionPathSegment | AgentActionPath\n} & (\n | {operation: 'unset'; value?: never}\n | {operation: Exclude<PatchOperation, 'unset'>; value: AnyNonNullable}\n)\n\n/**\n * Patches an existing document\n * @beta\n */\ninterface PatchExistingDocumentRequest {\n /**\n * @see #AgentActionSchema.forcePublishedWrite\n */\n documentId: string\n targetDocument?: never\n}\n\n/**\n * Create a new document, then patch it\n * @beta\n */\ninterface PatchTargetDocumentRequest<T extends Record<string, Any> = Record<string, Any>> {\n /**\n * @see #AgentActionSchema.forcePublishedWrite\n */\n targetDocument: GenerateTargetDocument<T>\n documentId?: never\n}\n\n/** @beta */\nexport type PatchDocumentSync<T extends Record<string, Any> = Record<string, Any>> = (\n | PatchExistingDocumentRequest\n | PatchTargetDocumentRequest<T>\n) &\n PatchRequestBase &\n AgentActionSync\n\n/** @beta */\nexport type PatchDocumentAsync<T extends Record<string, Any> = Record<string, Any>> = (\n | PatchExistingDocumentRequest\n | PatchTargetDocumentRequest<T>\n) &\n PatchRequestBase &\n AgentActionAsync\n\n/** @beta */\nexport type PatchDocument<T extends Record<string, Any> = Record<string, Any>> =\n | PatchDocumentSync<T>\n | PatchDocumentAsync<T>\n\nexport function _patch<DocumentShape extends Record<string, Any>>(\n client: SanityClient | ObservableSanityClient,\n httpRequest: HttpRequest,\n request: PatchDocument<DocumentShape>,\n): Observable<\n (typeof request)['async'] extends true\n ? {_id: string}\n : IdentifiedSanityDocumentStub & DocumentShape\n> {\n const dataset = hasDataset(client.config())\n return _request(client, httpRequest, {\n method: 'POST',\n uri: `/agent/action/patch/${dataset}`,\n body: request,\n })\n}\n","import {type Observable} from 'rxjs'\n\nimport {_request} from '../../data/dataMethods'\nimport type {ObservableSanityClient, SanityClient} from '../../SanityClient'\nimport type {AgentActionParams, Any, HttpRequest} from '../../types'\nimport {hasDataset} from '../../validators'\n\n/** @beta */\nexport interface PromptRequestBase {\n /**\n * Instruct the LLM how it should generate content. Be as specific and detailed as needed.\n *\n * The LLM only has access to information in the instruction, plus the target schema.\n *\n * String template with support for $variable from `instructionParams`.\n * */\n instruction: string\n /**\n * param values for the string template, keys are the variable name, ie if the template has \"$variable\", one key must be \"variable\"\n *\n * ### Examples\n *\n * #### Constant\n *\n * ##### Shorthand\n * ```ts\n * client.agent.action.prompt({\n * instruction: 'Give the following topic:\\n $topic \\n ---\\nReturns some facts about it',\n * instructionParams: {\n * topic: 'Grapefruit'\n * },\n * })\n * ```\n * ##### Object-form\n *\n * ```ts\n * client.agent.action.prompt({\n * instruction: 'Give the following topic:\\n $topic \\n ---\\nReturns some facts about it.',\n * instructionParams: {\n * topic: {\n * type: 'constant',\n * value: 'Grapefruit'\n * },\n * },\n * })\n * ```\n * #### Field\n * ```ts\n * client.agent.action.prompt({\n * instruction: 'Give the following field value:\\n $pte \\n ---\\nGenerate keywords.',\n * instructionParams: {\n * pte: {\n * type: 'field',\n * path: ['pteField'],\n * documentId: 'someSanityDocId'\n * },\n * },\n * })\n * ```\n * #### Document\n * ```ts\n * client.agent.action.prompt({\n * json: true,\n * instruction: 'Given the following document:$document\\nCreate a JSON string[] array with keywords describing it.',\n * instructionParams: {\n * document: {\n * type: 'document',\n * documentId: 'someSanityDocId'\n * },\n * },\n * })\n * ```\n *\n * #### GROQ\n * ```ts\n * client.agent.action.prompt({\n * instruction: 'Return the best title amongst these: $titles.',\n * instructionParams: {\n * titles: {\n * type: 'groq',\n * query: '* [_type==$type].title',\n * params: {type: 'article'}\n * },\n * },\n * })\n * ```\n * */\n instructionParams?: AgentActionParams<{docIdRequired: true}>\n\n /**\n * Controls how much variance the instructions will run with.\n *\n * Value must be in the range [0, 1] (inclusive).\n *\n * Default: 0.3\n */\n temperature?: number\n}\n\n/**\n * @beta\n */\n// need the unused generic here to allow for optional callsite casting\n// eslint-disable-next-line unused-imports/no-unused-vars\ninterface PromptJsonResponse<T extends Record<string, Any> = Record<string, Any>> {\n /**\n *\n * When format is 'json', the response will be json according to the instruction.\n * Note: In addition to setting this to 'json', `instruction` MUST include the word 'JSON', or 'json' for this to work.\n */\n format: 'json'\n}\n\ninterface PromptTextResponse {\n /**\n * When format is 'string', the response will be a raw text response to the instruction.\n */\n format?: 'string'\n}\n\n/** @beta */\nexport type PromptRequest<T extends Record<string, Any> = Record<string, Any>> = (\n | PromptTextResponse\n | PromptJsonResponse<T>\n) &\n PromptRequestBase\n\nexport function _prompt<const DocumentShape extends Record<string, Any>>(\n client: SanityClient | ObservableSanityClient,\n httpRequest: HttpRequest,\n request: PromptRequest<DocumentShape>,\n): Observable<(typeof request)['format'] extends 'json' ? DocumentShape : string> {\n const dataset = hasDataset(client.config())\n return _request(client, httpRequest, {\n method: 'POST',\n uri: `/agent/action/prompt/${dataset}`,\n body: request,\n })\n}\n","import {type Observable} from 'rxjs'\n\nimport {_request} from '../../data/dataMethods'\nimport type {ObservableSanityClient, SanityClient} from '../../SanityClient'\nimport type {\n AgentActionParams,\n AgentActionPath,\n Any,\n HttpRequest,\n IdentifiedSanityDocumentStub,\n} from '../../types'\nimport {hasDataset} from '../../validators'\nimport type {\n AgentActionAsync,\n AgentActionPathSegment,\n AgentActionRequestBase,\n AgentActionSync,\n AgentActionTarget,\n AgentActionTargetInclude,\n} from './commonTypes'\n\n/** @beta */\nexport interface TransformRequestBase extends AgentActionRequestBase {\n /** schemaId as reported by sanity deploy / sanity schema store */\n schemaId: string\n\n /**\n * The source document the transformation will use as input.\n *\n * @see #AgentActionSchema.forcePublishedWrite\n */\n documentId: string\n\n /**\n * The source document's content is first copied to the target,\n * then it is transformed according to the instruction.\n *\n * When omitted, the source document (documentId) is also the target document.\n *\n * @see #AgentActionSchema.forcePublishedWrite\n */\n targetDocument?: TransformTargetDocument\n\n /**\n * Instruct the LLM how to transform the input to th output.\n *\n * String template with support for $variable from `instructionParams`.\n *\n * Capped to 2000 characters, after variables has been injected.\n * */\n instruction: string\n /**\n *\n * param values for the string template, keys are the variable name, ie if the template has \"$variable\", one key must be \"variable\"\n *\n * ### Examples\n *\n * #### Constant\n *\n * ##### Shorthand\n * ```ts\n * client.agent.action.generate({\n * schemaId,\n * documentId,\n * instruction: 'Give the following topic:\\n $topic \\n ---\\nGenerate the full article.',\n * instructionParams: {\n * topic: 'Grapefruit'\n * },\n * })\n * ```\n * ##### Object-form\n *\n * ```ts\n * client.agent.action.transform({\n * schemaId,\n * documentId,\n * instruction: 'Give the following topic:\\n $topic \\n ---\\nGenerate the full article.',\n * instructionParams: {\n * topic: {\n * type: 'constant',\n * value: 'Grapefruit'\n * },\n * },\n * })\n * ```\n * #### Field\n * ```ts\n * client.agent.action.transform({\n * schemaId,\n * documentId,\n * instruction: 'Give the following field value:\\n $pte \\n ---\\nGenerate keywords.',\n * instructionParams: {\n * pte: {\n * type: 'field',\n * path: ['pteField'],\n * },\n * },\n * target: {path: 'keywords' }\n * })\n * ```\n * #### Document\n * ```ts\n * client.agent.action.transform({\n * schemaId,\n * documentId,\n * instruction: 'Give the following document value:\\n $document \\n ---\\nGenerate keywords.',\n * instructionParams: {\n * document: {\n * type: 'document',\n * },\n * },\n * target: {path: 'keywords' }\n * })\n * ```\n *\n * #### GROQ\n * ```ts\n * client.agent.action.transform({\n * schemaId,\n * documentId,\n * instruction: 'Give the following list of titles:\\n $list \\n ---\\nGenerate a similar title.',\n * instructionParams: {\n * list: {\n * type: 'groq',\n * query: '* [_type==$type].title',\n * params: {type: 'article'}\n * },\n * },\n * target: {path: 'title'}\n * })\n * ```\n * */\n instructionParams?: AgentActionParams\n\n /**\n * Target defines which parts of the document will be affected by the instruction.\n * It can be an array, so multiple parts of the document can be separately configured in detail.\n *\n * Omitting target implies that the document itself is the root.\n *\n * Notes:\n * - instruction can only affect fields up to `maxPathDepth`\n * - when multiple targets are provided, they will be coalesced into a single target sharing a common target root.\n * It is therefor an error to provide conflicting include/exclude across targets (ie, include title in one, and exclude it in another)\n *\n * Default max depth for transform: 12\n *\n * ## Transforming images\n *\n * To transform an existing image, directly target an image asset path.\n *\n * For example, all the following will transform the image into the provided asset:\n * * `target: {path: ['image', 'asset'] }`\n * * `target: {path: 'image', include: ['asset'] }`\n *\n * Image transform can be combined with regular content targets:\n * * `target: [{path: ['image', 'asset'] }, {include: ['title', 'description']}]`\n *\n * Image transform can have per-path instructions, just like any other target paths:\n * * `target: [{path: ['image', 'asset'], instruction: 'Make the sky blue' }`\n *\n * @see AgentActionRequestBase#conditionalPaths\n */\n target?: TransformTarget | TransformTarget[]\n}\n\n/**\n * @see #AgentActionSchema.forcePublishedWrite\n *\n * @beta\n */\nexport type TransformTargetDocument =\n | {operation: 'edit'; _id: string}\n | {operation: 'create'; _id?: string}\n | {operation: 'createIfNotExists'; _id: string}\n | {operation: 'createOrReplace'; _id: string}\n\n/**\n *\n * @see #TransformOperation\n * @beta\n */\nexport type ImageDescriptionOperation = {\n type: 'image-description'\n /**\n * When omitted, parent image value will be inferred from the arget path.\n *\n * When specified, the `sourcePath` should be a path to an image (or image asset) field:\n * - `['image']`\n * - `['wrapper', 'mainImage']`\n * - `['heroImage', 'asset'] // the asset segment is optional, but supported`\n */\n sourcePath?: AgentActionPath\n} & (\n | {\n /**\n * When omitted, parent image value will be inferred from the target path.\n *\n * When specified, the `sourcePath` should be a path to an image (or image asset) field:\n * - `['image']`\n * - `['wrapper', 'mainImage']`\n * - `['heroImage', 'asset'] // the asset segment is optional, but supported`\n *\n * Incompatible with `imageUrl`\n *\n */\n sourcePath?: AgentActionPath\n imageUrl?: never\n }\n | {\n /**\n * When specified, the image source to be described will be fetched from the URL.\n *\n * Incompatible with `sourcePath`\n */\n imageUrl?: `https://${string}`\n sourcePath?: never\n }\n)\n\n/**\n *\n * ## `set` by default\n * By default, Transform will change the value of every target field in place using a set operation.\n *\n * ## Image description\n *\n * ### Targeting image fields\n * Images can be transformed to a textual description by targeting a `string`, `text` or Portable Text field (`array` with `block`)\n * with `operation: {type: 'image-description'}`.\n *\n * Custom instructions for image description targets will be used to generate the description.\n *\n * Such targets must be a descendant field of an image object.\n *\n * For example:\n * - `target: {path: ['image', 'description'], operation: {type: 'image-description'} }`\n * - `target: {path: ['array', {_key: 'abc'}, 'alt'], operation: {type: 'image-description'} } //assuming the item in the array on the key-ed path is an image`\n * - `target: {path: ['image'], include: ['portableTextField'], operation: {type: 'image-description'}, instruction: 'Use formatting and headings to describe the image in great detail' }`\n *\n * ### Targeting non-image fields\n * If the target image description lives outside an image object, use the `sourcePath` option to specify the path to the image field.\n * `sourcePath` must be an image or image asset field.\n *\n * For example:\n * - `target: {path: ['description'], operation: operation: {type: 'image-description', sourcePath: ['image', 'asset'] }`\n * - `target: {path: ['wrapper', 'title'], operation: {type: 'image-description', sourcePath: ['array', {_key: 'abc'}, 'image'] }`\n * - `target: {path: ['wrapper'], include: ['portableTextField'], operation: {type: 'image-description', sourcePath: ['image', 'asset'] }, instruction: 'Use formatting and headings to describe the image in great detail' }`\n *\n * ### Targeting images outside the document (URL)\n * 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`.\n *\n * Example:\n * - `target: {path: ['description'], operation: operation: {type: 'image-description', imageUrL: 'https://www.sanity.io/static/images/favicons/android-icon-192x192.png?v=2' }`\n * @beta\n */\nexport type TransformOperation = 'set' | ImageDescriptionOperation\n\n/**\n * @see #TransformOperation\n * @beta\n * */\nexport interface TransformTargetInclude extends AgentActionTargetInclude {\n /**\n * Specifies a tailored instruction of this target.\n *\n * String template with support for $variable from `instructionParams`. */\n instruction?: string\n\n /**\n * By default, all children up to `target.maxPathDepth` are included.\n *\n * When `include` is specified, only segments explicitly listed will be included.\n *\n * Fields or array items not on the include list, are implicitly excluded.\n */\n include?: (AgentActionPathSegment | TransformTargetInclude)[]\n\n /**\n * Default: `set`\n * @see #TransformOperation\n */\n operation?: TransformOperation\n}\n\n/**\n * @see #TransformOperation\n * @beta\n * */\nexport interface TransformTarget extends AgentActionTarget {\n /**\n * Specifies a tailored instruction of this target.\n *\n * String template with support for $variable from `instructionParams`.\n * */\n instruction?: string\n\n /**\n * By default, all children up to `target.maxPathDepth` are included.\n *\n * When `include` is specified, only segments explicitly listed will be included.\n *\n * Fields or array items not on the include list, are implicitly excluded.\n */\n include?: (AgentActionPathSegment | TransformTargetInclude)[]\n\n /**\n * Default: `set`\n * @see #TransformOperation\n */\n operation?: TransformOperation\n}\n\n/** @beta */\n// need the generics to hold optional call-site response generics\n// eslint-disable-next-line unused-imports/no-unused-vars\nexport type TransformDocumentSync<T extends Record<string, Any> = Record<string, Any>> =\n TransformRequestBase & AgentActionSync\n\n/** @beta */\nexport type TransformDocumentAsync = TransformRequestBase & AgentActionAsync\n\n/** @beta */\nexport type TransformDocument<T extends Record<string, Any> = Record<string, Any>> =\n | TransformDocumentSync<T>\n | TransformDocumentAsync\n\nexport function _transform<DocumentShape extends Record<string, Any>>(\n client: SanityClient | ObservableSanityClient,\n httpRequest: HttpRequest,\n request: TransformDocument<DocumentShape>,\n): Observable<\n (typeof request)['async'] extends true\n ? {_id: string}\n : IdentifiedSanityDocumentStub & DocumentShape\n> {\n const dataset = hasDataset(client.config())\n return _request(client, httpRequest, {\n method: 'POST',\n uri: `/agent/action/transform/${dataset}`,\n body: request,\n })\n}\n","import {type Observable} from 'rxjs'\n\nimport {_request} from '../../data/dataMethods'\nimport type {ObservableSanityClient, SanityClient} from '../../SanityClient'\nimport type {\n AgentActionParams,\n AgentActionPathSegment,\n AgentActionTarget,\n Any,\n HttpRequest,\n IdentifiedSanityDocumentStub,\n} from '../../types'\nimport {hasDataset} from '../../validators'\nimport type {\n AgentActionAsync,\n AgentActionPath,\n AgentActionRequestBase,\n AgentActionSync,\n AgentActionTargetInclude,\n} from './commonTypes'\nimport type {TransformTargetDocument} from './transform'\n\n/** @beta */\nexport interface TranslateRequestBase extends AgentActionRequestBase {\n /** schemaId as reported by sanity deploy / sanity schema store */\n schemaId: string\n\n /**\n * The source document the transformation will use as input.\n * @see #AgentActionSchema.forcePublishedWrite\n */\n documentId: string\n\n /**\n * The target document will first get content copied over from the source,\n * then it is translated according to the instruction.\n *\n * When omitted, the source document (documentId) is also the target document.\n *\n * @see #AgentActionSchema.forcePublishedWrite\n */\n targetDocument?: TransformTargetDocument\n\n /**\n * While optional, it is recommended\n */\n fromLanguage?: TranslateLanguage\n toLanguage: TranslateLanguage\n\n /**\n * `styleGuide` can be used to tailor how the translation should be preformed.\n *\n * String template using $variable from styleGuideParams.\n *\n * Capped to 2000 characters, after variables has been injected.\n *\n * @see #protectedPhrases\n */\n styleGuide?: string\n /** param values for the string template, keys are the variable name, ie if the template has \"$variable\", one key must be \"variable\" */\n styleGuideParams?: AgentActionParams\n\n /**\n * When the input string contains any phrase from `protectedPhrases`, the LLM will be instructed not\n * to translate them.\n *\n * It is recommended to use `protectedPhrases` instead of `styleGuide` for deny-list words and phrases,\n * since it keeps token cost low, resulting in faster responses, and limits how much information the LLM\n * has to process, since only phrases that are actually in the input string will be included in the final prompt.\n */\n protectedPhrases?: string[]\n\n /**\n * When specified, the `toLanguage.id` will be stored in the specified path in the target document.\n *\n * The file _can_ be hidden: true (unlike other fields in the target, which will be ignored)\n */\n languageFieldPath?: AgentActionPathSegment | AgentActionPath\n\n /**\n * Target defines which parts of the document will be affected by the instruction.\n * It can be an array, so multiple parts of the document can be separately configured in detail.\n *\n * Omitting target implies that the document itself is the root.\n *\n * Notes:\n * - instruction can only affect fields up to `maxPathDepth`\n * - when multiple targets are provided, they will be coalesced into a single target sharing a common target root.\n * It is therefor an error to provide conflicting include/exclude across targets (ie, include title in one, and exclude it in another)\n *\n * @see AgentActionRequestBase#conditionalPaths\n */\n target?: TranslateTarget | TranslateTarget[]\n}\n\n/** @beta */\nexport interface TranslateLanguage {\n /**\n * Language code\n */\n id: string\n\n /**\n * While optional, it is recommended to provide a language title\n */\n title?: string\n}\n\n/** @beta */\nexport interface TranslateTargetInclude extends AgentActionTargetInclude {\n /** String template using $variable from styleGuideParams. */\n styleGuide?: string\n\n /**\n * By default, all children up to `target.maxPathDepth` are included.\n *\n * When `include` is specified, only segments explicitly listed will be included.\n *\n * Fields or array items not on the include list, are implicitly excluded.\n */\n include?: (AgentActionPathSegment | TranslateTargetInclude)[]\n}\n\n/** @beta */\nexport interface TranslateTarget extends AgentActionTarget {\n /** String template using $variable from styleGuideParams. */\n styleGuide?: string\n\n /**\n * By default, all children up to `target.maxPathDepth` are included.\n *\n * When `include` is specified, only segments explicitly listed will be included.\n *\n * Fields or array items not on the include list, are implicitly excluded.\n */\n include?: (AgentActionPathSegment | TranslateTargetInclude)[]\n}\n\n/** @beta */\n// need the generics to hold optional call-site response generics\n// eslint-disable-next-line unused-imports/no-unused-vars\nexport type TranslateDocumentSync<T extends Record<string, Any> = Record<string, Any>> =\n TranslateRequestBase & AgentActionSync\n\n/** @beta */\nexport type TranslateDocumentAsync = TranslateRequestBase & AgentActionAsync\n\n/** @beta */\nexport type TranslateDocument<T extends Record<string, Any> = Record<string, Any>> =\n | TranslateDocumentSync<T>\n | TranslateDocumentAsync\n\nexport function _translate<DocumentShape extends Record<string, Any>>(\n client: SanityClient | ObservableSanityClient,\n httpRequest: HttpRequest,\n request: TranslateDocument<DocumentShape>,\n): Observable<\n (typeof request)['async'] extends true\n ? {_id: string}\n : IdentifiedSanityDocumentStub & DocumentShape\n> {\n const dataset = hasDataset(client.config())\n return _request(client, httpRequest, {\n method: 'POST',\n uri: `/agent/action/translate/${dataset}`,\n body: request,\n })\n}\n","import {lastValueFrom, type Observable} from 'rxjs'\n\nimport type {ObservableSanityClient, SanityClient} from '../../SanityClient'\nimport type {Any, HttpRequest, IdentifiedSanityDocumentStub} from '../../types'\nimport {_generate, type GenerateInstruction} from './generate'\nimport {_patch, type PatchDocument} from './patch'\nimport {_prompt, type PromptRequest} from './prompt'\nimport {_transform, type TransformDocument} from './transform'\nimport {_translate, type TranslateDocument} from './translate'\n\n/** @public */\nexport class ObservableAgentsActionClient {\n #client: ObservableSanityClient\n #httpRequest: HttpRequest\n constructor(client: ObservableSanityClient, httpRequest: HttpRequest) {\n this.#client = client\n this.#httpRequest = httpRequest\n }\n\n /**\n * Run an instruction to generate content in a target document.\n * @param request - instruction request\n */\n generate<DocumentShape extends Record<string, Any>>(\n request: GenerateInstruction<DocumentShape>,\n ): Observable<\n (typeof request)['async'] extends true\n ? {_id: string}\n : IdentifiedSanityDocumentStub & DocumentShape\n > {\n return _generate(this.#client, this.#httpRequest, request)\n }\n\n /**\n * Transform a target document based on a source.\n * @param request - translation request\n */\n transform<DocumentShape extends Record<string, Any>>(\n request: TransformDocument<DocumentShape>,\n ): Observable<\n (typeof request)['async'] extends true\n ? {_id: string}\n : IdentifiedSanityDocumentStub & DocumentShape\n > {\n return _transform(this.#client, this.#httpRequest, request)\n }\n\n /**\n * Translate a target document based on a source.\n * @param request - translation request\n */\n translate<DocumentShape extends Record<string, Any>>(\n request: TranslateDocument<DocumentShape>,\n ): Observable<\n (typeof request)['async'] extends true\n ? {_id: string}\n : IdentifiedSanityDocumentStub & DocumentShape\n > {\n return _translate(this.#client, this.#httpRequest, request)\n }\n}\n\n/** @public */\nexport class AgentActionsClient {\n #client: SanityClient\n #httpRequest: HttpRequest\n constructor(client: SanityClient, httpRequest: HttpRequest) {\n this.#client = client\n this.#httpRequest = httpRequest\n }\n\n /**\n * Run an instruction to generate content in a target document.\n * @param request - instruction request\n */\n generate<DocumentShape extends Record<string, Any>>(\n request: GenerateInstruction<DocumentShape>,\n ): Promise<\n (typeof request)['async'] extends true\n ? {_id: string}\n : IdentifiedSanityDocumentStub & DocumentShape\n > {\n return lastValueFrom(_generate(this.#client, this.#httpRequest, request))\n }\n\n /**\n * Transform a target document based on a source.\n * @param request - translation request\n */\n transform<DocumentShape extends Record<string, Any>>(\n request: TransformDocument<DocumentShape>,\n ): Promise<\n (typeof request)['async'] extends true\n ? {_id: string}\n : IdentifiedSanityDocumentStub & DocumentShape\n > {\n return lastValueFrom(_transform(this.#client, this.#httpRequest, request))\n }\n\n /**\n * Translate a target document based on a source.\n * @param request - translation request\n */\n translate<DocumentShape extends Record<string, Any>>(\n request: TranslateDocument<DocumentShape>,\n ): Promise<\n (typeof request)['async'] extends true\n ? {_id: string}\n : IdentifiedSanityDocumentStub & DocumentShape\n > {\n return lastValueFrom(_translate(this.#client, this.#httpRequest, request))\n }\n\n /**\n * Run a raw instruction and return the result either as text or json\n * @param request - prompt request\n */\n prompt<const DocumentShape extends Record<string, Any>>(\n request: PromptRequest<DocumentShape>,\n ): Promise<(typeof request)['format'] extends 'json' ? DocumentShape : string> {\n return lastValueFrom(_prompt(this.#client, this.#httpRequest, request))\n }\n\n /**\n * Patch a document using a schema aware API.\n * Does not use an LLM, but uses the schema to ensure paths and values matches the schema.\n * @param request - instruction request\n */\n patch<DocumentShape extends Record<string, Any>>(\n request: PatchDocument<DocumentShape>,\n ): Promise<\n (typeof request)['async'] extends true\n ? {_id: string}\n : IdentifiedSanityDocumentStub & DocumentShape\n > {\n return lastValueFrom(_patch(this.#client, this.#httpRequest, request))\n }\n}\n","import {lastValueFrom, type Observable} from 'rxjs'\nimport {filter, map} from 'rxjs/operators'\n\nimport {_requestObservable} from '../data/dataMethods'\nimport type {ObservableSanityClient, SanityClient} from '../SanityClient'\nimport type {\n Any,\n HttpRequest,\n HttpRequestEvent,\n InitializedClientConfig,\n ResponseEvent,\n SanityAssetDocument,\n SanityImageAssetDocument,\n UploadBody,\n UploadClientConfig,\n} from '../types'\nimport * as validators from '../validators'\n\n/** @internal */\nexport class ObservableAssetsClient {\n #client: ObservableSanityClient\n #httpRequest: HttpRequest\n constructor(client: ObservableSanityClient, httpRequest: HttpRequest) {\n this.#client = client\n this.#httpRequest = httpRequest\n }\n\n /**\n * Uploads a file asset to the configured dataset\n *\n * @param assetType - Asset type (file)\n * @param body - Asset content - can be a browser File instance, a Blob, a Node.js Buffer instance or a Node.js ReadableStream.\n * @param options - Options to use for the upload\n */\n upload(\n assetType: 'file',\n body: UploadBody,\n options?: UploadClientConfig,\n ): Observable<HttpRequestEvent<{document: SanityAssetDocument}>>\n\n /**\n * Uploads an image asset to the configured dataset\n *\n * @param assetType - Asset type (image)\n * @param body - Asset content - can be a browser File instance, a Blob, a Node.js Buffer instance or a Node.js ReadableStream.\n * @param options - Options to use for the upload\n */\n upload(\n assetType: 'image',\n body: UploadBody,\n options?: UploadClientConfig,\n ): Observable<HttpRequestEvent<{document: SanityImageAssetDocument}>>\n /**\n * Uploads a file or an image asset to the configured dataset\n *\n * @param assetType - Asset type (file/image)\n * @param body - Asset content - can be a browser File instance, a Blob, a Node.js Buffer instance or a Node.js ReadableStream.\n * @param options - Options to use for the upload\n */\n upload(\n assetType: 'file' | 'image',\n body: UploadBody,\n options?: UploadClientConfig,\n ): Observable<HttpRequestEvent<{document: SanityAssetDocument | SanityImageAssetDocument}>>\n upload(\n assetType: 'file' | 'image',\n body: UploadBody,\n options?: UploadClientConfig,\n ): Observable<HttpRequestEvent<{document: SanityAssetDocument | SanityImageAssetDocument}>> {\n return _upload(this.#client, this.#httpRequest, assetType, body, options)\n }\n}\n\n/** @internal */\nexport class AssetsClient {\n #client: SanityClient\n #httpRequest: HttpRequest\n constructor(client: SanityClient, httpRequest: HttpRequest) {\n this.#client = client\n this.#httpRequest = httpRequest\n }\n\n /**\n * Uploads a file asset to the configured dataset\n *\n * @param assetType - Asset type (file)\n * @param body - Asset content - can be a browser File instance, a Blob, a Node.js Buffer instance or a Node.js ReadableStream.\n * @param options - Options to use for the upload\n */\n upload(\n assetType: 'file',\n body: UploadBody,\n options?: UploadClientConfig,\n ): Promise<SanityAssetDocument>\n /**\n * Uploads an image asset to the configured dataset\n *\n * @param assetType - Asset type (image)\n * @param body - Asset content - can be a browser File instance, a Blob, a Node.js Buffer instance or a Node.js ReadableStream.\n * @param options - Options to use for the upload\n */\n upload(\n assetType: 'image',\n body: UploadBody,\n options?: UploadClientConfig,\n ): Promise<SanityImageAssetDocument>\n /**\n * Uploads a file or an image asset to the configured dataset\n *\n * @param assetType - Asset type (file/image)\n * @param body - Asset content - can be a browser File instance, a Blob, a Node.js Buffer instance or a Node.js ReadableStream.\n * @param options - Options to use for the upload\n */\n upload(\n assetType: 'file' | 'image',\n body: UploadBody,\n options?: UploadClientConfig,\n ): Promise<SanityAssetDocument | SanityImageAssetDocument>\n upload(\n assetType: 'file' | 'image',\n body: UploadBody,\n options?: UploadClientConfig,\n ): Promise<SanityAssetDocument | SanityImageAssetDocument> {\n const observable = _upload(this.#client, this.#httpRequest, assetType, body, options)\n return lastValueFrom(\n observable.pipe(\n filter((event: Any) => event.type === 'response'),\n map(\n (event) =>\n (event as ResponseEvent<{document: SanityAssetDocument | SanityImageAssetDocument}>)\n .body.document,\n ),\n ),\n )\n }\n}\n\nfunction _upload(\n client: SanityClient | ObservableSanityClient,\n httpRequest: HttpRequest,\n assetType: 'image' | 'file',\n body: UploadBody,\n opts: UploadClientConfig = {},\n): Observable<HttpRequestEvent<{document: SanityAssetDocument | SanityImageAssetDocument}>> {\n validators.validateAssetType(assetType)\n\n // If an empty array is given, explicitly set `none` to override API defaults\n let meta = opts.extract || undefined\n if (meta && !meta.length) {\n meta = ['none']\n }\n\n const config = client.config()\n const options = optionsFromFile(opts, body)\n const {tag, label, title, description, creditLine, filename, source} = options\n const query: Any = {\n label,\n title,\n description,\n filename,\n meta,\n creditLine,\n }\n if (source) {\n query.sourceId = source.id\n query.sourceName = source.name\n query.sourceUrl = source.url\n }\n\n return _requestObservable(client, httpRequest, {\n tag,\n method: 'POST',\n timeout: options.timeout || 0,\n uri: buildAssetUploadUrl(config, assetType),\n headers: options.contentType ? {'Content-Type': options.contentType} : {},\n query,\n body,\n })\n}\n\nfunction buildAssetUploadUrl(config: InitializedClientConfig, assetType: 'image' | 'file'): string {\n const assetTypeEndpoint = assetType === 'image' ? 'images' : 'files'\n\n if (config['~experimental_resource']) {\n const {type, id} = config['~experimental_resource']\n switch (type) {\n case 'dataset': {\n throw new Error(\n 'Assets are not supported for dataset resources, yet. Configure the client with `{projectId: <projectId>, dataset: <datasetId>}` instead.',\n )\n }\n case 'canvas': {\n return `/canvases/${id}/assets/${assetTypeEndpoint}`\n }\n case 'media-library': {\n return `/media-libraries/${id}/upload`\n }\n case 'dashboard': {\n return `/dashboards/${id}/assets/${assetTypeEndpoint}`\n }\n default:\n // @ts-expect-error - handle all supported resource types\n throw new Error(`Unsupported resource type: ${type.toString()}`)\n }\n }\n\n const dataset = validators.hasDataset(config)\n return `assets/${assetTypeEndpoint}/${dataset}`\n}\n\nfunction optionsFromFile(opts: Record<string, Any>, file: Any) {\n if (typeof File === 'undefined' || !(file instanceof File)) {\n return opts\n }\n\n return Object.assign(\n {\n filename: opts.preserveFilename === false ? undefined : file.name,\n contentType: file.type,\n },\n opts,\n )\n}\n","import type {Any} from '../types'\n\nexport default (obj: Any, defaults: Any) =>\n Object.keys(defaults)\n .concat(Object.keys(obj))\n .reduce((target, prop) => {\n target[prop] = typeof obj[prop] === 'undefined' ? defaults[prop] : obj[prop]\n\n return target\n }, {} as Any)\n","import {type Any} from '../types'\n\nexport const pick = (obj: Any, props: Any) =>\n props.reduce((selection: Any, prop: Any) => {\n if (typeof obj[prop] === 'undefined') {\n return selection\n }\n\n selection[prop] = obj[prop]\n return selection\n }, {})\n","import {defer, shareReplay} from 'rxjs'\nimport {map} from 'rxjs/operators'\n\nexport const eventSourcePolyfill = defer(() => import('@sanity/eventsource')).pipe(\n map(({default: EventSource}) => EventSource as unknown as typeof globalThis.EventSource),\n shareReplay(1),\n)\n","import {\n catchError,\n concat,\n mergeMap,\n Observable,\n of,\n type OperatorFunction,\n throwError,\n timer,\n} from 'rxjs'\n\nimport {ConnectionFailedError} from './eventsource'\n\n/**\n * Note: connection failure is not the same as network disconnect which may happen more frequent.\n * The EventSource instance will automatically reconnect in case of a network disconnect, however,\n * in some rare cases a ConnectionFailed Error will be thrown and this operator explicitly retries these\n */\nexport function reconnectOnConnectionFailure<T>(): OperatorFunction<T, T | {type: 'reconnect'}> {\n return function (source: Observable<T>) {\n return source.pipe(\n catchError((err, caught) => {\n if (err instanceof ConnectionFailedError) {\n return concat(of({type: 'reconnect' as const}), timer(1000).pipe(mergeMap(() => caught)))\n }\n return throwError(() => err)\n }),\n )\n }\n}\n","import {Observable, of, throwError} from 'rxjs'\nimport {filter, map} from 'rxjs/operators'\n\nimport type {ObservableSanityClient, SanityClient} from '../SanityClient'\nimport {\n type Any,\n type ListenEvent,\n type ListenEventName,\n type ListenOptions,\n type ListenParams,\n type MutationEvent,\n type OpenEvent,\n type ReconnectEvent,\n type WelcomeEvent,\n} from '../types'\nimport defaults from '../util/defaults'\nimport {pick} from '../util/pick'\nimport {_getDataUrl} from './dataMethods'\nimport {encodeQueryString} from './encodeQueryString'\nimport {connectEventSource} from './eventsource'\nimport {eventSourcePolyfill} from './eventsourcePolyfill'\nimport {reconnectOnConnectionFailure} from './reconnectOnConnectionFailure'\n\n// Limit is 16K for a _request_, eg including headers. Have to account for an\n// unknown range of headers, but an average EventSource request from Chrome seems\n// to have around 700 bytes of cruft, so let us account for 1.2K to be \"safe\"\nconst MAX_URL_LENGTH = 16000 - 1200\n\nconst possibleOptions = [\n 'includePreviousRevision',\n 'includeResult',\n 'includeMutations',\n 'includeAllVersions',\n 'visibility',\n 'effectFormat',\n 'tag',\n]\n\nconst defaultOptions = {\n includeResult: true,\n}\n\n/**\n * Maps an array of listen events names to their corresponding listen event type, e.g:\n * ```\n * type Test = MapListenEventNamesToListenEvents<Doc, ['welcome']>\n * // ^? WelcomeEvent\n * ```\n *\n * @public\n */\nexport type MapListenEventNamesToListenEvents<\n R extends Record<string, Any> = Record<string, Any>,\n Events extends ListenEventName[] = ListenEventName[],\n> = Events extends (infer E)[]\n ? E extends 'welcome'\n ? WelcomeEvent\n : E extends 'mutation'\n ? MutationEvent<R>\n : E extends 'reconnect'\n ? ReconnectEvent\n : E extends 'open'\n ? OpenEvent\n : never\n : never\n\n/**\n * Maps a ListenOptions object and returns the Listen events opted for, e.g:\n * ```\n * type Test = ListenEventFromOptions<Doc, {events: ['welcome', 'mutation']}>\n * // ^? WelcomeEvent | MutationEvent<Doc>\n * ```\n *\n * @public\n */\nexport type ListenEventFromOptions<\n R extends Record<string, Any> = Record<string, Any>,\n Opts extends ListenOptions | undefined = undefined,\n> = Opts extends ListenOptions\n ? Opts['events'] extends ListenEventName[]\n ? MapListenEventNamesToListenEvents<R, Opts['events']>\n : // fall back to ListenEvent if opts events is present, but we can't infer the literal event names\n ListenEvent<R>\n : MutationEvent<R>\n\n/**\n * Set up a listener that will be notified when mutations occur on documents matching the provided query/filter.\n *\n * @param query - GROQ-filter to listen to changes for\n * @param params - Optional query parameters\n * @param options - Optional listener options\n * @public\n */\nexport function _listen<R extends Record<string, Any> = Record<string, Any>>(\n this: SanityClient | ObservableSanityClient,\n query: string,\n params?: ListenParams,\n): Observable<MutationEvent<R>>\n/**\n * Set up a listener that will be notified when mutations occur on documents matching the provided query/filter.\n *\n * @param query - GROQ-filter to listen to changes for\n * @param params - Optional query parameters\n * @param options - Optional listener options\n * @public\n */\nexport function _listen<\n R extends Record<string, Any> = Record<string, Any>,\n Opts extends ListenOptions = ListenOptions,\n>(\n this: SanityClient | ObservableSanityClient,\n query: string,\n params?: ListenParams,\n options?: Opts,\n): Observable<ListenEventFromOptions<R, Opts>>\n/** @public */\nexport function _listen<\n R extends Record<string, Any> = Record<string, Any>,\n Opts extends ListenOptions = ListenOptions,\n>(\n this: SanityClient | ObservableSanityClient,\n query: string,\n params?: ListenParams,\n opts: Opts = {} as Opts,\n): Observable<ListenEventFromOptions<R, Opts>> {\n const {url, token, withCredentials, requestTagPrefix, headers: configHeaders} = this.config()\n const tag = opts.tag && requestTagPrefix ? [requestTagPrefix, opts.tag].join('.') : opts.tag\n const options = {...defaults(opts, defaultOptions), tag}\n const listenOpts = pick(options, possibleOptions)\n const qs = encodeQueryString({query, params, options: {tag, ...listenOpts}})\n\n const uri = `${url}${_getDataUrl(this, 'listen', qs)}`\n if (uri.length > MAX_URL_LENGTH) {\n return throwError(() => new Error('Query too large for listener'))\n }\n\n const listenFor = (options.events ? options.events : ['mutation']) satisfies Opts['events']\n\n const esOptions: EventSourceInit & {headers?: Record<string, string>} = {}\n if (withCredentials) {\n esOptions.withCredentials = true\n }\n\n if (token || configHeaders) {\n esOptions.headers = {}\n\n if (token) {\n esOptions.headers.Authorization = `Bearer ${token}`\n }\n\n if (configHeaders) {\n Object.assign(esOptions.headers, configHeaders)\n }\n }\n\n const initEventSource = () =>\n // use polyfill if there is no global EventSource or if we need to set headers\n (typeof EventSource === 'undefined' || esOptions.headers\n ? eventSourcePolyfill\n : of(EventSource)\n ).pipe(map((EventSource) => new EventSource(uri, esOptions)))\n\n return connectEventSource(initEventSource, listenFor).pipe(\n reconnectOnConnectionFailure(),\n filter((event) => listenFor.includes(event.type)),\n map((event) => ({\n type: event.type,\n ...('data' in event ? (event.data as object) : {}),\n })),\n ) as Observable<ListenEventFromOptions<R, Opts>>\n}\n","import {\n finalize,\n merge,\n type MonoTypeOperatorFunction,\n Observable,\n share,\n type ShareConfig,\n tap,\n} from 'rxjs'\n\nexport type ShareReplayLatestConfig<T> = ShareConfig<T> & {predicate: (value: T) => boolean}\n\n/**\n * A variant of share that takes a predicate function to determine which value to replay to new subscribers\n * @param predicate - Predicate function to determine which value to replay\n */\nexport function shareReplayLatest<T>(predicate: (value: T) => boolean): MonoTypeOperatorFunction<T>\n\n/**\n * A variant of share that takes a predicate function to determine which value to replay to new subscribers\n * @param config - ShareConfig with additional predicate function\n */\nexport function shareReplayLatest<T>(\n config: ShareReplayLatestConfig<T>,\n): MonoTypeOperatorFunction<T>\n\n/**\n * A variant of share that takes a predicate function to determine which value to replay to new subscribers\n * @param configOrPredicate - Predicate function to determine which value to replay\n * @param config - Optional ShareConfig\n */\nexport function shareReplayLatest<T>(\n configOrPredicate: ShareReplayLatestConfig<T> | ShareReplayLatestConfig<T>['predicate'],\n config?: ShareConfig<T>,\n) {\n return _shareReplayLatest(\n typeof configOrPredicate === 'function'\n ? {predicate: configOrPredicate, ...config}\n : configOrPredicate,\n )\n}\nfunction _shareReplayLatest<T>(config: ShareReplayLatestConfig<T>): MonoTypeOperatorFunction<T> {\n return (source: Observable<T>) => {\n let latest: T | undefined\n let emitted = false\n\n // eslint-disable-next-line unused-imports/no-unused-vars\n const {predicate, ...shareConfig} = config\n\n const wrapped = source.pipe(\n tap((value) => {\n if (config.predicate(value)) {\n emitted = true\n latest = value\n }\n }),\n finalize(() => {\n emitted = false\n latest = undefined\n }),\n share(shareConfig),\n )\n const emitLatest = new Observable<T>((subscriber) => {\n if (emitted) {\n subscriber.next(\n // this cast is safe because of the emitted check which asserts that we got T from the source\n latest as T,\n )\n }\n subscriber.complete()\n })\n return merge(wrapped, emitLatest)\n }\n}\n","import {catchError, mergeMap, Observable, of} from 'rxjs'\nimport {finalize, map} from 'rxjs/operators'\n\nimport {CorsOriginError} from '../http/errors'\nimport type {ObservableSanityClient, SanityClient} from '../SanityClient'\nimport type {\n LiveEvent,\n LiveEventGoAway,\n LiveEventMessage,\n LiveEventReconnect,\n LiveEventRestart,\n LiveEventWelcome,\n SyncTag,\n} from '../types'\nimport {shareReplayLatest} from '../util/shareReplayLatest'\nimport * as validate from '../validators'\nimport {_getDataUrl} from './dataMethods'\nimport {connectEventSource} from './eventsource'\nimport {eventSourcePolyfill} from './eventsourcePolyfill'\nimport {reconnectOnConnectionFailure} from './reconnectOnConnectionFailure'\n\nconst requiredApiVersion = '2021-03-25'\n\n/**\n * @public\n */\nexport class LiveClient {\n #client: SanityClient | ObservableSanityClient\n constructor(client: SanityClient | ObservableSanityClient) {\n this.#client = client\n }\n\n /**\n * Requires `apiVersion` to be `2021-03-25` or later.\n */\n events({\n includeDrafts = false,\n tag: _tag,\n }: {\n includeDrafts?: boolean\n /**\n * Optional request tag for the listener. Use to identify the request in logs.\n *\n * @defaultValue `undefined`\n */\n tag?: string\n } = {}): Observable<LiveEvent> {\n validate.resourceGuard('live', this.#client.config())\n const {\n projectId,\n apiVersion: _apiVersion,\n token,\n withCredentials,\n requestTagPrefix,\n headers: configHeaders,\n } = this.#client.config()\n const apiVersion = _apiVersion.replace(/^v/, '')\n if (apiVersion !== 'X' && apiVersion < requiredApiVersion) {\n throw new Error(\n `The live events API requires API version ${requiredApiVersion} or later. ` +\n `The current API version is ${apiVersion}. ` +\n `Please update your API version to use this feature.`,\n )\n }\n if (includeDrafts && !token && !withCredentials) {\n throw new Error(\n `The live events API requires a token or withCredentials when 'includeDrafts: true'. Please update your client configuration. The token should have the lowest possible access role.`,\n )\n }\n const path = _getDataUrl(this.#client, 'live/events')\n const url = new URL(this.#client.getUrl(path, false))\n const tag = _tag && requestTagPrefix ? [requestTagPrefix, _tag].join('.') : _tag\n if (tag) {\n url.searchParams.set('tag', tag)\n }\n if (includeDrafts) {\n url.searchParams.set('includeDrafts', 'true')\n }\n const esOptions: EventSourceInit & {headers?: Record<string, string>} = {}\n if (includeDrafts && withCredentials) {\n esOptions.withCredentials = true\n }\n\n if ((includeDrafts && token) || configHeaders) {\n esOptions.headers = {}\n\n if (includeDrafts && token) {\n esOptions.headers.Authorization = `Bearer ${token}`\n }\n\n if (configHeaders) {\n Object.assign(esOptions.headers, configHeaders)\n }\n }\n\n const key = `${url.href}::${JSON.stringify(esOptions)}`\n const existing = eventsCache.get(key)\n\n if (existing) {\n return existing\n }\n\n const initEventSource = () =>\n // use polyfill if there is no global EventSource or if we need to set headers\n (typeof EventSource === 'undefined' || esOptions.headers\n ? eventSourcePolyfill\n : of(EventSource)\n ).pipe(map((EventSource) => new EventSource(url.href, esOptions)))\n\n const events = connectEventSource(initEventSource, [\n 'message',\n 'restart',\n 'welcome',\n 'reconnect',\n 'goaway',\n ])\n\n const checkCors = fetchObservable(url, {\n method: 'OPTIONS',\n mode: 'cors',\n credentials: esOptions.withCredentials ? 'include' : 'omit',\n headers: esOptions.headers,\n }).pipe(\n catchError(() => {\n // If the request fails, then we assume it was due to CORS, and we rethrow a special error that allows special handling in userland\n throw new CorsOriginError({projectId: projectId!})\n }),\n )\n\n const observable = events\n .pipe(\n reconnectOnConnectionFailure(),\n mergeMap((event) => {\n if (event.type === 'reconnect') {\n // Check for CORS on reconnect events (which happen on 403s)\n return checkCors.pipe(mergeMap(() => of(event)))\n }\n return of(event)\n }),\n catchError((err) => {\n return checkCors.pipe(\n mergeMap(() => {\n // rethrow the original error if checkCors passed\n throw err\n }),\n )\n }),\n map((event) => {\n if (event.type === 'message') {\n const {data, ...rest} = event\n // Splat data properties from the eventsource message onto the returned event\n return {...rest, tags: (data as {tags: SyncTag[]}).tags} as LiveEventMessage\n }\n return event as LiveEventRestart | LiveEventReconnect | LiveEventWelcome | LiveEventGoAway\n }),\n )\n .pipe(\n finalize(() => eventsCache.delete(key)),\n shareReplayLatest({\n predicate: (event) => event.type === 'welcome',\n }),\n )\n eventsCache.set(key, observable)\n return observable\n }\n}\n\nfunction fetchObservable(url: URL, init: RequestInit) {\n return new Observable((observer) => {\n const controller = new AbortController()\n const signal = controller.signal\n fetch(url, {...init, signal: controller.signal}).then(\n (response) => {\n observer.next(response)\n observer.complete()\n },\n (err) => {\n if (!signal.aborted) {\n observer.error(err)\n }\n },\n )\n return () => controller.abort()\n })\n}\n\nconst eventsCache = new Map<string, Observable<LiveEvent>>()\n","import {lastValueFrom, type Observable} from 'rxjs'\n\nimport {_request} from '../data/dataMethods'\nimport type {ObservableSanityClient, SanityClient} from '../SanityClient'\nimport type {DatasetAclMode, DatasetResponse, DatasetsResponse, HttpRequest} from '../types'\nimport * as validate from '../validators'\n\n/** @internal */\nexport class ObservableDatasetsClient {\n #client: ObservableSanityClient\n #httpRequest: HttpRequest\n constructor(client: ObservableSanityClient, httpRequest: HttpRequest) {\n this.#client = client\n this.#httpRequest = httpRequest\n }\n\n /**\n * Create a new dataset with the given name\n *\n * @param name - Name of the dataset to create\n * @param options - Options for the dataset\n */\n create(name: string, options?: {aclMode?: DatasetAclMode}): Observable<DatasetResponse> {\n return _modify<DatasetResponse>(this.#client, this.#httpRequest, 'PUT', name, options)\n }\n\n /**\n * Edit a dataset with the given name\n *\n * @param name - Name of the dataset to edit\n * @param options - New options for the dataset\n */\n edit(name: string, options?: {aclMode?: DatasetAclMode}): Observable<DatasetResponse> {\n return _modify<DatasetResponse>(this.#client, this.#httpRequest, 'PATCH', name, options)\n }\n\n /**\n * Delete a dataset with the given name\n *\n * @param name - Name of the dataset to delete\n */\n delete(name: string): Observable<{deleted: true}> {\n return _modify<{deleted: true}>(this.#client, this.#httpRequest, 'DELETE', name)\n }\n\n /**\n * Fetch a list of datasets for the configured project\n */\n list(): Observable<DatasetsResponse> {\n validate.resourceGuard('dataset', this.#client.config())\n const config = this.#client.config()\n const projectId = config.projectId\n let uri = '/datasets'\n if (config.useProjectHostname === false) {\n uri = `/projects/${projectId}/datasets`\n }\n\n return _request<DatasetsResponse>(this.#client, this.#httpRequest, {\n uri,\n tag: null,\n })\n }\n}\n\n/** @internal */\nexport class DatasetsClient {\n #client: SanityClient\n #httpRequest: HttpRequest\n constructor(client: SanityClient, httpRequest: HttpRequest) {\n this.#client = client\n this.#httpRequest = httpRequest\n }\n\n /**\n * Create a new dataset with the given name\n *\n * @param name - Name of the dataset to create\n * @param options - Options for the dataset\n */\n create(name: string, options?: {aclMode?: DatasetAclMode}): Promise<DatasetResponse> {\n validate.resourceGuard('dataset', this.#client.config())\n return lastValueFrom(\n _modify<DatasetResponse>(this.#client, this.#httpRequest, 'PUT', name, options),\n )\n }\n\n /**\n * Edit a dataset with the given name\n *\n * @param name - Name of the dataset to edit\n * @param options - New options for the dataset\n */\n edit(name: string, options?: {aclMode?: DatasetAclMode}): Promise<DatasetResponse> {\n validate.resourceGuard('dataset', this.#client.config())\n return lastValueFrom(\n _modify<DatasetResponse>(this.#client, this.#httpRequest, 'PATCH', name, options),\n )\n }\n\n /**\n * Delete a dataset with the given name\n *\n * @param name - Name of the dataset to delete\n */\n delete(name: string): Promise<{deleted: true}> {\n validate.resourceGuard('dataset', this.#client.config())\n return lastValueFrom(_modify<{deleted: true}>(this.#client, this.#httpRequest, 'DELETE', name))\n }\n\n /**\n * Fetch a list of datasets for the configured project\n */\n list(): Promise<DatasetsResponse> {\n validate.resourceGuard('dataset', this.#client.config())\n const config = this.#client.config()\n const projectId = config.projectId\n let uri = '/datasets'\n if (config.useProjectHostname === false) {\n uri = `/projects/${projectId}/datasets`\n }\n\n return lastValueFrom(\n _request<DatasetsResponse>(this.#client, this.#httpRequest, {uri, tag: null}),\n )\n }\n}\n\nfunction _modify<R = unknown>(\n client: SanityClient | ObservableSanityClient,\n httpRequest: HttpRequest,\n method: 'DELETE' | 'PATCH' | 'PUT',\n name: string,\n options?: {aclMode?: DatasetAclMode},\n) {\n validate.resourceGuard('dataset', client.config())\n validate.dataset(name)\n\n return _request<R>(client, httpRequest, {\n method,\n uri: `/datasets/${name}`,\n body: options,\n tag: null,\n })\n}\n","import {lastValueFrom, type Observable} from 'rxjs'\n\nimport {_request} from '../data/dataMethods'\nimport type {ObservableSanityClient, SanityClient} from '../SanityClient'\nimport type {\n HttpRequest,\n MediaLibraryAssetInstanceIdentifier,\n MediaLibraryPlaybackInfoOptions,\n SanityReference,\n VideoPlaybackInfo,\n} from '../types'\n\n/** @internal */\nexport class ObservableMediaLibraryVideoClient {\n #client: ObservableSanityClient\n #httpRequest: HttpRequest\n constructor(client: ObservableSanityClient, httpRequest: HttpRequest) {\n this.#client = client\n this.#httpRequest = httpRequest\n }\n\n /**\n * Get video playback information for a media library asset\n *\n * @param assetIdentifier - Asset instance identifier (GDR, video-prefixed ID, or container ID)\n * @param options - Options for transformations and expiration\n */\n getPlaybackInfo(\n assetIdentifier: MediaLibraryAssetInstanceIdentifier,\n options: MediaLibraryPlaybackInfoOptions = {},\n ): Observable<VideoPlaybackInfo> {\n const configMediaLibraryId = this.#client.config()['~experimental_resource']?.id\n\n const {instanceId, libraryId} = parseAssetInstanceId(assetIdentifier)\n const effectiveLibraryId = libraryId || configMediaLibraryId\n\n if (!effectiveLibraryId) {\n throw new Error(\n 'Could not determine Media Library ID - you need to provide a valid Media Library ID in the client config or a Media Library GDR',\n )\n }\n\n const uri = buildVideoPlaybackInfoUrl(instanceId, effectiveLibraryId)\n const queryParams = buildQueryParams(options)\n\n return _request<VideoPlaybackInfo>(this.#client, this.#httpRequest, {\n method: 'GET',\n uri,\n query: queryParams,\n })\n }\n}\n\n/** @internal */\nexport class MediaLibraryVideoClient {\n #client: SanityClient\n #httpRequest: HttpRequest\n constructor(client: SanityClient, httpRequest: HttpRequest) {\n this.#client = client\n this.#httpRequest = httpRequest\n }\n\n /**\n * Get video playback information for a media library asset\n *\n * @param assetIdentifier - Asset instance identifier (GDR, video-prefixed ID, or container ID)\n * @param options - Options for transformations and expiration\n */\n getPlaybackInfo(\n assetIdentifier: MediaLibraryAssetInstanceIdentifier,\n options: MediaLibraryPlaybackInfoOptions = {},\n ): Promise<VideoPlaybackInfo> {\n return lastValueFrom(\n new ObservableMediaLibraryVideoClient(\n this.#client.observable,\n this.#httpRequest,\n ).getPlaybackInfo(assetIdentifier, options),\n )\n }\n}\n\nconst ML_GDR_PATTERN = /^media-library:(ml[^:]+):([^:]+)$/\n\n/** @internal */\nfunction isSanityReference(\n assetIdentifier: MediaLibraryAssetInstanceIdentifier,\n): assetIdentifier is SanityReference {\n return typeof assetIdentifier === 'object' && '_ref' in assetIdentifier\n}\n\n/**\n * Parse the asset instance id and library id from the asset identifier\n *\n * @param assetIdentifier - The asset identifier - either a asset instance id or a Media Library GDR\n * @returns The asset instance id and library id\n */\nexport function parseAssetInstanceId(assetIdentifier: MediaLibraryAssetInstanceIdentifier): {\n instanceId: string\n libraryId?: string\n} {\n const ref = isSanityReference(assetIdentifier) ? assetIdentifier._ref : assetIdentifier\n\n const match = ML_GDR_PATTERN.exec(ref)\n if (match) {\n const [, libraryId, instanceId] = match\n return {libraryId, instanceId}\n }\n\n // Asumes valid asset instance id\n if (typeof assetIdentifier === 'string' && assetIdentifier.startsWith('video-')) {\n return {instanceId: assetIdentifier}\n }\n\n throw new Error(\n `Invalid video asset instance identifier \"${ref}\": must be a valid video instance id or a Global Dataset Reference (GDR) to the video asset in the Media Library`,\n )\n}\n\nfunction buildVideoPlaybackInfoUrl(instanceId: string, libraryId: string): string {\n return `/media-libraries/${libraryId}/video/${instanceId}/playback-info`\n}\n\nfunction buildQueryParams(options: MediaLibraryPlaybackInfoOptions): Record<string, unknown> {\n const params: Record<string, unknown> = {}\n\n if (options.transformations) {\n const {thumbnail, animated, storyboard} = options.transformations\n\n if (thumbnail) {\n if (thumbnail.width) params.thumbnailWidth = thumbnail.width\n if (thumbnail.height) params.thumbnailHeight = thumbnail.height\n if (thumbnail.time !== undefined) params.thumbnailTime = thumbnail.time\n if (thumbnail.fit) params.thumbnailFit = thumbnail.fit\n if (thumbnail.format) params.thumbnailFormat = thumbnail.format\n }\n\n if (animated) {\n if (animated.width) params.animatedWidth = animated.width\n if (animated.height) params.animatedHeight = animated.height\n if (animated.start !== undefined) params.animatedStart = animated.start\n if (animated.end !== undefined) params.animatedEnd = animated.end\n if (animated.fps) params.animatedFps = animated.fps\n if (animated.format) params.animatedFormat = animated.format\n }\n\n if (storyboard) {\n if (storyboard.format) params.storyboardFormat = storyboard.format\n }\n }\n\n if (options.expiration) {\n params.expiration = options.expiration\n }\n\n return params\n}\n","import {lastValueFrom, type Observable} from 'rxjs'\n\nimport {_request} from '../data/dataMethods'\nimport type {ObservableSanityClient, SanityClient} from '../SanityClient'\nimport type {HttpRequest, SanityProject} from '../types'\n\n/** @internal */\nexport class ObservableProjectsClient {\n #client: ObservableSanityClient\n #httpRequest: HttpRequest\n constructor(client: ObservableSanityClient, httpRequest: HttpRequest) {\n this.#client = client\n this.#httpRequest = httpRequest\n }\n\n /**\n * Fetch a list of projects the authenticated user has access to.\n *\n * @param options - Options for the list request\n * - `includeMembers` - Whether to include members in the response (default: true)\n * - `organizationId` - ID of the organization to fetch projects for\n */\n list(options?: {includeMembers?: true; organizationId?: string}): Observable<SanityProject[]>\n list(options?: {\n includeMembers?: false\n organizationId?: string\n }): Observable<Omit<SanityProject, 'members'>[]>\n list(options?: {\n includeMembers?: boolean\n organizationId?: string\n }): Observable<SanityProject[] | Omit<SanityProject, 'members'>[]> {\n const query: Record<string, string> = {}\n const uri = '/projects'\n if (options?.includeMembers === false) {\n query.includeMembers = 'false'\n }\n if (options?.organizationId) {\n query.organizationId = options.organizationId\n }\n\n return _request<SanityProject[]>(this.#client, this.#httpRequest, {uri, query})\n }\n\n /**\n * Fetch a project by project ID\n *\n * @param projectId - ID of the project to fetch\n */\n getById(projectId: string): Observable<SanityProject> {\n return _request<SanityProject>(this.#client, this.#httpRequest, {uri: `/projects/${projectId}`})\n }\n}\n\n/** @internal */\nexport class ProjectsClient {\n #client: SanityClient\n #httpRequest: HttpRequest\n constructor(client: SanityClient, httpRequest: HttpRequest) {\n this.#client = client\n this.#httpRequest = httpRequest\n }\n\n /**\n * Fetch a list of projects the authenticated user has access to.\n *\n * @param options - Options for the list request\n * - `includeMembers` - Whether to include members in the response (default: true)\n * - `organizationId` - ID of the organization to fetch projects for\n */\n list(options?: {includeMembers?: true; organizationId?: string}): Promise<SanityProject[]>\n list(options?: {\n includeMembers?: false\n organizationId?: string\n }): Promise<Omit<SanityProject, 'members'>[]>\n list(options?: {\n includeMembers?: boolean\n organizationId?: string\n }): Promise<SanityProject[] | Omit<SanityProject, 'members'>[]> {\n const query: Record<string, string> = {}\n const uri = '/projects'\n if (options?.includeMembers === false) {\n query.includeMembers = 'false'\n }\n if (options?.organizationId) {\n query.organizationId = options.organizationId\n }\n return lastValueFrom(_request<SanityProject[]>(this.#client, this.#httpRequest, {uri, query}))\n }\n\n /**\n * Fetch a project by project ID\n *\n * @param projectId - ID of the project to fetch\n */\n getById(projectId: string): Promise<SanityProject> {\n return lastValueFrom(\n _request<SanityProject>(this.#client, this.#httpRequest, {uri: `/projects/${projectId}`}),\n )\n }\n}\n","import {\n getDraftId,\n getVersionFromId,\n getVersionId,\n isDraftId,\n isVersionId,\n} from '@sanity/client/csm'\nimport {customAlphabet} from 'nanoid'\n\nimport type {IdentifiedSanityDocumentStub, SanityDocumentStub} from '../types'\nimport {validateVersionIdMatch} from '../validators'\n\n/**\n * @internal\n *\n * ~24 years (or 7.54e+8 seconds) needed, in order to have a 1% probability of at least one collision if 10 ID's are generated every hour.\n */\nexport const generateReleaseId = customAlphabet(\n 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',\n 8,\n)\n\n/** @internal */\nexport const getDocumentVersionId = (publishedId: string, releaseId?: string) =>\n releaseId ? getVersionId(publishedId, releaseId) : getDraftId(publishedId)\n\n/** @internal */\nexport function deriveDocumentVersionId(\n op: string,\n {\n releaseId,\n publishedId,\n document,\n }: {\n releaseId?: string\n publishedId?: string\n document: SanityDocumentStub | IdentifiedSanityDocumentStub\n },\n): string {\n if (publishedId && document._id) {\n const versionId = getDocumentVersionId(publishedId, releaseId)\n validateVersionIdMatch(versionId, document)\n return versionId\n }\n\n if (document._id) {\n const isDraft = isDraftId(document._id)\n const isVersion = isVersionId(document._id)\n\n if (!isDraft && !isVersion) {\n throw new Error(\n `\\`${op}()\\` requires a document with an \\`_id\\` that is a version or draft ID`,\n )\n }\n\n if (releaseId) {\n if (isDraft) {\n throw new Error(\n `\\`${op}()\\` was called with a document ID (\\`${document._id}\\`) that is a draft ID, but a release ID (\\`${releaseId}\\`) was also provided.`,\n )\n }\n\n const builtVersionId = getVersionFromId(document._id)\n if (builtVersionId !== releaseId) {\n throw new Error(\n `\\`${op}()\\` was called with a document ID (\\`${document._id}\\`) that is a version ID, but the release ID (\\`${releaseId}\\`) does not match the document's version ID (\\`${builtVersionId}\\`).`,\n )\n }\n }\n\n return document._id\n }\n\n if (publishedId) {\n return getDocumentVersionId(publishedId, releaseId)\n }\n\n throw new Error(`\\`${op}()\\` requires either a publishedId or a document with an \\`_id\\``)\n}\n","import type {BaseActionOptions, CreateReleaseAction, ReleaseDocument} from '@sanity/client'\n\nimport {generateReleaseId} from '../util/createVersionId'\n\ninterface ReleaseOrOptions extends BaseActionOptions {\n releaseId?: string\n metadata?: Partial<ReleaseDocument['metadata']>\n}\n\ninterface CompleteCreateReleaseAction extends CreateReleaseAction {\n metadata: ReleaseDocument['metadata']\n}\n\nconst getArgs = (\n releaseOrOptions?: ReleaseOrOptions,\n maybeOptions?: BaseActionOptions,\n): [string, Partial<ReleaseDocument['metadata']>, BaseActionOptions | undefined] => {\n const isReleaseInput =\n typeof releaseOrOptions === 'object' &&\n releaseOrOptions !== null &&\n ('releaseId' in releaseOrOptions || 'metadata' in releaseOrOptions)\n\n if (isReleaseInput) {\n const {releaseId = generateReleaseId(), metadata = {}} = releaseOrOptions\n return [releaseId, metadata, maybeOptions]\n }\n\n return [generateReleaseId(), {}, releaseOrOptions as BaseActionOptions]\n}\n\n/** @internal */\nexport const createRelease = (\n releaseOrOptions?: ReleaseOrOptions,\n maybeOptions?: BaseActionOptions,\n): {\n action: CompleteCreateReleaseAction\n options?: BaseActionOptions\n} => {\n const [releaseId, metadata, options] = getArgs(releaseOrOptions, maybeOptions)\n\n const finalMetadata: ReleaseDocument['metadata'] = {\n ...metadata,\n releaseType: metadata.releaseType || 'undecided',\n }\n\n const createAction: CompleteCreateReleaseAction = {\n actionType: 'sanity.action.release.create',\n releaseId,\n metadata: finalMetadata,\n }\n\n return {action: createAction, options}\n}\n","import {lastValueFrom, map, Observable} from 'rxjs'\n\nimport {_action, _getDocument, _getReleaseDocuments} from '../data/dataMethods'\nimport type {ObservableSanityClient, SanityClient} from '../SanityClient'\nimport type {\n ArchiveReleaseAction,\n BaseActionOptions,\n BaseMutationOptions,\n DeleteReleaseAction,\n EditReleaseAction,\n HttpRequest,\n PatchOperations,\n PublishReleaseAction,\n RawQueryResponse,\n ReleaseDocument,\n SanityDocument,\n ScheduleReleaseAction,\n SingleActionResult,\n UnarchiveReleaseAction,\n UnscheduleReleaseAction,\n} from '../types'\nimport {createRelease} from './createRelease'\n\n/** @public */\nexport class ObservableReleasesClient {\n #client: ObservableSanityClient\n #httpRequest: HttpRequest\n constructor(client: ObservableSanityClient, httpRequest: HttpRequest) {\n this.#client = client\n this.#httpRequest = httpRequest\n }\n\n /**\n * @public\n *\n * Retrieve a release by id.\n *\n * @category Releases\n *\n * @param params - Release action parameters:\n * - `releaseId` - The id of the release to retrieve.\n * @param options - Additional query options including abort signal and query tag.\n * @returns An observable that resolves to the release document {@link ReleaseDocument}.\n *\n * @example Retrieving a release by id\n * ```ts\n * client.observable.releases.get({releaseId: 'my-release'}).pipe(\n * tap((release) => console.log(release)),\n * // {\n * // _id: '_.releases.my-release',\n * // name: 'my-release'\n * // _type: 'system.release',\n * // metadata: {releaseType: 'asap'},\n * // _createdAt: '2021-01-01T00:00:00.000Z',\n * // ...\n * // }\n * ).subscribe()\n * ```\n */\n get(\n {releaseId}: {releaseId: string},\n options?: {signal?: AbortSignal; tag?: string},\n ): Observable<ReleaseDocument | undefined> {\n return _getDocument<ReleaseDocument>(\n this.#client,\n this.#httpRequest,\n `_.releases.${releaseId}`,\n options,\n )\n }\n\n /**\n * @public\n *\n * Creates a new release under the given id, with metadata.\n *\n * @remarks\n * * If no releaseId is provided, a release id will be generated.\n * * If no metadata is provided, then an `undecided` releaseType will be used.\n *\n * @category Releases\n *\n * @param params - Release action parameters:\n * - `releaseId` - The id of the release to create.\n * - `metadata` - The metadata to associate with the release {@link ReleaseDocument}.\n * @param options - Additional action options.\n * @returns An observable that resolves to the `transactionId` and the release id and metadata.\n *\n * @example Creating a release with a custom id and metadata\n * ```ts\n * const releaseId = 'my-release'\n * const metadata: ReleaseDocument['metadata'] = {\n * releaseType: 'asap',\n * }\n *\n * client.observable.releases.create({releaseId, metadata}).pipe(\n * tap(({transactionId, releaseId, metadata}) => console.log(transactionId, releaseId, metadata)),\n * // {\n * // transactionId: 'transaction-id',\n * // releaseId: 'my-release',\n * // metadata: {releaseType: 'asap'},\n * // }\n * ).subscribe()\n * ```\n *\n * @example Creating a release with generated id and metadata\n * ```ts\n * client.observable.releases.create().pipe(\n * tap(({metadata}) => console.log(metadata)),\n * // {\n * // metadata: {releaseType: 'undecided'},\n * // }\n * ).subscribe()\n * ```\n *\n * @example Creating a release using a custom transaction id\n * ```ts\n * client.observable.releases.create({transactionId: 'my-transaction-id'}).pipe(\n * tap(({transactionId, metadata}) => console.log(transactionId, metadata)),\n * // {\n * // transactionId: 'my-transaction-id',\n * // metadata: {releaseType: 'undecided'},\n * // }\n * ).subscribe()\n * ```\n */\n create(\n options: BaseActionOptions,\n ): Observable<SingleActionResult & {releaseId: string; metadata: ReleaseDocument['metadata']}>\n create(\n release: {releaseId?: string; metadata?: Partial<ReleaseDocument['metadata']>},\n options?: BaseActionOptions,\n ): Observable<SingleActionResult & {releaseId: string; metadata: ReleaseDocument['metadata']}>\n create(\n releaseOrOptions?:\n | {releaseId?: string; metadata?: Partial<ReleaseDocument['metadata']>}\n | BaseActionOptions,\n maybeOptions?: BaseActionOptions,\n ): Observable<SingleActionResult & {releaseId: string; metadata: ReleaseDocument['metadata']}> {\n const {action, options} = createRelease(releaseOrOptions, maybeOptions)\n const {releaseId, metadata} = action\n\n return _action(this.#client, this.#httpRequest, action, options).pipe(\n map((actionResult) => ({\n ...actionResult,\n releaseId,\n metadata,\n })),\n )\n }\n\n /**\n * @public\n *\n * Edits an existing release, updating the metadata.\n *\n * @category Releases\n *\n * @param params - Release action parameters:\n * - `releaseId` - The id of the release to edit.\n * - `patch` - The patch operation to apply on the release metadata {@link PatchMutationOperation}.\n * @param options - Additional action options.\n * @returns An observable that resolves to the `transactionId`.\n */\n edit(\n {releaseId, patch}: {releaseId: string; patch: PatchOperations},\n options?: BaseActionOptions,\n ): Observable<SingleActionResult> {\n const editAction: EditReleaseAction = {\n actionType: 'sanity.action.release.edit',\n releaseId,\n patch,\n }\n\n return _action(this.#client, this.#httpRequest, editAction, options)\n }\n\n /**\n * @public\n *\n * Publishes all documents in a release at once. For larger releases the effect of the publish\n * will be visible immediately when querying but the removal of the `versions.<releasesId>.*`\n * documents and creation of the corresponding published documents with the new content may\n * take some time.\n *\n * During this period both the source and target documents are locked and cannot be\n * modified through any other means.\n *\n * @category Releases\n *\n * @param params - Release action parameters:\n * - `releaseId` - The id of the release to publish.\n * @param options - Additional action options.\n * @returns An observable that resolves to the `transactionId`.\n */\n publish(\n {releaseId}: {releaseId: string},\n options?: BaseActionOptions,\n ): Observable<SingleActionResult> {\n const publishAction: PublishReleaseAction = {\n actionType: 'sanity.action.release.publish',\n releaseId,\n }\n\n return _action(this.#client, this.#httpRequest, publishAction, options)\n }\n\n /**\n * @public\n *\n * An archive action removes an active release. The documents that comprise the release\n * are deleted and therefore no longer queryable.\n *\n * While the documents remain in retention the last version can still be accessed using document history endpoint.\n *\n * @category Releases\n *\n * @param params - Release action parameters:\n * - `releaseId` - The id of the release to archive.\n * @param options - Additional action options.\n * @returns An observable that resolves to the `transactionId`.\n */\n archive(\n {releaseId}: {releaseId: string},\n options?: BaseActionOptions,\n ): Observable<SingleActionResult> {\n const archiveAction: ArchiveReleaseAction = {\n actionType: 'sanity.action.release.archive',\n releaseId,\n }\n\n return _action(this.#client, this.#httpRequest, archiveAction, options)\n }\n\n /**\n * @public\n *\n * An unarchive action restores an archived release and all documents\n * with the content they had just prior to archiving.\n *\n * @category Releases\n *\n * @param params - Release action parameters:\n * - `releaseId` - The id of the release to unarchive.\n * @param options - Additional action options.\n * @returns An observable that resolves to the `transactionId`.\n */\n unarchive(\n {releaseId}: {releaseId: string},\n options?: BaseActionOptions,\n ): Observable<SingleActionResult> {\n const unarchiveAction: UnarchiveReleaseAction = {\n actionType: 'sanity.action.release.unarchive',\n releaseId,\n }\n\n return _action(this.#client, this.#httpRequest, unarchiveAction, options)\n }\n\n /**\n * @public\n *\n * A schedule action queues a release for publishing at the given future time.\n * The release is locked such that no documents in the release can be modified and\n * no documents that it references can be deleted as this would make the publish fail.\n * At the given time, the same logic as for the publish action is triggered.\n *\n * @category Releases\n *\n * @param params - Release action parameters:\n * - `releaseId` - The id of the release to schedule.\n * - `publishAt` - The serialised date and time to publish the release. If the `publishAt` is in the past, the release will be published immediately.\n * @param options - Additional action options.\n * @returns An observable that resolves to the `transactionId`.\n */\n schedule(\n {releaseId, publishAt}: {releaseId: string; publishAt: string},\n options?: BaseActionOptions,\n ): Observable<SingleActionResult> {\n const scheduleAction: ScheduleReleaseAction = {\n actionType: 'sanity.action.release.schedule',\n releaseId,\n publishAt,\n }\n\n return _action(this.#client, this.#httpRequest, scheduleAction, options)\n }\n\n /**\n * @public\n *\n * An unschedule action stops a release from being published.\n * The documents in the release are considered unlocked and can be edited again.\n * This may fail if another release is scheduled to be published after this one and\n * has a reference to a document created by this one.\n *\n * @category Releases\n *\n * @param params - Release action parameters:\n * - `releaseId` - The id of the release to unschedule.\n * @param options - Additional action options.\n * @returns An observable that resolves to the `transactionId`.\n */\n unschedule(\n {releaseId}: {releaseId: string},\n options?: BaseActionOptions,\n ): Observable<SingleActionResult> {\n const unscheduleAction: UnscheduleReleaseAction = {\n actionType: 'sanity.action.release.unschedule',\n releaseId,\n }\n\n return _action(this.#client, this.#httpRequest, unscheduleAction, options)\n }\n\n /**\n * @public\n *\n * A delete action removes a published or archived release.\n * The backing system document will be removed from the dataset.\n *\n * @category Releases\n *\n * @param params - Release action parameters:\n * - `releaseId` - The id of the release to delete.\n * @param options - Additional action options.\n * @returns An observable that resolves to the `transactionId`.\n */\n delete(\n {releaseId}: {releaseId: string},\n options?: BaseActionOptions,\n ): Observable<SingleActionResult> {\n const deleteAction: DeleteReleaseAction = {\n actionType: 'sanity.action.release.delete',\n releaseId,\n }\n\n return _action(this.#client, this.#httpRequest, deleteAction, options)\n }\n\n /**\n * @public\n *\n * Fetch the documents in a release by release id.\n *\n * @category Releases\n *\n * @param params - Release action parameters:\n * - `releaseId` - The id of the release to fetch documents for.\n * @param options - Additional mutation options {@link BaseMutationOptions}.\n * @returns An observable that resolves to the documents in the release.\n */\n fetchDocuments(\n {releaseId}: {releaseId: string},\n options?: BaseMutationOptions,\n ): Observable<RawQueryResponse<SanityDocument[]>> {\n return _getReleaseDocuments(this.#client, this.#httpRequest, releaseId, options)\n }\n}\n\n/** @public */\nexport class ReleasesClient {\n #client: SanityClient\n #httpRequest: HttpRequest\n constructor(client: SanityClient, httpRequest: HttpRequest) {\n this.#client = client\n this.#httpRequest = httpRequest\n }\n\n /**\n * @public\n *\n * Retrieve a release by id.\n *\n * @category Releases\n *\n * @param params - Release action parameters:\n * - `releaseId` - The id of the release to retrieve.\n * @param options - Additional query options including abort signal and query tag.\n * @returns A promise that resolves to the release document {@link ReleaseDocument}.\n *\n * @example Retrieving a release by id\n * ```ts\n * const release = await client.releases.get({releaseId: 'my-release'})\n * console.log(release)\n * // {\n * // _id: '_.releases.my-release',\n * // name: 'my-release'\n * // _type: 'system.release',\n * // metadata: {releaseType: 'asap'},\n * // _createdAt: '2021-01-01T00:00:00.000Z',\n * // ...\n * // }\n * ```\n */\n get(\n {releaseId}: {releaseId: string},\n options?: {signal?: AbortSignal; tag?: string},\n ): Promise<ReleaseDocument | undefined> {\n return lastValueFrom(\n _getDocument<ReleaseDocument>(\n this.#client,\n this.#httpRequest,\n `_.releases.${releaseId}`,\n options,\n ),\n )\n }\n\n /**\n * @public\n *\n * Creates a new release under the given id, with metadata.\n *\n * @remarks\n * * If no releaseId is provided, a release id will be generated.\n * * If no metadata is provided, then an `undecided` releaseType will be used.\n *\n * @category Releases\n *\n * @param params - Release action parameters:\n * - `releaseId` - The id of the release to create.\n * - `metadata` - The metadata to associate with the release {@link ReleaseDocument}.\n * @param options - Additional action options.\n * @returns A promise that resolves to the `transactionId` and the release id and metadata.\n *\n * @example Creating a release with a custom id and metadata\n * ```ts\n * const releaseId = 'my-release'\n * const releaseMetadata: ReleaseDocument['metadata'] = {\n * releaseType: 'asap',\n * }\n *\n * const result =\n * await client.releases.create({releaseId, metadata: releaseMetadata})\n * console.log(result)\n * // {\n * // transactionId: 'transaction-id',\n * // releaseId: 'my-release',\n * // metadata: {releaseType: 'asap'},\n * // }\n * ```\n *\n * @example Creating a release with generated id and metadata\n * ```ts\n * const {metadata} = await client.releases.create()\n * console.log(metadata.releaseType) // 'undecided'\n * ```\n *\n * @example Creating a release with a custom transaction id\n * ```ts\n * const {transactionId, metadata} = await client.releases.create({transactionId: 'my-transaction-id'})\n * console.log(metadata.releaseType) // 'undecided'\n * console.log(transactionId) // 'my-transaction-id'\n * ```\n */\n async create(\n options: BaseActionOptions,\n ): Promise<SingleActionResult & {releaseId: string; metadata: ReleaseDocument['metadata']}>\n async create(\n release: {releaseId?: string; metadata?: Partial<ReleaseDocument['metadata']>},\n options?: BaseActionOptions,\n ): Promise<SingleActionResult & {releaseId: string; metadata: ReleaseDocument['metadata']}>\n async create(\n releaseOrOptions?:\n | {releaseId?: string; metadata?: Partial<ReleaseDocument['metadata']>}\n | BaseActionOptions,\n maybeOptions?: BaseActionOptions,\n ): Promise<SingleActionResult & {releaseId: string; metadata: ReleaseDocument['metadata']}> {\n const {action, options} = createRelease(releaseOrOptions, maybeOptions)\n const {releaseId, metadata} = action\n\n const actionResult = await lastValueFrom(\n _action(this.#client, this.#httpRequest, action, options),\n )\n\n return {...actionResult, releaseId, metadata}\n }\n\n /**\n * @public\n *\n * Edits an existing release, updating the metadata.\n *\n * @category Releases\n *\n * @param params - Release action parameters:\n * - `releaseId` - The id of the release to edit.\n * - `patch` - The patch operation to apply on the release metadata {@link PatchMutationOperation}.\n * @param options - Additional action options.\n * @returns A promise that resolves to the `transactionId`.\n */\n edit(\n {releaseId, patch}: {releaseId: string; patch: PatchOperations},\n options?: BaseActionOptions,\n ): Promise<SingleActionResult> {\n const editAction: EditReleaseAction = {\n actionType: 'sanity.action.release.edit',\n releaseId,\n patch,\n }\n\n return lastValueFrom(_action(this.#client, this.#httpRequest, editAction, options))\n }\n\n /**\n * @public\n *\n * Publishes all documents in a release at once. For larger releases the effect of the publish\n * will be visible immediately when querying but the removal of the `versions.<releasesId>.*`\n * documents and creation of the corresponding published documents with the new content may\n * take some time.\n *\n * During this period both the source and target documents are locked and cannot be\n * modified through any other means.\n *\n * @category Releases\n *\n * @param params - Release action parameters:\n * - `releaseId` - The id of the release to publish.\n * @param options - Additional action options.\n * @returns A promise that resolves to the `transactionId`.\n */\n publish(\n {releaseId}: {releaseId: string},\n options?: BaseActionOptions,\n ): Promise<SingleActionResult> {\n const publishAction: PublishReleaseAction = {\n actionType: 'sanity.action.release.publish',\n releaseId,\n }\n\n return lastValueFrom(_action(this.#client, this.#httpRequest, publishAction, options))\n }\n\n /**\n * @public\n *\n * An archive action removes an active release. The documents that comprise the release\n * are deleted and therefore no longer queryable.\n *\n * While the documents remain in retention the last version can still be accessed using document history endpoint.\n *\n * @category Releases\n *\n * @param params - Release action parameters:\n * - `releaseId` - The id of the release to archive.\n * @param options - Additional action options.\n * @returns A promise that resolves to the `transactionId`.\n */\n archive(\n {releaseId}: {releaseId: string},\n options?: BaseActionOptions,\n ): Promise<SingleActionResult> {\n const archiveAction: ArchiveReleaseAction = {\n actionType: 'sanity.action.release.archive',\n releaseId,\n }\n\n return lastValueFrom(_action(this.#client, this.#httpRequest, archiveAction, options))\n }\n\n /**\n * @public\n *\n * An unarchive action restores an archived release and all documents\n * with the content they had just prior to archiving.\n *\n * @category Releases\n *\n * @param params - Release action parameters:\n * - `releaseId` - The id of the release to unarchive.\n * @param options - Additional action options.\n * @returns A promise that resolves to the `transactionId`.\n */\n unarchive(\n {releaseId}: {releaseId: string},\n options?: BaseActionOptions,\n ): Promise<SingleActionResult> {\n const unarchiveAction: UnarchiveReleaseAction = {\n actionType: 'sanity.action.release.unarchive',\n releaseId,\n }\n\n return lastValueFrom(_action(this.#client, this.#httpRequest, unarchiveAction, options))\n }\n\n /**\n * @public\n *\n * A schedule action queues a release for publishing at the given future time.\n * The release is locked such that no documents in the release can be modified and\n * no documents that it references can be deleted as this would make the publish fail.\n * At the given time, the same logic as for the publish action is triggered.\n *\n * @category Releases\n *\n * @param params - Release action parameters:\n * - `releaseId` - The id of the release to schedule.\n * - `publishAt` - The serialised date and time to publish the release. If the `publishAt` is in the past, the release will be published immediately.\n * @param options - Additional action options.\n * @returns A promise that resolves to the `transactionId`.\n */\n schedule(\n {releaseId, publishAt}: {releaseId: string; publishAt: string},\n options?: BaseActionOptions,\n ): Promise<SingleActionResult> {\n const scheduleAction: ScheduleReleaseAction = {\n actionType: 'sanity.action.release.schedule',\n releaseId,\n publishAt,\n }\n\n return lastValueFrom(_action(this.#client, this.#httpRequest, scheduleAction, options))\n }\n\n /**\n * @public\n *\n * An unschedule action stops a release from being published.\n * The documents in the release are considered unlocked and can be edited again.\n * This may fail if another release is scheduled to be published after this one and\n * has a reference to a document created by this one.\n *\n * @category Releases\n *\n * @param params - Release action parameters:\n * - `releaseId` - The id of the release to unschedule.\n * @param options - Additional action options.\n * @returns A promise that resolves to the `transactionId`.\n */\n unschedule(\n {releaseId}: {releaseId: string},\n options?: BaseActionOptions,\n ): Promise<SingleActionResult> {\n const unscheduleAction: UnscheduleReleaseAction = {\n actionType: 'sanity.action.release.unschedule',\n releaseId,\n }\n\n return lastValueFrom(_action(this.#client, this.#httpRequest, unscheduleAction, options))\n }\n\n /**\n * @public\n *\n * A delete action removes a published or archived release.\n * The backing system document will be removed from the dataset.\n *\n * @category Releases\n *\n * @param params - Release action parameters:\n * - `releaseId` - The id of the release to delete.\n * @param options - Additional action options.\n * @returns A promise that resolves to the `transactionId`.\n */\n delete(\n {releaseId}: {releaseId: string},\n options?: BaseActionOptions,\n ): Promise<SingleActionResult> {\n const deleteAction: DeleteReleaseAction = {\n actionType: 'sanity.action.release.delete',\n releaseId,\n }\n\n return lastValueFrom(_action(this.#client, this.#httpRequest, deleteAction, options))\n }\n\n /**\n * @public\n *\n * Fetch the documents in a release by release id.\n *\n * @category Releases\n *\n * @param params - Release action parameters:\n * - `releaseId` - The id of the release to fetch documents for.\n * @param options - Additional mutation options {@link BaseMutationOptions}.\n * @returns A promise that resolves to the documents in the release.\n */\n fetchDocuments(\n {releaseId}: {releaseId: string},\n options?: BaseMutationOptions,\n ): Promise<RawQueryResponse<SanityDocument[]>> {\n return lastValueFrom(_getReleaseDocuments(this.#client, this.#httpRequest, releaseId, options))\n }\n}\n","import {lastValueFrom, type Observable} from 'rxjs'\n\nimport {_request} from '../data/dataMethods'\nimport type {ObservableSanityClient, SanityClient} from '../SanityClient'\nimport type {CurrentSanityUser, HttpRequest, SanityUser} from '../types'\n\n/** @public */\nexport class ObservableUsersClient {\n #client: ObservableSanityClient\n #httpRequest: HttpRequest\n constructor(client: ObservableSanityClient, httpRequest: HttpRequest) {\n this.#client = client\n this.#httpRequest = httpRequest\n }\n\n /**\n * Fetch a user by user ID\n *\n * @param id - User ID of the user to fetch. If `me` is provided, a minimal response including the users role is returned.\n */\n getById<T extends 'me' | string>(\n id: T,\n ): Observable<T extends 'me' ? CurrentSanityUser : SanityUser> {\n return _request<T extends 'me' ? CurrentSanityUser : SanityUser>(\n this.#client,\n this.#httpRequest,\n {uri: `/users/${id}`},\n )\n }\n}\n\n/** @public */\nexport class UsersClient {\n #client: SanityClient\n #httpRequest: HttpRequest\n constructor(client: SanityClient, httpRequest: HttpRequest) {\n this.#client = client\n this.#httpRequest = httpRequest\n }\n\n /**\n * Fetch a user by user ID\n *\n * @param id - User ID of the user to fetch. If `me` is provided, a minimal response including the users role is returned.\n */\n getById<T extends 'me' | string>(\n id: T,\n ): Promise<T extends 'me' ? CurrentSanityUser : SanityUser> {\n return lastValueFrom(\n _request<T extends 'me' ? CurrentSanityUser : SanityUser>(this.#client, this.#httpRequest, {\n uri: `/users/${id}`,\n }),\n )\n }\n}\n","import {getPublishedId, getVersionId} from '@sanity/client/csm'\nimport {firstValueFrom, lastValueFrom, Observable} from 'rxjs'\n\nimport {AgentActionsClient, ObservableAgentsActionClient} from './agent/actions/AgentActionsClient'\nimport {AssetsClient, ObservableAssetsClient} from './assets/AssetsClient'\nimport {defaultConfig, initConfig} from './config'\nimport * as dataMethods from './data/dataMethods'\nimport {_listen} from './data/listen'\nimport {LiveClient} from './data/live'\nimport {ObservablePatch, Patch} from './data/patch'\nimport {ObservableTransaction, Transaction} from './data/transaction'\nimport {DatasetsClient, ObservableDatasetsClient} from './datasets/DatasetsClient'\nimport {\n MediaLibraryVideoClient,\n ObservableMediaLibraryVideoClient,\n} from './mediaLibrary/MediaLibraryVideoClient'\nimport {ObservableProjectsClient, ProjectsClient} from './projects/ProjectsClient'\nimport {ObservableReleasesClient, ReleasesClient} from './releases/ReleasesClient'\nimport type {\n Action,\n AllDocumentIdsMutationOptions,\n AllDocumentsMutationOptions,\n Any,\n BaseActionOptions,\n BaseMutationOptions,\n ClientConfig,\n ClientReturn,\n FilteredResponseQueryOptions,\n FirstDocumentIdMutationOptions,\n FirstDocumentMutationOptions,\n HttpRequest,\n IdentifiedSanityDocumentStub,\n InitializedClientConfig,\n MultipleActionResult,\n MultipleMutationResult,\n Mutation,\n MutationSelection,\n PatchOperations,\n PatchSelection,\n QueryOptions,\n QueryParams,\n QueryWithoutParams,\n RawQuerylessQueryResponse,\n RawQueryResponse,\n RawRequestOptions,\n SanityDocument,\n SanityDocumentStub,\n SingleActionResult,\n SingleMutationResult,\n UnfilteredResponseQueryOptions,\n UnfilteredResponseWithoutQuery,\n} from './types'\nimport {ObservableUsersClient, UsersClient} from './users/UsersClient'\nimport {deriveDocumentVersionId, getDocumentVersionId} from './util/createVersionId'\n\nexport type {\n _listen,\n AssetsClient,\n DatasetsClient,\n LiveClient,\n MediaLibraryVideoClient,\n ObservableAssetsClient,\n ObservableDatasetsClient,\n ObservableMediaLibraryVideoClient,\n ObservableProjectsClient,\n ObservableUsersClient,\n ProjectsClient,\n UsersClient,\n}\n\n/** @public */\nexport class ObservableSanityClient {\n assets: ObservableAssetsClient\n datasets: ObservableDatasetsClient\n live: LiveClient\n mediaLibrary: {\n video: ObservableMediaLibraryVideoClient\n }\n projects: ObservableProjectsClient\n users: ObservableUsersClient\n agent: {\n action: ObservableAgentsActionClient\n }\n releases: ObservableReleasesClient\n\n /**\n * Private properties\n */\n #clientConfig: InitializedClientConfig\n #httpRequest: HttpRequest\n\n /**\n * Instance properties\n */\n listen = _listen\n\n constructor(httpRequest: HttpRequest, config: ClientConfig = defaultConfig) {\n this.config(config)\n\n this.#httpRequest = httpRequest\n\n this.assets = new ObservableAssetsClient(this, this.#httpRequest)\n this.datasets = new ObservableDatasetsClient(this, this.#httpRequest)\n this.live = new LiveClient(this)\n this.mediaLibrary = {\n video: new ObservableMediaLibraryVideoClient(this, this.#httpRequest),\n }\n this.projects = new ObservableProjectsClient(this, this.#httpRequest)\n this.users = new ObservableUsersClient(this, this.#httpRequest)\n this.agent = {\n action: new ObservableAgentsActionClient(this, this.#httpRequest),\n }\n this.releases = new ObservableReleasesClient(this, this.#httpRequest)\n }\n\n /**\n * Clone the client - returns a new instance\n */\n clone(): ObservableSanityClient {\n return new ObservableSanityClient(this.#httpRequest, this.config())\n }\n\n /**\n * Returns the current client configuration\n */\n config(): InitializedClientConfig\n /**\n * Reconfigure the client. Note that this _mutates_ the current client.\n */\n config(newConfig?: Partial<ClientConfig>): this\n config(newConfig?: Partial<ClientConfig>): ClientConfig | this {\n if (newConfig === undefined) {\n return {...this.#clientConfig}\n }\n\n if (this.#clientConfig && this.#clientConfig.allowReconfigure === false) {\n throw new Error(\n 'Existing client instance cannot be reconfigured - use `withConfig(newConfig)` to return a new client',\n )\n }\n\n this.#clientConfig = initConfig(newConfig, this.#clientConfig || {})\n return this\n }\n\n /**\n * Clone the client with a new (partial) configuration.\n *\n * @param newConfig - New client configuration properties, shallowly merged with existing configuration\n */\n withConfig(newConfig?: Partial<ClientConfig>): ObservableSanityClient {\n const thisConfig = this.config()\n return new ObservableSanityClient(this.#httpRequest, {\n ...thisConfig,\n ...newConfig,\n stega: {\n ...(thisConfig.stega || {}),\n ...(typeof newConfig?.stega === 'boolean'\n ? {enabled: newConfig.stega}\n : newConfig?.stega || {}),\n },\n })\n }\n\n /**\n * Perform a GROQ-query against the configured dataset.\n *\n * @param query - GROQ-query to perform\n */\n fetch<\n R = Any,\n Q extends QueryWithoutParams = QueryWithoutParams,\n const G extends string = string,\n >(query: G, params?: Q | QueryWithoutParams): Observable<ClientReturn<G, R>>\n /**\n * Perform a GROQ-query against the configured dataset.\n *\n * @param query - GROQ-query to perform\n * @param params - Optional query parameters\n * @param options - Optional request options\n */\n fetch<\n R = Any,\n Q extends QueryWithoutParams | QueryParams = QueryParams,\n const G extends string = string,\n >(\n query: G,\n params: Q extends QueryWithoutParams ? QueryWithoutParams : Q,\n options?: FilteredResponseQueryOptions,\n ): Observable<ClientReturn<G, R>>\n /**\n * Perform a GROQ-query against the configured dataset.\n *\n * @param query - GROQ-query to perform\n * @param params - Optional query parameters\n * @param options - Request options\n */\n fetch<\n R = Any,\n Q extends QueryWithoutParams | QueryParams = QueryParams,\n const G extends string = string,\n >(\n query: string,\n params: Q extends QueryWithoutParams ? QueryWithoutParams : Q,\n options: UnfilteredResponseQueryOptions,\n ): Observable<RawQueryResponse<ClientReturn<G, R>>>\n /**\n * Perform a GROQ-query against the configured dataset.\n *\n * @param query - GROQ-query to perform\n * @param params - Optional query parameters\n * @param options - Request options\n */\n fetch<\n R = Any,\n Q extends QueryWithoutParams | QueryParams = QueryParams,\n const G extends string = string,\n >(\n query: G,\n params: Q extends QueryWithoutParams ? QueryWithoutParams : Q,\n options: UnfilteredResponseWithoutQuery,\n ): Observable<RawQuerylessQueryResponse<ClientReturn<G, R>>>\n fetch<R, Q, const G extends string>(\n query: G,\n params?: Q,\n options?: QueryOptions,\n ): Observable<RawQueryResponse<R> | R> {\n return dataMethods._fetch<R, Q>(\n this,\n this.#httpRequest,\n this.#clientConfig.stega,\n query,\n params,\n options,\n )\n }\n\n /**\n * Fetch a single document with the given ID.\n *\n * @param id - Document ID to fetch\n * @param options - Request options\n */\n getDocument<R extends Record<string, Any> = Record<string, Any>>(\n id: string,\n options: {\n signal?: AbortSignal\n tag?: string\n releaseId?: string\n includeAllVersions: true\n },\n ): Observable<SanityDocument<R>[]>\n /**\n * Fetch a single document with the given ID.\n *\n * @param id - Document ID to fetch\n * @param options - Request options\n */\n getDocument<R extends Record<string, Any> = Record<string, Any>>(\n id: string,\n options?: {\n signal?: AbortSignal\n tag?: string\n releaseId?: string\n includeAllVersions?: false\n },\n ): Observable<SanityDocument<R> | undefined>\n getDocument<R extends Record<string, Any> = Record<string, Any>>(\n id: string,\n options?: {\n signal?: AbortSignal\n tag?: string\n releaseId?: string\n includeAllVersions?: boolean\n },\n ): Observable<SanityDocument<R> | undefined | SanityDocument<R>[]> {\n // Implementation needs to handle union type safely\n if (options?.includeAllVersions === true) {\n return dataMethods._getDocument<R>(this, this.#httpRequest, id, {\n ...options,\n includeAllVersions: true,\n })\n }\n // When includeAllVersions is not true, pass options but only include includeAllVersions if it was explicitly set\n const opts = {\n signal: options?.signal,\n tag: options?.tag,\n releaseId: options?.releaseId,\n ...(options && 'includeAllVersions' in options ? {includeAllVersions: false as const} : {}),\n }\n return dataMethods._getDocument<R>(this, this.#httpRequest, id, opts)\n }\n\n /**\n * Fetch multiple documents in one request.\n * Should be used sparingly - performing a query is usually a better option.\n * The order/position of documents is preserved based on the original array of IDs.\n * If any of the documents are missing, they will be replaced by a `null` entry in the returned array\n *\n * @param ids - Document IDs to fetch\n * @param options - Request options\n */\n getDocuments<R extends Record<string, Any> = Record<string, Any>>(\n ids: string[],\n options?: {tag?: string},\n ): Observable<(SanityDocument<R> | null)[]> {\n return dataMethods._getDocuments<R>(this, this.#httpRequest, ids, options)\n }\n\n /**\n * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.\n * Returns an observable that resolves to the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n create<R extends Record<string, Any> = Record<string, Any>>(\n document: SanityDocumentStub<R>,\n options: FirstDocumentMutationOptions,\n ): Observable<SanityDocument<R>>\n /**\n * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.\n * Returns an observable that resolves to an array containing the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n create<R extends Record<string, Any> = Record<string, Any>>(\n document: SanityDocumentStub<R>,\n options: AllDocumentsMutationOptions,\n ): Observable<SanityDocument<R>[]>\n /**\n * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.\n * Returns an observable that resolves to a mutation result object containing the ID of the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n create<R extends Record<string, Any> = Record<string, Any>>(\n document: SanityDocumentStub<R>,\n options: FirstDocumentIdMutationOptions,\n ): Observable<SingleMutationResult>\n /**\n * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.\n * Returns an observable that resolves to a mutation result object containing the ID of the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n create<R extends Record<string, Any> = Record<string, Any>>(\n document: SanityDocumentStub<R>,\n options: AllDocumentIdsMutationOptions,\n ): Observable<MultipleMutationResult>\n /**\n * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.\n * Returns an observable that resolves to the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n create<R extends Record<string, Any> = Record<string, Any>>(\n document: SanityDocumentStub<R>,\n options?: BaseMutationOptions,\n ): Observable<SanityDocument<R>>\n create<R extends Record<string, Any> = Record<string, Any>>(\n document: SanityDocumentStub<R>,\n options?:\n | AllDocumentIdsMutationOptions\n | AllDocumentsMutationOptions\n | BaseMutationOptions\n | FirstDocumentIdMutationOptions\n | FirstDocumentMutationOptions,\n ): Observable<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n return dataMethods._create<R>(this, this.#httpRequest, document, 'create', options)\n }\n\n /**\n * Create a document if no document with the same ID already exists.\n * Returns an observable that resolves to the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: FirstDocumentMutationOptions,\n ): Observable<SanityDocument<R>>\n /**\n * Create a document if no document with the same ID already exists.\n * Returns an observable that resolves to an array containing the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: AllDocumentsMutationOptions,\n ): Observable<SanityDocument<R>[]>\n /**\n * Create a document if no document with the same ID already exists.\n * Returns an observable that resolves to a mutation result object containing the ID of the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: FirstDocumentIdMutationOptions,\n ): Observable<SingleMutationResult>\n /**\n * Create a document if no document with the same ID already exists.\n * Returns an observable that resolves to a mutation result object containing the ID of the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: AllDocumentIdsMutationOptions,\n ): Observable<MultipleMutationResult>\n /**\n * Create a document if no document with the same ID already exists.\n * Returns an observable that resolves to the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options?: BaseMutationOptions,\n ): Observable<SanityDocument<R>>\n createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options?:\n | AllDocumentIdsMutationOptions\n | AllDocumentsMutationOptions\n | BaseMutationOptions\n | FirstDocumentIdMutationOptions\n | FirstDocumentMutationOptions,\n ): Observable<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n return dataMethods._createIfNotExists<R>(this, this.#httpRequest, document, options)\n }\n\n /**\n * Create a document if it does not exist, or replace a document with the same document ID\n * Returns an observable that resolves to the created document.\n *\n * @param document - Document to either create or replace\n * @param options - Mutation options\n */\n createOrReplace<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: FirstDocumentMutationOptions,\n ): Observable<SanityDocument<R>>\n /**\n * Create a document if it does not exist, or replace a document with the same document ID\n * Returns an observable that resolves to an array containing the created document.\n *\n * @param document - Document to either create or replace\n * @param options - Mutation options\n */\n createOrReplace<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: AllDocumentsMutationOptions,\n ): Observable<SanityDocument<R>[]>\n /**\n * Create a document if it does not exist, or replace a document with the same document ID\n * Returns an observable that resolves to a mutation result object containing the ID of the created document.\n *\n * @param document - Document to either create or replace\n * @param options - Mutation options\n */\n createOrReplace<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: FirstDocumentIdMutationOptions,\n ): Observable<SingleMutationResult>\n /**\n * Create a document if it does not exist, or replace a document with the same document ID\n * Returns an observable that resolves to a mutation result object containing the created document ID.\n *\n * @param document - Document to either create or replace\n * @param options - Mutation options\n */\n createOrReplace<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: AllDocumentIdsMutationOptions,\n ): Observable<MultipleMutationResult>\n /**\n * Create a document if it does not exist, or replace a document with the same document ID\n * Returns an observable that resolves to the created document.\n *\n * @param document - Document to either create or replace\n * @param options - Mutation options\n */\n createOrReplace<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options?: BaseMutationOptions,\n ): Observable<SanityDocument<R>>\n createOrReplace<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options?:\n | AllDocumentIdsMutationOptions\n | AllDocumentsMutationOptions\n | BaseMutationOptions\n | FirstDocumentIdMutationOptions\n | FirstDocumentMutationOptions,\n ): Observable<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n return dataMethods._createOrReplace<R>(this, this.#httpRequest, document, options)\n }\n\n /**\n * @public\n *\n * Creates a new version of a published document.\n *\n * @remarks\n * * Requires a document with a `_type` property.\n * * Creating a version with no `releaseId` will create a new draft version of the published document.\n * * 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`.\n * * If the `document._id` is not defined, it will be generated from `publishedId` and `releaseId`.\n * * To create a version of an unpublished document, use the `client.create` method.\n *\n * @category Versions\n *\n * @param params - Version action parameters:\n * - `document` - The document to create as a new version (must include `_type`).\n * - `publishedId` - The ID of the published document being versioned.\n * - `releaseId` - The ID of the release to create the version for.\n * @param options - Additional action options.\n * @returns an observable that resolves to the `transactionId`.\n *\n * @example Creating a new version of a published document with a generated version ID\n * ```ts\n * client.observable.createVersion({\n * // The document does not need to include an `_id` property since it will be generated from `publishedId` and `releaseId`\n * document: {_type: 'myDocument', title: 'My Document'},\n * publishedId: 'myDocument',\n * releaseId: 'myRelease',\n * })\n *\n * // The following document will be created:\n * // {\n * // _id: 'versions.myRelease.myDocument',\n * // _type: 'myDocument',\n * // title: 'My Document',\n * // }\n * ```\n *\n * @example Creating a new version of a published document with a specified version ID\n * ```ts\n * client.observable.createVersion({\n * document: {_type: 'myDocument', _id: 'versions.myRelease.myDocument', title: 'My Document'},\n * // `publishedId` and `releaseId` are not required since `document._id` has been specified\n * })\n *\n * // The following document will be created:\n * // {\n * // _id: 'versions.myRelease.myDocument',\n * // _type: 'myDocument',\n * // title: 'My Document',\n * // }\n * ```\n *\n * @example Creating a new draft version of a published document\n * ```ts\n * client.observable.createVersion({\n * document: {_type: 'myDocument', title: 'My Document'},\n * publishedId: 'myDocument',\n * })\n *\n * // The following document will be created:\n * // {\n * // _id: 'drafts.myDocument',\n * // _type: 'myDocument',\n * // title: 'My Document',\n * // }\n * ```\n */\n createVersion<R extends Record<string, Any>>(\n args: {\n document: SanityDocumentStub<R>\n publishedId: string\n releaseId?: string\n },\n options?: BaseActionOptions,\n ): Observable<SingleActionResult | MultipleActionResult>\n createVersion<R extends Record<string, Any>>(\n args: {\n document: IdentifiedSanityDocumentStub<R>\n publishedId?: string\n releaseId?: string\n },\n options?: BaseActionOptions,\n ): Observable<SingleActionResult | MultipleActionResult>\n createVersion(\n args: {\n baseId: string\n releaseId?: string\n publishedId: string\n ifBaseRevisionId?: string\n },\n options?: BaseActionOptions,\n ): Observable<SingleActionResult | MultipleActionResult>\n createVersion<R extends Record<string, Any>>(\n {\n document,\n publishedId,\n releaseId,\n baseId,\n ifBaseRevisionId,\n }: {\n document?: SanityDocumentStub<R> | IdentifiedSanityDocumentStub<R>\n publishedId?: string\n releaseId?: string\n baseId?: string\n ifBaseRevisionId?: string\n },\n options?: BaseActionOptions,\n ): Observable<SingleActionResult | MultipleActionResult> {\n if (!document) {\n return dataMethods._createVersionFromBase(\n this,\n this.#httpRequest,\n publishedId,\n baseId,\n releaseId,\n ifBaseRevisionId,\n options,\n )\n }\n\n const documentVersionId = deriveDocumentVersionId('createVersion', {\n document,\n publishedId,\n releaseId,\n })\n\n const documentVersion = {...document, _id: documentVersionId}\n const versionPublishedId = publishedId || getPublishedId(document._id)\n\n return dataMethods._createVersion<R>(\n this,\n this.#httpRequest,\n documentVersion,\n versionPublishedId,\n options,\n )\n }\n\n /**\n * Deletes a document with the given document ID.\n * Returns an observable that resolves to the deleted document.\n *\n * @param id - Document ID to delete\n * @param options - Options for the mutation\n */\n delete<R extends Record<string, Any> = Record<string, Any>>(\n id: string,\n options: FirstDocumentMutationOptions,\n ): Observable<SanityDocument<R>>\n /**\n * Deletes a document with the given document ID.\n * Returns an observable that resolves to an array containing the deleted document.\n *\n * @param id - Document ID to delete\n * @param options - Options for the mutation\n */\n delete<R extends Record<string, Any> = Record<string, Any>>(\n id: string,\n options: AllDocumentsMutationOptions,\n ): Observable<SanityDocument<R>[]>\n /**\n * Deletes a document with the given document ID.\n * Returns an observable that resolves to a mutation result object containing the deleted document ID.\n *\n * @param id - Document ID to delete\n * @param options - Options for the mutation\n */\n delete(id: string, options: FirstDocumentIdMutationOptions): Observable<SingleMutationResult>\n /**\n * Deletes a document with the given document ID.\n * Returns an observable that resolves to a mutation result object containing the deleted document ID.\n *\n * @param id - Document ID to delete\n * @param options - Options for the mutation\n */\n delete(id: string, options: AllDocumentIdsMutationOptions): Observable<MultipleMutationResult>\n /**\n * Deletes a document with the given document ID.\n * Returns an observable that resolves to the deleted document.\n *\n * @param id - Document ID to delete\n * @param options - Options for the mutation\n */\n delete<R extends Record<string, Any> = Record<string, Any>>(\n id: string,\n options?: BaseMutationOptions,\n ): Observable<SanityDocument<R>>\n /**\n * Deletes one or more documents matching the given query or document ID.\n * Returns an observable that resolves to first deleted document.\n *\n * @param selection - An object with either an `id` or `query` key defining what to delete\n * @param options - Options for the mutation\n */\n delete<R extends Record<string, Any> = Record<string, Any>>(\n selection: MutationSelection,\n options: FirstDocumentMutationOptions,\n ): Observable<SanityDocument<R>>\n /**\n * Deletes one or more documents matching the given query or document ID.\n * Returns an observable that resolves to an array containing the deleted documents.\n *\n * @param selection - An object with either an `id` or `query` key defining what to delete\n * @param options - Options for the mutation\n */\n delete<R extends Record<string, Any> = Record<string, Any>>(\n selection: MutationSelection,\n options: AllDocumentsMutationOptions,\n ): Observable<SanityDocument<R>[]>\n /**\n * Deletes one or more documents matching the given query or document ID.\n * Returns an observable that resolves to a mutation result object containing the ID of the first deleted document.\n *\n * @param selection - An object with either an `id` or `query` key defining what to delete\n * @param options - Options for the mutation\n */\n delete(\n selection: MutationSelection,\n options: FirstDocumentIdMutationOptions,\n ): Observable<SingleMutationResult>\n /**\n * Deletes one or more documents matching the given query or document ID.\n * Returns an observable that resolves to a mutation result object containing the document IDs that were deleted.\n *\n * @param selection - An object with either an `id` or `query` key defining what to delete\n * @param options - Options for the mutation\n */\n delete(\n selection: MutationSelection,\n options: AllDocumentIdsMutationOptions,\n ): Observable<MultipleMutationResult>\n /**\n * Deletes one or more documents matching the given query or document ID.\n * Returns an observable that resolves to first deleted document.\n *\n * @param selection - An object with either an `id` or `query` key defining what to delete\n * @param options - Options for the mutation\n */\n delete<R extends Record<string, Any> = Record<string, Any>>(\n selection: MutationSelection,\n options?: BaseMutationOptions,\n ): Observable<SanityDocument<R>>\n delete<R extends Record<string, Any> = Record<string, Any>>(\n selection: string | MutationSelection,\n options?:\n | AllDocumentIdsMutationOptions\n | AllDocumentsMutationOptions\n | BaseMutationOptions\n | FirstDocumentIdMutationOptions\n | FirstDocumentMutationOptions,\n ): Observable<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n return dataMethods._delete<R>(this, this.#httpRequest, selection, options)\n }\n\n /**\n * @public\n *\n * Deletes the draft or release version of a document.\n *\n * @remarks\n * * Discarding a version with no `releaseId` will discard the draft version of the published document.\n * * If the draft or release version does not exist, any error will throw.\n *\n * @param params - Version action parameters:\n * - `releaseId` - The ID of the release to discard the document from.\n * - `publishedId` - The published ID of the document to discard.\n * @param purge - if `true` the document history is also discarded.\n * @param options - Additional action options.\n * @returns an observable that resolves to the `transactionId`.\n *\n * @example Discarding a release version of a document\n * ```ts\n * client.observable.discardVersion({publishedId: 'myDocument', releaseId: 'myRelease'})\n * // The document with the ID `versions.myRelease.myDocument` will be discarded.\n * ```\n *\n * @example Discarding a draft version of a document\n * ```ts\n * client.observable.discardVersion({publishedId: 'myDocument'})\n * // The document with the ID `drafts.myDocument` will be discarded.\n * ```\n */\n discardVersion(\n {releaseId, publishedId}: {releaseId?: string; publishedId: string},\n purge?: boolean,\n options?: BaseActionOptions,\n ): Observable<SingleActionResult | MultipleActionResult> {\n const documentVersionId = getDocumentVersionId(publishedId, releaseId)\n\n return dataMethods._discardVersion(this, this.#httpRequest, documentVersionId, purge, options)\n }\n\n /**\n * @public\n *\n * Replaces an existing version document.\n *\n * @remarks\n * * Requires a document with a `_type` property.\n * * 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`.\n * * If the `document._id` is not defined, it will be generated from `publishedId` and `releaseId`.\n * * Replacing a version with no `releaseId` will replace the draft version of the published document.\n * * At least one of the **version** or **published** documents must exist.\n *\n * @param params - Version action parameters:\n * - `document` - The new document to replace the version with.\n * - `releaseId` - The ID of the release where the document version is replaced.\n * - `publishedId` - The ID of the published document to replace.\n * @param options - Additional action options.\n * @returns an observable that resolves to the `transactionId`.\n *\n * @example Replacing a release version of a published document with a generated version ID\n * ```ts\n * client.observable.replaceVersion({\n * document: {_type: 'myDocument', title: 'My Document'},\n * publishedId: 'myDocument',\n * releaseId: 'myRelease',\n * })\n *\n * // The following document will be patched:\n * // {\n * // _id: 'versions.myRelease.myDocument',\n * // _type: 'myDocument',\n * // title: 'My Document',\n * // }\n * ```\n *\n * @example Replacing a release version of a published document with a specified version ID\n * ```ts\n * client.observable.replaceVersion({\n * document: {_type: 'myDocument', _id: 'versions.myRelease.myDocument', title: 'My Document'},\n * // `publishedId` and `releaseId` are not required since `document._id` has been specified\n * })\n *\n * // The following document will be patched:\n * // {\n * // _id: 'versions.myRelease.myDocument',\n * // _type: 'myDocument',\n * // title: 'My Document',\n * // }\n * ```\n *\n * @example Replacing a draft version of a published document\n * ```ts\n * client.observable.replaceVersion({\n * document: {_type: 'myDocument', title: 'My Document'},\n * publishedId: 'myDocument',\n * })\n *\n * // The following document will be patched:\n * // {\n * // _id: 'drafts.myDocument',\n * // _type: 'myDocument',\n * // title: 'My Document',\n * // }\n * ```\n */\n replaceVersion<R extends Record<string, Any>>(\n args: {\n document: SanityDocumentStub<R>\n publishedId: string\n releaseId?: string\n },\n options?: BaseActionOptions,\n ): Observable<SingleActionResult | MultipleActionResult>\n replaceVersion<R extends Record<string, Any>>(\n args: {\n document: IdentifiedSanityDocumentStub<R>\n publishedId?: string\n releaseId?: string\n },\n options?: BaseActionOptions,\n ): Observable<SingleActionResult | MultipleActionResult>\n replaceVersion<R extends Record<string, Any>>(\n {\n document,\n publishedId,\n releaseId,\n }: {\n document: SanityDocumentStub<R> | IdentifiedSanityDocumentStub<R>\n publishedId?: string\n releaseId?: string\n },\n options?: BaseActionOptions,\n ): Observable<SingleActionResult | MultipleActionResult> {\n const documentVersionId = deriveDocumentVersionId('replaceVersion', {\n document,\n publishedId,\n releaseId,\n })\n\n const documentVersion = {...document, _id: documentVersionId}\n\n return dataMethods._replaceVersion<R>(this, this.#httpRequest, documentVersion, options)\n }\n\n /**\n * @public\n *\n * Used to indicate when a document within a release should be unpublished when\n * the release is run.\n *\n * @remarks\n * * If the published document does not exist, an error will be thrown.\n *\n * @param params - Version action parameters:\n * - `releaseId` - The ID of the release to unpublish the document from.\n * - `publishedId` - The published ID of the document to unpublish.\n * @param options - Additional action options.\n * @returns an observable that resolves to the `transactionId`.\n *\n * @example Unpublishing a release version of a published document\n * ```ts\n * client.observable.unpublishVersion({publishedId: 'myDocument', releaseId: 'myRelease'})\n * // The document with the ID `versions.myRelease.myDocument` will be unpublished. when `myRelease` is run.\n * ```\n */\n unpublishVersion(\n {releaseId, publishedId}: {releaseId: string; publishedId: string},\n options?: BaseActionOptions,\n ): Observable<SingleActionResult | MultipleActionResult> {\n const versionId = getVersionId(publishedId, releaseId)\n\n return dataMethods._unpublishVersion(this, this.#httpRequest, versionId, publishedId, options)\n }\n\n /**\n * Perform mutation operations against the configured dataset\n * Returns an observable that resolves to the first mutated document.\n *\n * @param operations - Mutation operations to execute\n * @param options - Mutation options\n */\n mutate<R extends Record<string, Any> = Record<string, Any>>(\n operations: Mutation<R>[] | ObservablePatch | ObservableTransaction,\n options: FirstDocumentMutationOptions,\n ): Observable<SanityDocument<R>>\n /**\n * Perform mutation operations against the configured dataset.\n * Returns an observable that resolves to an array of the mutated documents.\n *\n * @param operations - Mutation operations to execute\n * @param options - Mutation options\n */\n mutate<R extends Record<string, Any> = Record<string, Any>>(\n operations: Mutation<R>[] | ObservablePatch | ObservableTransaction,\n options: AllDocumentsMutationOptions,\n ): Observable<SanityDocument<R>[]>\n /**\n * Perform mutation operations against the configured dataset\n * Returns an observable that resolves to a mutation result object containing the document ID of the first mutated document.\n *\n * @param operations - Mutation operations to execute\n * @param options - Mutation options\n */\n mutate<R extends Record<string, Any> = Record<string, Any>>(\n operations: Mutation<R>[] | ObservablePatch | ObservableTransaction,\n options: FirstDocumentIdMutationOptions,\n ): Observable<SingleMutationResult>\n /**\n * Perform mutation operations against the configured dataset\n * Returns an observable that resolves to a mutation result object containing the mutated document IDs.\n *\n * @param operations - Mutation operations to execute\n * @param options - Mutation options\n */\n mutate<R extends Record<string, Any> = Record<string, Any>>(\n operations: Mutation<R>[] | ObservablePatch | ObservableTransaction,\n options: AllDocumentIdsMutationOptions,\n ): Observable<MultipleMutationResult>\n /**\n * Perform mutation operations against the configured dataset\n * Returns an observable that resolves to the first mutated document.\n *\n * @param operations - Mutation operations to execute\n * @param options - Mutation options\n */\n mutate<R extends Record<string, Any> = Record<string, Any>>(\n operations: Mutation<R>[] | ObservablePatch | ObservableTransaction,\n options?: BaseMutationOptions,\n ): Observable<SanityDocument<R>>\n mutate<R extends Record<string, Any> = Record<string, Any>>(\n operations: Mutation<R>[] | ObservablePatch | ObservableTransaction,\n options?:\n | FirstDocumentMutationOptions\n | AllDocumentsMutationOptions\n | FirstDocumentIdMutationOptions\n | AllDocumentIdsMutationOptions\n | BaseMutationOptions,\n ): Observable<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n return dataMethods._mutate<R>(this, this.#httpRequest, operations, options)\n }\n\n /**\n * Create a new buildable patch of operations to perform\n *\n * @param documentId - Document ID to patch\n * @param operations - Optional object of patch operations to initialize the patch instance with\n * @returns Patch instance - call `.commit()` to perform the operations defined\n */\n patch(documentId: string, operations?: PatchOperations): ObservablePatch\n\n /**\n * Create a new buildable patch of operations to perform\n *\n * @param documentIds - Array of document IDs to patch\n * @param operations - Optional object of patch operations to initialize the patch instance with\n * @returns Patch instance - call `.commit()` to perform the operations defined\n */\n patch(documentIds: string[], operations?: PatchOperations): ObservablePatch\n\n /**\n * Create a new buildable patch of operations to perform\n *\n * @param selection - An object with `query` and optional `params`, defining which document(s) to patch\n * @param operations - Optional object of patch operations to initialize the patch instance with\n * @returns Patch instance - call `.commit()` to perform the operations defined\n */\n patch(selection: MutationSelection, operations?: PatchOperations): ObservablePatch\n\n /**\n * Create a new buildable patch of operations to perform\n *\n * @param selection - Document ID, an array of document IDs, or an object with `query` and optional `params`, defining which document(s) to patch\n * @param operations - Optional object of patch operations to initialize the patch instance with\n * @returns Patch instance - call `.commit()` to perform the operations defined\n */\n patch(selection: PatchSelection, operations?: PatchOperations): ObservablePatch {\n return new ObservablePatch(selection, operations, this)\n }\n\n /**\n * Create a new transaction of mutations\n *\n * @param operations - Optional array of mutation operations to initialize the transaction instance with\n */\n transaction<R extends Record<string, Any> = Record<string, Any>>(\n operations?: Mutation<R>[],\n ): ObservableTransaction {\n return new ObservableTransaction(operations, this)\n }\n\n /**\n * Perform action operations against the configured dataset\n *\n * @param operations - Action operation(s) to execute\n * @param options - Action options\n */\n action(\n operations: Action | Action[],\n options?: BaseActionOptions,\n ): Observable<SingleActionResult | MultipleActionResult> {\n return dataMethods._action(this, this.#httpRequest, operations, options)\n }\n\n /**\n * Perform an HTTP request against the Sanity API\n *\n * @param options - Request options\n */\n request<R = Any>(options: RawRequestOptions): Observable<R> {\n return dataMethods._request(this, this.#httpRequest, options)\n }\n\n /**\n * Get a Sanity API URL for the URI provided\n *\n * @param uri - URI/path to build URL for\n * @param canUseCdn - Whether or not to allow using the API CDN for this route\n */\n getUrl(uri: string, canUseCdn?: boolean): string {\n return dataMethods._getUrl(this, uri, canUseCdn)\n }\n\n /**\n * Get a Sanity API URL for the data operation and path provided\n *\n * @param operation - Data operation (eg `query`, `mutate`, `listen` or similar)\n * @param path - Path to append after the operation\n */\n getDataUrl(operation: string, path?: string): string {\n return dataMethods._getDataUrl(this, operation, path)\n }\n}\n\n/** @public */\nexport class SanityClient {\n assets: AssetsClient\n datasets: DatasetsClient\n live: LiveClient\n mediaLibrary: {\n video: MediaLibraryVideoClient\n }\n projects: ProjectsClient\n users: UsersClient\n agent: {\n action: AgentActionsClient\n }\n releases: ReleasesClient\n\n /**\n * Observable version of the Sanity client, with the same configuration as the promise-based one\n */\n observable: ObservableSanityClient\n\n /**\n * Private properties\n */\n #clientConfig: InitializedClientConfig\n #httpRequest: HttpRequest\n\n /**\n * Instance properties\n */\n listen = _listen\n\n constructor(httpRequest: HttpRequest, config: ClientConfig = defaultConfig) {\n this.config(config)\n\n this.#httpRequest = httpRequest\n\n this.assets = new AssetsClient(this, this.#httpRequest)\n this.datasets = new DatasetsClient(this, this.#httpRequest)\n this.live = new LiveClient(this)\n this.mediaLibrary = {\n video: new MediaLibraryVideoClient(this, this.#httpRequest),\n }\n this.projects = new ProjectsClient(this, this.#httpRequest)\n this.users = new UsersClient(this, this.#httpRequest)\n this.agent = {\n action: new AgentActionsClient(this, this.#httpRequest),\n }\n this.releases = new ReleasesClient(this, this.#httpRequest)\n\n this.observable = new ObservableSanityClient(httpRequest, config)\n }\n\n /**\n * Clone the client - returns a new instance\n */\n clone(): SanityClient {\n return new SanityClient(this.#httpRequest, this.config())\n }\n\n /**\n * Returns the current client configuration\n */\n config(): InitializedClientConfig\n /**\n * Reconfigure the client. Note that this _mutates_ the current client.\n */\n config(newConfig?: Partial<ClientConfig>): this\n config(newConfig?: Partial<ClientConfig>): ClientConfig | this {\n if (newConfig === undefined) {\n return {...this.#clientConfig}\n }\n\n if (this.#clientConfig && this.#clientConfig.allowReconfigure === false) {\n throw new Error(\n 'Existing client instance cannot be reconfigured - use `withConfig(newConfig)` to return a new client',\n )\n }\n\n if (this.observable) {\n this.observable.config(newConfig)\n }\n\n this.#clientConfig = initConfig(newConfig, this.#clientConfig || {})\n return this\n }\n\n /**\n * Clone the client with a new (partial) configuration.\n *\n * @param newConfig - New client configuration properties, shallowly merged with existing configuration\n */\n withConfig(newConfig?: Partial<ClientConfig>): SanityClient {\n const thisConfig = this.config()\n return new SanityClient(this.#httpRequest, {\n ...thisConfig,\n ...newConfig,\n stega: {\n ...(thisConfig.stega || {}),\n ...(typeof newConfig?.stega === 'boolean'\n ? {enabled: newConfig.stega}\n : newConfig?.stega || {}),\n },\n })\n }\n\n /**\n * Perform a GROQ-query against the configured dataset.\n *\n * @param query - GROQ-query to perform\n */\n fetch<\n R = Any,\n Q extends QueryWithoutParams = QueryWithoutParams,\n const G extends string = string,\n >(query: G, params?: Q | QueryWithoutParams): Promise<ClientReturn<G, R>>\n /**\n * Perform a GROQ-query against the configured dataset.\n *\n * @param query - GROQ-query to perform\n * @param params - Optional query parameters\n * @param options - Optional request options\n */\n fetch<\n R = Any,\n Q extends QueryWithoutParams | QueryParams = QueryParams,\n const G extends string = string,\n >(\n query: G,\n params: Q extends QueryWithoutParams ? QueryWithoutParams : Q,\n options?: FilteredResponseQueryOptions,\n ): Promise<ClientReturn<G, R>>\n /**\n * Perform a GROQ-query against the configured dataset.\n *\n * @param query - GROQ-query to perform\n * @param params - Optional query parameters\n * @param options - Request options\n */\n fetch<\n R = Any,\n Q extends QueryWithoutParams | QueryParams = QueryParams,\n const G extends string = string,\n >(\n query: G,\n params: Q extends QueryWithoutParams ? QueryWithoutParams : Q,\n options: UnfilteredResponseQueryOptions,\n ): Promise<RawQueryResponse<ClientReturn<G, R>>>\n /**\n * Perform a GROQ-query against the configured dataset.\n *\n * @param query - GROQ-query to perform\n * @param params - Optional query parameters\n * @param options - Request options\n */\n fetch<\n R = Any,\n Q extends QueryWithoutParams | QueryParams = QueryParams,\n const G extends string = string,\n >(\n query: G,\n params: Q extends QueryWithoutParams ? QueryWithoutParams : Q,\n options: UnfilteredResponseWithoutQuery,\n ): Promise<RawQuerylessQueryResponse<ClientReturn<G, R>>>\n fetch<R, Q, const G extends string>(\n query: G,\n params?: Q,\n options?: QueryOptions,\n ): Promise<RawQueryResponse<ClientReturn<G, R>> | ClientReturn<G, R>> {\n return lastValueFrom(\n dataMethods._fetch<ClientReturn<G, R>, Q>(\n this,\n this.#httpRequest,\n this.#clientConfig.stega,\n query,\n params,\n options,\n ),\n )\n }\n\n /**\n * Fetch a single document with the given ID.\n *\n * @param id - Document ID to fetch\n * @param options - Request options\n */\n getDocument<R extends Record<string, Any> = Record<string, Any>>(\n id: string,\n options: {\n signal?: AbortSignal\n tag?: string\n releaseId?: string\n includeAllVersions: true\n },\n ): Promise<SanityDocument<R>[]>\n /**\n * Fetch a single document with the given ID.\n *\n * @param id - Document ID to fetch\n * @param options - Request options\n */\n getDocument<R extends Record<string, Any> = Record<string, Any>>(\n id: string,\n options?: {\n signal?: AbortSignal\n tag?: string\n releaseId?: string\n includeAllVersions?: false\n },\n ): Promise<SanityDocument<R> | undefined>\n getDocument<R extends Record<string, Any> = Record<string, Any>>(\n id: string,\n options?: {\n signal?: AbortSignal\n tag?: string\n releaseId?: string\n includeAllVersions?: boolean\n },\n ): Promise<SanityDocument<R> | undefined | SanityDocument<R>[]> {\n // Implementation needs to handle union type safely\n if (options?.includeAllVersions === true) {\n return lastValueFrom(\n dataMethods._getDocument<R>(this, this.#httpRequest, id, {\n ...options,\n includeAllVersions: true,\n }),\n )\n }\n // When includeAllVersions is not true, pass options but only include includeAllVersions if it was explicitly set\n const opts = {\n signal: options?.signal,\n tag: options?.tag,\n releaseId: options?.releaseId,\n ...(options && 'includeAllVersions' in options ? {includeAllVersions: false as const} : {}),\n }\n return lastValueFrom(dataMethods._getDocument<R>(this, this.#httpRequest, id, opts))\n }\n\n /**\n * Fetch multiple documents in one request.\n * Should be used sparingly - performing a query is usually a better option.\n * The order/position of documents is preserved based on the original array of IDs.\n * If any of the documents are missing, they will be replaced by a `null` entry in the returned array\n *\n * @param ids - Document IDs to fetch\n * @param options - Request options\n */\n getDocuments<R extends Record<string, Any> = Record<string, Any>>(\n ids: string[],\n options?: {signal?: AbortSignal; tag?: string},\n ): Promise<(SanityDocument<R> | null)[]> {\n return lastValueFrom(dataMethods._getDocuments<R>(this, this.#httpRequest, ids, options))\n }\n\n /**\n * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.\n * Returns a promise that resolves to the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n create<R extends Record<string, Any> = Record<string, Any>>(\n document: SanityDocumentStub<R>,\n options: FirstDocumentMutationOptions,\n ): Promise<SanityDocument<R>>\n /**\n * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.\n * Returns a promise that resolves to an array containing the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n create<R extends Record<string, Any> = Record<string, Any>>(\n document: SanityDocumentStub<R>,\n options: AllDocumentsMutationOptions,\n ): Promise<SanityDocument<R>[]>\n /**\n * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.\n * Returns a promise that resolves to a mutation result object containing the ID of the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n create<R extends Record<string, Any> = Record<string, Any>>(\n document: SanityDocumentStub<R>,\n options: FirstDocumentIdMutationOptions,\n ): Promise<SingleMutationResult>\n /**\n * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.\n * Returns a promise that resolves to a mutation result object containing the ID of the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n create<R extends Record<string, Any> = Record<string, Any>>(\n document: SanityDocumentStub<R>,\n options: AllDocumentIdsMutationOptions,\n ): Promise<MultipleMutationResult>\n /**\n * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.\n * Returns a promise that resolves to the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n create<R extends Record<string, Any> = Record<string, Any>>(\n document: SanityDocumentStub<R>,\n options?: BaseMutationOptions,\n ): Promise<SanityDocument<R>>\n create<R extends Record<string, Any> = Record<string, Any>>(\n document: SanityDocumentStub<R>,\n options?:\n | AllDocumentIdsMutationOptions\n | AllDocumentsMutationOptions\n | BaseMutationOptions\n | FirstDocumentIdMutationOptions\n | FirstDocumentMutationOptions,\n ): Promise<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n return lastValueFrom(\n dataMethods._create<R>(this, this.#httpRequest, document, 'create', options),\n )\n }\n\n /**\n * Create a document if no document with the same ID already exists.\n * Returns a promise that resolves to the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: FirstDocumentMutationOptions,\n ): Promise<SanityDocument<R>>\n /**\n * Create a document if no document with the same ID already exists.\n * Returns a promise that resolves to an array containing the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: AllDocumentsMutationOptions,\n ): Promise<SanityDocument<R>[]>\n /**\n * Create a document if no document with the same ID already exists.\n * Returns a promise that resolves to a mutation result object containing the ID of the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: FirstDocumentIdMutationOptions,\n ): Promise<SingleMutationResult>\n /**\n * Create a document if no document with the same ID already exists.\n * Returns a promise that resolves to a mutation result object containing the ID of the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: AllDocumentIdsMutationOptions,\n ): Promise<MultipleMutationResult>\n /**\n * Create a document if no document with the same ID already exists.\n * Returns a promise that resolves to the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options?: BaseMutationOptions,\n ): Promise<SanityDocument<R>>\n createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options?:\n | AllDocumentIdsMutationOptions\n | AllDocumentsMutationOptions\n | BaseMutationOptions\n | FirstDocumentIdMutationOptions\n | FirstDocumentMutationOptions,\n ): Promise<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n return lastValueFrom(\n dataMethods._createIfNotExists<R>(this, this.#httpRequest, document, options),\n )\n }\n\n /**\n * Create a document if it does not exist, or replace a document with the same document ID\n * Returns a promise that resolves to the created document.\n *\n * @param document - Document to either create or replace\n * @param options - Mutation options\n */\n createOrReplace<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: FirstDocumentMutationOptions,\n ): Promise<SanityDocument<R>>\n /**\n * Create a document if it does not exist, or replace a document with the same document ID\n * Returns a promise that resolves to an array containing the created document.\n *\n * @param document - Document to either create or replace\n * @param options - Mutation options\n */\n createOrReplace<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: AllDocumentsMutationOptions,\n ): Promise<SanityDocument<R>[]>\n /**\n * Create a document if it does not exist, or replace a document with the same document ID\n * Returns a promise that resolves to a mutation result object containing the ID of the created document.\n *\n * @param document - Document to either create or replace\n * @param options - Mutation options\n */\n createOrReplace<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: FirstDocumentIdMutationOptions,\n ): Promise<SingleMutationResult>\n /**\n * Create a document if it does not exist, or replace a document with the same document ID\n * Returns a promise that resolves to a mutation result object containing the created document ID.\n *\n * @param document - Document to either create or replace\n * @param options - Mutation options\n */\n createOrReplace<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: AllDocumentIdsMutationOptions,\n ): Promise<MultipleMutationResult>\n /**\n * Create a document if it does not exist, or replace a document with the same document ID\n * Returns a promise that resolves to the created document.\n *\n * @param document - Document to either create or replace\n * @param options - Mutation options\n */\n createOrReplace<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options?: BaseMutationOptions,\n ): Promise<SanityDocument<R>>\n createOrReplace<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options?:\n | AllDocumentIdsMutationOptions\n | AllDocumentsMutationOptions\n | BaseMutationOptions\n | FirstDocumentIdMutationOptions\n | FirstDocumentMutationOptions,\n ): Promise<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n return lastValueFrom(\n dataMethods._createOrReplace<R>(this, this.#httpRequest, document, options),\n )\n }\n\n /**\n * @public\n *\n * Creates a new version of a published document.\n *\n * @remarks\n * * 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.\n * * If `document` is provided, it must have a `_type` property.\n * * Creating a version with no `releaseId` will create a new draft version of the published document.\n * * 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`.\n * * If the `document._id` is not defined, it will be generated from `publishedId` and `releaseId`.\n * * To create a version of an unpublished document, use the `client.create` method.\n *\n * @category Versions\n *\n * @param params - Version action parameters:\n * - `baseId` - The ID of the published document from which to create a new version from.\n * - `ifBaseRevisionId` - If `baseId` is provided, this ensures the `baseId`'s revision Id is as expected before creating the new version from it.\n * - `document` - The document to create as a new version (must include `_type`).\n * - `publishedId` - The ID of the published document being versioned.\n * - `releaseId` - The ID of the release to create the version for.\n * @param options - Additional action options.\n * @returns A promise that resolves to the `transactionId`.\n *\n * @example Creating a new version of a published document\n * ```ts\n * const transactionId = await client.createVersion({\n * baseId: 'myDocument',\n * publishedId: 'myDocument',\n * releaseId: 'myRelease',\n * })\n *\n * // The following document will be created:\n * // {\n * // _id: 'versions.myRelease.myDocument',\n * // _type: 'myDocument',\n * // title: 'My Document',\n * // }\n * ```\n *\n *\n * @example Creating a new draft version of a published document\n * ```ts\n * const transactionId = await client.createVersion({\n * baseId: 'myDocument',\n * publishedId: 'myDocument',\n * })\n *\n * // The following document will be created:\n * // {\n * // _id: 'drafts.myDocument',\n * // _type: 'myDocument',\n * // title: 'My Document',\n * // }\n * ```\n */\n createVersion<R extends Record<string, Any>>(\n args: {\n document: SanityDocumentStub<R>\n publishedId: string\n releaseId?: string\n },\n options?: BaseActionOptions,\n ): Promise<SingleActionResult | MultipleActionResult>\n createVersion<R extends Record<string, Any>>(\n args: {\n document: IdentifiedSanityDocumentStub<R>\n publishedId?: string\n releaseId?: string\n },\n options?: BaseActionOptions,\n ): Promise<SingleActionResult | MultipleActionResult>\n createVersion(\n args: {\n publishedId: string\n baseId: string\n releaseId?: string\n ifBaseRevisionId?: string\n },\n options?: BaseActionOptions,\n ): Promise<SingleActionResult | MultipleActionResult>\n createVersion<R extends Record<string, Any>>(\n {\n document,\n publishedId,\n releaseId,\n baseId,\n ifBaseRevisionId,\n }: {\n document?: SanityDocumentStub<R> | IdentifiedSanityDocumentStub<R>\n publishedId?: string\n releaseId?: string\n baseId?: string\n ifBaseRevisionId?: string\n },\n options?: BaseActionOptions,\n ): Promise<SingleActionResult | MultipleActionResult> {\n if (!document) {\n return firstValueFrom(\n dataMethods._createVersionFromBase(\n this,\n this.#httpRequest,\n publishedId,\n baseId,\n releaseId,\n ifBaseRevisionId,\n options,\n ),\n )\n }\n\n const documentVersionId = deriveDocumentVersionId('createVersion', {\n document,\n publishedId,\n releaseId,\n })\n\n const documentVersion = {...document, _id: documentVersionId}\n const versionPublishedId = publishedId || getPublishedId(document._id)\n\n return firstValueFrom(\n dataMethods._createVersion<R>(\n this,\n this.#httpRequest,\n documentVersion,\n versionPublishedId,\n options,\n ),\n )\n }\n\n /**\n * Deletes a document with the given document ID.\n * Returns a promise that resolves to the deleted document.\n *\n * @param id - Document ID to delete\n * @param options - Options for the mutation\n */\n delete<R extends Record<string, Any> = Record<string, Any>>(\n id: string,\n options: FirstDocumentMutationOptions,\n ): Promise<SanityDocument<R>>\n /**\n * Deletes a document with the given document ID.\n * Returns a promise that resolves to an array containing the deleted document.\n *\n * @param id - Document ID to delete\n * @param options - Options for the mutation\n */\n delete<R extends Record<string, Any> = Record<string, Any>>(\n id: string,\n options: AllDocumentsMutationOptions,\n ): Promise<SanityDocument<R>[]>\n /**\n * Deletes a document with the given document ID.\n * Returns a promise that resolves to a mutation result object containing the deleted document ID.\n *\n * @param id - Document ID to delete\n * @param options - Options for the mutation\n */\n delete(id: string, options: FirstDocumentIdMutationOptions): Promise<SingleMutationResult>\n /**\n * Deletes a document with the given document ID.\n * Returns a promise that resolves to a mutation result object containing the deleted document ID.\n *\n * @param id - Document ID to delete\n * @param options - Options for the mutation\n */\n delete(id: string, options: AllDocumentIdsMutationOptions): Promise<MultipleMutationResult>\n /**\n * Deletes a document with the given document ID.\n * Returns a promise that resolves to the deleted document.\n *\n * @param id - Document ID to delete\n * @param options - Options for the mutation\n */\n delete<R extends Record<string, Any> = Record<string, Any>>(\n id: string,\n options?: BaseMutationOptions,\n ): Promise<SanityDocument<R>>\n /**\n * Deletes one or more documents matching the given query or document ID.\n * Returns a promise that resolves to first deleted document.\n *\n * @param selection - An object with either an `id` or `query` key defining what to delete\n * @param options - Options for the mutation\n */\n delete<R extends Record<string, Any> = Record<string, Any>>(\n selection: MutationSelection,\n options: FirstDocumentMutationOptions,\n ): Promise<SanityDocument<R>>\n /**\n * Deletes one or more documents matching the given query or document ID.\n * Returns a promise that resolves to an array containing the deleted documents.\n *\n * @param selection - An object with either an `id` or `query` key defining what to delete\n * @param options - Options for the mutation\n */\n delete<R extends Record<string, Any> = Record<string, Any>>(\n selection: MutationSelection,\n options: AllDocumentsMutationOptions,\n ): Promise<SanityDocument<R>[]>\n /**\n * Deletes one or more documents matching the given query or document ID.\n * Returns a promise that resolves to a mutation result object containing the ID of the first deleted document.\n *\n * @param selection - An object with either an `id` or `query` key defining what to delete\n * @param options - Options for the mutation\n */\n delete(\n selection: MutationSelection,\n options: FirstDocumentIdMutationOptions,\n ): Promise<SingleMutationResult>\n /**\n * Deletes one or more documents matching the given query or document ID.\n * Returns a promise that resolves to a mutation result object containing the document IDs that were deleted.\n *\n * @param selection - An object with either an `id` or `query` key defining what to delete\n * @param options - Options for the mutation\n */\n delete(\n selection: MutationSelection,\n options: AllDocumentIdsMutationOptions,\n ): Promise<MultipleMutationResult>\n /**\n * Deletes one or more documents matching the given query or document ID.\n * Returns a promise that resolves to first deleted document.\n *\n * @param selection - An object with either an `id` or `query` key defining what to delete\n * @param options - Options for the mutation\n */\n delete<R extends Record<string, Any> = Record<string, Any>>(\n selection: MutationSelection,\n options?: BaseMutationOptions,\n ): Promise<SanityDocument<R>>\n delete<R extends Record<string, Any> = Record<string, Any>>(\n selection: string | MutationSelection,\n options?:\n | AllDocumentIdsMutationOptions\n | AllDocumentsMutationOptions\n | BaseMutationOptions\n | FirstDocumentIdMutationOptions\n | FirstDocumentMutationOptions,\n ): Promise<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n return lastValueFrom(dataMethods._delete<R>(this, this.#httpRequest, selection, options))\n }\n\n /**\n * @public\n *\n * Deletes the draft or release version of a document.\n *\n * @remarks\n * * Discarding a version with no `releaseId` will discard the draft version of the published document.\n * * If the draft or release version does not exist, any error will throw.\n *\n * @param params - Version action parameters:\n * - `releaseId` - The ID of the release to discard the document from.\n * - `publishedId` - The published ID of the document to discard.\n * @param purge - if `true` the document history is also discarded.\n * @param options - Additional action options.\n * @returns a promise that resolves to the `transactionId`.\n *\n * @example Discarding a release version of a document\n * ```ts\n * client.discardVersion({publishedId: 'myDocument', releaseId: 'myRelease'})\n * // The document with the ID `versions.myRelease.myDocument` will be discarded.\n * ```\n *\n * @example Discarding a draft version of a document\n * ```ts\n * client.discardVersion({publishedId: 'myDocument'})\n * // The document with the ID `drafts.myDocument` will be discarded.\n * ```\n */\n discardVersion(\n {releaseId, publishedId}: {releaseId?: string; publishedId: string},\n purge?: boolean,\n options?: BaseActionOptions,\n ): Promise<SingleActionResult | MultipleActionResult> {\n const documentVersionId = getDocumentVersionId(publishedId, releaseId)\n\n return lastValueFrom(\n dataMethods._discardVersion(this, this.#httpRequest, documentVersionId, purge, options),\n )\n }\n\n /**\n * @public\n *\n * Replaces an existing version document.\n *\n * @remarks\n * * Requires a document with a `_type` property.\n * * 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`.\n * * If the `document._id` is not defined, it will be generated from `publishedId` and `releaseId`.\n * * Replacing a version with no `releaseId` will replace the draft version of the published document.\n * * At least one of the **version** or **published** documents must exist.\n *\n * @param params - Version action parameters:\n * - `document` - The new document to replace the version with.\n * - `releaseId` - The ID of the release where the document version is replaced.\n * - `publishedId` - The ID of the published document to replace.\n * @param options - Additional action options.\n * @returns a promise that resolves to the `transactionId`.\n *\n * @example Replacing a release version of a published document with a generated version ID\n * ```ts\n * await client.replaceVersion({\n * document: {_type: 'myDocument', title: 'My Document'},\n * publishedId: 'myDocument',\n * releaseId: 'myRelease',\n * })\n *\n * // The following document will be patched:\n * // {\n * // _id: 'versions.myRelease.myDocument',\n * // _type: 'myDocument',\n * // title: 'My Document',\n * // }\n * ```\n *\n * @example Replacing a release version of a published document with a specified version ID\n * ```ts\n * await client.replaceVersion({\n * document: {_type: 'myDocument', _id: 'versions.myRelease.myDocument', title: 'My Document'},\n * // `publishedId` and `releaseId` are not required since `document._id` has been specified\n * })\n *\n * // The following document will be patched:\n * // {\n * // _id: 'versions.myRelease.myDocument',\n * // _type: 'myDocument',\n * // title: 'My Document',\n * // }\n * ```\n *\n * @example Replacing a draft version of a published document\n * ```ts\n * await client.replaceVersion({\n * document: {_type: 'myDocument', title: 'My Document'},\n * publishedId: 'myDocument',\n * })\n *\n * // The following document will be patched:\n * // {\n * // _id: 'drafts.myDocument',\n * // _type: 'myDocument',\n * // title: 'My Document',\n * // }\n * ```\n */\n\n replaceVersion<R extends Record<string, Any>>(\n args: {\n document: SanityDocumentStub<R>\n publishedId: string\n releaseId?: string\n },\n options?: BaseActionOptions,\n ): Promise<SingleActionResult | MultipleActionResult>\n replaceVersion<R extends Record<string, Any>>(\n args: {\n document: IdentifiedSanityDocumentStub<R>\n publishedId?: string\n releaseId?: string\n },\n options?: BaseActionOptions,\n ): Promise<SingleActionResult | MultipleActionResult>\n replaceVersion<R extends Record<string, Any>>(\n {\n document,\n publishedId,\n releaseId,\n }: {\n document: SanityDocumentStub<R> | IdentifiedSanityDocumentStub<R>\n publishedId?: string\n releaseId?: string\n },\n options?: BaseActionOptions,\n ): Promise<SingleActionResult | MultipleActionResult> {\n const documentVersionId = deriveDocumentVersionId('replaceVersion', {\n document,\n publishedId,\n releaseId,\n })\n\n const documentVersion = {...document, _id: documentVersionId}\n\n return firstValueFrom(\n dataMethods._replaceVersion<R>(this, this.#httpRequest, documentVersion, options),\n )\n }\n\n /**\n * @public\n *\n * Used to indicate when a document within a release should be unpublished when\n * the release is run.\n *\n * @remarks\n * * If the published document does not exist, an error will be thrown.\n *\n * @param params - Version action parameters:\n * - `releaseId` - The ID of the release to unpublish the document from.\n * - `publishedId` - The published ID of the document to unpublish.\n * @param options - Additional action options.\n * @returns a promise that resolves to the `transactionId`.\n *\n * @example Unpublishing a release version of a published document\n * ```ts\n * await client.unpublishVersion({publishedId: 'myDocument', releaseId: 'myRelease'})\n * // The document with the ID `versions.myRelease.myDocument` will be unpublished. when `myRelease` is run.\n * ```\n */\n unpublishVersion(\n {releaseId, publishedId}: {releaseId: string; publishedId: string},\n options?: BaseActionOptions,\n ): Promise<SingleActionResult | MultipleActionResult> {\n const versionId = getVersionId(publishedId, releaseId)\n\n return lastValueFrom(\n dataMethods._unpublishVersion(this, this.#httpRequest, versionId, publishedId, options),\n )\n }\n\n /**\n * Perform mutation operations against the configured dataset\n * Returns a promise that resolves to the first mutated document.\n *\n * @param operations - Mutation operations to execute\n * @param options - Mutation options\n */\n mutate<R extends Record<string, Any> = Record<string, Any>>(\n operations: Mutation<R>[] | Patch | Transaction,\n options: FirstDocumentMutationOptions,\n ): Promise<SanityDocument<R>>\n /**\n * Perform mutation operations against the configured dataset.\n * Returns a promise that resolves to an array of the mutated documents.\n *\n * @param operations - Mutation operations to execute\n * @param options - Mutation options\n */\n mutate<R extends Record<string, Any> = Record<string, Any>>(\n operations: Mutation<R>[] | Patch | Transaction,\n options: AllDocumentsMutationOptions,\n ): Promise<SanityDocument<R>[]>\n /**\n * Perform mutation operations against the configured dataset\n * Returns a promise that resolves to a mutation result object containing the document ID of the first mutated document.\n *\n * @param operations - Mutation operations to execute\n * @param options - Mutation options\n */\n mutate<R extends Record<string, Any> = Record<string, Any>>(\n operations: Mutation<R>[] | Patch | Transaction,\n options: FirstDocumentIdMutationOptions,\n ): Promise<SingleMutationResult>\n /**\n * Perform mutation operations against the configured dataset\n * Returns a promise that resolves to a mutation result object containing the mutated document IDs.\n *\n * @param operations - Mutation operations to execute\n * @param options - Mutation options\n */\n mutate<R extends Record<string, Any> = Record<string, Any>>(\n operations: Mutation<R>[] | Patch | Transaction,\n options: AllDocumentIdsMutationOptions,\n ): Promise<MultipleMutationResult>\n /**\n * Perform mutation operations against the configured dataset\n * Returns a promise that resolves to the first mutated document.\n *\n * @param operations - Mutation operations to execute\n * @param options - Mutation options\n */\n mutate<R extends Record<string, Any> = Record<string, Any>>(\n operations: Mutation<R>[] | Patch | Transaction,\n options?: BaseMutationOptions,\n ): Promise<SanityDocument<R>>\n mutate<R extends Record<string, Any> = Record<string, Any>>(\n operations: Mutation<R>[] | Patch | Transaction,\n options?:\n | FirstDocumentMutationOptions\n | AllDocumentsMutationOptions\n | FirstDocumentIdMutationOptions\n | AllDocumentIdsMutationOptions\n | BaseMutationOptions,\n ): Promise<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n return lastValueFrom(dataMethods._mutate<R>(this, this.#httpRequest, operations, options))\n }\n\n /**\n * Create a new buildable patch of operations to perform\n *\n * @param documentId - Document ID to patch\n * @param operations - Optional object of patch operations to initialize the patch instance with\n * @returns Patch instance - call `.commit()` to perform the operations defined\n */\n patch(documentId: string, operations?: PatchOperations): Patch\n\n /**\n * Create a new buildable patch of operations to perform\n *\n * @param documentIds - Array of document IDs to patch\n * @param operations - Optional object of patch operations to initialize the patch instance with\n * @returns Patch instance - call `.commit()` to perform the operations defined\n */\n patch(documentIds: string[], operations?: PatchOperations): Patch\n\n /**\n * Create a new buildable patch of operations to perform\n *\n * @param selection - An object with `query` and optional `params`, defining which document(s) to patch\n * @param operations - Optional object of patch operations to initialize the patch instance with\n * @returns Patch instance - call `.commit()` to perform the operations defined\n */\n patch(selection: MutationSelection, operations?: PatchOperations): Patch\n\n /**\n * Create a new buildable patch of operations to perform\n *\n * @param selection - Document ID, an array of document IDs, or an object with `query` and optional `params`, defining which document(s) to patch\n * @param operations - Optional object of patch operations to initialize the patch instance with\n * @returns Patch instance - call `.commit()` to perform the operations defined\n */\n patch(documentId: PatchSelection, operations?: PatchOperations): Patch {\n return new Patch(documentId, operations, this)\n }\n\n /**\n * Create a new transaction of mutations\n *\n * @param operations - Optional array of mutation operations to initialize the transaction instance with\n */\n transaction<R extends Record<string, Any> = Record<string, Any>>(\n operations?: Mutation<R>[],\n ): Transaction {\n return new Transaction(operations, this)\n }\n\n /**\n * Perform action operations against the configured dataset\n * Returns a promise that resolves to the transaction result\n *\n * @param operations - Action operation(s) to execute\n * @param options - Action options\n */\n action(\n operations: Action | Action[],\n options?: BaseActionOptions,\n ): Promise<SingleActionResult | MultipleActionResult> {\n return lastValueFrom(dataMethods._action(this, this.#httpRequest, operations, options))\n }\n\n /**\n * Perform a request against the Sanity API\n * NOTE: Only use this for Sanity API endpoints, not for your own APIs!\n *\n * @param options - Request options\n * @returns Promise resolving to the response body\n */\n request<R = Any>(options: RawRequestOptions): Promise<R> {\n return lastValueFrom(dataMethods._request<R>(this, this.#httpRequest, options))\n }\n\n /**\n * Perform an HTTP request a `/data` sub-endpoint\n * NOTE: Considered internal, thus marked as deprecated. Use `request` instead.\n *\n * @deprecated - Use `request()` or your own HTTP library instead\n * @param endpoint - Endpoint to hit (mutate, query etc)\n * @param body - Request body\n * @param options - Request options\n * @internal\n */\n dataRequest(endpoint: string, body: unknown, options?: BaseMutationOptions): Promise<Any> {\n return lastValueFrom(dataMethods._dataRequest(this, this.#httpRequest, endpoint, body, options))\n }\n\n /**\n * Get a Sanity API URL for the URI provided\n *\n * @param uri - URI/path to build URL for\n * @param canUseCdn - Whether or not to allow using the API CDN for this route\n */\n getUrl(uri: string, canUseCdn?: boolean): string {\n return dataMethods._getUrl(this, uri, canUseCdn)\n }\n\n /**\n * Get a Sanity API URL for the data operation and path provided\n *\n * @param operation - Data operation (eg `query`, `mutate`, `listen` or similar)\n * @param path - Path to append after the operation\n */\n getDataUrl(operation: string, path?: string): string {\n return dataMethods._getDataUrl(this, operation, path)\n }\n}\n","import type {Middlewares} from 'get-it'\n\nimport {defineHttpRequest} from './http/request'\nimport type {Any, ClientConfig, HttpRequest} from './types'\n\nexport {validateApiPerspective} from './config'\nexport {\n ChannelError,\n connectEventSource,\n ConnectionFailedError,\n DisconnectError,\n type EventSourceEvent,\n type EventSourceInstance,\n MessageError,\n MessageParseError,\n type ServerSentEvent,\n} from './data/eventsource'\nexport * from './data/patch'\nexport * from './data/transaction'\nexport {\n ClientError,\n CorsOriginError,\n formatQueryParseError,\n type HttpError,\n isHttpError,\n isQueryParseError,\n ServerError,\n} from './http/errors'\nexport * from './SanityClient'\nexport * from './types'\n\n/** @alpha */\nexport {adapter as unstable__adapter, environment as unstable__environment} from 'get-it'\n\n/**\n * Create the `requester` and `createClient` exports, that have environment specific middleware for node and browsers\n * @internal\n */\nexport default function defineCreateClientExports<\n SanityClientType,\n ClientConfigType extends ClientConfig,\n>(\n envMiddleware: Middlewares,\n ClassConstructor: new (httpRequest: HttpRequest, config: ClientConfigType) => SanityClientType,\n) {\n // Set the http client to use for requests, and its environment specific middleware\n const defaultRequester = defineHttpRequest(envMiddleware)\n\n const createClient = (config: ClientConfigType) => {\n const clientRequester = defineHttpRequest(envMiddleware, {\n ignoreWarnings: config.ignoreWarnings,\n })\n return new ClassConstructor(\n (options, requester) =>\n (requester || clientRequester)({\n maxRedirects: 0,\n maxRetries: config.maxRetries,\n retryDelay: config.retryDelay,\n lineage: config.lineage,\n ...options,\n } as Any),\n config,\n )\n }\n\n return {requester: defaultRequester, createClient}\n}\n","import {printNoDefaultExport} from './warnings'\n\n/* @internal */\nexport function defineDeprecatedCreateClient<SanityClientType, ClientConfigType>(\n createClient: (config: ClientConfigType) => SanityClientType,\n) {\n return function deprecatedCreateClient(config: ClientConfigType) {\n printNoDefaultExport()\n return createClient(config)\n }\n}\n","export default []\n","import defineCreateClientExports, {type ClientConfig, SanityClient} from './defineCreateClient'\nimport {defineDeprecatedCreateClient} from './defineDeprecatedCreateClient'\nimport envMiddleware from './http/browserMiddleware'\n\nexport * from './defineCreateClient'\n\nconst exp = defineCreateClientExports<SanityClient, ClientConfig>(envMiddleware, SanityClient)\n\n/** @public */\nexport const requester = exp.requester\n\n/** @public */\nexport const createClient = exp.createClient\n\n/**\n * @public\n * @deprecated Use the named export `createClient` instead of the `default` export\n */\nconst deprecatedCreateClient = defineDeprecatedCreateClient(createClient)\nexport default deprecatedCreateClient\n"],"names":["location","projectId","envMiddleware","isQuery","warnings.printNoApiVersionSpecifiedWarning","validate.resourceConfig","warnings.printCredentialedTokenWarning","warnings.printBrowserTokenWarning","warnings.printCdnWarning","validate.projectId","validate.dataset","validate.requestTag","warnings.printCdnAndWithCredentialsWarning","merge","validators.validateObject","validators.requireDocumentId","validators.validateDocumentId","validators.requireDocumentType","validators.resourceConfig","uri","validators.hasDataset","dataset","observable","validators.validateAssetType","defaults","EventSource","validate.resourceGuard","finalize","map","dataMethods._fetch","dataMethods._getDocument","dataMethods._getDocuments","dataMethods._create","dataMethods._createIfNotExists","dataMethods._createOrReplace","dataMethods._createVersionFromBase","dataMethods._createVersion","dataMethods._delete","dataMethods._discardVersion","dataMethods._replaceVersion","dataMethods._unpublishVersion","dataMethods._mutate","dataMethods._action","dataMethods._request","dataMethods._getUrl","dataMethods._getDataUrl","dataMethods._dataRequest","requester","createClient"],"mappings":";;;;;;;;AAwBA,MAAM,UAAU;AAkBA,SAAA,UAAU,OAAeA,WAAwB,SAA0B;AACzF,QAAM,QAAQ,MAAM,MAAM,OAAO,GAC3B,MAAM;AAAA,IACV,OAAO,aAAaA,UAAS,OAAO,KAAK;AAAA,IACzC,KAAKA,UAAS,MAAM,aAAaA,UAAS,KAAK,KAAK,IAAI;AAAA,EAGpD,GAAA,EAAC,OAAO,KAAK,YAAW,IAAI,eAAe,KAAK,KAAK,GAErD,iBAAiB,GAAG,GAAG,GAAG;AAEhC,SAAO,MACJ,MAAM,SAAS,GAAG,EAClB,MAAM,OAAO,GAAG,EAChB,IAAI,CAAC,MAAM,UAAU;AACd,UAAA,SAAS,QAAQ,IAAI,OAErB,SAAS,IADM,IAAI,MAAM,GAAG,MAAM,CAAC,cAAc,CACxB,MACzB,YAAY,YAAY,MAAM,GAC9B,iBAAiB,CAAC,YAAY,SAAS,CAAC;AAC9C,QAAI,CAAC;AACI,aAAA,IAAI,MAAM,GAAG,KAAK,SAAS,IAAI,IAAI,IAAI,KAAK,EAAE;AAGvD,QAAI,aAAa;AACb,QAAA,MAAM,QAAQ,SAAS,GAAG;AACtB,YAAA,gBAAgB,KAAK,MAAM,GAAG,KAAK,IAAI,UAAU,CAAC,IAAI,GAAG,CAAC,CAAC,EAAE,QAAQ,UAAU,GAAG,GAClF,kBAAkB,UAAU,CAAC,KAAK;AAE3B,mBAAA;AAAA,QACX;AAAA;AAAA,QACA,OAAO,QAAQ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B;AAC1C,WAAA,qBAAA,GACdA,cAAa,MAAM;AAAA,EAC5B;AACF;ACVA,IAAA,gBAAe,CAAC;ACMhB,MAAM,MAAM,0BAAsD,eAAe,YAAY,GAGhF,YAAY,IAAI,WAGhB,eAAe,IAAI,cAM1B,yBAAyB,6BAA6B,YAAY;"}
|
|
1
|
+
{"version":3,"file":"index.browser.js","sources":["../src/util/codeFrame.ts","../src/http/errors.ts","../src/http/request.ts","../src/generateHelpUrl.ts","../src/validators.ts","../src/types.ts","../src/util/once.ts","../src/warnings.ts","../src/config.ts","../src/data/eventsource.ts","../src/util/getSelection.ts","../src/data/patch.ts","../src/data/transaction.ts","../src/http/requestOptions.ts","../src/data/encodeQueryString.ts","../src/data/dataMethods.ts","../src/agent/actions/generate.ts","../src/agent/actions/patch.ts","../src/agent/actions/prompt.ts","../src/agent/actions/transform.ts","../src/agent/actions/translate.ts","../src/agent/actions/AgentActionsClient.ts","../src/assets/AssetsClient.ts","../src/util/defaults.ts","../src/util/pick.ts","../src/data/eventsourcePolyfill.ts","../src/data/reconnectOnConnectionFailure.ts","../src/data/listen.ts","../src/util/shareReplayLatest.ts","../src/data/live.ts","../src/datasets/DatasetsClient.ts","../src/mediaLibrary/MediaLibraryVideoClient.ts","../src/projects/ProjectsClient.ts","../src/util/createVersionId.ts","../src/releases/createRelease.ts","../src/releases/ReleasesClient.ts","../src/users/UsersClient.ts","../src/SanityClient.ts","../src/defineCreateClient.ts","../src/defineDeprecatedCreateClient.ts","../src/http/browserMiddleware.ts","../src/index.browser.ts"],"sourcesContent":["/**\n * Inlined, modified version of the `codeFrameColumns` function from `@babel/code-frame`.\n * MIT-licensed - https://github.com/babel/babel/blob/main/LICENSE\n * Copyright (c) 2014-present Sebastian McKenzie and other contributors.\n */\ntype Location = {\n column: number\n line: number\n}\n\ntype NodeLocation = {\n start: Location\n end?: Location\n}\n\ntype GroqLocation = {\n start: number\n end?: number\n}\n\n/**\n * RegExp to test for newlines.\n */\n\nconst NEWLINE = /\\r\\n|[\\n\\r\\u2028\\u2029]/\n\n/**\n * Extract what lines should be marked and highlighted.\n */\n\ntype MarkerLines = Record<number, true | [number, number]>\n\n/**\n * Highlight a code frame with the given location and message.\n *\n * @param query - The query to be highlighted.\n * @param location - The location of the error in the code/query.\n * @param message - Message to be displayed inline (if possible) next to the highlighted\n * location in the code. If it can't be positioned inline, it will be placed above the\n * code frame.\n * @returns The highlighted code frame.\n */\nexport function codeFrame(query: string, location: GroqLocation, message?: string): string {\n const lines = query.split(NEWLINE)\n const loc = {\n start: columnToLine(location.start, lines),\n end: location.end ? columnToLine(location.end, lines) : undefined,\n }\n\n const {start, end, markerLines} = getMarkerLines(loc, lines)\n\n const numberMaxWidth = `${end}`.length\n\n return query\n .split(NEWLINE, end)\n .slice(start, end)\n .map((line, index) => {\n const number = start + 1 + index\n const paddedNumber = ` ${number}`.slice(-numberMaxWidth)\n const gutter = ` ${paddedNumber} |`\n const hasMarker = markerLines[number]\n const lastMarkerLine = !markerLines[number + 1]\n if (!hasMarker) {\n return ` ${gutter}${line.length > 0 ? ` ${line}` : ''}`\n }\n\n let markerLine = ''\n if (Array.isArray(hasMarker)) {\n const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\\t]/g, ' ')\n const numberOfMarkers = hasMarker[1] || 1\n\n markerLine = [\n '\\n ',\n gutter.replace(/\\d/g, ' '),\n ' ',\n markerSpacing,\n '^'.repeat(numberOfMarkers),\n ].join('')\n\n if (lastMarkerLine && message) {\n markerLine += ' ' + message\n }\n }\n return ['>', gutter, line.length > 0 ? ` ${line}` : '', markerLine].join('')\n })\n .join('\\n')\n}\n\nfunction getMarkerLines(\n loc: NodeLocation,\n source: Array<string>,\n): {\n start: number\n end: number\n markerLines: MarkerLines\n} {\n const startLoc: Location = {...loc.start}\n const endLoc: Location = {...startLoc, ...loc.end}\n const linesAbove = 2\n const linesBelow = 3\n const startLine = startLoc.line ?? -1\n const startColumn = startLoc.column ?? 0\n const endLine = endLoc.line\n const endColumn = endLoc.column\n\n let start = Math.max(startLine - (linesAbove + 1), 0)\n let end = Math.min(source.length, endLine + linesBelow)\n\n if (startLine === -1) {\n start = 0\n }\n\n if (endLine === -1) {\n end = source.length\n }\n\n const lineDiff = endLine - startLine\n const markerLines: MarkerLines = {}\n\n if (lineDiff) {\n for (let i = 0; i <= lineDiff; i++) {\n const lineNumber = i + startLine\n\n if (!startColumn) {\n markerLines[lineNumber] = true\n } else if (i === 0) {\n const sourceLength = source[lineNumber - 1].length\n\n markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1]\n } else if (i === lineDiff) {\n markerLines[lineNumber] = [0, endColumn]\n } else {\n const sourceLength = source[lineNumber - i].length\n\n markerLines[lineNumber] = [0, sourceLength]\n }\n }\n } else {\n if (startColumn === endColumn) {\n if (startColumn) {\n markerLines[startLine] = [startColumn, 0]\n } else {\n markerLines[startLine] = true\n }\n } else {\n markerLines[startLine] = [startColumn, endColumn - startColumn]\n }\n }\n\n return {start, end, markerLines}\n}\n\nfunction columnToLine(column: number, lines: string[]): Location {\n let offset = 0\n\n for (let i = 0; i < lines.length; i++) {\n const lineLength = lines[i].length + 1 // assume '\\n' after each line\n\n if (offset + lineLength > column) {\n return {\n line: i + 1, // 1-based line\n column: column - offset, // 0-based column\n }\n }\n\n offset += lineLength\n }\n\n // Fallback: beyond last line\n return {\n line: lines.length,\n column: lines[lines.length - 1]?.length ?? 0,\n }\n}\n","import type {HttpContext} from 'get-it'\n\nimport type {ActionError, Any, ErrorProps, MutationError, QueryParseError} from '../types'\nimport {codeFrame} from '../util/codeFrame'\nimport {isRecord} from '../util/isRecord'\n\nconst MAX_ITEMS_IN_ERROR_MESSAGE = 5\n\n/**\n * Shared properties for HTTP errors (eg both ClientError and ServerError)\n * Use `isHttpError` for type narrowing and accessing response properties.\n *\n * @public\n */\nexport interface HttpError {\n statusCode: number\n message: string\n response: {\n body: unknown\n url: string\n method: string\n headers: Record<string, string>\n statusCode: number\n statusMessage: string | null\n }\n}\n\n/**\n * Checks if the provided error is an HTTP error.\n *\n * @param error - The error to check.\n * @returns `true` if the error is an HTTP error, `false` otherwise.\n * @public\n */\nexport function isHttpError(error: unknown): error is HttpError {\n if (!isRecord(error)) {\n return false\n }\n\n const response = error.response\n if (\n typeof error.statusCode !== 'number' ||\n typeof error.message !== 'string' ||\n !isRecord(response)\n ) {\n return false\n }\n\n if (\n typeof response.body === 'undefined' ||\n typeof response.url !== 'string' ||\n typeof response.method !== 'string' ||\n typeof response.headers !== 'object' ||\n typeof response.statusCode !== 'number'\n ) {\n return false\n }\n\n return true\n}\n\n/** @public */\nexport class ClientError extends Error {\n response: ErrorProps['response']\n statusCode: ErrorProps['statusCode'] = 400\n responseBody: ErrorProps['responseBody']\n details: ErrorProps['details']\n\n constructor(res: Any, context?: HttpContext) {\n const props = extractErrorProps(res, context)\n super(props.message)\n Object.assign(this, props)\n }\n}\n\n/** @public */\nexport class ServerError extends Error {\n response: ErrorProps['response']\n statusCode: ErrorProps['statusCode'] = 500\n responseBody: ErrorProps['responseBody']\n details: ErrorProps['details']\n\n constructor(res: Any) {\n const props = extractErrorProps(res)\n super(props.message)\n Object.assign(this, props)\n }\n}\n\nfunction extractErrorProps(res: Any, context?: HttpContext): ErrorProps {\n const body = res.body\n const props = {\n response: res,\n statusCode: res.statusCode,\n responseBody: stringifyBody(body, res),\n message: '',\n details: undefined as Any,\n }\n\n // Fall back early if we didn't get a JSON object returned as expected\n if (!isRecord(body)) {\n props.message = httpErrorMessage(res, body)\n return props\n }\n\n const error = body.error\n\n // API/Boom style errors ({statusCode, error, message})\n if (typeof error === 'string' && typeof body.message === 'string') {\n props.message = `${error} - ${body.message}`\n return props\n }\n\n // Content Lake errors with a `error` prop being an object\n if (typeof error !== 'object' || error === null) {\n if (typeof error === 'string') {\n props.message = error\n } else if (typeof body.message === 'string') {\n props.message = body.message\n } else {\n props.message = httpErrorMessage(res, body)\n }\n return props\n }\n\n // Mutation errors (specifically)\n if (isMutationError(error) || isActionError(error)) {\n const allItems = error.items || []\n const items = allItems\n .slice(0, MAX_ITEMS_IN_ERROR_MESSAGE)\n .map((item) => item.error?.description)\n .filter(Boolean)\n let itemsStr = items.length ? `:\\n- ${items.join('\\n- ')}` : ''\n if (allItems.length > MAX_ITEMS_IN_ERROR_MESSAGE) {\n itemsStr += `\\n...and ${allItems.length - MAX_ITEMS_IN_ERROR_MESSAGE} more`\n }\n props.message = `${error.description}${itemsStr}`\n props.details = body.error\n return props\n }\n\n // Query parse errors\n if (isQueryParseError(error)) {\n const tag = context?.options?.query?.tag\n props.message = formatQueryParseError(error, tag)\n props.details = body.error\n return props\n }\n\n if ('description' in error && typeof error.description === 'string') {\n // Query/database errors ({error: {description, other, arb, props}})\n props.message = error.description\n props.details = error\n return props\n }\n\n // Other, more arbitrary errors\n props.message = httpErrorMessage(res, body)\n return props\n}\n\nfunction isMutationError(error: object): error is MutationError {\n return (\n 'type' in error &&\n error.type === 'mutationError' &&\n 'description' in error &&\n typeof error.description === 'string'\n )\n}\n\nfunction isActionError(error: object): error is ActionError {\n return (\n 'type' in error &&\n error.type === 'actionError' &&\n 'description' in error &&\n typeof error.description === 'string'\n )\n}\n\n/** @internal */\nexport function isQueryParseError(error: object): error is QueryParseError {\n return (\n isRecord(error) &&\n error.type === 'queryParseError' &&\n typeof error.query === 'string' &&\n typeof error.start === 'number' &&\n typeof error.end === 'number'\n )\n}\n\n/**\n * Formats a GROQ query parse error into a human-readable string.\n *\n * @param error - The error object containing details about the parse error.\n * @param tag - An optional tag to include in the error message.\n * @returns A formatted error message string.\n * @public\n */\nexport function formatQueryParseError(error: QueryParseError, tag?: string | null) {\n const {query, start, end, description} = error\n\n if (!query || typeof start === 'undefined') {\n return `GROQ query parse error: ${description}`\n }\n\n const withTag = tag ? `\\n\\nTag: ${tag}` : ''\n const framed = codeFrame(query, {start, end}, description)\n\n return `GROQ query parse error:\\n${framed}${withTag}`\n}\n\nfunction httpErrorMessage(res: Any, body: unknown) {\n const details = typeof body === 'string' ? ` (${sliceWithEllipsis(body, 100)})` : ''\n const statusMessage = res.statusMessage ? ` ${res.statusMessage}` : ''\n return `${res.method}-request to ${res.url} resulted in HTTP ${res.statusCode}${statusMessage}${details}`\n}\n\nfunction stringifyBody(body: Any, res: Any) {\n const contentType = (res.headers['content-type'] || '').toLowerCase()\n const isJson = contentType.indexOf('application/json') !== -1\n return isJson ? JSON.stringify(body, null, 2) : body\n}\n\nfunction sliceWithEllipsis(str: string, max: number) {\n return str.length > max ? `${str.slice(0, max)}…` : str\n}\n\n/** @public */\nexport class CorsOriginError extends Error {\n projectId: string\n addOriginUrl?: URL\n\n constructor({projectId}: {projectId: string}) {\n super('CorsOriginError')\n this.name = 'CorsOriginError'\n this.projectId = projectId\n\n const url = new URL(`https://sanity.io/manage/project/${projectId}/api`)\n if (typeof location !== 'undefined') {\n const {origin} = location\n url.searchParams.set('cors', 'add')\n url.searchParams.set('origin', origin)\n this.addOriginUrl = url\n this.message = `The current origin is not allowed to connect to the Live Content API. Add it here: ${url}`\n } else {\n this.message = `The current origin is not allowed to connect to the Live Content API. Change your configuration here: ${url}`\n }\n }\n}\n","import {getIt, type HttpContext, type Middlewares, type Requester} from 'get-it'\nimport {jsonRequest, jsonResponse, observable, progress, retry} from 'get-it/middleware'\nimport {Observable} from 'rxjs'\n\nimport type {Any} from '../types'\nimport {ClientError, ServerError} from './errors'\n\nconst httpError = {\n onResponse: (res: Any, context: HttpContext) => {\n if (res.statusCode >= 500) {\n throw new ServerError(res)\n } else if (res.statusCode >= 400) {\n throw new ClientError(res, context)\n }\n\n return res\n },\n}\n\nfunction printWarnings(config: {ignoreWarnings?: string | RegExp | Array<string | RegExp>} = {}) {\n const seen: Record<string, boolean> = {}\n\n // Helper function to check if a warning should be ignored\n const shouldIgnoreWarning = (message: string): boolean => {\n if (config.ignoreWarnings === undefined) return false\n\n const patterns = Array.isArray(config.ignoreWarnings)\n ? config.ignoreWarnings\n : [config.ignoreWarnings]\n\n return patterns.some((pattern) => {\n if (typeof pattern === 'string') {\n return message.includes(pattern)\n } else if (pattern instanceof RegExp) {\n return pattern.test(message)\n }\n return false\n })\n }\n\n return {\n onResponse: (res: Any) => {\n const warn = res.headers['x-sanity-warning']\n const warnings = Array.isArray(warn) ? warn : [warn]\n for (const msg of warnings) {\n if (!msg || seen[msg]) continue\n\n // Skip warnings that match ignore patterns\n if (shouldIgnoreWarning(msg)) {\n continue\n }\n\n seen[msg] = true\n console.warn(msg) // eslint-disable-line no-console\n }\n return res\n },\n }\n}\n\ntype HttpRequestConfig = {\n ignoreWarnings?: string | RegExp | Array<string | RegExp>\n}\n\n/** @internal */\nexport function defineHttpRequest(\n envMiddleware: Middlewares,\n config: HttpRequestConfig = {},\n): Requester {\n return getIt([\n retry({shouldRetry}),\n ...envMiddleware,\n printWarnings(config),\n jsonRequest(),\n jsonResponse(),\n progress(),\n httpError,\n observable({implementation: Observable}),\n ])\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction shouldRetry(err: any, attempt: number, options: any) {\n // Allow opting out of retries\n if (options.maxRetries === 0) return false\n\n // By default `retry.shouldRetry` doesn't retry on server errors so we add our own logic.\n\n const isSafe = options.method === 'GET' || options.method === 'HEAD'\n const uri = options.uri || options.url\n const isQuery = uri.startsWith('/data/query')\n const isRetriableResponse =\n err.response &&\n (err.response.statusCode === 429 ||\n err.response.statusCode === 502 ||\n err.response.statusCode === 503)\n\n // We retry the following errors:\n // - 429 means that the request was rate limited. It's a bit difficult\n // to know exactly how long it makes sense to wait and/or how many\n // attempts we should retry, but the backoff should alleviate the\n // additional load.\n // - 502/503 can occur when certain components struggle to talk to their\n // upstream dependencies. This is most likely a temporary problem\n // and retrying makes sense.\n\n if ((isSafe || isQuery) && isRetriableResponse) return true\n\n return retry.shouldRetry(err, attempt, options)\n}\n","const BASE_URL = 'https://www.sanity.io/help/'\n\nexport function generateHelpUrl(slug: string) {\n return BASE_URL + slug\n}\n","import type {Any, InitializedClientConfig, SanityDocumentStub} from './types'\n\nconst VALID_ASSET_TYPES = ['image', 'file']\nconst VALID_INSERT_LOCATIONS = ['before', 'after', 'replace']\n\nexport const dataset = (name: string) => {\n if (!/^(~[a-z0-9]{1}[-\\w]{0,63}|[a-z0-9]{1}[-\\w]{0,63})$/.test(name)) {\n throw new Error(\n 'Datasets can only contain lowercase characters, numbers, underscores and dashes, and start with tilde, and be maximum 64 characters',\n )\n }\n}\n\nexport const projectId = (id: string) => {\n if (!/^[-a-z0-9]+$/i.test(id)) {\n throw new Error('`projectId` can only contain only a-z, 0-9 and dashes')\n }\n}\n\nexport const validateAssetType = (type: string) => {\n if (VALID_ASSET_TYPES.indexOf(type) === -1) {\n throw new Error(`Invalid asset type: ${type}. Must be one of ${VALID_ASSET_TYPES.join(', ')}`)\n }\n}\n\nexport const validateObject = (op: string, val: Any) => {\n if (val === null || typeof val !== 'object' || Array.isArray(val)) {\n throw new Error(`${op}() takes an object of properties`)\n }\n}\n\nexport const validateDocumentId = (op: string, id: string) => {\n if (typeof id !== 'string' || !/^[a-z0-9_][a-z0-9_.-]{0,127}$/i.test(id) || id.includes('..')) {\n throw new Error(`${op}(): \"${id}\" is not a valid document ID`)\n }\n}\n\nexport const requireDocumentId = (op: string, doc: Record<string, Any>) => {\n if (!doc._id) {\n throw new Error(`${op}() requires that the document contains an ID (\"_id\" property)`)\n }\n\n validateDocumentId(op, doc._id)\n}\n\nexport const validateDocumentType = (op: string, type: string) => {\n if (typeof type !== 'string') {\n throw new Error(`\\`${op}()\\`: \\`${type}\\` is not a valid document type`)\n }\n}\n\nexport const requireDocumentType = (op: string, doc: Record<string, Any>) => {\n if (!doc._type) {\n throw new Error(`\\`${op}()\\` requires that the document contains a type (\\`_type\\` property)`)\n }\n\n validateDocumentType(op, doc._type)\n}\n\nexport const validateVersionIdMatch = (builtVersionId: string, document: SanityDocumentStub) => {\n if (document._id && document._id !== builtVersionId) {\n throw new Error(\n `The provided document ID (\\`${document._id}\\`) does not match the generated version ID (\\`${builtVersionId}\\`)`,\n )\n }\n}\n\nexport const validateInsert = (at: string, selector: string, items: Any[]) => {\n const signature = 'insert(at, selector, items)'\n if (VALID_INSERT_LOCATIONS.indexOf(at) === -1) {\n const valid = VALID_INSERT_LOCATIONS.map((loc) => `\"${loc}\"`).join(', ')\n throw new Error(`${signature} takes an \"at\"-argument which is one of: ${valid}`)\n }\n\n if (typeof selector !== 'string') {\n throw new Error(`${signature} takes a \"selector\"-argument which must be a string`)\n }\n\n if (!Array.isArray(items)) {\n throw new Error(`${signature} takes an \"items\"-argument which must be an array`)\n }\n}\n\nexport const hasDataset = (config: InitializedClientConfig): string => {\n // Check if dataset is directly on the config\n if (config.dataset) {\n return config.dataset\n }\n\n // Check if dataset is in resource configuration\n // Note: ~experimental_resource is normalized to resource during client initialization\n const resource = config.resource\n if (resource && resource.type === 'dataset') {\n const segments = resource.id.split('.')\n if (segments.length !== 2) {\n throw new Error('Dataset resource ID must be in the format \"project.dataset\"')\n }\n return segments[1]\n }\n\n throw new Error('`dataset` must be provided to perform queries')\n}\n\nexport const requestTag = (tag: string) => {\n if (typeof tag !== 'string' || !/^[a-z0-9._-]{1,75}$/i.test(tag)) {\n throw new Error(\n `Tag can only contain alphanumeric characters, underscores, dashes and dots, and be between one and 75 characters long.`,\n )\n }\n\n return tag\n}\n\nexport const resourceConfig = (config: InitializedClientConfig): void => {\n // Note: ~experimental_resource is normalized to resource during client initialization\n const resource = config.resource\n if (!resource) {\n throw new Error('`resource` must be provided to perform resource queries')\n }\n const {type, id} = resource\n\n switch (type) {\n case 'dataset': {\n const segments = id.split('.')\n if (segments.length !== 2) {\n throw new Error('Dataset resource ID must be in the format \"project.dataset\"')\n }\n return\n }\n case 'dashboard':\n case 'media-library':\n case 'canvas': {\n return\n }\n default:\n // @ts-expect-error - handle all supported resource types\n throw new Error(`Unsupported resource type: ${type.toString()}`)\n }\n}\n\nexport const resourceGuard = (service: string, config: InitializedClientConfig): void => {\n // Note: ~experimental_resource is normalized to resource during client initialization\n const resource = config.resource\n if (resource) {\n throw new Error(`\\`${service}\\` does not support resource-based operations`)\n }\n}\n","// deno-lint-ignore-file no-empty-interface\n/* eslint-disable @typescript-eslint/no-empty-object-type */\n\nimport type {Requester} from 'get-it'\n\nimport type {InitializedStegaConfig, StegaConfig} from './stega/types'\n\n/**\n * Used to tag types that is set to `any` as a temporary measure, but should be replaced with proper typings in the future\n * @internal\n */\nexport type Any = any // eslint-disable-line @typescript-eslint/no-explicit-any\n\ndeclare global {\n // Declare empty stub interfaces for environments where \"dom\" lib is not included\n interface File {}\n}\n\n/** @public */\nexport type UploadBody = File | Blob | Buffer | NodeJS.ReadableStream\n\n/** @public */\nexport interface RequestOptions {\n timeout?: number\n token?: string\n tag?: string\n headers?: Record<string, string>\n method?: string\n query?: Any\n body?: Any\n signal?: AbortSignal\n}\n\n/**\n * @public\n * @deprecated – The `r`-prefix is not required, use `string` instead\n */\nexport type ReleaseId = `r${string}`\n\n/**\n * @deprecated use 'drafts' instead\n */\ntype DeprecatedPreviewDrafts = 'previewDrafts'\n\n/** @public */\nexport type StackablePerspective = ('published' | 'drafts' | string) & {}\n\n/** @public */\nexport type ClientPerspective =\n | DeprecatedPreviewDrafts\n | 'published'\n | 'drafts'\n | 'raw'\n | StackablePerspective[]\n\ntype ClientConfigResource =\n | {\n type: 'canvas'\n id: string\n }\n | {\n type: 'media-library'\n id: string\n }\n | {\n type: 'dataset'\n id: string\n }\n | {\n type: 'dashboard'\n id: string\n }\n\n/** @public */\nexport interface ClientConfig {\n projectId?: string\n dataset?: string\n /** @defaultValue true */\n useCdn?: boolean\n token?: string\n\n /**\n * Configure the client to work with a specific Sanity resource (Media Library, Canvas, etc.)\n * @remarks\n * This allows the client to interact with resources beyond traditional project datasets.\n * When configured, methods like `fetch()`, `assets.upload()`, and mutations will operate on the specified resource.\n * @example\n * ```ts\n * createClient({\n * resource: {\n * type: 'media-library',\n * id: 'your-media-library-id'\n * }\n * })\n * ```\n */\n resource?: ClientConfigResource\n\n /**\n * @deprecated Use `resource` instead\n * @internal\n */\n '~experimental_resource'?: ClientConfigResource\n\n /**\n * What perspective to use for the client. See {@link https://www.sanity.io/docs/perspectives|perspective documentation}\n * @remarks\n * 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}\n * @defaultValue 'published'\n */\n perspective?: ClientPerspective\n apiHost?: string\n\n /**\n @remarks\n * 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}\n */\n apiVersion?: string\n proxy?: string\n\n /**\n * Optional request tag prefix for all request tags\n */\n requestTagPrefix?: string\n\n /**\n * Optional default headers to include with all requests\n *\n * @remarks request-specific headers will override any default headers with the same name.\n */\n headers?: Record<string, string>\n\n ignoreBrowserTokenWarning?: boolean\n /**\n * Ignore specific warning messages from the client.\n *\n * @remarks\n * - String values perform substring matching (not exact matching) against warning messages\n * - RegExp values are tested against the full warning message\n * - Array values allow multiple patterns to be specified\n *\n * @example\n * ```typescript\n * // Ignore warnings containing \"experimental\"\n * ignoreWarnings: 'experimental'\n *\n * // Ignore multiple warning types\n * ignoreWarnings: ['experimental', 'deprecated']\n *\n * // Use regex for exact matching\n * ignoreWarnings: /^This is an experimental API version$/\n *\n * // Mix strings and regex patterns\n * ignoreWarnings: ['rate limit', /^deprecated/i]\n * ```\n */\n ignoreWarnings?: string | RegExp | Array<string | RegExp>\n withCredentials?: boolean\n allowReconfigure?: boolean\n timeout?: number\n\n /** Number of retries for requests. Defaults to 5. */\n maxRetries?: number\n\n /**\n * The amount of time, in milliseconds, to wait before retrying, given an attemptNumber (starting at 0).\n *\n * Defaults to exponential back-off, starting at 100ms, doubling for each attempt, together with random\n * jitter between 0 and 100 milliseconds. More specifically the following algorithm is used:\n *\n * Delay = 100 * 2^attemptNumber + randomNumberBetween0and100\n */\n retryDelay?: (attemptNumber: number) => number\n\n /**\n * @deprecated Don't use\n */\n useProjectHostname?: boolean\n\n /**\n * @deprecated Don't use\n */\n requester?: Requester\n\n /**\n * Adds a `resultSourceMap` key to the API response, with the type `ContentSourceMap`\n */\n resultSourceMap?: boolean | 'withKeyArraySelector'\n /**\n *@deprecated set `cache` and `next` options on `client.fetch` instead\n */\n fetch?:\n | {\n cache?: ResponseQueryOptions['cache']\n next?: ResponseQueryOptions['next']\n }\n | boolean\n /**\n * Options for how, if enabled, Content Source Maps are encoded into query results using steganography\n */\n stega?: StegaConfig | boolean\n /**\n * Lineage token for recursion control\n */\n lineage?: string\n}\n\n/** @public */\nexport interface InitializedClientConfig extends ClientConfig {\n // These are required in the initialized config\n apiHost: string\n apiVersion: string\n useProjectHostname: boolean\n useCdn: boolean\n // These are added by the initConfig function\n /**\n * @deprecated Internal, don't use\n */\n isDefaultApi: boolean\n /**\n * @deprecated Internal, don't use\n */\n url: string\n /**\n * @deprecated Internal, don't use\n */\n cdnUrl: string\n /**\n * The fully initialized stega config, can be used to check if stega is enabled\n */\n stega: InitializedStegaConfig\n /**\n * Default headers to include with all requests\n *\n * @remarks request-specific headers will override any default headers with the same name.\n */\n headers?: Record<string, string>\n}\n\n/** @public */\nexport type AssetMetadataType =\n | 'location'\n | 'exif'\n | 'image'\n | 'palette'\n | 'lqip'\n | 'blurhash'\n | 'thumbhash'\n | 'none'\n\n/** @public */\nexport interface UploadClientConfig {\n /**\n * Optional request tag for the upload\n */\n tag?: string\n\n /**\n * Whether or not to preserve the original filename (default: true)\n */\n preserveFilename?: boolean\n\n /**\n * Filename for this file (optional)\n */\n filename?: string\n\n /**\n * Milliseconds to wait before timing the request out\n */\n timeout?: number\n\n /**\n * Mime type of the file\n */\n contentType?: string\n\n /**\n * Array of metadata parts to extract from asset\n */\n extract?: AssetMetadataType[]\n\n /**\n * Optional freeform label for the asset. Generally not used.\n */\n label?: string\n\n /**\n * Optional title for the asset\n */\n title?: string\n\n /**\n * Optional description for the asset\n */\n description?: string\n\n /**\n * The credit to person(s) and/or organization(s) required by the supplier of the asset to be used when published\n */\n creditLine?: string\n\n /**\n * Source data (when the asset is from an external service)\n */\n source?: {\n /**\n * The (u)id of the asset within the source, i.e. 'i-f323r1E'\n */\n id: string\n\n /**\n * The name of the source, i.e. 'unsplash'\n */\n name: string\n\n /**\n * A url to where to find the asset, or get more info about it in the source\n */\n url?: string\n }\n}\n\n/** @internal */\nexport interface SanityReference {\n _ref: string\n}\n\n/** @internal */\nexport type SanityDocument<T extends Record<string, Any> = Record<string, Any>> = {\n [P in keyof T]: T[P]\n} & {\n _id: string\n _rev: string\n _type: string\n _createdAt: string\n _updatedAt: string\n /**\n * Present when `perspective` is set to `previewDrafts`\n */\n _originalId?: string\n}\n\n/** @internal */\nexport interface SanityAssetDocument extends SanityDocument {\n url: string\n path: string\n size: number\n assetId: string\n mimeType: string\n sha1hash: string\n extension: string\n uploadId?: string\n originalFilename?: string\n}\n\n/** @internal */\nexport interface SanityImagePalette {\n background: string\n foreground: string\n population: number\n title: string\n}\n\n/** @internal */\nexport interface SanityImageAssetDocument extends SanityAssetDocument {\n metadata: {\n _type: 'sanity.imageMetadata'\n hasAlpha: boolean\n isOpaque: boolean\n lqip?: string\n blurHash?: string\n thumbHash?: string\n dimensions: {\n _type: 'sanity.imageDimensions'\n aspectRatio: number\n height: number\n width: number\n }\n palette?: {\n _type: 'sanity.imagePalette'\n darkMuted?: SanityImagePalette\n darkVibrant?: SanityImagePalette\n dominant?: SanityImagePalette\n lightMuted?: SanityImagePalette\n lightVibrant?: SanityImagePalette\n muted?: SanityImagePalette\n vibrant?: SanityImagePalette\n }\n image?: {\n _type: 'sanity.imageExifTags'\n [key: string]: Any\n }\n exif?: {\n _type: 'sanity.imageExifMetadata'\n [key: string]: Any\n }\n }\n}\n\n/** @public */\nexport interface ErrorProps {\n message: string\n response: Any\n statusCode: number\n responseBody: Any\n details: Any\n}\n\n/** @public */\nexport type HttpRequest = {\n (options: RequestOptions, requester: Requester): ReturnType<Requester>\n}\n\n/** @internal */\nexport interface RequestObservableOptions extends Omit<RequestOptions, 'url'> {\n url?: string\n uri?: string\n canUseCdn?: boolean\n useCdn?: boolean\n tag?: string\n returnQuery?: boolean\n resultSourceMap?: boolean | 'withKeyArraySelector'\n perspective?: ClientPerspective\n lastLiveEventId?: string\n cacheMode?: 'noStale'\n}\n\n/** @public */\nexport interface ProgressEvent {\n type: 'progress'\n stage: 'upload' | 'download'\n percent: number\n total?: number\n loaded?: number\n lengthComputable: boolean\n}\n\n/** @public */\nexport interface ResponseEvent<T = unknown> {\n type: 'response'\n body: T\n url: string\n method: string\n statusCode: number\n statusMessage?: string\n headers: Record<string, string>\n}\n\n/** @public */\nexport type HttpRequestEvent<T = unknown> = ResponseEvent<T> | ProgressEvent\n\n/** @internal */\nexport interface AuthProvider {\n name: string\n title: string\n url: string\n}\n\n/** @internal */\nexport type AuthProviderResponse = {providers: AuthProvider[]}\n\n/** @public */\nexport type DatasetAclMode = 'public' | 'private' | 'custom'\n\n/** @public */\nexport type DatasetResponse = {datasetName: string; aclMode: DatasetAclMode}\n/** @public */\nexport type DatasetsResponse = {\n name: string\n aclMode: DatasetAclMode\n createdAt: string\n createdByUserId: string\n addonFor: string | null\n datasetProfile: string\n features: string[]\n tags: string[]\n}[]\n\n/** @public */\nexport interface SanityProjectMember {\n id: string\n role: string\n isRobot: boolean\n isCurrentUser: boolean\n}\n\n/** @public */\nexport interface SanityProject {\n id: string\n displayName: string\n /**\n * @deprecated Use the `/user-applications` endpoint instead, which lists all deployed studios/applications\n * @see https://www.sanity.io/help/studio-host-user-applications\n */\n studioHost: string | null\n organizationId: string | null\n isBlocked: boolean\n isDisabled: boolean\n isDisabledByUser: boolean\n createdAt: string\n pendingInvites?: number\n maxRetentionDays?: number\n members: SanityProjectMember[]\n metadata: {\n cliInitializedAt?: string\n color?: string\n /**\n * @deprecated Use the `/user-applications` endpoint instead, which lists all deployed studios/applications\n * @see https://www.sanity.io/help/studio-host-user-applications\n */\n externalStudioHost?: string\n }\n}\n\n/** @public */\nexport interface SanityUser {\n id: string\n projectId: string\n displayName: string\n familyName: string | null\n givenName: string | null\n middleName: string | null\n imageUrl: string | null\n createdAt: string\n updatedAt: string\n isCurrentUser: boolean\n}\n\n/** @public */\nexport interface CurrentSanityUser {\n id: string\n name: string\n email: string\n profileImage: string | null\n role: string\n provider: string\n}\n\n/** @public */\nexport type SanityDocumentStub<T extends Record<string, Any> = Record<string, Any>> = {\n [P in keyof T]: T[P]\n} & {\n _type: string\n}\n\n/** @public */\nexport type IdentifiedSanityDocumentStub<T extends Record<string, Any> = Record<string, Any>> = {\n [P in keyof T]: T[P]\n} & {\n _id: string\n} & SanityDocumentStub\n\n/** @internal */\nexport type InsertPatch =\n | {before: string; items: Any[]}\n | {after: string; items: Any[]}\n | {replace: string; items: Any[]}\n\n// Note: this is actually incorrect/invalid, but implemented as-is for backwards compatibility\n/** @internal */\nexport interface PatchOperations {\n set?: {[key: string]: Any}\n setIfMissing?: {[key: string]: Any}\n diffMatchPatch?: {[key: string]: Any}\n unset?: string[]\n inc?: {[key: string]: number}\n dec?: {[key: string]: number}\n insert?: InsertPatch\n ifRevisionID?: string\n}\n\n/** @public */\nexport interface QueryParams {\n /* eslint-disable @typescript-eslint/no-explicit-any */\n [key: string]: any\n /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */\n body?: never\n /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */\n cache?: 'next' extends keyof RequestInit ? never : any\n /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */\n filterResponse?: never\n /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */\n headers?: never\n /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */\n method?: never\n /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */\n next?: 'next' extends keyof RequestInit ? never : any\n /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */\n perspective?: never\n /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */\n query?: never\n /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */\n resultSourceMap?: never\n /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */\n returnQuery?: never\n /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */\n signal?: never\n /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */\n stega?: never\n /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */\n tag?: never\n /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */\n timeout?: never\n /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */\n token?: never\n /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */\n useCdn?: never\n /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */\n lastLiveEventId?: never\n /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */\n cacheMode?: never\n /* eslint-enable @typescript-eslint/no-explicit-any */\n}\n\n/**\n * This type can be used with `client.fetch` to indicate that the query has no GROQ parameters.\n * @public\n */\nexport type QueryWithoutParams = Record<string, never> | undefined\n\n/** @internal */\nexport type MutationSelectionQueryParams = {[key: string]: Any}\n/** @internal */\nexport type MutationSelection =\n | {query: string; params?: MutationSelectionQueryParams}\n | {id: string | string[]}\n/** @internal */\nexport type PatchSelection = string | string[] | MutationSelection\n/** @internal */\nexport type PatchMutationOperation = PatchOperations & MutationSelection\n\n/** @public */\nexport type Mutation<R extends Record<string, Any> = Record<string, Any>> =\n | {create: SanityDocumentStub<R>}\n | {createOrReplace: IdentifiedSanityDocumentStub<R>}\n | {createIfNotExists: IdentifiedSanityDocumentStub<R>}\n | {delete: MutationSelection}\n | {patch: PatchMutationOperation}\n\n/** @public */\nexport type ReleaseAction =\n | CreateReleaseAction\n | EditReleaseAction\n | PublishReleaseAction\n | ArchiveReleaseAction\n | UnarchiveReleaseAction\n | ScheduleReleaseAction\n | UnscheduleReleaseAction\n | DeleteReleaseAction\n | ImportReleaseAction\n\n/** @public */\nexport type VersionAction =\n | CreateVersionAction\n | DiscardVersionAction\n | ReplaceVersionAction\n | UnpublishVersionAction\n\n/** @public */\nexport type Action =\n | CreateAction\n | ReplaceDraftAction\n | EditAction\n | DeleteAction\n | DiscardAction\n | PublishAction\n | UnpublishAction\n | VersionAction\n | ReleaseAction\n\n/** @public */\nexport type ImportReleaseAction =\n | {\n actionType: 'sanity.action.release.import'\n attributes: IdentifiedSanityDocumentStub\n releaseId: string\n ifExists: 'fail' | 'ignore' | 'replace'\n }\n | {\n actionType: 'sanity.action.release.import'\n document: IdentifiedSanityDocumentStub\n releaseId: string\n ifExists: 'fail' | 'ignore' | 'replace'\n }\n\n/**\n * Creates a new release under the given id, with metadata.\n *\n * @public\n */\nexport interface CreateReleaseAction {\n actionType: 'sanity.action.release.create'\n releaseId: string\n metadata?: Partial<ReleaseDocument['metadata']>\n}\n\n/**\n * Edits an existing release, updating the metadata.\n *\n * @public\n */\nexport interface EditReleaseAction {\n actionType: 'sanity.action.release.edit'\n releaseId: string\n patch: PatchOperations\n}\n\n/**\n * Publishes all documents in a release at once.\n *\n * @public\n */\nexport interface PublishReleaseAction {\n actionType: 'sanity.action.release.publish'\n releaseId: string\n}\n\n/**\n * Archives an `active` release, and deletes all the release documents.\n *\n * @public\n */\nexport interface ArchiveReleaseAction {\n actionType: 'sanity.action.release.archive'\n releaseId: string\n}\n\n/**\n * Unarchived an `archived` release, and restores all the release documents.\n *\n * @public\n */\nexport interface UnarchiveReleaseAction {\n actionType: 'sanity.action.release.unarchive'\n releaseId: string\n}\n\n/**\n * Queues release for publishing at the given future time.\n *\n * @public\n */\nexport interface ScheduleReleaseAction {\n actionType: 'sanity.action.release.schedule'\n releaseId: string\n publishAt: string\n}\n\n/**\n * Unschedules a `scheduled` release, stopping it from being published.\n *\n * @public\n */\nexport interface UnscheduleReleaseAction {\n actionType: 'sanity.action.release.unschedule'\n releaseId: string\n}\n\n/**\n * Deletes a `archived` or `published` release, and all the release documents versions.\n *\n * @public\n */\nexport interface DeleteReleaseAction {\n actionType: 'sanity.action.release.delete'\n releaseId: string\n}\n\n/**\n * Creates a new version of an existing document.\n *\n * If the `document` is provided, the version is created from the document\n * attached to the release as given by `document._id`\n *\n * If the `baseId` and `versionId` are provided, the version is created from the base document\n * and the version is attached to the release as given by `publishedId` and `versionId`\n *\n * @public\n */\nexport type CreateVersionAction = {\n actionType: 'sanity.action.document.version.create'\n publishedId: string\n} & (\n | {\n document: IdentifiedSanityDocumentStub\n }\n | {\n baseId: string\n versionId: string\n ifBaseRevisionId?: string\n }\n)\n\n/**\n * Delete a version of a document.\n *\n * @public\n */\nexport interface DiscardVersionAction {\n actionType: 'sanity.action.document.version.discard'\n versionId: string\n purge?: boolean\n}\n\n/**\n * Replace an existing version of a document.\n *\n * @public\n */\nexport interface ReplaceVersionAction {\n actionType: 'sanity.action.document.version.replace'\n document: IdentifiedSanityDocumentStub\n}\n\n/**\n * Identify that a version of a document should be unpublished when\n * the release that version is contained within is published.\n *\n * @public\n */\nexport interface UnpublishVersionAction {\n actionType: 'sanity.action.document.version.unpublish'\n versionId: string\n publishedId: string\n}\n\n/**\n * Creates a new draft document. The published version of the document must not already exist.\n * If the draft version of the document already exists the action will fail by default, but\n * this can be adjusted to instead leave the existing document in place.\n *\n * @public\n */\nexport type CreateAction = {\n actionType: 'sanity.action.document.create'\n\n /**\n * ID of the published document to create a draft for.\n */\n publishedId: string\n\n /**\n * Document to create. Requires a `_type` property.\n */\n attributes: IdentifiedSanityDocumentStub\n\n /**\n * ifExists controls what to do if the draft already exists\n */\n ifExists: 'fail' | 'ignore'\n}\n\n/**\n * Replaces an existing draft document.\n * At least one of the draft or published versions of the document must exist.\n *\n * @public\n * @deprecated Use {@link ReplaceVersionAction} instead\n */\nexport type ReplaceDraftAction = {\n actionType: 'sanity.action.document.replaceDraft'\n\n /**\n * Published document ID to create draft from, if draft does not exist\n */\n publishedId: string\n\n /**\n * Document to create if it does not already exist. Requires `_id` and `_type` properties.\n */\n attributes: IdentifiedSanityDocumentStub\n}\n\n/**\n * Modifies an existing draft document.\n * It applies the given patch to the document referenced by draftId.\n * If there is no such document then one is created using the current state of the published version and then that is updated accordingly.\n *\n * @public\n */\nexport type EditAction = {\n actionType: 'sanity.action.document.edit'\n\n /**\n * Draft document ID to edit\n */\n draftId: string\n\n /**\n * Published document ID to create draft from, if draft does not exist\n */\n publishedId: string\n\n /**\n * Patch operations to apply\n */\n patch: PatchOperations\n}\n\n/**\n * Deletes the published version of a document and optionally some (likely all known) draft versions.\n * If any draft version exists that is not specified for deletion this is an error.\n * If the purge flag is set then the document history is also deleted.\n *\n * @public\n */\nexport type DeleteAction = {\n actionType: 'sanity.action.document.delete'\n\n /**\n * Published document ID to delete\n */\n publishedId: string\n\n /**\n * Draft document ID to delete\n */\n includeDrafts: string[]\n\n /**\n * Delete document history\n */\n purge?: boolean\n}\n\n/**\n * Delete the draft version of a document.\n * It is an error if it does not exist. If the purge flag is set, the document history is also deleted.\n *\n * @public\n * @deprecated Use {@link DiscardVersionAction} instead\n */\nexport type DiscardAction = {\n actionType: 'sanity.action.document.discard'\n\n /**\n * Draft document ID to delete\n */\n draftId: string\n\n /**\n * Delete document history\n */\n purge?: boolean\n}\n\n/**\n * Publishes a draft document.\n * If a published version of the document already exists this is replaced by the current draft document.\n * In either case the draft document is deleted.\n * The optional revision id parameters can be used for optimistic locking to ensure\n * that the draft and/or published versions of the document have not been changed by another client.\n *\n * @public\n */\nexport type PublishAction = {\n actionType: 'sanity.action.document.publish'\n\n /**\n * Draft document ID to publish\n */\n draftId: string\n\n /**\n * Draft revision ID to match\n */\n ifDraftRevisionId?: string\n\n /**\n * Published document ID to replace\n */\n publishedId: string\n\n /**\n * Published revision ID to match\n */\n ifPublishedRevisionId?: string\n}\n\n/**\n * Retract a published document.\n * If there is no draft version then this is created from the published version.\n * In either case the published version is deleted.\n *\n * @public\n */\nexport type UnpublishAction = {\n actionType: 'sanity.action.document.unpublish'\n\n /**\n * Draft document ID to replace the published document with\n */\n draftId: string\n\n /**\n * Published document ID to delete\n */\n publishedId: string\n}\n\n/**\n * A mutation was performed. Note that when updating multiple documents in a transaction,\n * each document affected will get a separate mutation event.\n *\n * @public\n */\nexport type MutationEvent<R extends Record<string, Any> = Record<string, Any>> = {\n type: 'mutation'\n\n /**\n * The ID of the document that was affected\n */\n documentId: string\n\n /**\n * A unique ID for this event\n */\n eventId: string\n\n /**\n * The user ID of the user that performed the mutation\n */\n identity: string\n\n /**\n * An array of mutations that were performed. Note that this can differ slightly from the\n * mutations sent to the server, as the server may perform some mutations automatically.\n */\n mutations: Mutation[]\n\n /**\n * The revision ID of the document before the mutation was performed\n */\n previousRev?: string\n\n /**\n * The revision ID of the document after the mutation was performed\n */\n resultRev?: string\n\n /**\n * The document as it looked after the mutation was performed. This is only included if\n * the listener was configured with `includeResult: true`.\n */\n result?: SanityDocument<R>\n\n /**\n * The document as it looked before the mutation was performed. This is only included if\n * the listener was configured with `includePreviousRevision: true`.\n */\n previous?: SanityDocument<R> | null\n\n /**\n * The effects of the mutation, if the listener was configured with `effectFormat: 'mendoza'`.\n * Object with `apply` and `revert` arrays, see {@link https://github.com/sanity-io/mendoza}.\n */\n effects?: {apply: unknown[]; revert: unknown[]}\n\n /**\n * A timestamp for when the mutation was performed\n */\n timestamp: string\n\n /**\n * The transaction ID for the mutation\n */\n transactionId: string\n\n /**\n * The type of transition the document went through.\n *\n * - `update` means the document was previously part of the subscribed set of documents,\n * and still is.\n * - `appear` means the document was not previously part of the subscribed set of documents,\n * but is now. This can happen both on create or if updating to a state where it now matches\n * the filter provided to the listener.\n * - `disappear` means the document was previously part of the subscribed set of documents,\n * but is no longer. This can happen both on delete or if updating to a state where it no\n * longer matches the filter provided to the listener.\n */\n transition: 'update' | 'appear' | 'disappear'\n\n /**\n * Whether the change that triggered this event is visible to queries (query) or only to\n * subsequent transactions (transaction). The listener client can specify a preferred visibility\n * through the `visibility` parameter on the listener, but this is only on a best-effort basis,\n * and may yet not be accurate.\n */\n visibility: 'query' | 'transaction'\n\n /**\n * The total number of events that will be sent for this transaction.\n * Note that this may differ from the amount of _documents_ affected by the transaction, as this\n * number only includes the documents that matches the given filter.\n *\n * This can be useful if you need to perform changes to all matched documents atomically,\n * eg you would wait for `transactionTotalEvents` events with the same `transactionId` before\n * applying the changes locally.\n */\n transactionTotalEvents: number\n\n /**\n * The index of this event within the transaction. Note that events may be delivered out of order,\n * and that the index is zero-based.\n */\n transactionCurrentEvent: number\n}\n\n/**\n * An error occurred. This is different from a network-level error (which will be emitted as 'error').\n * Possible causes are things such as malformed filters, non-existant datasets or similar.\n *\n * @public\n */\nexport type ChannelErrorEvent = {\n type: 'channelError'\n message: string\n}\n\n/**\n * The listener has been told to explicitly disconnect and not reconnect.\n * This is a rare situation, but may occur if the API knows reconnect attempts will fail,\n * eg in the case of a deleted dataset, a blocked project or similar events.\n *\n * Note that this is not treated as an error on the observable, but will complete the observable.\n *\n * @public\n */\nexport type DisconnectEvent = {\n type: 'disconnect'\n reason: string\n}\n\n/**\n * The listener has been disconnected, and a reconnect attempt is scheduled.\n *\n * @public\n */\nexport type ReconnectEvent = {\n type: 'reconnect'\n}\n\n/**\n * The listener connection has been established\n * note: it's usually a better option to use the 'welcome' event\n * @public\n */\nexport type OpenEvent = {\n type: 'open'\n}\n\n/**\n * The listener has been established, and will start receiving events.\n * Note that this is also emitted upon _reconnection_.\n *\n * @public\n */\nexport type WelcomeEvent = {\n type: 'welcome'\n listenerName: string\n}\n\n/** @public */\nexport type ListenEvent<R extends Record<string, Any>> =\n | MutationEvent<R>\n | ReconnectEvent\n | WelcomeEvent\n | OpenEvent\n\n/** @public */\nexport type ListenEventName =\n /** A mutation was performed */\n | 'mutation'\n /** The listener has been (re)established */\n | 'welcome'\n /** The listener has been disconnected, and a reconnect attempt is scheduled */\n | 'reconnect'\n /**\n * The listener connection has been established\n * note: it's usually a better option to use the 'welcome' event\n */\n | 'open'\n\n/** @public */\nexport type ListenParams = {[key: string]: Any}\n\n/** @public */\nexport interface ListenOptions {\n /**\n * Whether or not to include the resulting document in addition to the mutations performed.\n * If you do not need the actual document, set this to `false` to reduce bandwidth usage.\n * The result will be available on the `.result` property of the events.\n * @defaultValue `true`\n */\n includeResult?: boolean\n\n /**\n * Whether or not to include the mutations that was performed.\n * If you do not need the mutations, set this to `false` to reduce bandwidth usage.\n * @defaultValue `true`\n */\n includeMutations?: boolean\n\n /**\n * Whether or not to include the document as it looked before the mutation event.\n * The previous revision will be available on the `.previous` property of the events,\n * and may be `null` in the case of a new document.\n * @defaultValue `false`\n */\n includePreviousRevision?: boolean\n\n /*\n * Whether to include events for drafts and versions. As of API Version >= v2025-02-19, only events\n * for published documents will be included by default (see {@link https://www.sanity.io/changelog/676aaa9d-2da6-44fb-abe5-580f28047c10|Changelog})\n * If you need events from drafts and versions, set this to `true`.\n * Note: Keep in mind that additional document variants may be introduced in the future, so it's\n * recommended to respond to events in a way that's tolerant of potential future variants, e.g. by\n * explicitly checking whether the event is for a draft or a version.\n * @defaultValue `false`\n */\n includeAllVersions?: boolean\n\n /**\n * Whether events should be sent as soon as a transaction has been committed (`transaction`, default),\n * or only after they are available for queries (query). Note that this is on a best-effort basis,\n * and listeners with `query` may in certain cases (notably with deferred transactions) receive events\n * that are not yet visible to queries.\n *\n * @defaultValue `'transaction'`\n */\n visibility?: 'transaction' | 'query'\n\n /**\n * Array of event names to include in the observable. By default, only mutation events are included.\n *\n * @defaultValue `['mutation']`\n */\n events?: ListenEventName[]\n\n /**\n * Format of \"effects\", eg the resulting changes of a mutation.\n * Currently only `mendoza` is supported, and (if set) will include `apply` and `revert` arrays\n * in the mutation events under the `effects` property.\n *\n * See {@link https://github.com/sanity-io/mendoza | The mendoza docs} for more info\n *\n * @defaultValue `undefined`\n */\n effectFormat?: 'mendoza'\n\n /**\n * Optional request tag for the listener. Use to identify the request in logs.\n *\n * @defaultValue `undefined`\n */\n tag?: string\n}\n\n/** @public */\nexport interface ResponseQueryOptions extends RequestOptions {\n perspective?: ClientPerspective\n resultSourceMap?: boolean | 'withKeyArraySelector'\n returnQuery?: boolean\n useCdn?: boolean\n stega?: boolean | StegaConfig\n // The `cache` and `next` options are specific to the Next.js App Router integration\n cache?: 'next' extends keyof RequestInit ? RequestInit['cache'] : never\n next?: ('next' extends keyof RequestInit ? RequestInit : never)['next']\n lastLiveEventId?: string | string[] | null\n\n /**\n * When set to `noStale`, APICDN will not return a cached response if the content is stale.\n * Tradeoff between latency and freshness of content.\n *\n * Only to be used with live content queries and when useCdn is true.\n */\n cacheMode?: 'noStale'\n}\n\n/** @public */\nexport interface FilteredResponseQueryOptions extends ResponseQueryOptions {\n filterResponse?: true\n}\n\n/** @public */\nexport interface UnfilteredResponseQueryOptions extends ResponseQueryOptions {\n filterResponse: false\n\n /**\n * When `filterResponse` is `false`, `returnQuery` also defaults to `true` for\n * backwards compatibility (on the client side, not from the content lake API).\n * Can also explicitly be set to `true`.\n */\n returnQuery?: true\n}\n\n/**\n * When using `filterResponse: false`, but you do not wish to receive back the query from\n * the content lake API.\n *\n * @public\n */\nexport interface UnfilteredResponseWithoutQuery extends ResponseQueryOptions {\n filterResponse: false\n returnQuery: false\n}\n\n/** @public */\nexport type QueryOptions =\n | FilteredResponseQueryOptions\n | UnfilteredResponseQueryOptions\n | UnfilteredResponseWithoutQuery\n\n/** @public */\nexport interface RawQueryResponse<R> {\n query: string\n ms: number\n result: R\n resultSourceMap?: ContentSourceMap\n /** Requires `apiVersion` to be `2021-03-25` or later. */\n syncTags?: SyncTag[]\n}\n\n/** @public */\nexport type RawQuerylessQueryResponse<R> = Omit<RawQueryResponse<R>, 'query'>\n\n/** @internal */\nexport type BaseMutationOptions = RequestOptions & {\n visibility?: 'sync' | 'async' | 'deferred'\n returnDocuments?: boolean\n returnFirst?: boolean\n dryRun?: boolean\n autoGenerateArrayKeys?: boolean\n skipCrossDatasetReferenceValidation?: boolean\n transactionId?: string\n}\n\n/** @internal */\nexport type FirstDocumentMutationOptions = BaseMutationOptions & {\n returnFirst?: true\n returnDocuments?: true\n}\n\n/** @internal */\nexport type FirstDocumentIdMutationOptions = BaseMutationOptions & {\n returnFirst?: true\n returnDocuments: false\n}\n\n/** @internal */\nexport type AllDocumentsMutationOptions = BaseMutationOptions & {\n returnFirst: false\n returnDocuments?: true\n}\n\n/** @internal */\nexport type MutationOperation = 'create' | 'delete' | 'update' | 'none'\n\n/** @internal */\nexport interface SingleMutationResult {\n transactionId: string\n documentId: string\n results: {id: string; operation: MutationOperation}[]\n}\n\n/** @internal */\nexport interface MultipleMutationResult {\n transactionId: string\n documentIds: string[]\n results: {id: string; operation: MutationOperation}[]\n}\n\n/** @internal */\nexport type AllDocumentIdsMutationOptions = BaseMutationOptions & {\n returnFirst: false\n returnDocuments: false\n}\n\n/** @internal */\nexport type AttributeSet = {[key: string]: Any}\n\n/** @internal */\nexport type TransactionFirstDocumentMutationOptions = BaseMutationOptions & {\n returnFirst: true\n returnDocuments: true\n}\n\n/** @internal */\nexport type TransactionFirstDocumentIdMutationOptions = BaseMutationOptions & {\n returnFirst: true\n returnDocuments?: false\n}\n\n/** @internal */\nexport type TransactionAllDocumentsMutationOptions = BaseMutationOptions & {\n returnFirst?: false\n returnDocuments: true\n}\n\n/** @internal */\nexport type TransactionAllDocumentIdsMutationOptions = BaseMutationOptions & {\n returnFirst?: false\n returnDocuments?: false\n}\n\n/** @internal */\nexport type TransactionMutationOptions =\n | TransactionFirstDocumentMutationOptions\n | TransactionFirstDocumentIdMutationOptions\n | TransactionAllDocumentsMutationOptions\n | TransactionAllDocumentIdsMutationOptions\n\n/** @internal */\nexport type BaseActionOptions = RequestOptions & {\n transactionId?: string\n skipCrossDatasetReferenceValidation?: boolean\n dryRun?: boolean\n}\n\n/** @internal */\nexport interface SingleActionResult {\n transactionId: string\n}\n\n/** @internal */\nexport interface MultipleActionResult {\n transactionId: string\n}\n\n/** @internal */\nexport interface RawRequestOptions {\n url?: string\n uri?: string\n method?: string\n token?: string\n json?: boolean\n tag?: string\n useGlobalApi?: boolean\n withCredentials?: boolean\n query?: {[key: string]: string | string[]}\n headers?: {[key: string]: string}\n timeout?: number\n proxy?: string\n body?: Any\n maxRedirects?: number\n signal?: AbortSignal\n}\n\n/** @internal */\nexport interface ApiError {\n error: string\n message: string\n statusCode: number\n}\n\n/** @internal */\nexport interface MutationError {\n type: 'mutationError'\n description: string\n items?: MutationErrorItem[]\n}\n\n/**\n * Returned from the Content Lake API when a query is malformed, usually with a start\n * and end column to indicate where the error occurred, but not always. Can we used to\n * provide a more structured error message to the user.\n *\n * This will be located under the response `error` property.\n *\n * @public\n */\nexport interface QueryParseError {\n type: 'queryParseError'\n description: string\n start?: number\n end?: number\n query?: string\n}\n\n/** @internal */\nexport interface MutationErrorItem {\n error: {\n type: string\n description: string\n value?: unknown\n }\n}\n\n/** @internal */\nexport interface ActionError {\n type: 'actionError'\n description: string\n items?: ActionErrorItem[]\n}\n\n/** @internal */\nexport interface ActionErrorItem {\n error: {\n type: string\n description: string\n value?: unknown\n }\n index: number\n}\n\n/** @internal */\nexport type PartialExcept<T, K extends keyof T> = Pick<T, K> & Partial<Omit<T, K>>\n\n/** @beta */\nexport type ReleaseState =\n | 'active'\n | 'archiving'\n | 'unarchiving'\n | 'archived'\n | 'published'\n | 'publishing'\n | 'scheduled'\n | 'scheduling'\n\n/** @internal */\nexport type ReleaseType = 'asap' | 'scheduled' | 'undecided'\n\n/** @public */\nexport type ReleaseCardinality = 'many' | 'one' | undefined\n\n/** @internal */\nexport interface ReleaseDocument extends SanityDocument {\n /**\n * typically\n * `_.releases.<name>`\n */\n _id: string\n /**\n * where a release has _id `_.releases.foo`, the name is `foo`\n */\n name: string\n _type: 'system.release'\n _createdAt: string\n _updatedAt: string\n _rev: string\n state: ReleaseState\n error?: {\n message: string\n }\n finalDocumentStates?: {\n /** Document ID */\n id: string\n }[]\n /**\n * If defined, it takes precedence over the intendedPublishAt, the state should be 'scheduled'\n */\n publishAt?: string\n /**\n * If defined, it provides the time the release was actually published\n */\n publishedAt?: string\n metadata: {\n title?: string\n description?: string\n intendedPublishAt?: string\n releaseType: ReleaseType\n cardinality?: ReleaseCardinality\n }\n}\n\n/** @internal */\nexport type EditableReleaseDocument = Omit<\n PartialExcept<ReleaseDocument, '_id'>,\n 'metadata' | '_type'\n> & {\n _id: string\n metadata: Partial<ReleaseDocument['metadata']>\n}\n\n/**\n * DocumentValueSource is a path to a value within a document\n * @public\n */\nexport interface ContentSourceMapDocumentValueSource {\n type: 'documentValue'\n // index location of the document\n document: number\n // index location of the path\n path: number\n}\n/**\n * When a value is not from a source, its a literal\n * @public\n */\nexport interface ContentSourceMapLiteralSource {\n type: 'literal'\n}\n/**\n * When a field source is unknown\n * @public\n */\nexport interface ContentSourceMapUnknownSource {\n type: 'unknown'\n}\n/** @public */\nexport type ContentSourceMapSource =\n | ContentSourceMapDocumentValueSource\n | ContentSourceMapLiteralSource\n | ContentSourceMapUnknownSource\n/**\n * ValueMapping is a mapping when for value that is from a single source value\n * It may refer to a field within a document or a literal value\n * @public\n */\nexport interface ContentSourceMapValueMapping {\n type: 'value'\n // source of the value\n source: ContentSourceMapSource\n}\n/** @public */\nexport type ContentSourceMapMapping = ContentSourceMapValueMapping\n\n/** @public */\nexport type ContentSourceMapMappings = Record<string, ContentSourceMapMapping>\n\n/** @public */\nexport interface ContentSourceMapDocumentBase {\n _id: string\n _type: string\n}\n\n/** @public */\nexport interface ContentSourceMapDocument extends ContentSourceMapDocumentBase {\n _projectId?: undefined\n _dataset?: undefined\n}\n\n/** @public */\nexport interface ContentSourceMapRemoteDocument extends ContentSourceMapDocumentBase {\n _projectId: string\n _dataset: string\n}\n\n/** @public */\nexport type ContentSourceMapDocuments = (\n | ContentSourceMapDocument\n | ContentSourceMapRemoteDocument\n)[]\n\n/** @public */\nexport type ContentSourceMapPaths = string[]\n\n/** @public */\nexport interface ContentSourceMap {\n mappings: ContentSourceMapMappings\n documents: ContentSourceMapDocuments\n paths: ContentSourceMapPaths\n}\n\n/** @public */\nexport type SyncTag = `s1:${string}`\n/** @public */\nexport interface LiveEventRestart {\n type: 'restart'\n id: string\n}\n/** @public */\nexport interface LiveEventReconnect {\n type: 'reconnect'\n}\n/** @public */\nexport interface LiveEventMessage {\n type: 'message'\n id: string\n tags: SyncTag[]\n}\n/** @public */\nexport interface LiveEventWelcome {\n type: 'welcome'\n}\n/**\n * The `id` field is the position at which the connection was rejected or closed.\n * The `reason` field will specify why the connection rejected/closed.\n * @public\n */\nexport interface LiveEventGoAway {\n type: 'goaway'\n id: string\n reason: string\n}\n/** @public */\nexport type LiveEvent =\n | LiveEventRestart\n | LiveEventReconnect\n | LiveEventMessage\n | LiveEventWelcome\n | LiveEventGoAway\n\n/** @public */\nexport interface SanityQueries {}\n\n/** @public */\nexport type ClientReturn<\n GroqString extends string,\n Fallback = Any,\n> = GroqString extends keyof SanityQueries ? SanityQueries[GroqString] : Fallback\n\nexport type {\n AgentActionParam,\n AgentActionParams,\n AgentActionPath,\n AgentActionPathSegment,\n AgentActionTarget,\n ConstantAgentActionParam,\n DocumentAgentActionParam,\n FieldAgentActionParam,\n GroqAgentActionParam,\n} from './agent/actions/commonTypes'\nexport type {\n GenerateInstruction,\n GenerateOperation,\n GenerateTarget,\n GenerateTargetDocument,\n GenerateTargetInclude,\n} from './agent/actions/generate'\nexport type {PatchDocument, PatchOperation, PatchTarget} from './agent/actions/patch'\nexport type {PromptRequest} from './agent/actions/prompt'\nexport type {\n ImageDescriptionOperation,\n TransformDocument,\n TransformOperation,\n TransformTarget,\n TransformTargetDocument,\n TransformTargetInclude,\n} from './agent/actions/transform'\nexport type {\n TranslateDocument,\n TranslateTarget,\n TranslateTargetInclude,\n} from './agent/actions/translate'\nexport type {\n ContentSourceMapParsedPath,\n ContentSourceMapParsedPathKeyedSegment,\n FilterDefault,\n InitializedStegaConfig,\n Logger,\n ResolveStudioUrl,\n StegaConfig,\n StegaConfigRequiredKeys,\n StudioBaseRoute,\n StudioBaseUrl,\n StudioUrl,\n} from './stega/types'\n\n/**\n * A string constant containing the experimental API version warning message.\n * Use this with the `ignoreWarnings` option to suppress warnings when using experimental API versions.\n *\n * @example\n * ```typescript\n * import { createClient, EXPERIMENTAL_API_WARNING } from '@sanity/client'\n *\n * const client = createClient({\n * projectId: 'your-project-id',\n * dataset: 'production',\n * apiVersion: 'vX', // experimental version\n * ignoreWarnings: EXPERIMENTAL_API_WARNING\n * })\n * ```\n *\n * @public\n */\nexport const EXPERIMENTAL_API_WARNING = 'This is an experimental API version'\n\n// Media Libraries types\n/**\n * Fit / resize modes accepted for thumbnail params.\n * @public\n */\nexport type FitMode = 'preserve' | 'stretch' | 'crop' | 'smartcrop' | 'pad'\n\n/**\n * Allowed still image formats (thumbnail + storyboard).\n * @public\n */\nexport type StillImageFormat = 'jpg' | 'png' | 'webp'\n\n/**\n * Allowed animated image formats.\n * @public\n */\nexport type AnimatedImageFormat = 'gif' | 'webp'\n\n/**\n * Thumbnail rendition (single frame) options.\n * @public\n */\nexport interface ThumbnailTransformOptions {\n /** Pixel width of the thumbnail frame. */\n width?: number\n /** Pixel height of the thumbnail frame. */\n height?: number\n /** Timestamp (seconds) from which to grab the frame. */\n time?: number\n /** Resize / fit mode applied to the extracted frame. */\n fit?: FitMode\n /** Output image format. */\n format?: StillImageFormat\n}\n\n/**\n * Animated preview rendition options (e.g. GIF / animated WebP).\n * @public\n */\nexport interface AnimatedTransformOptions {\n /** Pixel width of the animated output. Max 640 px. */\n width?: number\n /** Pixel height of the animated output. Max 640 px. */\n height?: number\n /** Start time in seconds (inclusive). */\n start?: number\n /** End time in seconds. */\n end?: number\n /** Frames per second (1–30). */\n fps?: number\n /** Output animated format. */\n format?: AnimatedImageFormat\n}\n\n/**\n * Storyboard (contact sheet) options.\n * @public\n */\nexport interface StoryboardTransformOptions {\n /** Output image format for the storyboard. */\n format?: StillImageFormat\n}\n\n/**\n * Video-specific playback transformation option groups.\n * Only explicitly provided values are serialized into query parameters.\n * @public\n */\nexport interface MediaLibraryVideoPlaybackTransformations {\n /** Static thumbnail (single frame) options. */\n thumbnail?: ThumbnailTransformOptions\n /** Animated preview options (GIF / animated WebP). */\n animated?: AnimatedTransformOptions\n /** Storyboard (contact sheet) options. */\n storyboard?: StoryboardTransformOptions\n}\n\n/**\n * Options for requesting playback info (URLs + optional tokens) for a Media Library video asset.\n *\n * Removed: generic fallback parameters (width, height, fit, format). Supply per‑transformation values instead.\n * Animated transformations intentionally exclude any fit option (not supported by Mux).\n *\n * includeTokens is a client-side flag (not sent to the server) controlling whether\n * returned tokens should be appended to URLs when consumed.\n * @public\n */\nexport interface MediaLibraryPlaybackInfoOptions {\n /** Explicit per-video transformation options (thumbnail, animated, storyboard). */\n transformations?: MediaLibraryVideoPlaybackTransformations\n /** Expiration hint for secured/signed URLs (string or number, number will be stringified). */\n expiration?: string | number\n}\n\n/** @public */\nexport interface VideoPlaybackInfoItemPublic {\n url: string\n}\n\n/** @public */\nexport interface VideoPlaybackInfoItemSigned extends VideoPlaybackInfoItemPublic {\n token: string\n}\n\n/** @public */\nexport type VideoPlaybackInfoItem = VideoPlaybackInfoItemPublic | VideoPlaybackInfoItemSigned\n\n/** @public */\nexport interface VideoPlaybackInfo<T extends VideoPlaybackInfoItem = VideoPlaybackInfoItem> {\n id: string\n thumbnail: T\n animated: T\n storyboard: T\n stream: T\n duration: number\n aspectRatio: number\n}\n\n/** @public */\nexport type VideoPlaybackInfoSigned = VideoPlaybackInfo<VideoPlaybackInfoItemSigned>\n\n/** @public */\nexport type VideoPlaybackInfoPublic = VideoPlaybackInfo<VideoPlaybackInfoItemPublic>\n\n/** @public */\nexport interface VideoPlaybackTokens {\n stream?: string\n thumbnail?: string\n storyboard?: string\n animated?: string\n}\n\n/** @public */\nexport type MediaLibraryAssetInstanceIdentifier = string | SanityReference\n","import type {Any} from '../types'\n\nexport function once(fn: Any) {\n let didCall = false\n let returnValue: Any\n return (...args: Any[]) => {\n if (didCall) {\n return returnValue\n }\n returnValue = fn(...args)\n didCall = true\n return returnValue\n }\n}\n","import {generateHelpUrl} from './generateHelpUrl'\nimport {type Any} from './types'\nimport {once} from './util/once'\n\nconst createWarningPrinter = (message: string[]) =>\n // eslint-disable-next-line no-console\n once((...args: Any[]) => console.warn(message.join(' '), ...args))\n\nexport const printCdnAndWithCredentialsWarning = createWarningPrinter([\n `Because you set \\`withCredentials\\` to true, we will override your \\`useCdn\\``,\n `setting to be false since (cookie-based) credentials are never set on the CDN`,\n])\n\nexport const printCdnWarning = createWarningPrinter([\n `Since you haven't set a value for \\`useCdn\\`, we will deliver content using our`,\n `global, edge-cached API-CDN. If you wish to have content delivered faster, set`,\n `\\`useCdn: false\\` to use the Live API. Note: You may incur higher costs using the live API.`,\n])\n\nexport const printCdnPreviewDraftsWarning = createWarningPrinter([\n `The Sanity client is configured with the \\`perspective\\` set to \\`drafts\\` or \\`previewDrafts\\`, which doesn't support the API-CDN.`,\n `The Live API will be used instead. Set \\`useCdn: false\\` in your configuration to hide this warning.`,\n])\n\nexport const printPreviewDraftsDeprecationWarning = createWarningPrinter([\n `The \\`previewDrafts\\` perspective has been renamed to \\`drafts\\` and will be removed in a future API version`,\n])\n\nexport const printBrowserTokenWarning = createWarningPrinter([\n 'You have configured Sanity client to use a token in the browser. This may cause unintentional security issues.',\n `See ${generateHelpUrl(\n 'js-client-browser-token',\n )} for more information and how to hide this warning.`,\n])\n\nexport const printCredentialedTokenWarning = createWarningPrinter([\n 'You have configured Sanity client to use a token, but also provided `withCredentials: true`.',\n 'This is no longer supported - only token will be used - remove `withCredentials: true`.',\n])\n\nexport const printNoApiVersionSpecifiedWarning = createWarningPrinter([\n 'Using the Sanity client without specifying an API version is deprecated.',\n `See ${generateHelpUrl('js-client-api-version')}`,\n])\n\nexport const printNoDefaultExport = createWarningPrinter([\n 'The default export of @sanity/client has been deprecated. Use the named export `createClient` instead.',\n])\n\nexport const printCreateVersionWithBaseIdWarning = createWarningPrinter([\n 'You have called `createVersion()` with a defined `document`. The recommended approach is to provide a `baseId` and `releaseId` instead.',\n])\n\nexport const printDeprecatedResourceConfigWarning = createWarningPrinter([\n 'The `~experimental_resource` configuration property has been renamed to `resource`.',\n 'Please update your client configuration to use `resource` instead. Support for `~experimental_resource` will be removed in a future version.',\n])\n","import {generateHelpUrl} from './generateHelpUrl'\nimport type {ClientConfig, ClientPerspective, InitializedClientConfig} from './types'\nimport * as validate from './validators'\nimport * as warnings from './warnings'\n\nconst defaultCdnHost = 'apicdn.sanity.io'\nexport const defaultConfig = {\n apiHost: 'https://api.sanity.io',\n apiVersion: '1',\n useProjectHostname: true,\n stega: {enabled: false},\n} satisfies ClientConfig\n\nconst LOCALHOSTS = ['localhost', '127.0.0.1', '0.0.0.0']\nconst isLocal = (host: string) => LOCALHOSTS.indexOf(host) !== -1\n\nfunction validateApiVersion(apiVersion: string) {\n if (apiVersion === '1' || apiVersion === 'X') {\n return\n }\n\n const apiDate = new Date(apiVersion)\n const apiVersionValid =\n /^\\d{4}-\\d{2}-\\d{2}$/.test(apiVersion) && apiDate instanceof Date && apiDate.getTime() > 0\n\n if (!apiVersionValid) {\n throw new Error('Invalid API version string, expected `1` or date in format `YYYY-MM-DD`')\n }\n}\n\n/**\n * @internal - it may have breaking changes in any release\n */\nexport function validateApiPerspective(\n perspective: unknown,\n): asserts perspective is ClientPerspective {\n if (Array.isArray(perspective) && perspective.length > 1 && perspective.includes('raw')) {\n throw new TypeError(\n `Invalid API perspective value: \"raw\". The raw-perspective can not be combined with other perspectives`,\n )\n }\n}\n\nexport const initConfig = (\n config: Partial<ClientConfig>,\n prevConfig: Partial<ClientConfig>,\n): InitializedClientConfig => {\n const specifiedConfig = {\n ...prevConfig,\n ...config,\n stega: {\n ...(typeof prevConfig.stega === 'boolean'\n ? {enabled: prevConfig.stega}\n : prevConfig.stega || defaultConfig.stega),\n ...(typeof config.stega === 'boolean' ? {enabled: config.stega} : config.stega || {}),\n },\n }\n if (!specifiedConfig.apiVersion) {\n warnings.printNoApiVersionSpecifiedWarning()\n }\n\n const newConfig = {\n ...defaultConfig,\n ...specifiedConfig,\n } as InitializedClientConfig\n\n // Normalize resource configuration - prefer `resource` over deprecated `~experimental_resource`\n if (newConfig['~experimental_resource'] && !newConfig.resource) {\n warnings.printDeprecatedResourceConfigWarning()\n newConfig.resource = newConfig['~experimental_resource']\n }\n\n const resourceConfig = newConfig.resource\n const projectBased = newConfig.useProjectHostname && !resourceConfig\n\n if (typeof Promise === 'undefined') {\n const helpUrl = generateHelpUrl('js-client-promise-polyfill')\n throw new Error(`No native Promise-implementation found, polyfill needed - see ${helpUrl}`)\n }\n\n if (projectBased && !newConfig.projectId) {\n throw new Error('Configuration must contain `projectId`')\n }\n\n if (resourceConfig) {\n validate.resourceConfig(newConfig)\n }\n\n if (typeof newConfig.perspective !== 'undefined') {\n validateApiPerspective(newConfig.perspective)\n }\n\n if ('encodeSourceMap' in newConfig) {\n throw new Error(\n `It looks like you're using options meant for '@sanity/preview-kit/client'. 'encodeSourceMap' is not supported in '@sanity/client'. Did you mean 'stega.enabled'?`,\n )\n }\n if ('encodeSourceMapAtPath' in newConfig) {\n throw new Error(\n `It looks like you're using options meant for '@sanity/preview-kit/client'. 'encodeSourceMapAtPath' is not supported in '@sanity/client'. Did you mean 'stega.filter'?`,\n )\n }\n if (typeof newConfig.stega.enabled !== 'boolean') {\n throw new Error(`stega.enabled must be a boolean, received ${newConfig.stega.enabled}`)\n }\n if (newConfig.stega.enabled && newConfig.stega.studioUrl === undefined) {\n throw new Error(`stega.studioUrl must be defined when stega.enabled is true`)\n }\n if (\n newConfig.stega.enabled &&\n typeof newConfig.stega.studioUrl !== 'string' &&\n typeof newConfig.stega.studioUrl !== 'function'\n ) {\n throw new Error(\n `stega.studioUrl must be a string or a function, received ${newConfig.stega.studioUrl}`,\n )\n }\n\n const isBrowser = typeof window !== 'undefined' && window.location && window.location.hostname\n const isLocalhost = isBrowser && isLocal(window.location.hostname)\n\n const hasToken = Boolean(newConfig.token)\n if (newConfig.withCredentials && hasToken) {\n warnings.printCredentialedTokenWarning()\n newConfig.withCredentials = false\n }\n\n if (isBrowser && isLocalhost && hasToken && newConfig.ignoreBrowserTokenWarning !== true) {\n warnings.printBrowserTokenWarning()\n } else if (typeof newConfig.useCdn === 'undefined') {\n warnings.printCdnWarning()\n }\n\n if (projectBased) {\n validate.projectId(newConfig.projectId!)\n }\n\n if (newConfig.dataset) {\n validate.dataset(newConfig.dataset)\n }\n\n if ('requestTagPrefix' in newConfig) {\n // Allow setting and unsetting request tag prefix\n newConfig.requestTagPrefix = newConfig.requestTagPrefix\n ? validate.requestTag(newConfig.requestTagPrefix).replace(/\\.+$/, '')\n : undefined\n }\n\n newConfig.apiVersion = `${newConfig.apiVersion}`.replace(/^v/, '')\n newConfig.isDefaultApi = newConfig.apiHost === defaultConfig.apiHost\n\n if (newConfig.useCdn === true && newConfig.withCredentials) {\n warnings.printCdnAndWithCredentialsWarning()\n }\n\n // If `useCdn` is undefined, we treat it as `true`\n newConfig.useCdn = newConfig.useCdn !== false && !newConfig.withCredentials\n\n validateApiVersion(newConfig.apiVersion)\n\n const hostParts = newConfig.apiHost.split('://', 2)\n const protocol = hostParts[0]\n const host = hostParts[1]\n const cdnHost = newConfig.isDefaultApi ? defaultCdnHost : host\n\n if (projectBased) {\n newConfig.url = `${protocol}://${newConfig.projectId}.${host}/v${newConfig.apiVersion}`\n newConfig.cdnUrl = `${protocol}://${newConfig.projectId}.${cdnHost}/v${newConfig.apiVersion}`\n } else {\n newConfig.url = `${newConfig.apiHost}/v${newConfig.apiVersion}`\n newConfig.cdnUrl = newConfig.url\n }\n\n return newConfig\n}\n","import {defer, isObservable, mergeMap, Observable, of} from 'rxjs'\n\nimport {formatQueryParseError, isQueryParseError} from '../http/errors'\nimport {type Any} from '../types'\n\n/**\n * @public\n * Thrown if the EventSource connection could not be established.\n * Note that ConnectionFailedErrors are rare, and disconnects will normally be handled by the EventSource instance itself and emitted as `reconnect` events.\n */\nexport class ConnectionFailedError extends Error {\n readonly name = 'ConnectionFailedError'\n}\n\n/**\n * The listener has been told to explicitly disconnect.\n * This is a rare situation, but may occur if the API knows reconnect attempts will fail,\n * eg in the case of a deleted dataset, a blocked project or similar events.\n * @public\n */\nexport class DisconnectError extends Error {\n readonly name = 'DisconnectError'\n readonly reason?: string\n constructor(message: string, reason?: string, options: ErrorOptions = {}) {\n super(message, options)\n this.reason = reason\n }\n}\n\n/**\n * @public\n * The server sent a `channelError` message. Usually indicative of a bad or malformed request\n */\nexport class ChannelError extends Error {\n readonly name = 'ChannelError'\n readonly data?: unknown\n constructor(message: string, data: unknown) {\n super(message)\n this.data = data\n }\n}\n\n/**\n * @public\n * The server sent an `error`-event to tell the client that an unexpected error has happened.\n */\nexport class MessageError extends Error {\n readonly name = 'MessageError'\n readonly data?: unknown\n constructor(message: string, data: unknown, options: ErrorOptions = {}) {\n super(message, options)\n this.data = data\n }\n}\n\n/**\n * @public\n * An error occurred while parsing the message sent by the server as JSON. Should normally not happen.\n */\nexport class MessageParseError extends Error {\n readonly name = 'MessageParseError'\n}\n\n/**\n * @public\n */\nexport interface ServerSentEvent<Name extends string> {\n type: Name\n id?: string\n data?: unknown\n}\n\n// Always listen for these events, no matter what\nconst REQUIRED_EVENTS = ['channelError', 'disconnect']\n\n/**\n * @internal\n */\nexport type EventSourceEvent<Name extends string> = ServerSentEvent<Name>\n\n/**\n * @internal\n */\nexport type EventSourceInstance = InstanceType<typeof globalThis.EventSource>\n\n/**\n * Sanity API specific EventSource handler shared between the listen and live APIs\n *\n * Since the `EventSource` API is not provided by all environments, this function enables custom initialization of the EventSource instance\n * for runtimes that requires polyfilling or custom setup logic (e.g. custom HTTP headers)\n * via the passed `initEventSource` function which must return an EventSource instance.\n *\n * Possible errors to be thrown on the returned observable are:\n * - {@link MessageError}\n * - {@link MessageParseError}\n * - {@link ChannelError}\n * - {@link DisconnectError}\n * - {@link ConnectionFailedError}\n *\n * @param initEventSource - A function that returns an EventSource instance or an Observable that resolves to an EventSource instance\n * @param events - an array of named events from the API to listen for.\n *\n * @internal\n */\nexport function connectEventSource<EventName extends string>(\n initEventSource: () => EventSourceInstance | Observable<EventSourceInstance>,\n events: EventName[],\n) {\n return defer(() => {\n const es = initEventSource()\n return isObservable(es) ? es : of(es)\n }).pipe(mergeMap((es) => connectWithESInstance(es, events))) as Observable<\n ServerSentEvent<EventName>\n >\n}\n\n/**\n * Provides an observable from the passed EventSource instance, subscribing to the passed list of names of events types to listen for\n * Handles connection logic, adding/removing event listeners, payload parsing, error propagation, etc.\n *\n * @param es - The EventSource instance\n * @param events - List of event names to listen for\n */\nfunction connectWithESInstance<EventTypeName extends string>(\n es: EventSourceInstance,\n events: EventTypeName[],\n) {\n return new Observable<EventSourceEvent<EventTypeName>>((observer) => {\n const emitOpen = (events as string[]).includes('open')\n const emitReconnect = (events as string[]).includes('reconnect')\n\n // EventSource will emit a regular Event if it fails to connect, however the API may also emit an `error` MessageEvent\n // So we need to handle both cases\n function onError(evt: MessageEvent | Event) {\n // If the event has a `data` property, then it`s a MessageEvent emitted by the API and we should forward the error\n if ('data' in evt) {\n const [parseError, event] = parseEvent(evt as MessageEvent)\n observer.error(\n parseError\n ? new MessageParseError('Unable to parse EventSource error message', {cause: event})\n : new MessageError((event?.data as {message: string}).message, event),\n )\n return\n }\n\n // We should never be in a disconnected state. By default, EventSource will reconnect\n // automatically, but in some cases (like when a laptop lid is closed), it will trigger onError\n // if it can't reconnect.\n // see https://html.spec.whatwg.org/multipage/server-sent-events.html#sse-processing-model\n if (es.readyState === es.CLOSED) {\n // In these cases we'll signal to consumers (via the error path) that a retry/reconnect is needed.\n observer.error(new ConnectionFailedError('EventSource connection failed'))\n } else if (emitReconnect) {\n observer.next({type: 'reconnect' as EventTypeName})\n }\n }\n\n function onOpen() {\n // The open event of the EventSource API is fired when a connection with an event source is opened.\n observer.next({type: 'open' as EventTypeName})\n }\n\n function onMessage(message: MessageEvent) {\n const [parseError, event] = parseEvent(message)\n if (parseError) {\n observer.error(\n new MessageParseError('Unable to parse EventSource message', {cause: parseError}),\n )\n return\n }\n if (message.type === 'channelError') {\n // An error occurred. This is different from a network-level error (which will be emitted as 'error').\n // Possible causes are things such as malformed filters, non-existant datasets\n // or similar.\n const tag = new URL(es.url).searchParams.get('tag')\n observer.error(new ChannelError(extractErrorMessage(event?.data, tag), event.data))\n return\n }\n if (message.type === 'disconnect') {\n // The listener has been told to explicitly disconnect and not reconnect.\n // This is a rare situation, but may occur if the API knows reconnect attempts will fail,\n // eg in the case of a deleted dataset, a blocked project or similar events.\n observer.error(\n new DisconnectError(\n `Server disconnected client: ${\n (event.data as {reason?: string})?.reason || 'unknown error'\n }`,\n ),\n )\n return\n }\n observer.next({\n type: message.type as EventTypeName,\n id: message.lastEventId,\n ...(event.data ? {data: event.data} : {}),\n })\n }\n\n es.addEventListener('error', onError)\n\n if (emitOpen) {\n es.addEventListener('open', onOpen)\n }\n\n // Make sure we have a unique list of events types to avoid listening multiple times,\n const cleanedEvents = [...new Set([...REQUIRED_EVENTS, ...events])]\n // filter out events that are handled separately\n .filter((type) => type !== 'error' && type !== 'open' && type !== 'reconnect')\n\n cleanedEvents.forEach((type: string) => es.addEventListener(type, onMessage))\n\n return () => {\n es.removeEventListener('error', onError)\n if (emitOpen) {\n es.removeEventListener('open', onOpen)\n }\n cleanedEvents.forEach((type: string) => es.removeEventListener(type, onMessage))\n es.close()\n }\n })\n}\n\nfunction parseEvent(\n message: MessageEvent,\n): [null, {type: string; id: string; data?: unknown}] | [Error, null] {\n try {\n const data = typeof message.data === 'string' && JSON.parse(message.data)\n return [\n null,\n {\n type: message.type,\n id: message.lastEventId,\n ...(isEmptyObject(data) ? {} : {data}),\n },\n ]\n } catch (err) {\n return [err as Error, null]\n }\n}\n\nfunction extractErrorMessage(err: Any, tag?: string | null) {\n const error = err.error\n\n if (!error) {\n return err.message || 'Unknown listener error'\n }\n\n if (isQueryParseError(error)) {\n return formatQueryParseError(error, tag)\n }\n\n if (error.description) {\n return error.description\n }\n\n return typeof error === 'string' ? error : JSON.stringify(error, null, 2)\n}\n\nfunction isEmptyObject(data: object) {\n for (const _ in data) {\n return false\n }\n return true\n}\n","import type {MutationSelection} from '../types'\n\nexport function getSelection(sel: unknown): MutationSelection {\n if (typeof sel === 'string') {\n return {id: sel}\n }\n\n if (Array.isArray(sel)) {\n return {query: '*[_id in $ids]', params: {ids: sel}}\n }\n\n if (typeof sel === 'object' && sel !== null && 'query' in sel && typeof sel.query === 'string') {\n return 'params' in sel && typeof sel.params === 'object' && sel.params !== null\n ? {query: sel.query, params: sel.params}\n : {query: sel.query}\n }\n\n const selectionOpts = [\n '* Document ID (<docId>)',\n '* Array of document IDs',\n '* Object containing `query`',\n ].join('\\n')\n\n throw new Error(`Unknown selection - must be one of:\\n\\n${selectionOpts}`)\n}\n","import {type Observable} from 'rxjs'\n\nimport type {ObservableSanityClient, SanityClient} from '../SanityClient'\nimport type {\n AllDocumentIdsMutationOptions,\n AllDocumentsMutationOptions,\n Any,\n AttributeSet,\n BaseMutationOptions,\n FirstDocumentIdMutationOptions,\n FirstDocumentMutationOptions,\n MultipleMutationResult,\n PatchMutationOperation,\n PatchOperations,\n PatchSelection,\n SanityDocument,\n SingleMutationResult,\n} from '../types'\nimport {getSelection} from '../util/getSelection'\nimport {validateInsert, validateObject} from '../validators'\n\n/** @internal */\nexport class BasePatch {\n protected selection: PatchSelection\n protected operations: PatchOperations\n constructor(selection: PatchSelection, operations: PatchOperations = {}) {\n this.selection = selection\n this.operations = operations\n }\n\n /**\n * Sets the given attributes to the document. Does NOT merge objects.\n * The operation is added to the current patch, ready to be commited by `commit()`\n *\n * @param attrs - Attributes to set. To set a deep attribute, use JSONMatch, eg: \\{\"nested.prop\": \"value\"\\}\n */\n set(attrs: AttributeSet): this {\n return this._assign('set', attrs)\n }\n\n /**\n * Sets the given attributes to the document if they are not currently set. Does NOT merge objects.\n * The operation is added to the current patch, ready to be commited by `commit()`\n *\n * @param attrs - Attributes to set. To set a deep attribute, use JSONMatch, eg: \\{\"nested.prop\": \"value\"\\}\n */\n setIfMissing(attrs: AttributeSet): this {\n return this._assign('setIfMissing', attrs)\n }\n\n /**\n * Performs a \"diff-match-patch\" operation on the string attributes provided.\n * The operation is added to the current patch, ready to be commited by `commit()`\n *\n * @param attrs - Attributes to perform operation on. To set a deep attribute, use JSONMatch, eg: \\{\"nested.prop\": \"dmp\"\\}\n */\n diffMatchPatch(attrs: AttributeSet): this {\n validateObject('diffMatchPatch', attrs)\n return this._assign('diffMatchPatch', attrs)\n }\n\n /**\n * Unsets the attribute paths provided.\n * The operation is added to the current patch, ready to be commited by `commit()`\n *\n * @param attrs - Attribute paths to unset.\n */\n unset(attrs: string[]): this {\n if (!Array.isArray(attrs)) {\n throw new Error('unset(attrs) takes an array of attributes to unset, non-array given')\n }\n\n this.operations = Object.assign({}, this.operations, {unset: attrs})\n return this\n }\n\n /**\n * 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.\n *\n * @param attrs - Object of attribute paths to increment, values representing the number to increment by.\n */\n inc(attrs: {[key: string]: number}): this {\n return this._assign('inc', attrs)\n }\n\n /**\n * 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.\n *\n * @param attrs - Object of attribute paths to decrement, values representing the number to decrement by.\n */\n dec(attrs: {[key: string]: number}): this {\n return this._assign('dec', attrs)\n }\n\n /**\n * Provides methods for modifying arrays, by inserting, appending and replacing elements via a JSONPath expression.\n *\n * @param at - Location to insert at, relative to the given selector, or 'replace' the matched path\n * @param selector - JSONPath expression, eg `comments[-1]` or `blocks[_key==\"abc123\"]`\n * @param items - Array of items to insert/replace\n */\n insert(at: 'before' | 'after' | 'replace', selector: string, items: Any[]): this {\n validateInsert(at, selector, items)\n return this._assign('insert', {[at]: selector, items})\n }\n\n /**\n * Append the given items to the array at the given JSONPath\n *\n * @param selector - Attribute/path to append to, eg `comments` or `person.hobbies`\n * @param items - Array of items to append to the array\n */\n append(selector: string, items: Any[]): this {\n return this.insert('after', `${selector}[-1]`, items)\n }\n\n /**\n * Prepend the given items to the array at the given JSONPath\n *\n * @param selector - Attribute/path to prepend to, eg `comments` or `person.hobbies`\n * @param items - Array of items to prepend to the array\n */\n prepend(selector: string, items: Any[]): this {\n return this.insert('before', `${selector}[0]`, items)\n }\n\n /**\n * Change the contents of an array by removing existing elements and/or adding new elements.\n *\n * @param selector - Attribute or JSONPath expression for array\n * @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\n * @param deleteCount - An integer indicating the number of old array elements to remove.\n * @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.\n */\n splice(selector: string, start: number, deleteCount?: number, items?: Any[]): this {\n // Negative indexes doesn't mean the same in Sanity as they do in JS;\n // -1 means \"actually at the end of the array\", which allows inserting\n // at the end of the array without knowing its length. We therefore have\n // to substract negative indexes by one to match JS. If you want Sanity-\n // behaviour, just use `insert('replace', selector, items)` directly\n const delAll = typeof deleteCount === 'undefined' || deleteCount === -1\n const startIndex = start < 0 ? start - 1 : start\n const delCount = delAll ? -1 : Math.max(0, start + deleteCount)\n const delRange = startIndex < 0 && delCount >= 0 ? '' : delCount\n const rangeSelector = `${selector}[${startIndex}:${delRange}]`\n return this.insert('replace', rangeSelector, items || [])\n }\n\n /**\n * Adds a revision clause, preventing the document from being patched if the `_rev` property does not match the given value\n *\n * @param rev - Revision to lock the patch to\n */\n ifRevisionId(rev: string): this {\n this.operations.ifRevisionID = rev\n return this\n }\n\n /**\n * Return a plain JSON representation of the patch\n */\n serialize(): PatchMutationOperation {\n return {...getSelection(this.selection), ...this.operations}\n }\n\n /**\n * Return a plain JSON representation of the patch\n */\n toJSON(): PatchMutationOperation {\n return this.serialize()\n }\n\n /**\n * Clears the patch of all operations\n */\n reset(): this {\n this.operations = {}\n return this\n }\n\n protected _assign(op: keyof PatchOperations, props: Any, merge = true): this {\n validateObject(op, props)\n this.operations = Object.assign({}, this.operations, {\n [op]: Object.assign({}, (merge && this.operations[op]) || {}, props),\n })\n return this\n }\n\n protected _set(op: keyof PatchOperations, props: Any): this {\n return this._assign(op, props, false)\n }\n}\n\n/** @public */\nexport class ObservablePatch extends BasePatch {\n #client?: ObservableSanityClient\n\n constructor(\n selection: PatchSelection,\n operations?: PatchOperations,\n client?: ObservableSanityClient,\n ) {\n super(selection, operations)\n this.#client = client\n }\n\n /**\n * Clones the patch\n */\n clone(): ObservablePatch {\n return new ObservablePatch(this.selection, {...this.operations}, this.#client)\n }\n\n /**\n * Commit the patch, returning an observable that produces the first patched document\n *\n * @param options - Options for the mutation operation\n */\n commit<R extends Record<string, Any> = Record<string, Any>>(\n options: FirstDocumentMutationOptions,\n ): Observable<SanityDocument<R>>\n /**\n * Commit the patch, returning an observable that produces an array of the mutated documents\n *\n * @param options - Options for the mutation operation\n */\n commit<R extends Record<string, Any> = Record<string, Any>>(\n options: AllDocumentsMutationOptions,\n ): Observable<SanityDocument<R>[]>\n /**\n * Commit the patch, returning an observable that produces a mutation result object\n *\n * @param options - Options for the mutation operation\n */\n commit(options: FirstDocumentIdMutationOptions): Observable<SingleMutationResult>\n /**\n * Commit the patch, returning an observable that produces a mutation result object\n *\n * @param options - Options for the mutation operation\n */\n commit(options: AllDocumentIdsMutationOptions): Observable<MultipleMutationResult>\n /**\n * Commit the patch, returning an observable that produces the first patched document\n *\n * @param options - Options for the mutation operation\n */\n commit<R extends Record<string, Any> = Record<string, Any>>(\n options?: BaseMutationOptions,\n ): Observable<SanityDocument<R>>\n commit<R extends Record<string, Any> = Record<string, Any>>(\n options?:\n | FirstDocumentMutationOptions\n | AllDocumentsMutationOptions\n | FirstDocumentIdMutationOptions\n | AllDocumentIdsMutationOptions\n | BaseMutationOptions,\n ): Observable<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n if (!this.#client) {\n throw new Error(\n 'No `client` passed to patch, either provide one or pass the ' +\n 'patch to a clients `mutate()` method',\n )\n }\n\n const returnFirst = typeof this.selection === 'string'\n const opts = Object.assign({returnFirst, returnDocuments: true}, options)\n return this.#client.mutate<R>({patch: this.serialize()} as Any, opts)\n }\n}\n\n/** @public */\nexport class Patch extends BasePatch {\n #client?: SanityClient\n constructor(selection: PatchSelection, operations?: PatchOperations, client?: SanityClient) {\n super(selection, operations)\n this.#client = client\n }\n\n /**\n * Clones the patch\n */\n clone(): Patch {\n return new Patch(this.selection, {...this.operations}, this.#client)\n }\n\n /**\n * Commit the patch, returning a promise that resolves to the first patched document\n *\n * @param options - Options for the mutation operation\n */\n commit<R extends Record<string, Any> = Record<string, Any>>(\n options: FirstDocumentMutationOptions,\n ): Promise<SanityDocument<R>>\n /**\n * Commit the patch, returning a promise that resolves to an array of the mutated documents\n *\n * @param options - Options for the mutation operation\n */\n commit<R extends Record<string, Any> = Record<string, Any>>(\n options: AllDocumentsMutationOptions,\n ): Promise<SanityDocument<R>[]>\n /**\n * Commit the patch, returning a promise that resolves to a mutation result object\n *\n * @param options - Options for the mutation operation\n */\n commit(options: FirstDocumentIdMutationOptions): Promise<SingleMutationResult>\n /**\n * Commit the patch, returning a promise that resolves to a mutation result object\n *\n * @param options - Options for the mutation operation\n */\n commit(options: AllDocumentIdsMutationOptions): Promise<MultipleMutationResult>\n /**\n * Commit the patch, returning a promise that resolves to the first patched document\n *\n * @param options - Options for the mutation operation\n */\n commit<R extends Record<string, Any> = Record<string, Any>>(\n options?: BaseMutationOptions,\n ): Promise<SanityDocument<R>>\n commit<R extends Record<string, Any> = Record<string, Any>>(\n options?:\n | FirstDocumentMutationOptions\n | AllDocumentsMutationOptions\n | FirstDocumentIdMutationOptions\n | AllDocumentIdsMutationOptions\n | BaseMutationOptions,\n ): Promise<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n if (!this.#client) {\n throw new Error(\n 'No `client` passed to patch, either provide one or pass the ' +\n 'patch to a clients `mutate()` method',\n )\n }\n\n const returnFirst = typeof this.selection === 'string'\n const opts = Object.assign({returnFirst, returnDocuments: true}, options)\n return this.#client.mutate<R>({patch: this.serialize()} as Any, opts)\n }\n}\n","import type {Observable} from 'rxjs'\n\nimport type {ObservableSanityClient, SanityClient} from '../SanityClient'\nimport type {\n Any,\n BaseMutationOptions,\n IdentifiedSanityDocumentStub,\n MultipleMutationResult,\n Mutation,\n MutationSelection,\n PatchOperations,\n SanityDocument,\n SanityDocumentStub,\n SingleMutationResult,\n TransactionAllDocumentIdsMutationOptions,\n TransactionAllDocumentsMutationOptions,\n TransactionFirstDocumentIdMutationOptions,\n TransactionFirstDocumentMutationOptions,\n} from '../types'\nimport * as validators from '../validators'\nimport {ObservablePatch, Patch} from './patch'\n\n/** @public */\nexport type PatchBuilder = (patch: Patch) => Patch\n/** @public */\nexport type ObservablePatchBuilder = (patch: ObservablePatch) => ObservablePatch\n\nconst defaultMutateOptions = {returnDocuments: false}\n\n/** @internal */\nexport class BaseTransaction {\n protected operations: Mutation[]\n protected trxId?: string\n constructor(operations: Mutation[] = [], transactionId?: string) {\n this.operations = operations\n this.trxId = transactionId\n }\n /**\n * 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.\n * The operation is added to the current transaction, ready to be commited by `commit()`\n *\n * @param doc - Document to create. Requires a `_type` property.\n */\n create<R extends Record<string, Any> = Record<string, Any>>(doc: SanityDocumentStub<R>): this {\n validators.validateObject('create', doc)\n return this._add({create: doc})\n }\n\n /**\n * Creates a new Sanity document. If a document with the same `_id` already exists, the create operation will be ignored.\n * The operation is added to the current transaction, ready to be commited by `commit()`\n *\n * @param doc - Document to create if it does not already exist. Requires `_id` and `_type` properties.\n */\n createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(\n doc: IdentifiedSanityDocumentStub<R>,\n ): this {\n const op = 'createIfNotExists'\n validators.validateObject(op, doc)\n validators.requireDocumentId(op, doc)\n return this._add({[op]: doc})\n }\n\n /**\n * Creates a new Sanity document, or replaces an existing one if the same `_id` is already used.\n * The operation is added to the current transaction, ready to be commited by `commit()`\n *\n * @param doc - Document to create or replace. Requires `_id` and `_type` properties.\n */\n createOrReplace<R extends Record<string, Any> = Record<string, Any>>(\n doc: IdentifiedSanityDocumentStub<R>,\n ): this {\n const op = 'createOrReplace'\n validators.validateObject(op, doc)\n validators.requireDocumentId(op, doc)\n return this._add({[op]: doc})\n }\n\n /**\n * Deletes the document with the given document ID\n * The operation is added to the current transaction, ready to be commited by `commit()`\n *\n * @param documentId - Document ID to delete\n */\n delete(documentId: string): this {\n validators.validateDocumentId('delete', documentId)\n return this._add({delete: {id: documentId}})\n }\n\n /**\n * Gets the current transaction ID, if any\n */\n transactionId(): string | undefined\n /**\n * Set the ID of this transaction.\n *\n * @param id - Transaction ID\n */\n transactionId(id: string): this\n transactionId(id?: string): this | string | undefined {\n if (!id) {\n return this.trxId\n }\n\n this.trxId = id\n return this\n }\n\n /**\n * Return a plain JSON representation of the transaction\n */\n serialize(): Mutation[] {\n return [...this.operations]\n }\n\n /**\n * Return a plain JSON representation of the transaction\n */\n toJSON(): Mutation[] {\n return this.serialize()\n }\n\n /**\n * Clears the transaction of all operations\n */\n reset(): this {\n this.operations = []\n return this\n }\n\n protected _add(mut: Mutation): this {\n this.operations.push(mut)\n return this\n }\n}\n\n/** @public */\nexport class Transaction extends BaseTransaction {\n #client?: SanityClient\n constructor(operations?: Mutation[], client?: SanityClient, transactionId?: string) {\n super(operations, transactionId)\n this.#client = client\n }\n\n /**\n * Clones the transaction\n */\n clone(): Transaction {\n return new Transaction([...this.operations], this.#client, this.trxId)\n }\n\n /**\n * Commit the transaction, returning a promise that resolves to the first mutated document\n *\n * @param options - Options for the mutation operation\n */\n commit<R extends Record<string, Any>>(\n options: TransactionFirstDocumentMutationOptions,\n ): Promise<SanityDocument<R>>\n /**\n * Commit the transaction, returning a promise that resolves to an array of the mutated documents\n *\n * @param options - Options for the mutation operation\n */\n commit<R extends Record<string, Any>>(\n options: TransactionAllDocumentsMutationOptions,\n ): Promise<SanityDocument<R>[]>\n /**\n * Commit the transaction, returning a promise that resolves to a mutation result object\n *\n * @param options - Options for the mutation operation\n */\n commit(options: TransactionFirstDocumentIdMutationOptions): Promise<SingleMutationResult>\n /**\n * Commit the transaction, returning a promise that resolves to a mutation result object\n *\n * @param options - Options for the mutation operation\n */\n commit(options: TransactionAllDocumentIdsMutationOptions): Promise<MultipleMutationResult>\n /**\n * Commit the transaction, returning a promise that resolves to a mutation result object\n *\n * @param options - Options for the mutation operation\n */\n commit(options?: BaseMutationOptions): Promise<MultipleMutationResult>\n commit<R extends Record<string, Any> = Record<string, Any>>(\n options?:\n | TransactionFirstDocumentMutationOptions\n | TransactionAllDocumentsMutationOptions\n | TransactionFirstDocumentIdMutationOptions\n | TransactionAllDocumentIdsMutationOptions\n | BaseMutationOptions,\n ): Promise<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n if (!this.#client) {\n throw new Error(\n 'No `client` passed to transaction, either provide one or pass the ' +\n 'transaction to a clients `mutate()` method',\n )\n }\n\n return this.#client.mutate<R>(\n this.serialize() as Any,\n Object.assign({transactionId: this.trxId}, defaultMutateOptions, options || {}),\n )\n }\n\n /**\n * Performs a patch on the given document ID. Can either be a builder function or an object of patch operations.\n * The operation is added to the current transaction, ready to be commited by `commit()`\n *\n * @param documentId - Document ID to perform the patch operation on\n * @param patchOps - Operations to perform, or a builder function\n */\n patch(documentId: string, patchOps?: PatchBuilder | PatchOperations): this\n /**\n * Performs a patch on the given selection. Can either be a builder function or an object of patch operations.\n *\n * @param selection - An object with `query` and optional `params`, defining which document(s) to patch\n * @param patchOps - Operations to perform, or a builder function\n */\n patch(patch: MutationSelection, patchOps?: PatchBuilder | PatchOperations): this\n /**\n * Adds the given patch instance to the transaction.\n * The operation is added to the current transaction, ready to be commited by `commit()`\n *\n * @param patch - Patch to execute\n */\n patch(patch: Patch): this\n patch(\n patchOrDocumentId: Patch | MutationSelection | string,\n patchOps?: PatchBuilder | PatchOperations,\n ): this {\n const isBuilder = typeof patchOps === 'function'\n const isPatch = typeof patchOrDocumentId !== 'string' && patchOrDocumentId instanceof Patch\n const isMutationSelection =\n typeof patchOrDocumentId === 'object' &&\n ('query' in patchOrDocumentId || 'id' in patchOrDocumentId)\n\n // transaction.patch(client.patch('documentId').inc({visits: 1}))\n if (isPatch) {\n return this._add({patch: patchOrDocumentId.serialize()})\n }\n\n // patch => patch.inc({visits: 1}).set({foo: 'bar'})\n if (isBuilder) {\n const patch = patchOps(new Patch(patchOrDocumentId, {}, this.#client))\n if (!(patch instanceof Patch)) {\n throw new Error('function passed to `patch()` must return the patch')\n }\n\n return this._add({patch: patch.serialize()})\n }\n\n /*\n * transaction.patch(\n * {query: \"*[_type == 'person' && points >= $threshold]\", params: { threshold: 100 }},\n * {dec: { points: 100 }, inc: { bonuses: 1 }}\n * )\n */\n if (isMutationSelection) {\n const patch = new Patch(patchOrDocumentId, patchOps || {}, this.#client)\n return this._add({patch: patch.serialize()})\n }\n\n return this._add({patch: {id: patchOrDocumentId, ...patchOps}})\n }\n}\n\n/** @public */\nexport class ObservableTransaction extends BaseTransaction {\n #client?: ObservableSanityClient\n constructor(operations?: Mutation[], client?: ObservableSanityClient, transactionId?: string) {\n super(operations, transactionId)\n this.#client = client\n }\n\n /**\n * Clones the transaction\n */\n clone(): ObservableTransaction {\n return new ObservableTransaction([...this.operations], this.#client, this.trxId)\n }\n\n /**\n * Commit the transaction, returning an observable that produces the first mutated document\n *\n * @param options - Options for the mutation operation\n */\n commit<R extends Record<string, Any>>(\n options: TransactionFirstDocumentMutationOptions,\n ): Observable<SanityDocument<R>>\n /**\n * Commit the transaction, returning an observable that produces an array of the mutated documents\n *\n * @param options - Options for the mutation operation\n */\n commit<R extends Record<string, Any>>(\n options: TransactionAllDocumentsMutationOptions,\n ): Observable<SanityDocument<R>[]>\n /**\n * Commit the transaction, returning an observable that produces a mutation result object\n *\n * @param options - Options for the mutation operation\n */\n commit(options: TransactionFirstDocumentIdMutationOptions): Observable<SingleMutationResult>\n /**\n * Commit the transaction, returning an observable that produces a mutation result object\n *\n * @param options - Options for the mutation operation\n */\n commit(options: TransactionAllDocumentIdsMutationOptions): Observable<MultipleMutationResult>\n /**\n * Commit the transaction, returning an observable that produces a mutation result object\n *\n * @param options - Options for the mutation operation\n */\n commit(options?: BaseMutationOptions): Observable<MultipleMutationResult>\n commit<R extends Record<string, Any> = Record<string, Any>>(\n options?:\n | TransactionFirstDocumentMutationOptions\n | TransactionAllDocumentsMutationOptions\n | TransactionFirstDocumentIdMutationOptions\n | TransactionAllDocumentIdsMutationOptions\n | BaseMutationOptions,\n ): Observable<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n if (!this.#client) {\n throw new Error(\n 'No `client` passed to transaction, either provide one or pass the ' +\n 'transaction to a clients `mutate()` method',\n )\n }\n\n return this.#client.mutate<R>(\n this.serialize() as Any,\n Object.assign({transactionId: this.trxId}, defaultMutateOptions, options || {}),\n )\n }\n\n /**\n * Performs a patch on the given document ID. Can either be a builder function or an object of patch operations.\n * The operation is added to the current transaction, ready to be commited by `commit()`\n *\n * @param documentId - Document ID to perform the patch operation on\n * @param patchOps - Operations to perform, or a builder function\n */\n patch(documentId: string, patchOps?: ObservablePatchBuilder | PatchOperations): this\n /**\n * Adds the given patch instance to the transaction.\n * The operation is added to the current transaction, ready to be commited by `commit()`\n *\n * @param patch - ObservablePatch to execute\n */\n patch(patch: ObservablePatch): this\n patch(\n patchOrDocumentId: ObservablePatch | string,\n patchOps?: ObservablePatchBuilder | PatchOperations,\n ): this {\n const isBuilder = typeof patchOps === 'function'\n const isPatch =\n typeof patchOrDocumentId !== 'string' && patchOrDocumentId instanceof ObservablePatch\n\n // transaction.patch(client.patch('documentId').inc({visits: 1}))\n if (isPatch) {\n return this._add({patch: patchOrDocumentId.serialize()})\n }\n\n // patch => patch.inc({visits: 1}).set({foo: 'bar'})\n if (isBuilder) {\n const patch = patchOps(new ObservablePatch(patchOrDocumentId, {}, this.#client))\n if (!(patch instanceof ObservablePatch)) {\n throw new Error('function passed to `patch()` must return the patch')\n }\n\n return this._add({patch: patch.serialize()})\n }\n\n return this._add({patch: {id: patchOrDocumentId, ...patchOps}})\n }\n}\n","import type {RequestOptions} from 'get-it'\n\nimport type {Any} from '../types'\n\nconst projectHeader = 'X-Sanity-Project-ID'\n\nexport function requestOptions(config: Any, overrides: Any = {}): Omit<RequestOptions, 'url'> {\n const headers: Any = {}\n\n if (config.headers) {\n Object.assign(headers, config.headers)\n }\n\n const token = overrides.token || config.token\n if (token) {\n headers.Authorization = `Bearer ${token}`\n }\n\n if (!overrides.useGlobalApi && !config.useProjectHostname && config.projectId) {\n headers[projectHeader] = config.projectId\n }\n\n const withCredentials = Boolean(\n typeof overrides.withCredentials === 'undefined'\n ? config.withCredentials\n : overrides.withCredentials,\n )\n\n const timeout = typeof overrides.timeout === 'undefined' ? config.timeout : overrides.timeout\n return Object.assign({}, overrides, {\n headers: Object.assign({}, headers, overrides.headers || {}),\n timeout: typeof timeout === 'undefined' ? 5 * 60 * 1000 : timeout,\n proxy: overrides.proxy || config.proxy,\n json: true,\n withCredentials,\n fetch:\n typeof overrides.fetch === 'object' && typeof config.fetch === 'object'\n ? {...config.fetch, ...overrides.fetch}\n : overrides.fetch || config.fetch,\n })\n}\n","import type {Any, ListenParams, QueryParams} from '../types'\n\nexport const encodeQueryString = ({\n query,\n params = {},\n options = {},\n}: {\n query: string\n params?: ListenParams | QueryParams\n options?: Any\n}) => {\n const searchParams = new URLSearchParams()\n // We generally want tag at the start of the query string\n const {tag, includeMutations, returnQuery, ...opts} = options\n // We're using `append` instead of `set` to support React Native: https://github.com/facebook/react-native/blob/1982c4722fcc51aa87e34cf562672ee4aff540f1/packages/react-native/Libraries/Blob/URL.js#L86-L88\n if (tag) searchParams.append('tag', tag)\n searchParams.append('query', query)\n\n // Iterate params, the keys are prefixed with `$` and their values JSON stringified\n for (const [key, value] of Object.entries(params)) {\n if (value !== undefined) searchParams.append(`$${key}`, JSON.stringify(value))\n }\n // Options are passed as-is\n for (const [key, value] of Object.entries(opts)) {\n // Skip falsy values\n if (value) searchParams.append(key, `${value}`)\n }\n\n // `returnQuery` is default `true`, so needs an explicit `false` handling\n if (returnQuery === false) searchParams.append('returnQuery', 'false')\n\n // `includeMutations` is default `true`, so needs an explicit `false` handling\n if (includeMutations === false) searchParams.append('includeMutations', 'false')\n\n return `?${searchParams}`\n}\n","import {getDraftId, getVersionFromId, getVersionId, isDraftId} from '@sanity/client/csm'\nimport {from, type MonoTypeOperatorFunction, Observable} from 'rxjs'\nimport {combineLatestWith, filter, map} from 'rxjs/operators'\n\nimport {validateApiPerspective} from '../config'\nimport {requestOptions} from '../http/requestOptions'\nimport type {ObservableSanityClient, SanityClient} from '../SanityClient'\nimport {stegaClean} from '../stega/stegaClean'\nimport type {\n Action,\n AllDocumentIdsMutationOptions,\n AllDocumentsMutationOptions,\n Any,\n BaseActionOptions,\n BaseMutationOptions,\n CreateVersionAction,\n DiscardVersionAction,\n FirstDocumentIdMutationOptions,\n FirstDocumentMutationOptions,\n HttpRequest,\n HttpRequestEvent,\n IdentifiedSanityDocumentStub,\n InitializedClientConfig,\n InitializedStegaConfig,\n MultipleActionResult,\n MultipleMutationResult,\n Mutation,\n MutationSelection,\n QueryOptions,\n RawQueryResponse,\n ReplaceVersionAction,\n RequestObservableOptions,\n RequestOptions,\n SanityDocument,\n SingleActionResult,\n SingleMutationResult,\n UnpublishVersionAction,\n} from '../types'\nimport {getSelection} from '../util/getSelection'\nimport * as validate from '../validators'\nimport * as validators from '../validators'\nimport {\n printCdnPreviewDraftsWarning,\n printCreateVersionWithBaseIdWarning,\n printPreviewDraftsDeprecationWarning,\n} from '../warnings'\nimport {encodeQueryString} from './encodeQueryString'\nimport {ObservablePatch, Patch} from './patch'\nimport {ObservableTransaction, Transaction} from './transaction'\n\ntype Client = SanityClient | ObservableSanityClient\n\nconst excludeFalsey = (param: Any, defValue: Any) => {\n const value = typeof param === 'undefined' ? defValue : param\n return param === false ? undefined : value\n}\n\nconst getMutationQuery = (options: BaseMutationOptions = {}) => {\n return {\n dryRun: options.dryRun,\n returnIds: true,\n returnDocuments: excludeFalsey(options.returnDocuments, true),\n visibility: options.visibility || 'sync',\n autoGenerateArrayKeys: options.autoGenerateArrayKeys,\n skipCrossDatasetReferenceValidation: options.skipCrossDatasetReferenceValidation,\n }\n}\n\nconst isResponse = (event: Any) => event.type === 'response'\nconst getBody = (event: Any) => event.body\n\nconst indexBy = (docs: Any[], attr: Any) =>\n docs.reduce((indexed, doc) => {\n indexed[attr(doc)] = doc\n return indexed\n }, Object.create(null))\n\nconst getQuerySizeLimit = 11264\n\n/** @internal */\nexport function _fetch<R, Q>(\n client: Client,\n httpRequest: HttpRequest,\n _stega: InitializedStegaConfig,\n query: string,\n _params: Q = {} as Q,\n options: QueryOptions = {},\n): Observable<RawQueryResponse<R> | R> {\n const stega =\n 'stega' in options\n ? {\n ...(_stega || {}),\n ...(typeof options.stega === 'boolean' ? {enabled: options.stega} : options.stega || {}),\n }\n : _stega\n const params = stega.enabled ? stegaClean(_params) : _params\n const mapResponse =\n options.filterResponse === false ? (res: Any) => res : (res: Any) => res.result\n\n const {cache, next, ...opts} = {\n // Opt out of setting a `signal` on an internal `fetch` if one isn't provided.\n // This is necessary in React Server Components to avoid opting out of Request Memoization.\n useAbortSignal: typeof options.signal !== 'undefined',\n // Set `resultSourceMap' when stega is enabled, as it's required for encoding.\n resultSourceMap: stega.enabled ? 'withKeyArraySelector' : options.resultSourceMap,\n ...options,\n // Default to not returning the query, unless `filterResponse` is `false`,\n // or `returnQuery` is explicitly set. `true` is the default in Content Lake, so skip if truthy\n returnQuery: options.filterResponse === false && options.returnQuery !== false,\n }\n const reqOpts =\n typeof cache !== 'undefined' || typeof next !== 'undefined'\n ? {...opts, fetch: {cache, next}}\n : opts\n\n const $request = _dataRequest(client, httpRequest, 'query', {query, params}, reqOpts)\n return stega.enabled\n ? $request.pipe(\n combineLatestWith(\n from(\n import('../stega/stegaEncodeSourceMap').then(\n ({stegaEncodeSourceMap}) => stegaEncodeSourceMap,\n ),\n ),\n ),\n map(\n ([res, stegaEncodeSourceMap]: [\n Any,\n (typeof import('../stega/stegaEncodeSourceMap'))['stegaEncodeSourceMap'],\n ]) => {\n const result = stegaEncodeSourceMap(res.result, res.resultSourceMap, stega)\n return mapResponse({...res, result})\n },\n ),\n )\n : $request.pipe(map(mapResponse))\n}\n\n/** @internal */\nexport function _getDocument<R extends Record<string, Any>>(\n client: Client,\n httpRequest: HttpRequest,\n id: string,\n opts: {signal?: AbortSignal; tag?: string; releaseId?: string; includeAllVersions: true},\n): Observable<SanityDocument<R>[]>\n/** @internal */\nexport function _getDocument<R extends Record<string, Any>>(\n client: Client,\n httpRequest: HttpRequest,\n id: string,\n opts?: {signal?: AbortSignal; tag?: string; releaseId?: string; includeAllVersions?: false},\n): Observable<SanityDocument<R> | undefined>\n/** @internal */\nexport function _getDocument<R extends Record<string, Any>>(\n client: Client,\n httpRequest: HttpRequest,\n id: string,\n opts: {signal?: AbortSignal; tag?: string; releaseId?: string; includeAllVersions?: boolean} = {},\n): Observable<SanityDocument<R> | undefined | SanityDocument<R>[]> {\n const getDocId = () => {\n if (!opts.releaseId) {\n return id\n }\n\n const versionId = getVersionFromId(id)\n if (!versionId) {\n if (isDraftId(id)) {\n throw new Error(\n `The document ID (\\`${id}\\`) is a draft, but \\`options.releaseId\\` is set as \\`${opts.releaseId}\\``,\n )\n }\n\n return getVersionId(id, opts.releaseId)\n }\n\n if (versionId !== opts.releaseId) {\n throw new Error(\n `The document ID (\\`${id}\\`) is already a version of \\`${versionId}\\` release, but this does not match the provided \\`options.releaseId\\` (\\`${opts.releaseId}\\`)`,\n )\n }\n\n return id\n }\n const docId = getDocId()\n\n const options = {\n uri: _getDataUrl(client, 'doc', docId),\n json: true,\n tag: opts.tag,\n signal: opts.signal,\n query:\n opts.includeAllVersions !== undefined\n ? {includeAllVersions: opts.includeAllVersions}\n : undefined,\n }\n return _requestObservable<SanityDocument<R> | undefined | SanityDocument<R>[]>(\n client,\n httpRequest,\n options,\n ).pipe(\n filter(isResponse),\n map((event) => {\n const documents = event.body.documents\n if (!documents) {\n return opts.includeAllVersions ? [] : undefined\n }\n return opts.includeAllVersions ? documents : documents[0]\n }),\n )\n}\n\n/** @internal */\nexport function _getDocuments<R extends Record<string, Any>>(\n client: Client,\n httpRequest: HttpRequest,\n ids: string[],\n opts: {signal?: AbortSignal; tag?: string} = {},\n): Observable<(SanityDocument<R> | null)[]> {\n const options = {\n uri: _getDataUrl(client, 'doc', ids.join(',')),\n json: true,\n tag: opts.tag,\n signal: opts.signal,\n }\n return _requestObservable<(SanityDocument<R> | null)[]>(client, httpRequest, options).pipe(\n filter(isResponse),\n map((event: Any) => {\n const indexed = indexBy(event.body.documents || [], (doc: Any) => doc._id)\n return ids.map((id) => indexed[id] || null)\n }),\n )\n}\n\n/** @internal */\nexport function _getReleaseDocuments<R extends Record<string, Any>>(\n client: ObservableSanityClient | SanityClient,\n httpRequest: HttpRequest,\n releaseId: string,\n opts: BaseMutationOptions = {},\n): Observable<RawQueryResponse<SanityDocument<R>[]>> {\n return _dataRequest(\n client,\n httpRequest,\n 'query',\n {\n query: '*[sanity::partOfRelease($releaseId)]',\n params: {\n releaseId,\n },\n },\n opts,\n )\n}\n\n/** @internal */\nexport function _createIfNotExists<R extends Record<string, Any>>(\n client: Client,\n httpRequest: HttpRequest,\n doc: IdentifiedSanityDocumentStub<R>,\n options?:\n | AllDocumentIdsMutationOptions\n | AllDocumentsMutationOptions\n | BaseMutationOptions\n | FirstDocumentIdMutationOptions\n | FirstDocumentMutationOptions,\n): Observable<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n> {\n validators.requireDocumentId('createIfNotExists', doc)\n return _create<R>(client, httpRequest, doc, 'createIfNotExists', options)\n}\n\n/** @internal */\nexport function _createOrReplace<R extends Record<string, Any>>(\n client: Client,\n httpRequest: HttpRequest,\n doc: IdentifiedSanityDocumentStub<R>,\n options?:\n | AllDocumentIdsMutationOptions\n | AllDocumentsMutationOptions\n | BaseMutationOptions\n | FirstDocumentIdMutationOptions\n | FirstDocumentMutationOptions,\n): Observable<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n> {\n validators.requireDocumentId('createOrReplace', doc)\n return _create<R>(client, httpRequest, doc, 'createOrReplace', options)\n}\n\n/** @internal */\nexport function _createVersion<R extends Record<string, Any>>(\n client: ObservableSanityClient | SanityClient,\n httpRequest: HttpRequest,\n doc: IdentifiedSanityDocumentStub<R>,\n publishedId: string,\n options?: BaseActionOptions,\n): Observable<SingleActionResult> {\n validators.requireDocumentId('createVersion', doc)\n validators.requireDocumentType('createVersion', doc)\n printCreateVersionWithBaseIdWarning()\n\n const createVersionAction: CreateVersionAction = {\n actionType: 'sanity.action.document.version.create',\n publishedId,\n document: doc,\n }\n\n return _action(client, httpRequest, createVersionAction, options)\n}\n\n/** @internal */\nexport function _createVersionFromBase(\n client: ObservableSanityClient | SanityClient,\n httpRequest: HttpRequest,\n publishedId?: string,\n baseId?: string,\n releaseId?: string,\n ifBaseRevisionId?: string,\n options?: BaseActionOptions,\n): Observable<SingleActionResult> {\n if (!baseId) {\n throw new Error('`createVersion()` requires `baseId` when no `document` is provided')\n }\n\n if (!publishedId) {\n throw new Error('`createVersion()` requires `publishedId` when `baseId` is provided')\n }\n\n validators.validateDocumentId('createVersion', baseId)\n validators.validateDocumentId('createVersion', publishedId)\n\n const createVersionAction: CreateVersionAction = {\n actionType: 'sanity.action.document.version.create',\n publishedId,\n baseId,\n versionId: releaseId ? getVersionId(publishedId, releaseId) : getDraftId(publishedId),\n ifBaseRevisionId,\n }\n\n return _action(client, httpRequest, createVersionAction, options)\n}\n\n/** @internal */\nexport function _delete<R extends Record<string, Any>>(\n client: Client,\n httpRequest: HttpRequest,\n selection: string | MutationSelection,\n options?:\n | AllDocumentIdsMutationOptions\n | AllDocumentsMutationOptions\n | BaseMutationOptions\n | FirstDocumentIdMutationOptions\n | FirstDocumentMutationOptions,\n): Observable<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n> {\n return _dataRequest(\n client,\n httpRequest,\n 'mutate',\n {mutations: [{delete: getSelection(selection)}]},\n options,\n )\n}\n\n/** @internal */\nexport function _discardVersion(\n client: ObservableSanityClient | SanityClient,\n httpRequest: HttpRequest,\n versionId: string,\n purge: boolean = false,\n options?: BaseActionOptions,\n): Observable<SingleActionResult> {\n const discardVersionAction: DiscardVersionAction = {\n actionType: 'sanity.action.document.version.discard',\n versionId,\n purge,\n }\n\n return _action(client, httpRequest, discardVersionAction, options)\n}\n\n/** @internal */\nexport function _replaceVersion<R extends Record<string, Any>>(\n client: ObservableSanityClient | SanityClient,\n httpRequest: HttpRequest,\n doc: IdentifiedSanityDocumentStub<R>,\n options?: BaseActionOptions,\n): Observable<SingleActionResult> {\n validators.requireDocumentId('replaceVersion', doc)\n validators.requireDocumentType('replaceVersion', doc)\n\n const replaceVersionAction: ReplaceVersionAction = {\n actionType: 'sanity.action.document.version.replace',\n document: doc,\n }\n\n return _action(client, httpRequest, replaceVersionAction, options)\n}\n\n/** @internal */\nexport function _unpublishVersion(\n client: ObservableSanityClient | SanityClient,\n httpRequest: HttpRequest,\n versionId: string,\n publishedId: string,\n options?: BaseActionOptions,\n): Observable<SingleActionResult> {\n const unpublishVersionAction: UnpublishVersionAction = {\n actionType: 'sanity.action.document.version.unpublish',\n versionId,\n publishedId,\n }\n\n return _action(client, httpRequest, unpublishVersionAction, options)\n}\n\n/** @internal */\nexport function _mutate<R extends Record<string, Any>>(\n client: Client,\n httpRequest: HttpRequest,\n mutations: Mutation<R>[] | Patch | ObservablePatch | Transaction | ObservableTransaction,\n options?:\n | AllDocumentIdsMutationOptions\n | AllDocumentsMutationOptions\n | BaseMutationOptions\n | FirstDocumentIdMutationOptions\n | FirstDocumentMutationOptions,\n): Observable<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n> {\n let mut: Mutation | Mutation[]\n if (mutations instanceof Patch || mutations instanceof ObservablePatch) {\n mut = {patch: mutations.serialize()}\n } else if (mutations instanceof Transaction || mutations instanceof ObservableTransaction) {\n mut = mutations.serialize()\n } else {\n mut = mutations\n }\n\n const muts = Array.isArray(mut) ? mut : [mut]\n const transactionId = (options && options.transactionId) || undefined\n return _dataRequest(client, httpRequest, 'mutate', {mutations: muts, transactionId}, options)\n}\n\n/**\n * @internal\n */\nexport function _action(\n client: Client,\n httpRequest: HttpRequest,\n actions: Action | Action[],\n options?: BaseActionOptions,\n): Observable<SingleActionResult | MultipleActionResult> {\n const acts = Array.isArray(actions) ? actions : [actions]\n const transactionId = (options && options.transactionId) || undefined\n const skipCrossDatasetReferenceValidation =\n (options && options.skipCrossDatasetReferenceValidation) || undefined\n const dryRun = (options && options.dryRun) || undefined\n\n return _dataRequest(\n client,\n httpRequest,\n 'actions',\n {actions: acts, transactionId, skipCrossDatasetReferenceValidation, dryRun},\n options,\n )\n}\n\n/**\n * @internal\n */\nexport function _dataRequest(\n client: Client,\n httpRequest: HttpRequest,\n endpoint: string,\n body: Any,\n options: Any = {},\n): Any {\n const isMutation = endpoint === 'mutate'\n const isAction = endpoint === 'actions'\n const isQuery = endpoint === 'query'\n\n // Check if the query string is within a configured threshold,\n // in which case we can use GET. Otherwise, use POST.\n const strQuery = isMutation || isAction ? '' : encodeQueryString(body)\n const useGet = !isMutation && !isAction && strQuery.length < getQuerySizeLimit\n const stringQuery = useGet ? strQuery : ''\n const returnFirst = options.returnFirst\n const {timeout, token, tag, headers, returnQuery, lastLiveEventId, cacheMode} = options\n\n const uri = _getDataUrl(client, endpoint, stringQuery)\n\n const reqOptions = {\n method: useGet ? 'GET' : 'POST',\n uri: uri,\n json: true,\n body: useGet ? undefined : body,\n query: isMutation && getMutationQuery(options),\n timeout,\n headers,\n token,\n tag,\n returnQuery,\n perspective: options.perspective,\n resultSourceMap: options.resultSourceMap,\n lastLiveEventId: Array.isArray(lastLiveEventId) ? lastLiveEventId[0] : lastLiveEventId,\n cacheMode: cacheMode,\n canUseCdn: isQuery,\n signal: options.signal,\n fetch: options.fetch,\n useAbortSignal: options.useAbortSignal,\n useCdn: options.useCdn,\n }\n\n return _requestObservable(client, httpRequest, reqOptions).pipe(\n filter(isResponse),\n map(getBody),\n map((res) => {\n if (!isMutation) {\n return res\n }\n\n // Should we return documents?\n const results = res.results || []\n if (options.returnDocuments) {\n return returnFirst\n ? results[0] && results[0].document\n : results.map((mut: Any) => mut.document)\n }\n\n // Return a reduced subset\n const key = returnFirst ? 'documentId' : 'documentIds'\n const ids = returnFirst ? results[0] && results[0].id : results.map((mut: Any) => mut.id)\n return {\n transactionId: res.transactionId,\n results: results,\n [key]: ids,\n }\n }),\n )\n}\n\n/**\n * @internal\n */\nexport function _create<R extends Record<string, Any>>(\n client: Client,\n httpRequest: HttpRequest,\n doc: Any,\n op: Any,\n options: Any = {},\n): Observable<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n> {\n const mutation = {[op]: doc}\n const opts = Object.assign({returnFirst: true, returnDocuments: true}, options)\n return _dataRequest(client, httpRequest, 'mutate', {mutations: [mutation]}, opts)\n}\n\nconst hasDataConfig = (client: Client) => {\n const config = client.config()\n return (\n (config.dataset !== undefined && config.projectId !== undefined) ||\n config.resource !== undefined\n )\n}\n\nconst isQuery = (client: Client, uri: string) =>\n hasDataConfig(client) && uri.startsWith(_getDataUrl(client, 'query'))\n\nconst isMutate = (client: Client, uri: string) =>\n hasDataConfig(client) && uri.startsWith(_getDataUrl(client, 'mutate'))\n\nconst isDoc = (client: Client, uri: string) =>\n hasDataConfig(client) && uri.startsWith(_getDataUrl(client, 'doc', ''))\n\nconst isListener = (client: Client, uri: string) =>\n hasDataConfig(client) && uri.startsWith(_getDataUrl(client, 'listen'))\n\nconst isHistory = (client: Client, uri: string) =>\n hasDataConfig(client) && uri.startsWith(_getDataUrl(client, 'history', ''))\n\nconst isData = (client: Client, uri: string) =>\n uri.startsWith('/data/') ||\n isQuery(client, uri) ||\n isMutate(client, uri) ||\n isDoc(client, uri) ||\n isListener(client, uri) ||\n isHistory(client, uri)\n\n/**\n * @internal\n */\nexport function _requestObservable<R>(\n client: Client,\n httpRequest: HttpRequest,\n options: RequestObservableOptions,\n): Observable<HttpRequestEvent<R>> {\n const uri = options.url || (options.uri as string)\n const config = client.config()\n\n // If the `canUseCdn`-option is not set we detect it automatically based on the method + URL.\n // Only the /data endpoint is currently available through API-CDN.\n const canUseCdn =\n typeof options.canUseCdn === 'undefined'\n ? ['GET', 'HEAD'].indexOf(options.method || 'GET') >= 0 && isData(client, uri)\n : options.canUseCdn\n\n let useCdn = (options.useCdn ?? config.useCdn) && canUseCdn\n\n const tag =\n options.tag && config.requestTagPrefix\n ? [config.requestTagPrefix, options.tag].join('.')\n : options.tag || config.requestTagPrefix\n\n if (tag && options.tag !== null) {\n options.query = {tag: validate.requestTag(tag), ...options.query}\n }\n\n // GROQ query-only parameters\n if (['GET', 'HEAD', 'POST'].indexOf(options.method || 'GET') >= 0 && isQuery(client, uri)) {\n const resultSourceMap = options.resultSourceMap ?? config.resultSourceMap\n if (resultSourceMap !== undefined && resultSourceMap !== false) {\n options.query = {resultSourceMap, ...options.query}\n }\n const perspectiveOption = options.perspective || config.perspective\n if (typeof perspectiveOption !== 'undefined') {\n if (perspectiveOption === 'previewDrafts') {\n printPreviewDraftsDeprecationWarning()\n }\n validateApiPerspective(perspectiveOption)\n options.query = {\n perspective: Array.isArray(perspectiveOption)\n ? perspectiveOption.join(',')\n : perspectiveOption,\n ...options.query,\n }\n // If the perspective is set to `drafts` or multiple perspectives we can't use the CDN, the API will throw\n if (\n ((Array.isArray(perspectiveOption) && perspectiveOption.length > 0) ||\n // previewDrafts was renamed to drafts, but keep for backwards compat\n perspectiveOption === 'previewDrafts' ||\n perspectiveOption === 'drafts') &&\n useCdn\n ) {\n useCdn = false\n printCdnPreviewDraftsWarning()\n }\n }\n\n if (options.lastLiveEventId) {\n options.query = {...options.query, lastLiveEventId: options.lastLiveEventId}\n }\n\n if (options.returnQuery === false) {\n options.query = {returnQuery: 'false', ...options.query}\n }\n\n if (useCdn && options.cacheMode == 'noStale') {\n options.query = {cacheMode: 'noStale', ...options.query}\n }\n }\n\n const reqOptions = requestOptions(\n config,\n Object.assign({}, options, {\n url: _getUrl(client, uri, useCdn),\n }),\n ) as RequestOptions\n\n const request = new Observable<HttpRequestEvent<R>>((subscriber) =>\n httpRequest(reqOptions, config.requester!).subscribe(subscriber),\n )\n\n return options.signal ? request.pipe(_withAbortSignal(options.signal)) : request\n}\n\n/**\n * @internal\n */\nexport function _request<R>(client: Client, httpRequest: HttpRequest, options: Any): Observable<R> {\n const observable = _requestObservable<R>(client, httpRequest, options).pipe(\n filter((event: Any) => event.type === 'response'),\n map((event: Any) => event.body),\n )\n\n return observable\n}\n\n/**\n * @internal\n */\nexport function _getDataUrl(client: Client, operation: string, path?: string): string {\n const config = client.config()\n const resource = config.resource\n if (resource) {\n validators.resourceConfig(config)\n const resourceBase = resourceDataBase(config)\n const uri = path !== undefined ? `${operation}/${path}` : operation\n return `${resourceBase}/${uri}`.replace(/\\/($|\\?)/, '$1')\n }\n const catalog = validators.hasDataset(config)\n const baseUri = `/${operation}/${catalog}`\n const uri = path !== undefined ? `${baseUri}/${path}` : baseUri\n return `/data${uri}`.replace(/\\/($|\\?)/, '$1')\n}\n\n/**\n * @internal\n */\nexport function _getUrl(client: Client, uri: string, canUseCdn = false): string {\n const {url, cdnUrl} = client.config()\n const base = canUseCdn ? cdnUrl : url\n return `${base}/${uri.replace(/^\\//, '')}`\n}\n\n/**\n * @internal\n */\nfunction _withAbortSignal<T>(signal: AbortSignal): MonoTypeOperatorFunction<T> {\n return (input) => {\n return new Observable((observer) => {\n const abort = () => observer.error(_createAbortError(signal))\n\n if (signal && signal.aborted) {\n abort()\n return\n }\n const subscription = input.subscribe(observer)\n signal.addEventListener('abort', abort)\n return () => {\n signal.removeEventListener('abort', abort)\n subscription.unsubscribe()\n }\n })\n }\n}\n// DOMException is supported on most modern browsers and Node.js 18+.\n// @see https://developer.mozilla.org/en-US/docs/Web/API/DOMException#browser_compatibility\nconst isDomExceptionSupported = Boolean(globalThis.DOMException)\n\n/**\n * @internal\n * @param signal - The abort signal to use.\n * Original source copied from https://github.com/sindresorhus/ky/blob/740732c78aad97e9aec199e9871bdbf0ae29b805/source/errors/DOMException.ts\n * TODO: When targeting Node.js 18, use `signal.throwIfAborted()` (https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/throwIfAborted)\n */\nfunction _createAbortError(signal?: AbortSignal) {\n /*\n NOTE: Use DomException with AbortError name as specified in MDN docs (https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort)\n > When abort() is called, the fetch() promise rejects with an Error of type DOMException, with name AbortError.\n */\n if (isDomExceptionSupported) {\n return new DOMException(signal?.reason ?? 'The operation was aborted.', 'AbortError')\n }\n\n // DOMException not supported. Fall back to use of error and override name.\n const error = new Error(signal?.reason ?? 'The operation was aborted.')\n error.name = 'AbortError'\n\n return error\n}\n\nconst resourceDataBase = (config: InitializedClientConfig): string => {\n const resource = config.resource\n if (!resource) {\n throw new Error('`resource` must be provided to perform resource queries')\n }\n const {type, id} = resource\n\n switch (type) {\n case 'dataset': {\n const segments = id.split('.')\n if (segments.length !== 2) {\n throw new Error('Dataset ID must be in the format \"project.dataset\"')\n }\n return `/projects/${segments[0]}/datasets/${segments[1]}`\n }\n case 'canvas': {\n return `/canvases/${id}`\n }\n case 'media-library': {\n return `/media-libraries/${id}`\n }\n case 'dashboard': {\n return `/dashboards/${id}`\n }\n default:\n // @ts-expect-error - handle all supported resource types\n throw new Error(`Unsupported resource type: ${type.toString()}`)\n }\n}\n","import {type Observable} from 'rxjs'\n\nimport {_request} from '../../data/dataMethods'\nimport type {ObservableSanityClient, SanityClient} from '../../SanityClient'\nimport type {AgentActionParams, Any, HttpRequest, IdentifiedSanityDocumentStub} from '../../types'\nimport {hasDataset} from '../../validators'\nimport type {\n AgentActionAsync,\n AgentActionPathSegment,\n AgentActionRequestBase,\n AgentActionSync,\n AgentActionTarget,\n AgentActionTargetInclude,\n} from './commonTypes'\n\n/** @beta */\nexport type GenerateOperation = 'set' | 'append' | 'mixed'\n\n/** @beta */\nexport interface GenerateRequestBase extends AgentActionRequestBase {\n /** schemaId as reported by sanity deploy / sanity schema store */\n schemaId: string\n /**\n * Instruct the LLM how it should generate content. Be as specific and detailed as needed.\n *\n * The LLM only has access to information in the instruction, plus the target schema.\n *\n * String template with support for $variable from `instructionParams`.\n * */\n instruction: string\n /**\n * param values for the string template, keys are the variable name, ie if the template has \"$variable\", one key must be \"variable\"\n *\n * ### Examples\n *\n * #### Constant\n *\n * ##### Shorthand\n * ```ts\n * client.agent.action.generate({\n * schemaId,\n * documentId,\n * instruction: 'Give the following topic:\\n $topic \\n ---\\nGenerate the full article.',\n * instructionParams: {\n * topic: 'Grapefruit'\n * },\n * })\n * ```\n * ##### Object-form\n *\n * ```ts\n * client.agent.action.generate({\n * schemaId,\n * documentId,\n * instruction: 'Give the following topic:\\n $topic \\n ---\\nGenerate the full article.',\n * instructionParams: {\n * topic: {\n * type: 'constant',\n * value: 'Grapefruit'\n * },\n * },\n * })\n * ```\n * #### Field\n * ```ts\n * client.agent.action.generate({\n * schemaId,\n * documentId,\n * instruction: 'Give the following field value:\\n $pte \\n ---\\nGenerate keywords.',\n * instructionParams: {\n * pte: {\n * type: 'field',\n * path: ['pteField'],\n * },\n * },\n * target: {path: 'keywords' }\n * })\n * ```\n * #### Document\n * ```ts\n * client.agent.action.generate({\n * schemaId,\n * documentId,\n * instruction: 'Give the following document value:\\n $document \\n ---\\nGenerate keywords.',\n * instructionParams: {\n * document: {\n * type: 'document',\n * },\n * },\n * target: {path: 'keywords' }\n * })\n * ```\n *\n * #### GROQ\n * ```ts\n * client.agent.action.generate({\n * schemaId,\n * documentId,\n * instruction: 'Give the following list of titles:\\n $list \\n ---\\nGenerate a similar title.',\n * instructionParams: {\n * list: {\n * type: 'groq',\n * query: '* [_type==$type].title',\n * params: {type: 'article'}\n * },\n * },\n * target: {path: 'title' }\n * })\n * ```\n * */\n instructionParams?: AgentActionParams\n\n /**\n * Target defines which parts of the document will be affected by the instruction.\n * It can be an array, so multiple parts of the document can be separately configured in detail.\n *\n * Omitting target implies that the document itself is the root.\n *\n * Notes:\n * - instruction can only affect fields up to `maxPathDepth`\n * - when multiple targets are provided, they will be coalesced into a single target sharing a common target root.\n * It is therefor an error to provide conflicting include/exclude across targets (ie, include title in one, and exclude it in another)\n *\n * ## Generating images\n *\n * Generate will generate images the same was as AI Assist, for images that have been configured using\n * [AI Assist schema options](https://github.com/sanity-io/assist/tree/main/plugin#image-generation).\n *\n * To generate images _without_ changing the schema, directly target an image asset path.\n *\n * For example, all the following will generate an image into the provided asset:\n * * `target: {path: ['image', 'asset'] }`\n * * `target: {path: 'image', include: ['asset'] }`\n *\n * Image generation can be combined with regular content targets:\n * * `target: [{path: ['image', 'asset'] }, {include: ['title', 'description']}]`\n *\n * Since Generate happens in a single LLM pass, the image will be contextually related to other generated content.\n * @see AgentActionRequestBase#conditionalPaths\n */\n target?: GenerateTarget | GenerateTarget[]\n}\n\n/** @beta */\nexport interface GenerateTargetInclude extends AgentActionTargetInclude {\n /**\n * Sets the operation for this path, and all its children.\n * This overrides any operation set parents or the root target.\n * @see #GenerateTarget.operation\n * @see #include\n */\n operation?: GenerateOperation\n\n /**\n * By default, all children up to `target.maxPathDepth` are included.\n *\n * When `include` is specified, only segments explicitly listed will be included.\n *\n * Fields or array items not on the include list, are implicitly excluded.\n */\n include?: (AgentActionPathSegment | GenerateTargetInclude)[]\n}\n\n/** @beta */\nexport interface GenerateTarget extends AgentActionTarget {\n /**\n * Sets the default operation for all paths in the target.\n * Generate runs in `'mixed'` operation mode by default:\n * Changes are set in all non-array fields, and append to all array fields.\n *\n * ### Operation types\n * - `'set'` – an *overwriting* operation, and replaces the full field value.\n * - `'append'`:\n * – array fields: appends new items to the end of the array,\n * - string fields: '\"existing content\" \"new content\"'\n * - text fields: '\"existing content\"\\\\n\"new content\"'\n * - number fields: existing + new\n * - other field types not mentioned will set instead (dates, url)\n * - `'mixed'` – (default) sets non-array fields, and appends to array fields\n *\n * The default operation can be overridden on a per-path basis using `include`.\n *\n * Nested fields inherit the operation specified by their parent and falls back to the\n * top level target operation if not otherwise specified.\n *\n * Use `include` to change the `operation` of individual fields or items.\n *\n * #### Appending in the middle of arrays\n * `target: {path: ['array'], operation: 'append'}` will append the output of the instruction to the end of the array.\n *\n * To insert in the middle of the array, use `target: {path: ['array', {_key: 'appendAfterKey'}], operation: 'append'}`.\n * Here, the output of the instruction will be appended after the array item with key `'appendAfterKey'`.\n *\n * @see #AgentActionTargetInclude.operation\n * @see #include\n * @see #AgentActionTargetInclude.include\n * @see #AgentActionSchema.forcePublishedWrite\n */\n operation?: GenerateOperation\n\n /**\n * By default, all children up to `target.maxPathDepth` are included.\n *\n * When `include` is specified, only segments explicitly listed will be included.\n *\n * Fields or array items not on the include list, are implicitly excluded.\n */\n include?: (AgentActionPathSegment | GenerateTargetInclude)[]\n}\n\n/** @beta */\nexport type GenerateTargetDocument<T extends Record<string, Any> = Record<string, Any>> =\n | {\n operation: 'edit'\n /**\n * @see #AgentActionSchema.forcePublishedWrite\n */\n _id: string\n }\n | {\n operation: 'create'\n /**\n * @see #AgentActionSchema.forcePublishedWrite\n */\n _id?: string\n _type: string\n initialValues?: T\n }\n | {\n operation: 'createIfNotExists'\n /**\n * @see #AgentActionSchema.forcePublishedWrite\n */\n _id: string\n _type: string\n initialValues?: T\n }\n | {\n operation: 'createOrReplace'\n /**\n * @see #AgentActionSchema.forcePublishedWrite\n */\n _id: string\n _type: string\n initialValues?: T\n }\n\n/**\n * Instruction for an existing document.\n * @beta\n */\ninterface GenerateExistingDocumentRequest {\n /**\n * @see #AgentActionSchema.forcePublishedWrite\n */\n documentId: string\n targetDocument?: never\n}\n\n/**\n * Instruction to create a new document\n * @beta\n */\ninterface GenerateTargetDocumentRequest<T extends Record<string, Any> = Record<string, Any>> {\n /**\n * @see #AgentActionSchema.forcePublishedWrite\n */\n targetDocument: GenerateTargetDocument<T>\n documentId?: never\n}\n\n/** @beta */\nexport type GenerateSyncInstruction<T extends Record<string, Any> = Record<string, Any>> = (\n | GenerateExistingDocumentRequest\n | GenerateTargetDocumentRequest<T>\n) &\n GenerateRequestBase &\n AgentActionSync\n\n/** @beta */\nexport type GenerateAsyncInstruction<T extends Record<string, Any> = Record<string, Any>> = (\n | GenerateExistingDocumentRequest\n | GenerateTargetDocumentRequest<T>\n) &\n GenerateRequestBase &\n AgentActionAsync\n\n/** @beta */\nexport type GenerateInstruction<T extends Record<string, Any> = Record<string, Any>> =\n | GenerateSyncInstruction<T>\n | GenerateAsyncInstruction<T>\n\nexport function _generate<DocumentShape extends Record<string, Any>>(\n client: SanityClient | ObservableSanityClient,\n httpRequest: HttpRequest,\n request: GenerateInstruction<DocumentShape>,\n): Observable<\n (typeof request)['async'] extends true\n ? {_id: string}\n : IdentifiedSanityDocumentStub & DocumentShape\n> {\n const dataset = hasDataset(client.config())\n return _request(client, httpRequest, {\n method: 'POST',\n uri: `/agent/action/generate/${dataset}`,\n body: request,\n })\n}\n","import {type Observable} from 'rxjs'\n\nimport {_request} from '../../data/dataMethods'\nimport type {ObservableSanityClient, SanityClient} from '../../SanityClient'\nimport type {\n AgentActionPath,\n AgentActionPathSegment,\n Any,\n GenerateTargetDocument,\n HttpRequest,\n IdentifiedSanityDocumentStub,\n} from '../../types'\nimport {hasDataset} from '../../validators'\nimport type {AgentActionAsync, AgentActionSchema, AgentActionSync} from './commonTypes'\n\n/** @beta */\nexport type PatchOperation = 'set' | 'append' | 'mixed' | 'unset'\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyNonNullable = Exclude<any, null | undefined>\n\n/** @beta */\nexport interface PatchRequestBase extends AgentActionSchema {\n /**\n * Target defines which parts of the document will be affected by the instruction.\n * It can be an array, so multiple parts of the document can be separately configured in detail.\n *\n * Omitting target implies that the document itself is the root.\n *\n * Notes:\n * - instruction can only affect fields up to `maxPathDepth`\n * - when multiple targets are provided, they will be coalesced into a single target sharing a common target root.\n * It is therefore an error to provide conflicting include/exclude across targets (ie, include title in one, and exclude it in another)\n *\n * @see AgentActionRequestBase#conditionalPaths\n */\n target: PatchTarget | PatchTarget[]\n}\n\n/** @beta */\nexport type PatchTarget = {\n /**\n * Determines how the target path will be patched.\n *\n * ### Operation types\n * - `'set'` – an *overwriting* operation: sets the full field value for primitive targets, and merges the provided value with existing values for objects\n * - `'append'`:\n * – array fields: appends new items to the end of the array,\n * - string fields: '\"existing content\" \"new content\"'\n * - text fields: '\"existing content\"\\\\n\"new content\"'\n * - number fields: existing + new\n * - other field types not mentioned will set instead (dates, url)\n * - `'mixed'` – sets non-array fields, and appends to array fields\n * - `'unset'` – removes whatever value is on the target path\n *\n * All operations except unset requires a `value`.\n *\n * #### Appending in the middle of arrays\n * To append to an array, use the 'append' operation, and provide an array value with one or more array items.\n *\n * `target: {path: ['array'], operation: 'append', value: [{_type: 'item' _key: 'a'}]}` will append the items in the value to the existing array.\n *\n * To insert in the middle of the array, use `target: {path: ['array', {_key: 'appendAfterKey'}], operation: 'append', value: [{_type: 'item' _key: 'a'}]}`.\n * Here, `{_type: 'item' _key: 'a'}` will be appended after the array item with key `'appendAfterKey'`\n *\n * It is optional to provide a _key for inserted array items; if one isn't provided, it will be generated.\n */\n operation: PatchOperation\n\n path: AgentActionPathSegment | AgentActionPath\n} & (\n | {operation: 'unset'; value?: never}\n | {operation: Exclude<PatchOperation, 'unset'>; value: AnyNonNullable}\n)\n\n/**\n * Patches an existing document\n * @beta\n */\ninterface PatchExistingDocumentRequest {\n /**\n * @see #AgentActionSchema.forcePublishedWrite\n */\n documentId: string\n targetDocument?: never\n}\n\n/**\n * Create a new document, then patch it\n * @beta\n */\ninterface PatchTargetDocumentRequest<T extends Record<string, Any> = Record<string, Any>> {\n /**\n * @see #AgentActionSchema.forcePublishedWrite\n */\n targetDocument: GenerateTargetDocument<T>\n documentId?: never\n}\n\n/** @beta */\nexport type PatchDocumentSync<T extends Record<string, Any> = Record<string, Any>> = (\n | PatchExistingDocumentRequest\n | PatchTargetDocumentRequest<T>\n) &\n PatchRequestBase &\n AgentActionSync\n\n/** @beta */\nexport type PatchDocumentAsync<T extends Record<string, Any> = Record<string, Any>> = (\n | PatchExistingDocumentRequest\n | PatchTargetDocumentRequest<T>\n) &\n PatchRequestBase &\n AgentActionAsync\n\n/** @beta */\nexport type PatchDocument<T extends Record<string, Any> = Record<string, Any>> =\n | PatchDocumentSync<T>\n | PatchDocumentAsync<T>\n\nexport function _patch<DocumentShape extends Record<string, Any>>(\n client: SanityClient | ObservableSanityClient,\n httpRequest: HttpRequest,\n request: PatchDocument<DocumentShape>,\n): Observable<\n (typeof request)['async'] extends true\n ? {_id: string}\n : IdentifiedSanityDocumentStub & DocumentShape\n> {\n const dataset = hasDataset(client.config())\n return _request(client, httpRequest, {\n method: 'POST',\n uri: `/agent/action/patch/${dataset}`,\n body: request,\n })\n}\n","import {type Observable} from 'rxjs'\n\nimport {_request} from '../../data/dataMethods'\nimport type {ObservableSanityClient, SanityClient} from '../../SanityClient'\nimport type {AgentActionParams, Any, HttpRequest} from '../../types'\nimport {hasDataset} from '../../validators'\n\n/** @beta */\nexport interface PromptRequestBase {\n /**\n * Instruct the LLM how it should generate content. Be as specific and detailed as needed.\n *\n * The LLM only has access to information in the instruction, plus the target schema.\n *\n * String template with support for $variable from `instructionParams`.\n * */\n instruction: string\n /**\n * param values for the string template, keys are the variable name, ie if the template has \"$variable\", one key must be \"variable\"\n *\n * ### Examples\n *\n * #### Constant\n *\n * ##### Shorthand\n * ```ts\n * client.agent.action.prompt({\n * instruction: 'Give the following topic:\\n $topic \\n ---\\nReturns some facts about it',\n * instructionParams: {\n * topic: 'Grapefruit'\n * },\n * })\n * ```\n * ##### Object-form\n *\n * ```ts\n * client.agent.action.prompt({\n * instruction: 'Give the following topic:\\n $topic \\n ---\\nReturns some facts about it.',\n * instructionParams: {\n * topic: {\n * type: 'constant',\n * value: 'Grapefruit'\n * },\n * },\n * })\n * ```\n * #### Field\n * ```ts\n * client.agent.action.prompt({\n * instruction: 'Give the following field value:\\n $pte \\n ---\\nGenerate keywords.',\n * instructionParams: {\n * pte: {\n * type: 'field',\n * path: ['pteField'],\n * documentId: 'someSanityDocId'\n * },\n * },\n * })\n * ```\n * #### Document\n * ```ts\n * client.agent.action.prompt({\n * json: true,\n * instruction: 'Given the following document:$document\\nCreate a JSON string[] array with keywords describing it.',\n * instructionParams: {\n * document: {\n * type: 'document',\n * documentId: 'someSanityDocId'\n * },\n * },\n * })\n * ```\n *\n * #### GROQ\n * ```ts\n * client.agent.action.prompt({\n * instruction: 'Return the best title amongst these: $titles.',\n * instructionParams: {\n * titles: {\n * type: 'groq',\n * query: '* [_type==$type].title',\n * params: {type: 'article'}\n * },\n * },\n * })\n * ```\n * */\n instructionParams?: AgentActionParams<{docIdRequired: true}>\n\n /**\n * Controls how much variance the instructions will run with.\n *\n * Value must be in the range [0, 1] (inclusive).\n *\n * Default: 0.3\n */\n temperature?: number\n}\n\n/**\n * @beta\n */\n// need the unused generic here to allow for optional callsite casting\n// eslint-disable-next-line unused-imports/no-unused-vars\ninterface PromptJsonResponse<T extends Record<string, Any> = Record<string, Any>> {\n /**\n *\n * When format is 'json', the response will be json according to the instruction.\n * Note: In addition to setting this to 'json', `instruction` MUST include the word 'JSON', or 'json' for this to work.\n */\n format: 'json'\n}\n\ninterface PromptTextResponse {\n /**\n * When format is 'string', the response will be a raw text response to the instruction.\n */\n format?: 'string'\n}\n\n/** @beta */\nexport type PromptRequest<T extends Record<string, Any> = Record<string, Any>> = (\n | PromptTextResponse\n | PromptJsonResponse<T>\n) &\n PromptRequestBase\n\nexport function _prompt<const DocumentShape extends Record<string, Any>>(\n client: SanityClient | ObservableSanityClient,\n httpRequest: HttpRequest,\n request: PromptRequest<DocumentShape>,\n): Observable<(typeof request)['format'] extends 'json' ? DocumentShape : string> {\n const dataset = hasDataset(client.config())\n return _request(client, httpRequest, {\n method: 'POST',\n uri: `/agent/action/prompt/${dataset}`,\n body: request,\n })\n}\n","import {type Observable} from 'rxjs'\n\nimport {_request} from '../../data/dataMethods'\nimport type {ObservableSanityClient, SanityClient} from '../../SanityClient'\nimport type {\n AgentActionParams,\n AgentActionPath,\n Any,\n HttpRequest,\n IdentifiedSanityDocumentStub,\n} from '../../types'\nimport {hasDataset} from '../../validators'\nimport type {\n AgentActionAsync,\n AgentActionPathSegment,\n AgentActionRequestBase,\n AgentActionSync,\n AgentActionTarget,\n AgentActionTargetInclude,\n} from './commonTypes'\n\n/** @beta */\nexport interface TransformRequestBase extends AgentActionRequestBase {\n /** schemaId as reported by sanity deploy / sanity schema store */\n schemaId: string\n\n /**\n * The source document the transformation will use as input.\n *\n * @see #AgentActionSchema.forcePublishedWrite\n */\n documentId: string\n\n /**\n * The source document's content is first copied to the target,\n * then it is transformed according to the instruction.\n *\n * When omitted, the source document (documentId) is also the target document.\n *\n * @see #AgentActionSchema.forcePublishedWrite\n */\n targetDocument?: TransformTargetDocument\n\n /**\n * Instruct the LLM how to transform the input to th output.\n *\n * String template with support for $variable from `instructionParams`.\n *\n * Capped to 2000 characters, after variables has been injected.\n * */\n instruction: string\n /**\n *\n * param values for the string template, keys are the variable name, ie if the template has \"$variable\", one key must be \"variable\"\n *\n * ### Examples\n *\n * #### Constant\n *\n * ##### Shorthand\n * ```ts\n * client.agent.action.generate({\n * schemaId,\n * documentId,\n * instruction: 'Give the following topic:\\n $topic \\n ---\\nGenerate the full article.',\n * instructionParams: {\n * topic: 'Grapefruit'\n * },\n * })\n * ```\n * ##### Object-form\n *\n * ```ts\n * client.agent.action.transform({\n * schemaId,\n * documentId,\n * instruction: 'Give the following topic:\\n $topic \\n ---\\nGenerate the full article.',\n * instructionParams: {\n * topic: {\n * type: 'constant',\n * value: 'Grapefruit'\n * },\n * },\n * })\n * ```\n * #### Field\n * ```ts\n * client.agent.action.transform({\n * schemaId,\n * documentId,\n * instruction: 'Give the following field value:\\n $pte \\n ---\\nGenerate keywords.',\n * instructionParams: {\n * pte: {\n * type: 'field',\n * path: ['pteField'],\n * },\n * },\n * target: {path: 'keywords' }\n * })\n * ```\n * #### Document\n * ```ts\n * client.agent.action.transform({\n * schemaId,\n * documentId,\n * instruction: 'Give the following document value:\\n $document \\n ---\\nGenerate keywords.',\n * instructionParams: {\n * document: {\n * type: 'document',\n * },\n * },\n * target: {path: 'keywords' }\n * })\n * ```\n *\n * #### GROQ\n * ```ts\n * client.agent.action.transform({\n * schemaId,\n * documentId,\n * instruction: 'Give the following list of titles:\\n $list \\n ---\\nGenerate a similar title.',\n * instructionParams: {\n * list: {\n * type: 'groq',\n * query: '* [_type==$type].title',\n * params: {type: 'article'}\n * },\n * },\n * target: {path: 'title'}\n * })\n * ```\n * */\n instructionParams?: AgentActionParams\n\n /**\n * Target defines which parts of the document will be affected by the instruction.\n * It can be an array, so multiple parts of the document can be separately configured in detail.\n *\n * Omitting target implies that the document itself is the root.\n *\n * Notes:\n * - instruction can only affect fields up to `maxPathDepth`\n * - when multiple targets are provided, they will be coalesced into a single target sharing a common target root.\n * It is therefor an error to provide conflicting include/exclude across targets (ie, include title in one, and exclude it in another)\n *\n * Default max depth for transform: 12\n *\n * ## Transforming images\n *\n * To transform an existing image, directly target an image asset path.\n *\n * For example, all the following will transform the image into the provided asset:\n * * `target: {path: ['image', 'asset'] }`\n * * `target: {path: 'image', include: ['asset'] }`\n *\n * Image transform can be combined with regular content targets:\n * * `target: [{path: ['image', 'asset'] }, {include: ['title', 'description']}]`\n *\n * Image transform can have per-path instructions, just like any other target paths:\n * * `target: [{path: ['image', 'asset'], instruction: 'Make the sky blue' }`\n *\n * @see AgentActionRequestBase#conditionalPaths\n */\n target?: TransformTarget | TransformTarget[]\n}\n\n/**\n * @see #AgentActionSchema.forcePublishedWrite\n *\n * @beta\n */\nexport type TransformTargetDocument =\n | {operation: 'edit'; _id: string}\n | {operation: 'create'; _id?: string}\n | {operation: 'createIfNotExists'; _id: string}\n | {operation: 'createOrReplace'; _id: string}\n\n/**\n *\n * @see #TransformOperation\n * @beta\n */\nexport type ImageDescriptionOperation = {\n type: 'image-description'\n /**\n * When omitted, parent image value will be inferred from the arget path.\n *\n * When specified, the `sourcePath` should be a path to an image (or image asset) field:\n * - `['image']`\n * - `['wrapper', 'mainImage']`\n * - `['heroImage', 'asset'] // the asset segment is optional, but supported`\n */\n sourcePath?: AgentActionPath\n} & (\n | {\n /**\n * When omitted, parent image value will be inferred from the target path.\n *\n * When specified, the `sourcePath` should be a path to an image (or image asset) field:\n * - `['image']`\n * - `['wrapper', 'mainImage']`\n * - `['heroImage', 'asset'] // the asset segment is optional, but supported`\n *\n * Incompatible with `imageUrl`\n *\n */\n sourcePath?: AgentActionPath\n imageUrl?: never\n }\n | {\n /**\n * When specified, the image source to be described will be fetched from the URL.\n *\n * Incompatible with `sourcePath`\n */\n imageUrl?: `https://${string}`\n sourcePath?: never\n }\n)\n\n/**\n *\n * ## `set` by default\n * By default, Transform will change the value of every target field in place using a set operation.\n *\n * ## Image description\n *\n * ### Targeting image fields\n * Images can be transformed to a textual description by targeting a `string`, `text` or Portable Text field (`array` with `block`)\n * with `operation: {type: 'image-description'}`.\n *\n * Custom instructions for image description targets will be used to generate the description.\n *\n * Such targets must be a descendant field of an image object.\n *\n * For example:\n * - `target: {path: ['image', 'description'], operation: {type: 'image-description'} }`\n * - `target: {path: ['array', {_key: 'abc'}, 'alt'], operation: {type: 'image-description'} } //assuming the item in the array on the key-ed path is an image`\n * - `target: {path: ['image'], include: ['portableTextField'], operation: {type: 'image-description'}, instruction: 'Use formatting and headings to describe the image in great detail' }`\n *\n * ### Targeting non-image fields\n * If the target image description lives outside an image object, use the `sourcePath` option to specify the path to the image field.\n * `sourcePath` must be an image or image asset field.\n *\n * For example:\n * - `target: {path: ['description'], operation: operation: {type: 'image-description', sourcePath: ['image', 'asset'] }`\n * - `target: {path: ['wrapper', 'title'], operation: {type: 'image-description', sourcePath: ['array', {_key: 'abc'}, 'image'] }`\n * - `target: {path: ['wrapper'], include: ['portableTextField'], operation: {type: 'image-description', sourcePath: ['image', 'asset'] }, instruction: 'Use formatting and headings to describe the image in great detail' }`\n *\n * ### Targeting images outside the document (URL)\n * 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`.\n *\n * Example:\n * - `target: {path: ['description'], operation: operation: {type: 'image-description', imageUrL: 'https://www.sanity.io/static/images/favicons/android-icon-192x192.png?v=2' }`\n * @beta\n */\nexport type TransformOperation = 'set' | ImageDescriptionOperation\n\n/**\n * @see #TransformOperation\n * @beta\n * */\nexport interface TransformTargetInclude extends AgentActionTargetInclude {\n /**\n * Specifies a tailored instruction of this target.\n *\n * String template with support for $variable from `instructionParams`. */\n instruction?: string\n\n /**\n * By default, all children up to `target.maxPathDepth` are included.\n *\n * When `include` is specified, only segments explicitly listed will be included.\n *\n * Fields or array items not on the include list, are implicitly excluded.\n */\n include?: (AgentActionPathSegment | TransformTargetInclude)[]\n\n /**\n * Default: `set`\n * @see #TransformOperation\n */\n operation?: TransformOperation\n}\n\n/**\n * @see #TransformOperation\n * @beta\n * */\nexport interface TransformTarget extends AgentActionTarget {\n /**\n * Specifies a tailored instruction of this target.\n *\n * String template with support for $variable from `instructionParams`.\n * */\n instruction?: string\n\n /**\n * By default, all children up to `target.maxPathDepth` are included.\n *\n * When `include` is specified, only segments explicitly listed will be included.\n *\n * Fields or array items not on the include list, are implicitly excluded.\n */\n include?: (AgentActionPathSegment | TransformTargetInclude)[]\n\n /**\n * Default: `set`\n * @see #TransformOperation\n */\n operation?: TransformOperation\n}\n\n/** @beta */\n// need the generics to hold optional call-site response generics\n// eslint-disable-next-line unused-imports/no-unused-vars\nexport type TransformDocumentSync<T extends Record<string, Any> = Record<string, Any>> =\n TransformRequestBase & AgentActionSync\n\n/** @beta */\nexport type TransformDocumentAsync = TransformRequestBase & AgentActionAsync\n\n/** @beta */\nexport type TransformDocument<T extends Record<string, Any> = Record<string, Any>> =\n | TransformDocumentSync<T>\n | TransformDocumentAsync\n\nexport function _transform<DocumentShape extends Record<string, Any>>(\n client: SanityClient | ObservableSanityClient,\n httpRequest: HttpRequest,\n request: TransformDocument<DocumentShape>,\n): Observable<\n (typeof request)['async'] extends true\n ? {_id: string}\n : IdentifiedSanityDocumentStub & DocumentShape\n> {\n const dataset = hasDataset(client.config())\n return _request(client, httpRequest, {\n method: 'POST',\n uri: `/agent/action/transform/${dataset}`,\n body: request,\n })\n}\n","import {type Observable} from 'rxjs'\n\nimport {_request} from '../../data/dataMethods'\nimport type {ObservableSanityClient, SanityClient} from '../../SanityClient'\nimport type {\n AgentActionParams,\n AgentActionPathSegment,\n AgentActionTarget,\n Any,\n HttpRequest,\n IdentifiedSanityDocumentStub,\n} from '../../types'\nimport {hasDataset} from '../../validators'\nimport type {\n AgentActionAsync,\n AgentActionPath,\n AgentActionRequestBase,\n AgentActionSync,\n AgentActionTargetInclude,\n} from './commonTypes'\nimport type {TransformTargetDocument} from './transform'\n\n/** @beta */\nexport interface TranslateRequestBase extends AgentActionRequestBase {\n /** schemaId as reported by sanity deploy / sanity schema store */\n schemaId: string\n\n /**\n * The source document the transformation will use as input.\n * @see #AgentActionSchema.forcePublishedWrite\n */\n documentId: string\n\n /**\n * The target document will first get content copied over from the source,\n * then it is translated according to the instruction.\n *\n * When omitted, the source document (documentId) is also the target document.\n *\n * @see #AgentActionSchema.forcePublishedWrite\n */\n targetDocument?: TransformTargetDocument\n\n /**\n * While optional, it is recommended\n */\n fromLanguage?: TranslateLanguage\n toLanguage: TranslateLanguage\n\n /**\n * `styleGuide` can be used to tailor how the translation should be preformed.\n *\n * String template using $variable from styleGuideParams.\n *\n * Capped to 2000 characters, after variables has been injected.\n *\n * @see #protectedPhrases\n */\n styleGuide?: string\n /** param values for the string template, keys are the variable name, ie if the template has \"$variable\", one key must be \"variable\" */\n styleGuideParams?: AgentActionParams\n\n /**\n * When the input string contains any phrase from `protectedPhrases`, the LLM will be instructed not\n * to translate them.\n *\n * It is recommended to use `protectedPhrases` instead of `styleGuide` for deny-list words and phrases,\n * since it keeps token cost low, resulting in faster responses, and limits how much information the LLM\n * has to process, since only phrases that are actually in the input string will be included in the final prompt.\n */\n protectedPhrases?: string[]\n\n /**\n * When specified, the `toLanguage.id` will be stored in the specified path in the target document.\n *\n * The file _can_ be hidden: true (unlike other fields in the target, which will be ignored)\n */\n languageFieldPath?: AgentActionPathSegment | AgentActionPath\n\n /**\n * Target defines which parts of the document will be affected by the instruction.\n * It can be an array, so multiple parts of the document can be separately configured in detail.\n *\n * Omitting target implies that the document itself is the root.\n *\n * Notes:\n * - instruction can only affect fields up to `maxPathDepth`\n * - when multiple targets are provided, they will be coalesced into a single target sharing a common target root.\n * It is therefor an error to provide conflicting include/exclude across targets (ie, include title in one, and exclude it in another)\n *\n * @see AgentActionRequestBase#conditionalPaths\n */\n target?: TranslateTarget | TranslateTarget[]\n}\n\n/** @beta */\nexport interface TranslateLanguage {\n /**\n * Language code\n */\n id: string\n\n /**\n * While optional, it is recommended to provide a language title\n */\n title?: string\n}\n\n/** @beta */\nexport interface TranslateTargetInclude extends AgentActionTargetInclude {\n /** String template using $variable from styleGuideParams. */\n styleGuide?: string\n\n /**\n * By default, all children up to `target.maxPathDepth` are included.\n *\n * When `include` is specified, only segments explicitly listed will be included.\n *\n * Fields or array items not on the include list, are implicitly excluded.\n */\n include?: (AgentActionPathSegment | TranslateTargetInclude)[]\n}\n\n/** @beta */\nexport interface TranslateTarget extends AgentActionTarget {\n /** String template using $variable from styleGuideParams. */\n styleGuide?: string\n\n /**\n * By default, all children up to `target.maxPathDepth` are included.\n *\n * When `include` is specified, only segments explicitly listed will be included.\n *\n * Fields or array items not on the include list, are implicitly excluded.\n */\n include?: (AgentActionPathSegment | TranslateTargetInclude)[]\n}\n\n/** @beta */\n// need the generics to hold optional call-site response generics\n// eslint-disable-next-line unused-imports/no-unused-vars\nexport type TranslateDocumentSync<T extends Record<string, Any> = Record<string, Any>> =\n TranslateRequestBase & AgentActionSync\n\n/** @beta */\nexport type TranslateDocumentAsync = TranslateRequestBase & AgentActionAsync\n\n/** @beta */\nexport type TranslateDocument<T extends Record<string, Any> = Record<string, Any>> =\n | TranslateDocumentSync<T>\n | TranslateDocumentAsync\n\nexport function _translate<DocumentShape extends Record<string, Any>>(\n client: SanityClient | ObservableSanityClient,\n httpRequest: HttpRequest,\n request: TranslateDocument<DocumentShape>,\n): Observable<\n (typeof request)['async'] extends true\n ? {_id: string}\n : IdentifiedSanityDocumentStub & DocumentShape\n> {\n const dataset = hasDataset(client.config())\n return _request(client, httpRequest, {\n method: 'POST',\n uri: `/agent/action/translate/${dataset}`,\n body: request,\n })\n}\n","import {lastValueFrom, type Observable} from 'rxjs'\n\nimport type {ObservableSanityClient, SanityClient} from '../../SanityClient'\nimport type {Any, HttpRequest, IdentifiedSanityDocumentStub} from '../../types'\nimport {_generate, type GenerateInstruction} from './generate'\nimport {_patch, type PatchDocument} from './patch'\nimport {_prompt, type PromptRequest} from './prompt'\nimport {_transform, type TransformDocument} from './transform'\nimport {_translate, type TranslateDocument} from './translate'\n\n/** @public */\nexport class ObservableAgentsActionClient {\n #client: ObservableSanityClient\n #httpRequest: HttpRequest\n constructor(client: ObservableSanityClient, httpRequest: HttpRequest) {\n this.#client = client\n this.#httpRequest = httpRequest\n }\n\n /**\n * Run an instruction to generate content in a target document.\n * @param request - instruction request\n */\n generate<DocumentShape extends Record<string, Any>>(\n request: GenerateInstruction<DocumentShape>,\n ): Observable<\n (typeof request)['async'] extends true\n ? {_id: string}\n : IdentifiedSanityDocumentStub & DocumentShape\n > {\n return _generate(this.#client, this.#httpRequest, request)\n }\n\n /**\n * Transform a target document based on a source.\n * @param request - translation request\n */\n transform<DocumentShape extends Record<string, Any>>(\n request: TransformDocument<DocumentShape>,\n ): Observable<\n (typeof request)['async'] extends true\n ? {_id: string}\n : IdentifiedSanityDocumentStub & DocumentShape\n > {\n return _transform(this.#client, this.#httpRequest, request)\n }\n\n /**\n * Translate a target document based on a source.\n * @param request - translation request\n */\n translate<DocumentShape extends Record<string, Any>>(\n request: TranslateDocument<DocumentShape>,\n ): Observable<\n (typeof request)['async'] extends true\n ? {_id: string}\n : IdentifiedSanityDocumentStub & DocumentShape\n > {\n return _translate(this.#client, this.#httpRequest, request)\n }\n}\n\n/** @public */\nexport class AgentActionsClient {\n #client: SanityClient\n #httpRequest: HttpRequest\n constructor(client: SanityClient, httpRequest: HttpRequest) {\n this.#client = client\n this.#httpRequest = httpRequest\n }\n\n /**\n * Run an instruction to generate content in a target document.\n * @param request - instruction request\n */\n generate<DocumentShape extends Record<string, Any>>(\n request: GenerateInstruction<DocumentShape>,\n ): Promise<\n (typeof request)['async'] extends true\n ? {_id: string}\n : IdentifiedSanityDocumentStub & DocumentShape\n > {\n return lastValueFrom(_generate(this.#client, this.#httpRequest, request))\n }\n\n /**\n * Transform a target document based on a source.\n * @param request - translation request\n */\n transform<DocumentShape extends Record<string, Any>>(\n request: TransformDocument<DocumentShape>,\n ): Promise<\n (typeof request)['async'] extends true\n ? {_id: string}\n : IdentifiedSanityDocumentStub & DocumentShape\n > {\n return lastValueFrom(_transform(this.#client, this.#httpRequest, request))\n }\n\n /**\n * Translate a target document based on a source.\n * @param request - translation request\n */\n translate<DocumentShape extends Record<string, Any>>(\n request: TranslateDocument<DocumentShape>,\n ): Promise<\n (typeof request)['async'] extends true\n ? {_id: string}\n : IdentifiedSanityDocumentStub & DocumentShape\n > {\n return lastValueFrom(_translate(this.#client, this.#httpRequest, request))\n }\n\n /**\n * Run a raw instruction and return the result either as text or json\n * @param request - prompt request\n */\n prompt<const DocumentShape extends Record<string, Any>>(\n request: PromptRequest<DocumentShape>,\n ): Promise<(typeof request)['format'] extends 'json' ? DocumentShape : string> {\n return lastValueFrom(_prompt(this.#client, this.#httpRequest, request))\n }\n\n /**\n * Patch a document using a schema aware API.\n * Does not use an LLM, but uses the schema to ensure paths and values matches the schema.\n * @param request - instruction request\n */\n patch<DocumentShape extends Record<string, Any>>(\n request: PatchDocument<DocumentShape>,\n ): Promise<\n (typeof request)['async'] extends true\n ? {_id: string}\n : IdentifiedSanityDocumentStub & DocumentShape\n > {\n return lastValueFrom(_patch(this.#client, this.#httpRequest, request))\n }\n}\n","import {lastValueFrom, type Observable} from 'rxjs'\nimport {filter, map} from 'rxjs/operators'\n\nimport {_requestObservable} from '../data/dataMethods'\nimport type {ObservableSanityClient, SanityClient} from '../SanityClient'\nimport type {\n Any,\n HttpRequest,\n HttpRequestEvent,\n InitializedClientConfig,\n ResponseEvent,\n SanityAssetDocument,\n SanityImageAssetDocument,\n UploadBody,\n UploadClientConfig,\n} from '../types'\nimport * as validators from '../validators'\n\n/** @internal */\nexport class ObservableAssetsClient {\n #client: ObservableSanityClient\n #httpRequest: HttpRequest\n constructor(client: ObservableSanityClient, httpRequest: HttpRequest) {\n this.#client = client\n this.#httpRequest = httpRequest\n }\n\n /**\n * Uploads a file asset to the configured dataset\n *\n * @param assetType - Asset type (file)\n * @param body - Asset content - can be a browser File instance, a Blob, a Node.js Buffer instance or a Node.js ReadableStream.\n * @param options - Options to use for the upload\n */\n upload(\n assetType: 'file',\n body: UploadBody,\n options?: UploadClientConfig,\n ): Observable<HttpRequestEvent<{document: SanityAssetDocument}>>\n\n /**\n * Uploads an image asset to the configured dataset\n *\n * @param assetType - Asset type (image)\n * @param body - Asset content - can be a browser File instance, a Blob, a Node.js Buffer instance or a Node.js ReadableStream.\n * @param options - Options to use for the upload\n */\n upload(\n assetType: 'image',\n body: UploadBody,\n options?: UploadClientConfig,\n ): Observable<HttpRequestEvent<{document: SanityImageAssetDocument}>>\n /**\n * Uploads a file or an image asset to the configured dataset\n *\n * @param assetType - Asset type (file/image)\n * @param body - Asset content - can be a browser File instance, a Blob, a Node.js Buffer instance or a Node.js ReadableStream.\n * @param options - Options to use for the upload\n */\n upload(\n assetType: 'file' | 'image',\n body: UploadBody,\n options?: UploadClientConfig,\n ): Observable<HttpRequestEvent<{document: SanityAssetDocument | SanityImageAssetDocument}>>\n upload(\n assetType: 'file' | 'image',\n body: UploadBody,\n options?: UploadClientConfig,\n ): Observable<HttpRequestEvent<{document: SanityAssetDocument | SanityImageAssetDocument}>> {\n return _upload(this.#client, this.#httpRequest, assetType, body, options)\n }\n}\n\n/** @internal */\nexport class AssetsClient {\n #client: SanityClient\n #httpRequest: HttpRequest\n constructor(client: SanityClient, httpRequest: HttpRequest) {\n this.#client = client\n this.#httpRequest = httpRequest\n }\n\n /**\n * Uploads a file asset to the configured dataset\n *\n * @param assetType - Asset type (file)\n * @param body - Asset content - can be a browser File instance, a Blob, a Node.js Buffer instance or a Node.js ReadableStream.\n * @param options - Options to use for the upload\n */\n upload(\n assetType: 'file',\n body: UploadBody,\n options?: UploadClientConfig,\n ): Promise<SanityAssetDocument>\n /**\n * Uploads an image asset to the configured dataset\n *\n * @param assetType - Asset type (image)\n * @param body - Asset content - can be a browser File instance, a Blob, a Node.js Buffer instance or a Node.js ReadableStream.\n * @param options - Options to use for the upload\n */\n upload(\n assetType: 'image',\n body: UploadBody,\n options?: UploadClientConfig,\n ): Promise<SanityImageAssetDocument>\n /**\n * Uploads a file or an image asset to the configured dataset\n *\n * @param assetType - Asset type (file/image)\n * @param body - Asset content - can be a browser File instance, a Blob, a Node.js Buffer instance or a Node.js ReadableStream.\n * @param options - Options to use for the upload\n */\n upload(\n assetType: 'file' | 'image',\n body: UploadBody,\n options?: UploadClientConfig,\n ): Promise<SanityAssetDocument | SanityImageAssetDocument>\n upload(\n assetType: 'file' | 'image',\n body: UploadBody,\n options?: UploadClientConfig,\n ): Promise<SanityAssetDocument | SanityImageAssetDocument> {\n const observable = _upload(this.#client, this.#httpRequest, assetType, body, options)\n return lastValueFrom(\n observable.pipe(\n filter((event: Any) => event.type === 'response'),\n map(\n (event) =>\n (event as ResponseEvent<{document: SanityAssetDocument | SanityImageAssetDocument}>)\n .body.document,\n ),\n ),\n )\n }\n}\n\nfunction _upload(\n client: SanityClient | ObservableSanityClient,\n httpRequest: HttpRequest,\n assetType: 'image' | 'file',\n body: UploadBody,\n opts: UploadClientConfig = {},\n): Observable<HttpRequestEvent<{document: SanityAssetDocument | SanityImageAssetDocument}>> {\n validators.validateAssetType(assetType)\n\n // If an empty array is given, explicitly set `none` to override API defaults\n let meta = opts.extract || undefined\n if (meta && !meta.length) {\n meta = ['none']\n }\n\n const config = client.config()\n const options = optionsFromFile(opts, body)\n const {tag, label, title, description, creditLine, filename, source} = options\n const resource = config.resource\n const isMediaLibrary = resource?.type === 'media-library'\n\n // Media Library has a simpler upload API with fewer supported parameters\n const query: Any = isMediaLibrary\n ? {\n // Media Library only supports basic parameters\n title,\n filename,\n }\n : {\n // Content Lake supports full set of parameters\n label,\n title,\n description,\n filename,\n meta,\n creditLine,\n }\n\n // Source parameters are only for Content Lake\n if (source && !isMediaLibrary) {\n query.sourceId = source.id\n query.sourceName = source.name\n query.sourceUrl = source.url\n }\n\n return _requestObservable(client, httpRequest, {\n tag,\n method: 'POST',\n timeout: options.timeout || 0,\n uri: buildAssetUploadUrl(config, assetType),\n headers: options.contentType ? {'Content-Type': options.contentType} : {},\n query,\n body,\n })\n}\n\nfunction buildAssetUploadUrl(config: InitializedClientConfig, assetType: 'image' | 'file'): string {\n const assetTypeEndpoint = assetType === 'image' ? 'images' : 'files'\n const resource = config.resource\n\n if (resource) {\n const {type, id} = resource\n switch (type) {\n case 'dataset': {\n throw new Error(\n 'Assets are not supported for dataset resources, yet. Configure the client with `{projectId: <projectId>, dataset: <datasetId>}` instead.',\n )\n }\n case 'canvas': {\n return `/canvases/${id}/assets/${assetTypeEndpoint}`\n }\n case 'media-library': {\n return `/media-libraries/${id}/upload`\n }\n case 'dashboard': {\n return `/dashboards/${id}/assets/${assetTypeEndpoint}`\n }\n default:\n // @ts-expect-error - handle all supported resource types\n throw new Error(`Unsupported resource type: ${type.toString()}`)\n }\n }\n\n const dataset = validators.hasDataset(config)\n return `assets/${assetTypeEndpoint}/${dataset}`\n}\n\nfunction optionsFromFile(opts: Record<string, Any>, file: Any) {\n if (typeof File === 'undefined' || !(file instanceof File)) {\n return opts\n }\n\n return Object.assign(\n {\n filename: opts.preserveFilename === false ? undefined : file.name,\n contentType: file.type,\n },\n opts,\n )\n}\n","import type {Any} from '../types'\n\nexport default (obj: Any, defaults: Any) =>\n Object.keys(defaults)\n .concat(Object.keys(obj))\n .reduce((target, prop) => {\n target[prop] = typeof obj[prop] === 'undefined' ? defaults[prop] : obj[prop]\n\n return target\n }, {} as Any)\n","import {type Any} from '../types'\n\nexport const pick = (obj: Any, props: Any) =>\n props.reduce((selection: Any, prop: Any) => {\n if (typeof obj[prop] === 'undefined') {\n return selection\n }\n\n selection[prop] = obj[prop]\n return selection\n }, {})\n","import {defer, shareReplay} from 'rxjs'\nimport {map} from 'rxjs/operators'\n\nexport const eventSourcePolyfill = defer(() => import('@sanity/eventsource')).pipe(\n map(({default: EventSource}) => EventSource as unknown as typeof globalThis.EventSource),\n shareReplay(1),\n)\n","import {\n catchError,\n concat,\n mergeMap,\n Observable,\n of,\n type OperatorFunction,\n throwError,\n timer,\n} from 'rxjs'\n\nimport {ConnectionFailedError} from './eventsource'\n\n/**\n * Note: connection failure is not the same as network disconnect which may happen more frequent.\n * The EventSource instance will automatically reconnect in case of a network disconnect, however,\n * in some rare cases a ConnectionFailed Error will be thrown and this operator explicitly retries these\n */\nexport function reconnectOnConnectionFailure<T>(): OperatorFunction<T, T | {type: 'reconnect'}> {\n return function (source: Observable<T>) {\n return source.pipe(\n catchError((err, caught) => {\n if (err instanceof ConnectionFailedError) {\n return concat(of({type: 'reconnect' as const}), timer(1000).pipe(mergeMap(() => caught)))\n }\n return throwError(() => err)\n }),\n )\n }\n}\n","import {Observable, of, throwError} from 'rxjs'\nimport {filter, map} from 'rxjs/operators'\n\nimport type {ObservableSanityClient, SanityClient} from '../SanityClient'\nimport {\n type Any,\n type ListenEvent,\n type ListenEventName,\n type ListenOptions,\n type ListenParams,\n type MutationEvent,\n type OpenEvent,\n type ReconnectEvent,\n type WelcomeEvent,\n} from '../types'\nimport defaults from '../util/defaults'\nimport {pick} from '../util/pick'\nimport {_getDataUrl} from './dataMethods'\nimport {encodeQueryString} from './encodeQueryString'\nimport {connectEventSource} from './eventsource'\nimport {eventSourcePolyfill} from './eventsourcePolyfill'\nimport {reconnectOnConnectionFailure} from './reconnectOnConnectionFailure'\n\n// Limit is 16K for a _request_, eg including headers. Have to account for an\n// unknown range of headers, but an average EventSource request from Chrome seems\n// to have around 700 bytes of cruft, so let us account for 1.2K to be \"safe\"\nconst MAX_URL_LENGTH = 16000 - 1200\n\nconst possibleOptions = [\n 'includePreviousRevision',\n 'includeResult',\n 'includeMutations',\n 'includeAllVersions',\n 'visibility',\n 'effectFormat',\n 'tag',\n]\n\nconst defaultOptions = {\n includeResult: true,\n}\n\n/**\n * Maps an array of listen events names to their corresponding listen event type, e.g:\n * ```\n * type Test = MapListenEventNamesToListenEvents<Doc, ['welcome']>\n * // ^? WelcomeEvent\n * ```\n *\n * @public\n */\nexport type MapListenEventNamesToListenEvents<\n R extends Record<string, Any> = Record<string, Any>,\n Events extends ListenEventName[] = ListenEventName[],\n> = Events extends (infer E)[]\n ? E extends 'welcome'\n ? WelcomeEvent\n : E extends 'mutation'\n ? MutationEvent<R>\n : E extends 'reconnect'\n ? ReconnectEvent\n : E extends 'open'\n ? OpenEvent\n : never\n : never\n\n/**\n * Maps a ListenOptions object and returns the Listen events opted for, e.g:\n * ```\n * type Test = ListenEventFromOptions<Doc, {events: ['welcome', 'mutation']}>\n * // ^? WelcomeEvent | MutationEvent<Doc>\n * ```\n *\n * @public\n */\nexport type ListenEventFromOptions<\n R extends Record<string, Any> = Record<string, Any>,\n Opts extends ListenOptions | undefined = undefined,\n> = Opts extends ListenOptions\n ? Opts['events'] extends ListenEventName[]\n ? MapListenEventNamesToListenEvents<R, Opts['events']>\n : // fall back to ListenEvent if opts events is present, but we can't infer the literal event names\n ListenEvent<R>\n : MutationEvent<R>\n\n/**\n * Set up a listener that will be notified when mutations occur on documents matching the provided query/filter.\n *\n * @param query - GROQ-filter to listen to changes for\n * @param params - Optional query parameters\n * @param options - Optional listener options\n * @public\n */\nexport function _listen<R extends Record<string, Any> = Record<string, Any>>(\n this: SanityClient | ObservableSanityClient,\n query: string,\n params?: ListenParams,\n): Observable<MutationEvent<R>>\n/**\n * Set up a listener that will be notified when mutations occur on documents matching the provided query/filter.\n *\n * @param query - GROQ-filter to listen to changes for\n * @param params - Optional query parameters\n * @param options - Optional listener options\n * @public\n */\nexport function _listen<\n R extends Record<string, Any> = Record<string, Any>,\n Opts extends ListenOptions = ListenOptions,\n>(\n this: SanityClient | ObservableSanityClient,\n query: string,\n params?: ListenParams,\n options?: Opts,\n): Observable<ListenEventFromOptions<R, Opts>>\n/** @public */\nexport function _listen<\n R extends Record<string, Any> = Record<string, Any>,\n Opts extends ListenOptions = ListenOptions,\n>(\n this: SanityClient | ObservableSanityClient,\n query: string,\n params?: ListenParams,\n opts: Opts = {} as Opts,\n): Observable<ListenEventFromOptions<R, Opts>> {\n const {url, token, withCredentials, requestTagPrefix, headers: configHeaders} = this.config()\n const tag = opts.tag && requestTagPrefix ? [requestTagPrefix, opts.tag].join('.') : opts.tag\n const options = {...defaults(opts, defaultOptions), tag}\n const listenOpts = pick(options, possibleOptions)\n const qs = encodeQueryString({query, params, options: {tag, ...listenOpts}})\n\n const uri = `${url}${_getDataUrl(this, 'listen', qs)}`\n if (uri.length > MAX_URL_LENGTH) {\n return throwError(() => new Error('Query too large for listener'))\n }\n\n const listenFor = (options.events ? options.events : ['mutation']) satisfies Opts['events']\n\n const esOptions: EventSourceInit & {headers?: Record<string, string>} = {}\n if (withCredentials) {\n esOptions.withCredentials = true\n }\n\n if (token || configHeaders) {\n esOptions.headers = {}\n\n if (token) {\n esOptions.headers.Authorization = `Bearer ${token}`\n }\n\n if (configHeaders) {\n Object.assign(esOptions.headers, configHeaders)\n }\n }\n\n const initEventSource = () =>\n // use polyfill if there is no global EventSource or if we need to set headers\n (typeof EventSource === 'undefined' || esOptions.headers\n ? eventSourcePolyfill\n : of(EventSource)\n ).pipe(map((EventSource) => new EventSource(uri, esOptions)))\n\n return connectEventSource(initEventSource, listenFor).pipe(\n reconnectOnConnectionFailure(),\n filter((event) => listenFor.includes(event.type)),\n map((event) => ({\n type: event.type,\n ...('data' in event ? (event.data as object) : {}),\n })),\n ) as Observable<ListenEventFromOptions<R, Opts>>\n}\n","import {\n finalize,\n merge,\n type MonoTypeOperatorFunction,\n Observable,\n share,\n type ShareConfig,\n tap,\n} from 'rxjs'\n\nexport type ShareReplayLatestConfig<T> = ShareConfig<T> & {predicate: (value: T) => boolean}\n\n/**\n * A variant of share that takes a predicate function to determine which value to replay to new subscribers\n * @param predicate - Predicate function to determine which value to replay\n */\nexport function shareReplayLatest<T>(predicate: (value: T) => boolean): MonoTypeOperatorFunction<T>\n\n/**\n * A variant of share that takes a predicate function to determine which value to replay to new subscribers\n * @param config - ShareConfig with additional predicate function\n */\nexport function shareReplayLatest<T>(\n config: ShareReplayLatestConfig<T>,\n): MonoTypeOperatorFunction<T>\n\n/**\n * A variant of share that takes a predicate function to determine which value to replay to new subscribers\n * @param configOrPredicate - Predicate function to determine which value to replay\n * @param config - Optional ShareConfig\n */\nexport function shareReplayLatest<T>(\n configOrPredicate: ShareReplayLatestConfig<T> | ShareReplayLatestConfig<T>['predicate'],\n config?: ShareConfig<T>,\n) {\n return _shareReplayLatest(\n typeof configOrPredicate === 'function'\n ? {predicate: configOrPredicate, ...config}\n : configOrPredicate,\n )\n}\nfunction _shareReplayLatest<T>(config: ShareReplayLatestConfig<T>): MonoTypeOperatorFunction<T> {\n return (source: Observable<T>) => {\n let latest: T | undefined\n let emitted = false\n\n // eslint-disable-next-line unused-imports/no-unused-vars\n const {predicate, ...shareConfig} = config\n\n const wrapped = source.pipe(\n tap((value) => {\n if (config.predicate(value)) {\n emitted = true\n latest = value\n }\n }),\n finalize(() => {\n emitted = false\n latest = undefined\n }),\n share(shareConfig),\n )\n const emitLatest = new Observable<T>((subscriber) => {\n if (emitted) {\n subscriber.next(\n // this cast is safe because of the emitted check which asserts that we got T from the source\n latest as T,\n )\n }\n subscriber.complete()\n })\n return merge(wrapped, emitLatest)\n }\n}\n","import {catchError, mergeMap, Observable, of} from 'rxjs'\nimport {finalize, map} from 'rxjs/operators'\n\nimport {CorsOriginError} from '../http/errors'\nimport type {ObservableSanityClient, SanityClient} from '../SanityClient'\nimport type {\n LiveEvent,\n LiveEventGoAway,\n LiveEventMessage,\n LiveEventReconnect,\n LiveEventRestart,\n LiveEventWelcome,\n SyncTag,\n} from '../types'\nimport {shareReplayLatest} from '../util/shareReplayLatest'\nimport * as validate from '../validators'\nimport {_getDataUrl} from './dataMethods'\nimport {connectEventSource} from './eventsource'\nimport {eventSourcePolyfill} from './eventsourcePolyfill'\nimport {reconnectOnConnectionFailure} from './reconnectOnConnectionFailure'\n\nconst requiredApiVersion = '2021-03-25'\n\n/**\n * @public\n */\nexport class LiveClient {\n #client: SanityClient | ObservableSanityClient\n constructor(client: SanityClient | ObservableSanityClient) {\n this.#client = client\n }\n\n /**\n * Requires `apiVersion` to be `2021-03-25` or later.\n */\n events({\n includeDrafts = false,\n tag: _tag,\n }: {\n includeDrafts?: boolean\n /**\n * Optional request tag for the listener. Use to identify the request in logs.\n *\n * @defaultValue `undefined`\n */\n tag?: string\n } = {}): Observable<LiveEvent> {\n validate.resourceGuard('live', this.#client.config())\n const {\n projectId,\n apiVersion: _apiVersion,\n token,\n withCredentials,\n requestTagPrefix,\n headers: configHeaders,\n } = this.#client.config()\n const apiVersion = _apiVersion.replace(/^v/, '')\n if (apiVersion !== 'X' && apiVersion < requiredApiVersion) {\n throw new Error(\n `The live events API requires API version ${requiredApiVersion} or later. ` +\n `The current API version is ${apiVersion}. ` +\n `Please update your API version to use this feature.`,\n )\n }\n if (includeDrafts && !token && !withCredentials) {\n throw new Error(\n `The live events API requires a token or withCredentials when 'includeDrafts: true'. Please update your client configuration. The token should have the lowest possible access role.`,\n )\n }\n const path = _getDataUrl(this.#client, 'live/events')\n const url = new URL(this.#client.getUrl(path, false))\n const tag = _tag && requestTagPrefix ? [requestTagPrefix, _tag].join('.') : _tag\n if (tag) {\n url.searchParams.set('tag', tag)\n }\n if (includeDrafts) {\n url.searchParams.set('includeDrafts', 'true')\n }\n const esOptions: EventSourceInit & {headers?: Record<string, string>} = {}\n if (includeDrafts && withCredentials) {\n esOptions.withCredentials = true\n }\n\n if ((includeDrafts && token) || configHeaders) {\n esOptions.headers = {}\n\n if (includeDrafts && token) {\n esOptions.headers.Authorization = `Bearer ${token}`\n }\n\n if (configHeaders) {\n Object.assign(esOptions.headers, configHeaders)\n }\n }\n\n const key = `${url.href}::${JSON.stringify(esOptions)}`\n const existing = eventsCache.get(key)\n\n if (existing) {\n return existing\n }\n\n const initEventSource = () =>\n // use polyfill if there is no global EventSource or if we need to set headers\n (typeof EventSource === 'undefined' || esOptions.headers\n ? eventSourcePolyfill\n : of(EventSource)\n ).pipe(map((EventSource) => new EventSource(url.href, esOptions)))\n\n const events = connectEventSource(initEventSource, [\n 'message',\n 'restart',\n 'welcome',\n 'reconnect',\n 'goaway',\n ])\n\n const checkCors = fetchObservable(url, {\n method: 'OPTIONS',\n mode: 'cors',\n credentials: esOptions.withCredentials ? 'include' : 'omit',\n headers: esOptions.headers,\n }).pipe(\n catchError(() => {\n // If the request fails, then we assume it was due to CORS, and we rethrow a special error that allows special handling in userland\n throw new CorsOriginError({projectId: projectId!})\n }),\n )\n\n const observable = events\n .pipe(\n reconnectOnConnectionFailure(),\n mergeMap((event) => {\n if (event.type === 'reconnect') {\n // Check for CORS on reconnect events (which happen on 403s)\n return checkCors.pipe(mergeMap(() => of(event)))\n }\n return of(event)\n }),\n catchError((err) => {\n return checkCors.pipe(\n mergeMap(() => {\n // rethrow the original error if checkCors passed\n throw err\n }),\n )\n }),\n map((event) => {\n if (event.type === 'message') {\n const {data, ...rest} = event\n // Splat data properties from the eventsource message onto the returned event\n return {...rest, tags: (data as {tags: SyncTag[]}).tags} as LiveEventMessage\n }\n return event as LiveEventRestart | LiveEventReconnect | LiveEventWelcome | LiveEventGoAway\n }),\n )\n .pipe(\n finalize(() => eventsCache.delete(key)),\n shareReplayLatest({\n predicate: (event) => event.type === 'welcome',\n }),\n )\n eventsCache.set(key, observable)\n return observable\n }\n}\n\nfunction fetchObservable(url: URL, init: RequestInit) {\n return new Observable((observer) => {\n const controller = new AbortController()\n const signal = controller.signal\n fetch(url, {...init, signal: controller.signal}).then(\n (response) => {\n observer.next(response)\n observer.complete()\n },\n (err) => {\n if (!signal.aborted) {\n observer.error(err)\n }\n },\n )\n return () => controller.abort()\n })\n}\n\nconst eventsCache = new Map<string, Observable<LiveEvent>>()\n","import {lastValueFrom, type Observable} from 'rxjs'\n\nimport {_request} from '../data/dataMethods'\nimport type {ObservableSanityClient, SanityClient} from '../SanityClient'\nimport type {DatasetAclMode, DatasetResponse, DatasetsResponse, HttpRequest} from '../types'\nimport * as validate from '../validators'\n\n/** @internal */\nexport class ObservableDatasetsClient {\n #client: ObservableSanityClient\n #httpRequest: HttpRequest\n constructor(client: ObservableSanityClient, httpRequest: HttpRequest) {\n this.#client = client\n this.#httpRequest = httpRequest\n }\n\n /**\n * Create a new dataset with the given name\n *\n * @param name - Name of the dataset to create\n * @param options - Options for the dataset\n */\n create(name: string, options?: {aclMode?: DatasetAclMode}): Observable<DatasetResponse> {\n return _modify<DatasetResponse>(this.#client, this.#httpRequest, 'PUT', name, options)\n }\n\n /**\n * Edit a dataset with the given name\n *\n * @param name - Name of the dataset to edit\n * @param options - New options for the dataset\n */\n edit(name: string, options?: {aclMode?: DatasetAclMode}): Observable<DatasetResponse> {\n return _modify<DatasetResponse>(this.#client, this.#httpRequest, 'PATCH', name, options)\n }\n\n /**\n * Delete a dataset with the given name\n *\n * @param name - Name of the dataset to delete\n */\n delete(name: string): Observable<{deleted: true}> {\n return _modify<{deleted: true}>(this.#client, this.#httpRequest, 'DELETE', name)\n }\n\n /**\n * Fetch a list of datasets for the configured project\n */\n list(): Observable<DatasetsResponse> {\n validate.resourceGuard('dataset', this.#client.config())\n const config = this.#client.config()\n const projectId = config.projectId\n let uri = '/datasets'\n if (config.useProjectHostname === false) {\n uri = `/projects/${projectId}/datasets`\n }\n\n return _request<DatasetsResponse>(this.#client, this.#httpRequest, {\n uri,\n tag: null,\n })\n }\n}\n\n/** @internal */\nexport class DatasetsClient {\n #client: SanityClient\n #httpRequest: HttpRequest\n constructor(client: SanityClient, httpRequest: HttpRequest) {\n this.#client = client\n this.#httpRequest = httpRequest\n }\n\n /**\n * Create a new dataset with the given name\n *\n * @param name - Name of the dataset to create\n * @param options - Options for the dataset\n */\n create(name: string, options?: {aclMode?: DatasetAclMode}): Promise<DatasetResponse> {\n validate.resourceGuard('dataset', this.#client.config())\n return lastValueFrom(\n _modify<DatasetResponse>(this.#client, this.#httpRequest, 'PUT', name, options),\n )\n }\n\n /**\n * Edit a dataset with the given name\n *\n * @param name - Name of the dataset to edit\n * @param options - New options for the dataset\n */\n edit(name: string, options?: {aclMode?: DatasetAclMode}): Promise<DatasetResponse> {\n validate.resourceGuard('dataset', this.#client.config())\n return lastValueFrom(\n _modify<DatasetResponse>(this.#client, this.#httpRequest, 'PATCH', name, options),\n )\n }\n\n /**\n * Delete a dataset with the given name\n *\n * @param name - Name of the dataset to delete\n */\n delete(name: string): Promise<{deleted: true}> {\n validate.resourceGuard('dataset', this.#client.config())\n return lastValueFrom(_modify<{deleted: true}>(this.#client, this.#httpRequest, 'DELETE', name))\n }\n\n /**\n * Fetch a list of datasets for the configured project\n */\n list(): Promise<DatasetsResponse> {\n validate.resourceGuard('dataset', this.#client.config())\n const config = this.#client.config()\n const projectId = config.projectId\n let uri = '/datasets'\n if (config.useProjectHostname === false) {\n uri = `/projects/${projectId}/datasets`\n }\n\n return lastValueFrom(\n _request<DatasetsResponse>(this.#client, this.#httpRequest, {uri, tag: null}),\n )\n }\n}\n\nfunction _modify<R = unknown>(\n client: SanityClient | ObservableSanityClient,\n httpRequest: HttpRequest,\n method: 'DELETE' | 'PATCH' | 'PUT',\n name: string,\n options?: {aclMode?: DatasetAclMode},\n) {\n validate.resourceGuard('dataset', client.config())\n validate.dataset(name)\n\n return _request<R>(client, httpRequest, {\n method,\n uri: `/datasets/${name}`,\n body: options,\n tag: null,\n })\n}\n","import {lastValueFrom, type Observable} from 'rxjs'\n\nimport {_request} from '../data/dataMethods'\nimport type {ObservableSanityClient, SanityClient} from '../SanityClient'\nimport type {\n HttpRequest,\n MediaLibraryAssetInstanceIdentifier,\n MediaLibraryPlaybackInfoOptions,\n SanityReference,\n VideoPlaybackInfo,\n} from '../types'\n\n/** @internal */\nexport class ObservableMediaLibraryVideoClient {\n #client: ObservableSanityClient\n #httpRequest: HttpRequest\n constructor(client: ObservableSanityClient, httpRequest: HttpRequest) {\n this.#client = client\n this.#httpRequest = httpRequest\n }\n\n /**\n * Get video playback information for a media library asset\n *\n * @param assetIdentifier - Asset instance identifier (GDR, video-prefixed ID, or container ID)\n * @param options - Options for transformations and expiration\n */\n getPlaybackInfo(\n assetIdentifier: MediaLibraryAssetInstanceIdentifier,\n options: MediaLibraryPlaybackInfoOptions = {},\n ): Observable<VideoPlaybackInfo> {\n const config = this.#client.config()\n const resource = config.resource || config['~experimental_resource']\n const configMediaLibraryId = resource?.id\n\n const {instanceId, libraryId} = parseAssetInstanceId(assetIdentifier)\n const effectiveLibraryId = libraryId || configMediaLibraryId\n\n if (!effectiveLibraryId) {\n throw new Error(\n 'Could not determine Media Library ID - you need to provide a valid Media Library ID in the client config or a Media Library GDR',\n )\n }\n\n const uri = buildVideoPlaybackInfoUrl(instanceId, effectiveLibraryId)\n const queryParams = buildQueryParams(options)\n\n return _request<VideoPlaybackInfo>(this.#client, this.#httpRequest, {\n method: 'GET',\n uri,\n query: queryParams,\n })\n }\n}\n\n/** @internal */\nexport class MediaLibraryVideoClient {\n #client: SanityClient\n #httpRequest: HttpRequest\n constructor(client: SanityClient, httpRequest: HttpRequest) {\n this.#client = client\n this.#httpRequest = httpRequest\n }\n\n /**\n * Get video playback information for a media library asset\n *\n * @param assetIdentifier - Asset instance identifier (GDR, video-prefixed ID, or container ID)\n * @param options - Options for transformations and expiration\n */\n getPlaybackInfo(\n assetIdentifier: MediaLibraryAssetInstanceIdentifier,\n options: MediaLibraryPlaybackInfoOptions = {},\n ): Promise<VideoPlaybackInfo> {\n return lastValueFrom(\n new ObservableMediaLibraryVideoClient(\n this.#client.observable,\n this.#httpRequest,\n ).getPlaybackInfo(assetIdentifier, options),\n )\n }\n}\n\nconst ML_GDR_PATTERN = /^media-library:(ml[^:]+):([^:]+)$/\n\n/** @internal */\nfunction isSanityReference(\n assetIdentifier: MediaLibraryAssetInstanceIdentifier,\n): assetIdentifier is SanityReference {\n return typeof assetIdentifier === 'object' && '_ref' in assetIdentifier\n}\n\n/**\n * Parse the asset instance id and library id from the asset identifier\n *\n * @param assetIdentifier - The asset identifier - either a asset instance id or a Media Library GDR\n * @returns The asset instance id and library id\n */\nexport function parseAssetInstanceId(assetIdentifier: MediaLibraryAssetInstanceIdentifier): {\n instanceId: string\n libraryId?: string\n} {\n const ref = isSanityReference(assetIdentifier) ? assetIdentifier._ref : assetIdentifier\n\n const match = ML_GDR_PATTERN.exec(ref)\n if (match) {\n const [, libraryId, instanceId] = match\n return {libraryId, instanceId}\n }\n\n // Asumes valid asset instance id\n if (typeof assetIdentifier === 'string' && assetIdentifier.startsWith('video-')) {\n return {instanceId: assetIdentifier}\n }\n\n throw new Error(\n `Invalid video asset instance identifier \"${ref}\": must be a valid video instance id or a Global Dataset Reference (GDR) to the video asset in the Media Library`,\n )\n}\n\nfunction buildVideoPlaybackInfoUrl(instanceId: string, libraryId: string): string {\n return `/media-libraries/${libraryId}/video/${instanceId}/playback-info`\n}\n\nfunction buildQueryParams(options: MediaLibraryPlaybackInfoOptions): Record<string, unknown> {\n const params: Record<string, unknown> = {}\n\n if (options.transformations) {\n const {thumbnail, animated, storyboard} = options.transformations\n\n if (thumbnail) {\n if (thumbnail.width) params.thumbnailWidth = thumbnail.width\n if (thumbnail.height) params.thumbnailHeight = thumbnail.height\n if (thumbnail.time !== undefined) params.thumbnailTime = thumbnail.time\n if (thumbnail.fit) params.thumbnailFit = thumbnail.fit\n if (thumbnail.format) params.thumbnailFormat = thumbnail.format\n }\n\n if (animated) {\n if (animated.width) params.animatedWidth = animated.width\n if (animated.height) params.animatedHeight = animated.height\n if (animated.start !== undefined) params.animatedStart = animated.start\n if (animated.end !== undefined) params.animatedEnd = animated.end\n if (animated.fps) params.animatedFps = animated.fps\n if (animated.format) params.animatedFormat = animated.format\n }\n\n if (storyboard) {\n if (storyboard.format) params.storyboardFormat = storyboard.format\n }\n }\n\n if (options.expiration) {\n params.expiration = options.expiration\n }\n\n return params\n}\n","import {lastValueFrom, type Observable} from 'rxjs'\n\nimport {_request} from '../data/dataMethods'\nimport type {ObservableSanityClient, SanityClient} from '../SanityClient'\nimport type {HttpRequest, SanityProject} from '../types'\n\n/** @internal */\nexport class ObservableProjectsClient {\n #client: ObservableSanityClient\n #httpRequest: HttpRequest\n constructor(client: ObservableSanityClient, httpRequest: HttpRequest) {\n this.#client = client\n this.#httpRequest = httpRequest\n }\n\n /**\n * Fetch a list of projects the authenticated user has access to.\n *\n * @param options - Options for the list request\n * - `includeMembers` - Whether to include members in the response (default: true)\n * - `organizationId` - ID of the organization to fetch projects for\n */\n list(options?: {includeMembers?: true; organizationId?: string}): Observable<SanityProject[]>\n list(options?: {\n includeMembers?: false\n organizationId?: string\n }): Observable<Omit<SanityProject, 'members'>[]>\n list(options?: {\n includeMembers?: boolean\n organizationId?: string\n }): Observable<SanityProject[] | Omit<SanityProject, 'members'>[]> {\n const query: Record<string, string> = {}\n const uri = '/projects'\n if (options?.includeMembers === false) {\n query.includeMembers = 'false'\n }\n if (options?.organizationId) {\n query.organizationId = options.organizationId\n }\n\n return _request<SanityProject[]>(this.#client, this.#httpRequest, {uri, query})\n }\n\n /**\n * Fetch a project by project ID\n *\n * @param projectId - ID of the project to fetch\n */\n getById(projectId: string): Observable<SanityProject> {\n return _request<SanityProject>(this.#client, this.#httpRequest, {uri: `/projects/${projectId}`})\n }\n}\n\n/** @internal */\nexport class ProjectsClient {\n #client: SanityClient\n #httpRequest: HttpRequest\n constructor(client: SanityClient, httpRequest: HttpRequest) {\n this.#client = client\n this.#httpRequest = httpRequest\n }\n\n /**\n * Fetch a list of projects the authenticated user has access to.\n *\n * @param options - Options for the list request\n * - `includeMembers` - Whether to include members in the response (default: true)\n * - `organizationId` - ID of the organization to fetch projects for\n */\n list(options?: {includeMembers?: true; organizationId?: string}): Promise<SanityProject[]>\n list(options?: {\n includeMembers?: false\n organizationId?: string\n }): Promise<Omit<SanityProject, 'members'>[]>\n list(options?: {\n includeMembers?: boolean\n organizationId?: string\n }): Promise<SanityProject[] | Omit<SanityProject, 'members'>[]> {\n const query: Record<string, string> = {}\n const uri = '/projects'\n if (options?.includeMembers === false) {\n query.includeMembers = 'false'\n }\n if (options?.organizationId) {\n query.organizationId = options.organizationId\n }\n return lastValueFrom(_request<SanityProject[]>(this.#client, this.#httpRequest, {uri, query}))\n }\n\n /**\n * Fetch a project by project ID\n *\n * @param projectId - ID of the project to fetch\n */\n getById(projectId: string): Promise<SanityProject> {\n return lastValueFrom(\n _request<SanityProject>(this.#client, this.#httpRequest, {uri: `/projects/${projectId}`}),\n )\n }\n}\n","import {\n getDraftId,\n getVersionFromId,\n getVersionId,\n isDraftId,\n isVersionId,\n} from '@sanity/client/csm'\nimport {customAlphabet} from 'nanoid'\n\nimport type {IdentifiedSanityDocumentStub, SanityDocumentStub} from '../types'\nimport {validateVersionIdMatch} from '../validators'\n\n/**\n * @internal\n *\n * ~24 years (or 7.54e+8 seconds) needed, in order to have a 1% probability of at least one collision if 10 ID's are generated every hour.\n */\nexport const generateReleaseId = customAlphabet(\n 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',\n 8,\n)\n\n/** @internal */\nexport const getDocumentVersionId = (publishedId: string, releaseId?: string) =>\n releaseId ? getVersionId(publishedId, releaseId) : getDraftId(publishedId)\n\n/** @internal */\nexport function deriveDocumentVersionId(\n op: string,\n {\n releaseId,\n publishedId,\n document,\n }: {\n releaseId?: string\n publishedId?: string\n document: SanityDocumentStub | IdentifiedSanityDocumentStub\n },\n): string {\n if (publishedId && document._id) {\n const versionId = getDocumentVersionId(publishedId, releaseId)\n validateVersionIdMatch(versionId, document)\n return versionId\n }\n\n if (document._id) {\n const isDraft = isDraftId(document._id)\n const isVersion = isVersionId(document._id)\n\n if (!isDraft && !isVersion) {\n throw new Error(\n `\\`${op}()\\` requires a document with an \\`_id\\` that is a version or draft ID`,\n )\n }\n\n if (releaseId) {\n if (isDraft) {\n throw new Error(\n `\\`${op}()\\` was called with a document ID (\\`${document._id}\\`) that is a draft ID, but a release ID (\\`${releaseId}\\`) was also provided.`,\n )\n }\n\n const builtVersionId = getVersionFromId(document._id)\n if (builtVersionId !== releaseId) {\n throw new Error(\n `\\`${op}()\\` was called with a document ID (\\`${document._id}\\`) that is a version ID, but the release ID (\\`${releaseId}\\`) does not match the document's version ID (\\`${builtVersionId}\\`).`,\n )\n }\n }\n\n return document._id\n }\n\n if (publishedId) {\n return getDocumentVersionId(publishedId, releaseId)\n }\n\n throw new Error(`\\`${op}()\\` requires either a publishedId or a document with an \\`_id\\``)\n}\n","import type {BaseActionOptions, CreateReleaseAction, ReleaseDocument} from '@sanity/client'\n\nimport {generateReleaseId} from '../util/createVersionId'\n\ninterface ReleaseOrOptions extends BaseActionOptions {\n releaseId?: string\n metadata?: Partial<ReleaseDocument['metadata']>\n}\n\ninterface CompleteCreateReleaseAction extends CreateReleaseAction {\n metadata: ReleaseDocument['metadata']\n}\n\nconst getArgs = (\n releaseOrOptions?: ReleaseOrOptions,\n maybeOptions?: BaseActionOptions,\n): [string, Partial<ReleaseDocument['metadata']>, BaseActionOptions | undefined] => {\n const isReleaseInput =\n typeof releaseOrOptions === 'object' &&\n releaseOrOptions !== null &&\n ('releaseId' in releaseOrOptions || 'metadata' in releaseOrOptions)\n\n if (isReleaseInput) {\n const {releaseId = generateReleaseId(), metadata = {}} = releaseOrOptions\n return [releaseId, metadata, maybeOptions]\n }\n\n return [generateReleaseId(), {}, releaseOrOptions as BaseActionOptions]\n}\n\n/** @internal */\nexport const createRelease = (\n releaseOrOptions?: ReleaseOrOptions,\n maybeOptions?: BaseActionOptions,\n): {\n action: CompleteCreateReleaseAction\n options?: BaseActionOptions\n} => {\n const [releaseId, metadata, options] = getArgs(releaseOrOptions, maybeOptions)\n\n const finalMetadata: ReleaseDocument['metadata'] = {\n ...metadata,\n releaseType: metadata.releaseType || 'undecided',\n }\n\n const createAction: CompleteCreateReleaseAction = {\n actionType: 'sanity.action.release.create',\n releaseId,\n metadata: finalMetadata,\n }\n\n return {action: createAction, options}\n}\n","import {lastValueFrom, map, Observable} from 'rxjs'\n\nimport {_action, _getDocument, _getReleaseDocuments} from '../data/dataMethods'\nimport type {ObservableSanityClient, SanityClient} from '../SanityClient'\nimport type {\n ArchiveReleaseAction,\n BaseActionOptions,\n BaseMutationOptions,\n DeleteReleaseAction,\n EditReleaseAction,\n HttpRequest,\n PatchOperations,\n PublishReleaseAction,\n RawQueryResponse,\n ReleaseDocument,\n SanityDocument,\n ScheduleReleaseAction,\n SingleActionResult,\n UnarchiveReleaseAction,\n UnscheduleReleaseAction,\n} from '../types'\nimport {createRelease} from './createRelease'\n\n/** @public */\nexport class ObservableReleasesClient {\n #client: ObservableSanityClient\n #httpRequest: HttpRequest\n constructor(client: ObservableSanityClient, httpRequest: HttpRequest) {\n this.#client = client\n this.#httpRequest = httpRequest\n }\n\n /**\n * @public\n *\n * Retrieve a release by id.\n *\n * @category Releases\n *\n * @param params - Release action parameters:\n * - `releaseId` - The id of the release to retrieve.\n * @param options - Additional query options including abort signal and query tag.\n * @returns An observable that resolves to the release document {@link ReleaseDocument}.\n *\n * @example Retrieving a release by id\n * ```ts\n * client.observable.releases.get({releaseId: 'my-release'}).pipe(\n * tap((release) => console.log(release)),\n * // {\n * // _id: '_.releases.my-release',\n * // name: 'my-release'\n * // _type: 'system.release',\n * // metadata: {releaseType: 'asap'},\n * // _createdAt: '2021-01-01T00:00:00.000Z',\n * // ...\n * // }\n * ).subscribe()\n * ```\n */\n get(\n {releaseId}: {releaseId: string},\n options?: {signal?: AbortSignal; tag?: string},\n ): Observable<ReleaseDocument | undefined> {\n return _getDocument<ReleaseDocument>(\n this.#client,\n this.#httpRequest,\n `_.releases.${releaseId}`,\n options,\n )\n }\n\n /**\n * @public\n *\n * Creates a new release under the given id, with metadata.\n *\n * @remarks\n * * If no releaseId is provided, a release id will be generated.\n * * If no metadata is provided, then an `undecided` releaseType will be used.\n *\n * @category Releases\n *\n * @param params - Release action parameters:\n * - `releaseId` - The id of the release to create.\n * - `metadata` - The metadata to associate with the release {@link ReleaseDocument}.\n * @param options - Additional action options.\n * @returns An observable that resolves to the `transactionId` and the release id and metadata.\n *\n * @example Creating a release with a custom id and metadata\n * ```ts\n * const releaseId = 'my-release'\n * const metadata: ReleaseDocument['metadata'] = {\n * releaseType: 'asap',\n * }\n *\n * client.observable.releases.create({releaseId, metadata}).pipe(\n * tap(({transactionId, releaseId, metadata}) => console.log(transactionId, releaseId, metadata)),\n * // {\n * // transactionId: 'transaction-id',\n * // releaseId: 'my-release',\n * // metadata: {releaseType: 'asap'},\n * // }\n * ).subscribe()\n * ```\n *\n * @example Creating a release with generated id and metadata\n * ```ts\n * client.observable.releases.create().pipe(\n * tap(({metadata}) => console.log(metadata)),\n * // {\n * // metadata: {releaseType: 'undecided'},\n * // }\n * ).subscribe()\n * ```\n *\n * @example Creating a release using a custom transaction id\n * ```ts\n * client.observable.releases.create({transactionId: 'my-transaction-id'}).pipe(\n * tap(({transactionId, metadata}) => console.log(transactionId, metadata)),\n * // {\n * // transactionId: 'my-transaction-id',\n * // metadata: {releaseType: 'undecided'},\n * // }\n * ).subscribe()\n * ```\n */\n create(\n options: BaseActionOptions,\n ): Observable<SingleActionResult & {releaseId: string; metadata: ReleaseDocument['metadata']}>\n create(\n release: {releaseId?: string; metadata?: Partial<ReleaseDocument['metadata']>},\n options?: BaseActionOptions,\n ): Observable<SingleActionResult & {releaseId: string; metadata: ReleaseDocument['metadata']}>\n create(\n releaseOrOptions?:\n | {releaseId?: string; metadata?: Partial<ReleaseDocument['metadata']>}\n | BaseActionOptions,\n maybeOptions?: BaseActionOptions,\n ): Observable<SingleActionResult & {releaseId: string; metadata: ReleaseDocument['metadata']}> {\n const {action, options} = createRelease(releaseOrOptions, maybeOptions)\n const {releaseId, metadata} = action\n\n return _action(this.#client, this.#httpRequest, action, options).pipe(\n map((actionResult) => ({\n ...actionResult,\n releaseId,\n metadata,\n })),\n )\n }\n\n /**\n * @public\n *\n * Edits an existing release, updating the metadata.\n *\n * @category Releases\n *\n * @param params - Release action parameters:\n * - `releaseId` - The id of the release to edit.\n * - `patch` - The patch operation to apply on the release metadata {@link PatchMutationOperation}.\n * @param options - Additional action options.\n * @returns An observable that resolves to the `transactionId`.\n */\n edit(\n {releaseId, patch}: {releaseId: string; patch: PatchOperations},\n options?: BaseActionOptions,\n ): Observable<SingleActionResult> {\n const editAction: EditReleaseAction = {\n actionType: 'sanity.action.release.edit',\n releaseId,\n patch,\n }\n\n return _action(this.#client, this.#httpRequest, editAction, options)\n }\n\n /**\n * @public\n *\n * Publishes all documents in a release at once. For larger releases the effect of the publish\n * will be visible immediately when querying but the removal of the `versions.<releasesId>.*`\n * documents and creation of the corresponding published documents with the new content may\n * take some time.\n *\n * During this period both the source and target documents are locked and cannot be\n * modified through any other means.\n *\n * @category Releases\n *\n * @param params - Release action parameters:\n * - `releaseId` - The id of the release to publish.\n * @param options - Additional action options.\n * @returns An observable that resolves to the `transactionId`.\n */\n publish(\n {releaseId}: {releaseId: string},\n options?: BaseActionOptions,\n ): Observable<SingleActionResult> {\n const publishAction: PublishReleaseAction = {\n actionType: 'sanity.action.release.publish',\n releaseId,\n }\n\n return _action(this.#client, this.#httpRequest, publishAction, options)\n }\n\n /**\n * @public\n *\n * An archive action removes an active release. The documents that comprise the release\n * are deleted and therefore no longer queryable.\n *\n * While the documents remain in retention the last version can still be accessed using document history endpoint.\n *\n * @category Releases\n *\n * @param params - Release action parameters:\n * - `releaseId` - The id of the release to archive.\n * @param options - Additional action options.\n * @returns An observable that resolves to the `transactionId`.\n */\n archive(\n {releaseId}: {releaseId: string},\n options?: BaseActionOptions,\n ): Observable<SingleActionResult> {\n const archiveAction: ArchiveReleaseAction = {\n actionType: 'sanity.action.release.archive',\n releaseId,\n }\n\n return _action(this.#client, this.#httpRequest, archiveAction, options)\n }\n\n /**\n * @public\n *\n * An unarchive action restores an archived release and all documents\n * with the content they had just prior to archiving.\n *\n * @category Releases\n *\n * @param params - Release action parameters:\n * - `releaseId` - The id of the release to unarchive.\n * @param options - Additional action options.\n * @returns An observable that resolves to the `transactionId`.\n */\n unarchive(\n {releaseId}: {releaseId: string},\n options?: BaseActionOptions,\n ): Observable<SingleActionResult> {\n const unarchiveAction: UnarchiveReleaseAction = {\n actionType: 'sanity.action.release.unarchive',\n releaseId,\n }\n\n return _action(this.#client, this.#httpRequest, unarchiveAction, options)\n }\n\n /**\n * @public\n *\n * A schedule action queues a release for publishing at the given future time.\n * The release is locked such that no documents in the release can be modified and\n * no documents that it references can be deleted as this would make the publish fail.\n * At the given time, the same logic as for the publish action is triggered.\n *\n * @category Releases\n *\n * @param params - Release action parameters:\n * - `releaseId` - The id of the release to schedule.\n * - `publishAt` - The serialised date and time to publish the release. If the `publishAt` is in the past, the release will be published immediately.\n * @param options - Additional action options.\n * @returns An observable that resolves to the `transactionId`.\n */\n schedule(\n {releaseId, publishAt}: {releaseId: string; publishAt: string},\n options?: BaseActionOptions,\n ): Observable<SingleActionResult> {\n const scheduleAction: ScheduleReleaseAction = {\n actionType: 'sanity.action.release.schedule',\n releaseId,\n publishAt,\n }\n\n return _action(this.#client, this.#httpRequest, scheduleAction, options)\n }\n\n /**\n * @public\n *\n * An unschedule action stops a release from being published.\n * The documents in the release are considered unlocked and can be edited again.\n * This may fail if another release is scheduled to be published after this one and\n * has a reference to a document created by this one.\n *\n * @category Releases\n *\n * @param params - Release action parameters:\n * - `releaseId` - The id of the release to unschedule.\n * @param options - Additional action options.\n * @returns An observable that resolves to the `transactionId`.\n */\n unschedule(\n {releaseId}: {releaseId: string},\n options?: BaseActionOptions,\n ): Observable<SingleActionResult> {\n const unscheduleAction: UnscheduleReleaseAction = {\n actionType: 'sanity.action.release.unschedule',\n releaseId,\n }\n\n return _action(this.#client, this.#httpRequest, unscheduleAction, options)\n }\n\n /**\n * @public\n *\n * A delete action removes a published or archived release.\n * The backing system document will be removed from the dataset.\n *\n * @category Releases\n *\n * @param params - Release action parameters:\n * - `releaseId` - The id of the release to delete.\n * @param options - Additional action options.\n * @returns An observable that resolves to the `transactionId`.\n */\n delete(\n {releaseId}: {releaseId: string},\n options?: BaseActionOptions,\n ): Observable<SingleActionResult> {\n const deleteAction: DeleteReleaseAction = {\n actionType: 'sanity.action.release.delete',\n releaseId,\n }\n\n return _action(this.#client, this.#httpRequest, deleteAction, options)\n }\n\n /**\n * @public\n *\n * Fetch the documents in a release by release id.\n *\n * @category Releases\n *\n * @param params - Release action parameters:\n * - `releaseId` - The id of the release to fetch documents for.\n * @param options - Additional mutation options {@link BaseMutationOptions}.\n * @returns An observable that resolves to the documents in the release.\n */\n fetchDocuments(\n {releaseId}: {releaseId: string},\n options?: BaseMutationOptions,\n ): Observable<RawQueryResponse<SanityDocument[]>> {\n return _getReleaseDocuments(this.#client, this.#httpRequest, releaseId, options)\n }\n}\n\n/** @public */\nexport class ReleasesClient {\n #client: SanityClient\n #httpRequest: HttpRequest\n constructor(client: SanityClient, httpRequest: HttpRequest) {\n this.#client = client\n this.#httpRequest = httpRequest\n }\n\n /**\n * @public\n *\n * Retrieve a release by id.\n *\n * @category Releases\n *\n * @param params - Release action parameters:\n * - `releaseId` - The id of the release to retrieve.\n * @param options - Additional query options including abort signal and query tag.\n * @returns A promise that resolves to the release document {@link ReleaseDocument}.\n *\n * @example Retrieving a release by id\n * ```ts\n * const release = await client.releases.get({releaseId: 'my-release'})\n * console.log(release)\n * // {\n * // _id: '_.releases.my-release',\n * // name: 'my-release'\n * // _type: 'system.release',\n * // metadata: {releaseType: 'asap'},\n * // _createdAt: '2021-01-01T00:00:00.000Z',\n * // ...\n * // }\n * ```\n */\n get(\n {releaseId}: {releaseId: string},\n options?: {signal?: AbortSignal; tag?: string},\n ): Promise<ReleaseDocument | undefined> {\n return lastValueFrom(\n _getDocument<ReleaseDocument>(\n this.#client,\n this.#httpRequest,\n `_.releases.${releaseId}`,\n options,\n ),\n )\n }\n\n /**\n * @public\n *\n * Creates a new release under the given id, with metadata.\n *\n * @remarks\n * * If no releaseId is provided, a release id will be generated.\n * * If no metadata is provided, then an `undecided` releaseType will be used.\n *\n * @category Releases\n *\n * @param params - Release action parameters:\n * - `releaseId` - The id of the release to create.\n * - `metadata` - The metadata to associate with the release {@link ReleaseDocument}.\n * @param options - Additional action options.\n * @returns A promise that resolves to the `transactionId` and the release id and metadata.\n *\n * @example Creating a release with a custom id and metadata\n * ```ts\n * const releaseId = 'my-release'\n * const releaseMetadata: ReleaseDocument['metadata'] = {\n * releaseType: 'asap',\n * }\n *\n * const result =\n * await client.releases.create({releaseId, metadata: releaseMetadata})\n * console.log(result)\n * // {\n * // transactionId: 'transaction-id',\n * // releaseId: 'my-release',\n * // metadata: {releaseType: 'asap'},\n * // }\n * ```\n *\n * @example Creating a release with generated id and metadata\n * ```ts\n * const {metadata} = await client.releases.create()\n * console.log(metadata.releaseType) // 'undecided'\n * ```\n *\n * @example Creating a release with a custom transaction id\n * ```ts\n * const {transactionId, metadata} = await client.releases.create({transactionId: 'my-transaction-id'})\n * console.log(metadata.releaseType) // 'undecided'\n * console.log(transactionId) // 'my-transaction-id'\n * ```\n */\n async create(\n options: BaseActionOptions,\n ): Promise<SingleActionResult & {releaseId: string; metadata: ReleaseDocument['metadata']}>\n async create(\n release: {releaseId?: string; metadata?: Partial<ReleaseDocument['metadata']>},\n options?: BaseActionOptions,\n ): Promise<SingleActionResult & {releaseId: string; metadata: ReleaseDocument['metadata']}>\n async create(\n releaseOrOptions?:\n | {releaseId?: string; metadata?: Partial<ReleaseDocument['metadata']>}\n | BaseActionOptions,\n maybeOptions?: BaseActionOptions,\n ): Promise<SingleActionResult & {releaseId: string; metadata: ReleaseDocument['metadata']}> {\n const {action, options} = createRelease(releaseOrOptions, maybeOptions)\n const {releaseId, metadata} = action\n\n const actionResult = await lastValueFrom(\n _action(this.#client, this.#httpRequest, action, options),\n )\n\n return {...actionResult, releaseId, metadata}\n }\n\n /**\n * @public\n *\n * Edits an existing release, updating the metadata.\n *\n * @category Releases\n *\n * @param params - Release action parameters:\n * - `releaseId` - The id of the release to edit.\n * - `patch` - The patch operation to apply on the release metadata {@link PatchMutationOperation}.\n * @param options - Additional action options.\n * @returns A promise that resolves to the `transactionId`.\n */\n edit(\n {releaseId, patch}: {releaseId: string; patch: PatchOperations},\n options?: BaseActionOptions,\n ): Promise<SingleActionResult> {\n const editAction: EditReleaseAction = {\n actionType: 'sanity.action.release.edit',\n releaseId,\n patch,\n }\n\n return lastValueFrom(_action(this.#client, this.#httpRequest, editAction, options))\n }\n\n /**\n * @public\n *\n * Publishes all documents in a release at once. For larger releases the effect of the publish\n * will be visible immediately when querying but the removal of the `versions.<releasesId>.*`\n * documents and creation of the corresponding published documents with the new content may\n * take some time.\n *\n * During this period both the source and target documents are locked and cannot be\n * modified through any other means.\n *\n * @category Releases\n *\n * @param params - Release action parameters:\n * - `releaseId` - The id of the release to publish.\n * @param options - Additional action options.\n * @returns A promise that resolves to the `transactionId`.\n */\n publish(\n {releaseId}: {releaseId: string},\n options?: BaseActionOptions,\n ): Promise<SingleActionResult> {\n const publishAction: PublishReleaseAction = {\n actionType: 'sanity.action.release.publish',\n releaseId,\n }\n\n return lastValueFrom(_action(this.#client, this.#httpRequest, publishAction, options))\n }\n\n /**\n * @public\n *\n * An archive action removes an active release. The documents that comprise the release\n * are deleted and therefore no longer queryable.\n *\n * While the documents remain in retention the last version can still be accessed using document history endpoint.\n *\n * @category Releases\n *\n * @param params - Release action parameters:\n * - `releaseId` - The id of the release to archive.\n * @param options - Additional action options.\n * @returns A promise that resolves to the `transactionId`.\n */\n archive(\n {releaseId}: {releaseId: string},\n options?: BaseActionOptions,\n ): Promise<SingleActionResult> {\n const archiveAction: ArchiveReleaseAction = {\n actionType: 'sanity.action.release.archive',\n releaseId,\n }\n\n return lastValueFrom(_action(this.#client, this.#httpRequest, archiveAction, options))\n }\n\n /**\n * @public\n *\n * An unarchive action restores an archived release and all documents\n * with the content they had just prior to archiving.\n *\n * @category Releases\n *\n * @param params - Release action parameters:\n * - `releaseId` - The id of the release to unarchive.\n * @param options - Additional action options.\n * @returns A promise that resolves to the `transactionId`.\n */\n unarchive(\n {releaseId}: {releaseId: string},\n options?: BaseActionOptions,\n ): Promise<SingleActionResult> {\n const unarchiveAction: UnarchiveReleaseAction = {\n actionType: 'sanity.action.release.unarchive',\n releaseId,\n }\n\n return lastValueFrom(_action(this.#client, this.#httpRequest, unarchiveAction, options))\n }\n\n /**\n * @public\n *\n * A schedule action queues a release for publishing at the given future time.\n * The release is locked such that no documents in the release can be modified and\n * no documents that it references can be deleted as this would make the publish fail.\n * At the given time, the same logic as for the publish action is triggered.\n *\n * @category Releases\n *\n * @param params - Release action parameters:\n * - `releaseId` - The id of the release to schedule.\n * - `publishAt` - The serialised date and time to publish the release. If the `publishAt` is in the past, the release will be published immediately.\n * @param options - Additional action options.\n * @returns A promise that resolves to the `transactionId`.\n */\n schedule(\n {releaseId, publishAt}: {releaseId: string; publishAt: string},\n options?: BaseActionOptions,\n ): Promise<SingleActionResult> {\n const scheduleAction: ScheduleReleaseAction = {\n actionType: 'sanity.action.release.schedule',\n releaseId,\n publishAt,\n }\n\n return lastValueFrom(_action(this.#client, this.#httpRequest, scheduleAction, options))\n }\n\n /**\n * @public\n *\n * An unschedule action stops a release from being published.\n * The documents in the release are considered unlocked and can be edited again.\n * This may fail if another release is scheduled to be published after this one and\n * has a reference to a document created by this one.\n *\n * @category Releases\n *\n * @param params - Release action parameters:\n * - `releaseId` - The id of the release to unschedule.\n * @param options - Additional action options.\n * @returns A promise that resolves to the `transactionId`.\n */\n unschedule(\n {releaseId}: {releaseId: string},\n options?: BaseActionOptions,\n ): Promise<SingleActionResult> {\n const unscheduleAction: UnscheduleReleaseAction = {\n actionType: 'sanity.action.release.unschedule',\n releaseId,\n }\n\n return lastValueFrom(_action(this.#client, this.#httpRequest, unscheduleAction, options))\n }\n\n /**\n * @public\n *\n * A delete action removes a published or archived release.\n * The backing system document will be removed from the dataset.\n *\n * @category Releases\n *\n * @param params - Release action parameters:\n * - `releaseId` - The id of the release to delete.\n * @param options - Additional action options.\n * @returns A promise that resolves to the `transactionId`.\n */\n delete(\n {releaseId}: {releaseId: string},\n options?: BaseActionOptions,\n ): Promise<SingleActionResult> {\n const deleteAction: DeleteReleaseAction = {\n actionType: 'sanity.action.release.delete',\n releaseId,\n }\n\n return lastValueFrom(_action(this.#client, this.#httpRequest, deleteAction, options))\n }\n\n /**\n * @public\n *\n * Fetch the documents in a release by release id.\n *\n * @category Releases\n *\n * @param params - Release action parameters:\n * - `releaseId` - The id of the release to fetch documents for.\n * @param options - Additional mutation options {@link BaseMutationOptions}.\n * @returns A promise that resolves to the documents in the release.\n */\n fetchDocuments(\n {releaseId}: {releaseId: string},\n options?: BaseMutationOptions,\n ): Promise<RawQueryResponse<SanityDocument[]>> {\n return lastValueFrom(_getReleaseDocuments(this.#client, this.#httpRequest, releaseId, options))\n }\n}\n","import {lastValueFrom, type Observable} from 'rxjs'\n\nimport {_request} from '../data/dataMethods'\nimport type {ObservableSanityClient, SanityClient} from '../SanityClient'\nimport type {CurrentSanityUser, HttpRequest, SanityUser} from '../types'\n\n/** @public */\nexport class ObservableUsersClient {\n #client: ObservableSanityClient\n #httpRequest: HttpRequest\n constructor(client: ObservableSanityClient, httpRequest: HttpRequest) {\n this.#client = client\n this.#httpRequest = httpRequest\n }\n\n /**\n * Fetch a user by user ID\n *\n * @param id - User ID of the user to fetch. If `me` is provided, a minimal response including the users role is returned.\n */\n getById<T extends 'me' | string>(\n id: T,\n ): Observable<T extends 'me' ? CurrentSanityUser : SanityUser> {\n return _request<T extends 'me' ? CurrentSanityUser : SanityUser>(\n this.#client,\n this.#httpRequest,\n {uri: `/users/${id}`},\n )\n }\n}\n\n/** @public */\nexport class UsersClient {\n #client: SanityClient\n #httpRequest: HttpRequest\n constructor(client: SanityClient, httpRequest: HttpRequest) {\n this.#client = client\n this.#httpRequest = httpRequest\n }\n\n /**\n * Fetch a user by user ID\n *\n * @param id - User ID of the user to fetch. If `me` is provided, a minimal response including the users role is returned.\n */\n getById<T extends 'me' | string>(\n id: T,\n ): Promise<T extends 'me' ? CurrentSanityUser : SanityUser> {\n return lastValueFrom(\n _request<T extends 'me' ? CurrentSanityUser : SanityUser>(this.#client, this.#httpRequest, {\n uri: `/users/${id}`,\n }),\n )\n }\n}\n","import {getPublishedId, getVersionId} from '@sanity/client/csm'\nimport {firstValueFrom, lastValueFrom, Observable} from 'rxjs'\n\nimport {AgentActionsClient, ObservableAgentsActionClient} from './agent/actions/AgentActionsClient'\nimport {AssetsClient, ObservableAssetsClient} from './assets/AssetsClient'\nimport {defaultConfig, initConfig} from './config'\nimport * as dataMethods from './data/dataMethods'\nimport {_listen} from './data/listen'\nimport {LiveClient} from './data/live'\nimport {ObservablePatch, Patch} from './data/patch'\nimport {ObservableTransaction, Transaction} from './data/transaction'\nimport {DatasetsClient, ObservableDatasetsClient} from './datasets/DatasetsClient'\nimport {\n MediaLibraryVideoClient,\n ObservableMediaLibraryVideoClient,\n} from './mediaLibrary/MediaLibraryVideoClient'\nimport {ObservableProjectsClient, ProjectsClient} from './projects/ProjectsClient'\nimport {ObservableReleasesClient, ReleasesClient} from './releases/ReleasesClient'\nimport type {\n Action,\n AllDocumentIdsMutationOptions,\n AllDocumentsMutationOptions,\n Any,\n BaseActionOptions,\n BaseMutationOptions,\n ClientConfig,\n ClientReturn,\n FilteredResponseQueryOptions,\n FirstDocumentIdMutationOptions,\n FirstDocumentMutationOptions,\n HttpRequest,\n IdentifiedSanityDocumentStub,\n InitializedClientConfig,\n MultipleActionResult,\n MultipleMutationResult,\n Mutation,\n MutationSelection,\n PatchOperations,\n PatchSelection,\n QueryOptions,\n QueryParams,\n QueryWithoutParams,\n RawQuerylessQueryResponse,\n RawQueryResponse,\n RawRequestOptions,\n SanityDocument,\n SanityDocumentStub,\n SingleActionResult,\n SingleMutationResult,\n UnfilteredResponseQueryOptions,\n UnfilteredResponseWithoutQuery,\n} from './types'\nimport {ObservableUsersClient, UsersClient} from './users/UsersClient'\nimport {deriveDocumentVersionId, getDocumentVersionId} from './util/createVersionId'\n\nexport type {\n _listen,\n AssetsClient,\n DatasetsClient,\n LiveClient,\n MediaLibraryVideoClient,\n ObservableAssetsClient,\n ObservableDatasetsClient,\n ObservableMediaLibraryVideoClient,\n ObservableProjectsClient,\n ObservableUsersClient,\n ProjectsClient,\n UsersClient,\n}\n\n/** @public */\nexport class ObservableSanityClient {\n assets: ObservableAssetsClient\n datasets: ObservableDatasetsClient\n live: LiveClient\n mediaLibrary: {\n video: ObservableMediaLibraryVideoClient\n }\n projects: ObservableProjectsClient\n users: ObservableUsersClient\n agent: {\n action: ObservableAgentsActionClient\n }\n releases: ObservableReleasesClient\n\n /**\n * Private properties\n */\n #clientConfig: InitializedClientConfig\n #httpRequest: HttpRequest\n\n /**\n * Instance properties\n */\n listen = _listen\n\n constructor(httpRequest: HttpRequest, config: ClientConfig = defaultConfig) {\n this.config(config)\n\n this.#httpRequest = httpRequest\n\n this.assets = new ObservableAssetsClient(this, this.#httpRequest)\n this.datasets = new ObservableDatasetsClient(this, this.#httpRequest)\n this.live = new LiveClient(this)\n this.mediaLibrary = {\n video: new ObservableMediaLibraryVideoClient(this, this.#httpRequest),\n }\n this.projects = new ObservableProjectsClient(this, this.#httpRequest)\n this.users = new ObservableUsersClient(this, this.#httpRequest)\n this.agent = {\n action: new ObservableAgentsActionClient(this, this.#httpRequest),\n }\n this.releases = new ObservableReleasesClient(this, this.#httpRequest)\n }\n\n /**\n * Clone the client - returns a new instance\n */\n clone(): ObservableSanityClient {\n return new ObservableSanityClient(this.#httpRequest, this.config())\n }\n\n /**\n * Returns the current client configuration\n */\n config(): InitializedClientConfig\n /**\n * Reconfigure the client. Note that this _mutates_ the current client.\n */\n config(newConfig?: Partial<ClientConfig>): this\n config(newConfig?: Partial<ClientConfig>): ClientConfig | this {\n if (newConfig === undefined) {\n return {...this.#clientConfig}\n }\n\n if (this.#clientConfig && this.#clientConfig.allowReconfigure === false) {\n throw new Error(\n 'Existing client instance cannot be reconfigured - use `withConfig(newConfig)` to return a new client',\n )\n }\n\n this.#clientConfig = initConfig(newConfig, this.#clientConfig || {})\n return this\n }\n\n /**\n * Clone the client with a new (partial) configuration.\n *\n * @param newConfig - New client configuration properties, shallowly merged with existing configuration\n */\n withConfig(newConfig?: Partial<ClientConfig>): ObservableSanityClient {\n const thisConfig = this.config()\n return new ObservableSanityClient(this.#httpRequest, {\n ...thisConfig,\n ...newConfig,\n stega: {\n ...(thisConfig.stega || {}),\n ...(typeof newConfig?.stega === 'boolean'\n ? {enabled: newConfig.stega}\n : newConfig?.stega || {}),\n },\n })\n }\n\n /**\n * Perform a GROQ-query against the configured dataset.\n *\n * @param query - GROQ-query to perform\n */\n fetch<\n R = Any,\n Q extends QueryWithoutParams = QueryWithoutParams,\n const G extends string = string,\n >(query: G, params?: Q | QueryWithoutParams): Observable<ClientReturn<G, R>>\n /**\n * Perform a GROQ-query against the configured dataset.\n *\n * @param query - GROQ-query to perform\n * @param params - Optional query parameters\n * @param options - Optional request options\n */\n fetch<\n R = Any,\n Q extends QueryWithoutParams | QueryParams = QueryParams,\n const G extends string = string,\n >(\n query: G,\n params: Q extends QueryWithoutParams ? QueryWithoutParams : Q,\n options?: FilteredResponseQueryOptions,\n ): Observable<ClientReturn<G, R>>\n /**\n * Perform a GROQ-query against the configured dataset.\n *\n * @param query - GROQ-query to perform\n * @param params - Optional query parameters\n * @param options - Request options\n */\n fetch<\n R = Any,\n Q extends QueryWithoutParams | QueryParams = QueryParams,\n const G extends string = string,\n >(\n query: string,\n params: Q extends QueryWithoutParams ? QueryWithoutParams : Q,\n options: UnfilteredResponseQueryOptions,\n ): Observable<RawQueryResponse<ClientReturn<G, R>>>\n /**\n * Perform a GROQ-query against the configured dataset.\n *\n * @param query - GROQ-query to perform\n * @param params - Optional query parameters\n * @param options - Request options\n */\n fetch<\n R = Any,\n Q extends QueryWithoutParams | QueryParams = QueryParams,\n const G extends string = string,\n >(\n query: G,\n params: Q extends QueryWithoutParams ? QueryWithoutParams : Q,\n options: UnfilteredResponseWithoutQuery,\n ): Observable<RawQuerylessQueryResponse<ClientReturn<G, R>>>\n fetch<R, Q, const G extends string>(\n query: G,\n params?: Q,\n options?: QueryOptions,\n ): Observable<RawQueryResponse<R> | R> {\n return dataMethods._fetch<R, Q>(\n this,\n this.#httpRequest,\n this.#clientConfig.stega,\n query,\n params,\n options,\n )\n }\n\n /**\n * Fetch a single document with the given ID.\n *\n * @param id - Document ID to fetch\n * @param options - Request options\n */\n getDocument<R extends Record<string, Any> = Record<string, Any>>(\n id: string,\n options: {\n signal?: AbortSignal\n tag?: string\n releaseId?: string\n includeAllVersions: true\n },\n ): Observable<SanityDocument<R>[]>\n /**\n * Fetch a single document with the given ID.\n *\n * @param id - Document ID to fetch\n * @param options - Request options\n */\n getDocument<R extends Record<string, Any> = Record<string, Any>>(\n id: string,\n options?: {\n signal?: AbortSignal\n tag?: string\n releaseId?: string\n includeAllVersions?: false\n },\n ): Observable<SanityDocument<R> | undefined>\n getDocument<R extends Record<string, Any> = Record<string, Any>>(\n id: string,\n options?: {\n signal?: AbortSignal\n tag?: string\n releaseId?: string\n includeAllVersions?: boolean\n },\n ): Observable<SanityDocument<R> | undefined | SanityDocument<R>[]> {\n // Implementation needs to handle union type safely\n if (options?.includeAllVersions === true) {\n return dataMethods._getDocument<R>(this, this.#httpRequest, id, {\n ...options,\n includeAllVersions: true,\n })\n }\n // When includeAllVersions is not true, pass options but only include includeAllVersions if it was explicitly set\n const opts = {\n signal: options?.signal,\n tag: options?.tag,\n releaseId: options?.releaseId,\n ...(options && 'includeAllVersions' in options ? {includeAllVersions: false as const} : {}),\n }\n return dataMethods._getDocument<R>(this, this.#httpRequest, id, opts)\n }\n\n /**\n * Fetch multiple documents in one request.\n * Should be used sparingly - performing a query is usually a better option.\n * The order/position of documents is preserved based on the original array of IDs.\n * If any of the documents are missing, they will be replaced by a `null` entry in the returned array\n *\n * @param ids - Document IDs to fetch\n * @param options - Request options\n */\n getDocuments<R extends Record<string, Any> = Record<string, Any>>(\n ids: string[],\n options?: {tag?: string},\n ): Observable<(SanityDocument<R> | null)[]> {\n return dataMethods._getDocuments<R>(this, this.#httpRequest, ids, options)\n }\n\n /**\n * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.\n * Returns an observable that resolves to the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n create<R extends Record<string, Any> = Record<string, Any>>(\n document: SanityDocumentStub<R>,\n options: FirstDocumentMutationOptions,\n ): Observable<SanityDocument<R>>\n /**\n * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.\n * Returns an observable that resolves to an array containing the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n create<R extends Record<string, Any> = Record<string, Any>>(\n document: SanityDocumentStub<R>,\n options: AllDocumentsMutationOptions,\n ): Observable<SanityDocument<R>[]>\n /**\n * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.\n * Returns an observable that resolves to a mutation result object containing the ID of the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n create<R extends Record<string, Any> = Record<string, Any>>(\n document: SanityDocumentStub<R>,\n options: FirstDocumentIdMutationOptions,\n ): Observable<SingleMutationResult>\n /**\n * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.\n * Returns an observable that resolves to a mutation result object containing the ID of the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n create<R extends Record<string, Any> = Record<string, Any>>(\n document: SanityDocumentStub<R>,\n options: AllDocumentIdsMutationOptions,\n ): Observable<MultipleMutationResult>\n /**\n * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.\n * Returns an observable that resolves to the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n create<R extends Record<string, Any> = Record<string, Any>>(\n document: SanityDocumentStub<R>,\n options?: BaseMutationOptions,\n ): Observable<SanityDocument<R>>\n create<R extends Record<string, Any> = Record<string, Any>>(\n document: SanityDocumentStub<R>,\n options?:\n | AllDocumentIdsMutationOptions\n | AllDocumentsMutationOptions\n | BaseMutationOptions\n | FirstDocumentIdMutationOptions\n | FirstDocumentMutationOptions,\n ): Observable<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n return dataMethods._create<R>(this, this.#httpRequest, document, 'create', options)\n }\n\n /**\n * Create a document if no document with the same ID already exists.\n * Returns an observable that resolves to the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: FirstDocumentMutationOptions,\n ): Observable<SanityDocument<R>>\n /**\n * Create a document if no document with the same ID already exists.\n * Returns an observable that resolves to an array containing the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: AllDocumentsMutationOptions,\n ): Observable<SanityDocument<R>[]>\n /**\n * Create a document if no document with the same ID already exists.\n * Returns an observable that resolves to a mutation result object containing the ID of the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: FirstDocumentIdMutationOptions,\n ): Observable<SingleMutationResult>\n /**\n * Create a document if no document with the same ID already exists.\n * Returns an observable that resolves to a mutation result object containing the ID of the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: AllDocumentIdsMutationOptions,\n ): Observable<MultipleMutationResult>\n /**\n * Create a document if no document with the same ID already exists.\n * Returns an observable that resolves to the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options?: BaseMutationOptions,\n ): Observable<SanityDocument<R>>\n createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options?:\n | AllDocumentIdsMutationOptions\n | AllDocumentsMutationOptions\n | BaseMutationOptions\n | FirstDocumentIdMutationOptions\n | FirstDocumentMutationOptions,\n ): Observable<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n return dataMethods._createIfNotExists<R>(this, this.#httpRequest, document, options)\n }\n\n /**\n * Create a document if it does not exist, or replace a document with the same document ID\n * Returns an observable that resolves to the created document.\n *\n * @param document - Document to either create or replace\n * @param options - Mutation options\n */\n createOrReplace<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: FirstDocumentMutationOptions,\n ): Observable<SanityDocument<R>>\n /**\n * Create a document if it does not exist, or replace a document with the same document ID\n * Returns an observable that resolves to an array containing the created document.\n *\n * @param document - Document to either create or replace\n * @param options - Mutation options\n */\n createOrReplace<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: AllDocumentsMutationOptions,\n ): Observable<SanityDocument<R>[]>\n /**\n * Create a document if it does not exist, or replace a document with the same document ID\n * Returns an observable that resolves to a mutation result object containing the ID of the created document.\n *\n * @param document - Document to either create or replace\n * @param options - Mutation options\n */\n createOrReplace<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: FirstDocumentIdMutationOptions,\n ): Observable<SingleMutationResult>\n /**\n * Create a document if it does not exist, or replace a document with the same document ID\n * Returns an observable that resolves to a mutation result object containing the created document ID.\n *\n * @param document - Document to either create or replace\n * @param options - Mutation options\n */\n createOrReplace<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: AllDocumentIdsMutationOptions,\n ): Observable<MultipleMutationResult>\n /**\n * Create a document if it does not exist, or replace a document with the same document ID\n * Returns an observable that resolves to the created document.\n *\n * @param document - Document to either create or replace\n * @param options - Mutation options\n */\n createOrReplace<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options?: BaseMutationOptions,\n ): Observable<SanityDocument<R>>\n createOrReplace<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options?:\n | AllDocumentIdsMutationOptions\n | AllDocumentsMutationOptions\n | BaseMutationOptions\n | FirstDocumentIdMutationOptions\n | FirstDocumentMutationOptions,\n ): Observable<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n return dataMethods._createOrReplace<R>(this, this.#httpRequest, document, options)\n }\n\n /**\n * @public\n *\n * Creates a new version of a published document.\n *\n * @remarks\n * * Requires a document with a `_type` property.\n * * Creating a version with no `releaseId` will create a new draft version of the published document.\n * * 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`.\n * * If the `document._id` is not defined, it will be generated from `publishedId` and `releaseId`.\n * * To create a version of an unpublished document, use the `client.create` method.\n *\n * @category Versions\n *\n * @param params - Version action parameters:\n * - `document` - The document to create as a new version (must include `_type`).\n * - `publishedId` - The ID of the published document being versioned.\n * - `releaseId` - The ID of the release to create the version for.\n * @param options - Additional action options.\n * @returns an observable that resolves to the `transactionId`.\n *\n * @example Creating a new version of a published document with a generated version ID\n * ```ts\n * client.observable.createVersion({\n * // The document does not need to include an `_id` property since it will be generated from `publishedId` and `releaseId`\n * document: {_type: 'myDocument', title: 'My Document'},\n * publishedId: 'myDocument',\n * releaseId: 'myRelease',\n * })\n *\n * // The following document will be created:\n * // {\n * // _id: 'versions.myRelease.myDocument',\n * // _type: 'myDocument',\n * // title: 'My Document',\n * // }\n * ```\n *\n * @example Creating a new version of a published document with a specified version ID\n * ```ts\n * client.observable.createVersion({\n * document: {_type: 'myDocument', _id: 'versions.myRelease.myDocument', title: 'My Document'},\n * // `publishedId` and `releaseId` are not required since `document._id` has been specified\n * })\n *\n * // The following document will be created:\n * // {\n * // _id: 'versions.myRelease.myDocument',\n * // _type: 'myDocument',\n * // title: 'My Document',\n * // }\n * ```\n *\n * @example Creating a new draft version of a published document\n * ```ts\n * client.observable.createVersion({\n * document: {_type: 'myDocument', title: 'My Document'},\n * publishedId: 'myDocument',\n * })\n *\n * // The following document will be created:\n * // {\n * // _id: 'drafts.myDocument',\n * // _type: 'myDocument',\n * // title: 'My Document',\n * // }\n * ```\n */\n createVersion<R extends Record<string, Any>>(\n args: {\n document: SanityDocumentStub<R>\n publishedId: string\n releaseId?: string\n },\n options?: BaseActionOptions,\n ): Observable<SingleActionResult | MultipleActionResult>\n createVersion<R extends Record<string, Any>>(\n args: {\n document: IdentifiedSanityDocumentStub<R>\n publishedId?: string\n releaseId?: string\n },\n options?: BaseActionOptions,\n ): Observable<SingleActionResult | MultipleActionResult>\n createVersion(\n args: {\n baseId: string\n releaseId?: string\n publishedId: string\n ifBaseRevisionId?: string\n },\n options?: BaseActionOptions,\n ): Observable<SingleActionResult | MultipleActionResult>\n createVersion<R extends Record<string, Any>>(\n {\n document,\n publishedId,\n releaseId,\n baseId,\n ifBaseRevisionId,\n }: {\n document?: SanityDocumentStub<R> | IdentifiedSanityDocumentStub<R>\n publishedId?: string\n releaseId?: string\n baseId?: string\n ifBaseRevisionId?: string\n },\n options?: BaseActionOptions,\n ): Observable<SingleActionResult | MultipleActionResult> {\n if (!document) {\n return dataMethods._createVersionFromBase(\n this,\n this.#httpRequest,\n publishedId,\n baseId,\n releaseId,\n ifBaseRevisionId,\n options,\n )\n }\n\n const documentVersionId = deriveDocumentVersionId('createVersion', {\n document,\n publishedId,\n releaseId,\n })\n\n const documentVersion = {...document, _id: documentVersionId}\n const versionPublishedId = publishedId || getPublishedId(document._id)\n\n return dataMethods._createVersion<R>(\n this,\n this.#httpRequest,\n documentVersion,\n versionPublishedId,\n options,\n )\n }\n\n /**\n * Deletes a document with the given document ID.\n * Returns an observable that resolves to the deleted document.\n *\n * @param id - Document ID to delete\n * @param options - Options for the mutation\n */\n delete<R extends Record<string, Any> = Record<string, Any>>(\n id: string,\n options: FirstDocumentMutationOptions,\n ): Observable<SanityDocument<R>>\n /**\n * Deletes a document with the given document ID.\n * Returns an observable that resolves to an array containing the deleted document.\n *\n * @param id - Document ID to delete\n * @param options - Options for the mutation\n */\n delete<R extends Record<string, Any> = Record<string, Any>>(\n id: string,\n options: AllDocumentsMutationOptions,\n ): Observable<SanityDocument<R>[]>\n /**\n * Deletes a document with the given document ID.\n * Returns an observable that resolves to a mutation result object containing the deleted document ID.\n *\n * @param id - Document ID to delete\n * @param options - Options for the mutation\n */\n delete(id: string, options: FirstDocumentIdMutationOptions): Observable<SingleMutationResult>\n /**\n * Deletes a document with the given document ID.\n * Returns an observable that resolves to a mutation result object containing the deleted document ID.\n *\n * @param id - Document ID to delete\n * @param options - Options for the mutation\n */\n delete(id: string, options: AllDocumentIdsMutationOptions): Observable<MultipleMutationResult>\n /**\n * Deletes a document with the given document ID.\n * Returns an observable that resolves to the deleted document.\n *\n * @param id - Document ID to delete\n * @param options - Options for the mutation\n */\n delete<R extends Record<string, Any> = Record<string, Any>>(\n id: string,\n options?: BaseMutationOptions,\n ): Observable<SanityDocument<R>>\n /**\n * Deletes one or more documents matching the given query or document ID.\n * Returns an observable that resolves to first deleted document.\n *\n * @param selection - An object with either an `id` or `query` key defining what to delete\n * @param options - Options for the mutation\n */\n delete<R extends Record<string, Any> = Record<string, Any>>(\n selection: MutationSelection,\n options: FirstDocumentMutationOptions,\n ): Observable<SanityDocument<R>>\n /**\n * Deletes one or more documents matching the given query or document ID.\n * Returns an observable that resolves to an array containing the deleted documents.\n *\n * @param selection - An object with either an `id` or `query` key defining what to delete\n * @param options - Options for the mutation\n */\n delete<R extends Record<string, Any> = Record<string, Any>>(\n selection: MutationSelection,\n options: AllDocumentsMutationOptions,\n ): Observable<SanityDocument<R>[]>\n /**\n * Deletes one or more documents matching the given query or document ID.\n * Returns an observable that resolves to a mutation result object containing the ID of the first deleted document.\n *\n * @param selection - An object with either an `id` or `query` key defining what to delete\n * @param options - Options for the mutation\n */\n delete(\n selection: MutationSelection,\n options: FirstDocumentIdMutationOptions,\n ): Observable<SingleMutationResult>\n /**\n * Deletes one or more documents matching the given query or document ID.\n * Returns an observable that resolves to a mutation result object containing the document IDs that were deleted.\n *\n * @param selection - An object with either an `id` or `query` key defining what to delete\n * @param options - Options for the mutation\n */\n delete(\n selection: MutationSelection,\n options: AllDocumentIdsMutationOptions,\n ): Observable<MultipleMutationResult>\n /**\n * Deletes one or more documents matching the given query or document ID.\n * Returns an observable that resolves to first deleted document.\n *\n * @param selection - An object with either an `id` or `query` key defining what to delete\n * @param options - Options for the mutation\n */\n delete<R extends Record<string, Any> = Record<string, Any>>(\n selection: MutationSelection,\n options?: BaseMutationOptions,\n ): Observable<SanityDocument<R>>\n delete<R extends Record<string, Any> = Record<string, Any>>(\n selection: string | MutationSelection,\n options?:\n | AllDocumentIdsMutationOptions\n | AllDocumentsMutationOptions\n | BaseMutationOptions\n | FirstDocumentIdMutationOptions\n | FirstDocumentMutationOptions,\n ): Observable<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n return dataMethods._delete<R>(this, this.#httpRequest, selection, options)\n }\n\n /**\n * @public\n *\n * Deletes the draft or release version of a document.\n *\n * @remarks\n * * Discarding a version with no `releaseId` will discard the draft version of the published document.\n * * If the draft or release version does not exist, any error will throw.\n *\n * @param params - Version action parameters:\n * - `releaseId` - The ID of the release to discard the document from.\n * - `publishedId` - The published ID of the document to discard.\n * @param purge - if `true` the document history is also discarded.\n * @param options - Additional action options.\n * @returns an observable that resolves to the `transactionId`.\n *\n * @example Discarding a release version of a document\n * ```ts\n * client.observable.discardVersion({publishedId: 'myDocument', releaseId: 'myRelease'})\n * // The document with the ID `versions.myRelease.myDocument` will be discarded.\n * ```\n *\n * @example Discarding a draft version of a document\n * ```ts\n * client.observable.discardVersion({publishedId: 'myDocument'})\n * // The document with the ID `drafts.myDocument` will be discarded.\n * ```\n */\n discardVersion(\n {releaseId, publishedId}: {releaseId?: string; publishedId: string},\n purge?: boolean,\n options?: BaseActionOptions,\n ): Observable<SingleActionResult | MultipleActionResult> {\n const documentVersionId = getDocumentVersionId(publishedId, releaseId)\n\n return dataMethods._discardVersion(this, this.#httpRequest, documentVersionId, purge, options)\n }\n\n /**\n * @public\n *\n * Replaces an existing version document.\n *\n * @remarks\n * * Requires a document with a `_type` property.\n * * 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`.\n * * If the `document._id` is not defined, it will be generated from `publishedId` and `releaseId`.\n * * Replacing a version with no `releaseId` will replace the draft version of the published document.\n * * At least one of the **version** or **published** documents must exist.\n *\n * @param params - Version action parameters:\n * - `document` - The new document to replace the version with.\n * - `releaseId` - The ID of the release where the document version is replaced.\n * - `publishedId` - The ID of the published document to replace.\n * @param options - Additional action options.\n * @returns an observable that resolves to the `transactionId`.\n *\n * @example Replacing a release version of a published document with a generated version ID\n * ```ts\n * client.observable.replaceVersion({\n * document: {_type: 'myDocument', title: 'My Document'},\n * publishedId: 'myDocument',\n * releaseId: 'myRelease',\n * })\n *\n * // The following document will be patched:\n * // {\n * // _id: 'versions.myRelease.myDocument',\n * // _type: 'myDocument',\n * // title: 'My Document',\n * // }\n * ```\n *\n * @example Replacing a release version of a published document with a specified version ID\n * ```ts\n * client.observable.replaceVersion({\n * document: {_type: 'myDocument', _id: 'versions.myRelease.myDocument', title: 'My Document'},\n * // `publishedId` and `releaseId` are not required since `document._id` has been specified\n * })\n *\n * // The following document will be patched:\n * // {\n * // _id: 'versions.myRelease.myDocument',\n * // _type: 'myDocument',\n * // title: 'My Document',\n * // }\n * ```\n *\n * @example Replacing a draft version of a published document\n * ```ts\n * client.observable.replaceVersion({\n * document: {_type: 'myDocument', title: 'My Document'},\n * publishedId: 'myDocument',\n * })\n *\n * // The following document will be patched:\n * // {\n * // _id: 'drafts.myDocument',\n * // _type: 'myDocument',\n * // title: 'My Document',\n * // }\n * ```\n */\n replaceVersion<R extends Record<string, Any>>(\n args: {\n document: SanityDocumentStub<R>\n publishedId: string\n releaseId?: string\n },\n options?: BaseActionOptions,\n ): Observable<SingleActionResult | MultipleActionResult>\n replaceVersion<R extends Record<string, Any>>(\n args: {\n document: IdentifiedSanityDocumentStub<R>\n publishedId?: string\n releaseId?: string\n },\n options?: BaseActionOptions,\n ): Observable<SingleActionResult | MultipleActionResult>\n replaceVersion<R extends Record<string, Any>>(\n {\n document,\n publishedId,\n releaseId,\n }: {\n document: SanityDocumentStub<R> | IdentifiedSanityDocumentStub<R>\n publishedId?: string\n releaseId?: string\n },\n options?: BaseActionOptions,\n ): Observable<SingleActionResult | MultipleActionResult> {\n const documentVersionId = deriveDocumentVersionId('replaceVersion', {\n document,\n publishedId,\n releaseId,\n })\n\n const documentVersion = {...document, _id: documentVersionId}\n\n return dataMethods._replaceVersion<R>(this, this.#httpRequest, documentVersion, options)\n }\n\n /**\n * @public\n *\n * Used to indicate when a document within a release should be unpublished when\n * the release is run.\n *\n * @remarks\n * * If the published document does not exist, an error will be thrown.\n *\n * @param params - Version action parameters:\n * - `releaseId` - The ID of the release to unpublish the document from.\n * - `publishedId` - The published ID of the document to unpublish.\n * @param options - Additional action options.\n * @returns an observable that resolves to the `transactionId`.\n *\n * @example Unpublishing a release version of a published document\n * ```ts\n * client.observable.unpublishVersion({publishedId: 'myDocument', releaseId: 'myRelease'})\n * // The document with the ID `versions.myRelease.myDocument` will be unpublished. when `myRelease` is run.\n * ```\n */\n unpublishVersion(\n {releaseId, publishedId}: {releaseId: string; publishedId: string},\n options?: BaseActionOptions,\n ): Observable<SingleActionResult | MultipleActionResult> {\n const versionId = getVersionId(publishedId, releaseId)\n\n return dataMethods._unpublishVersion(this, this.#httpRequest, versionId, publishedId, options)\n }\n\n /**\n * Perform mutation operations against the configured dataset\n * Returns an observable that resolves to the first mutated document.\n *\n * @param operations - Mutation operations to execute\n * @param options - Mutation options\n */\n mutate<R extends Record<string, Any> = Record<string, Any>>(\n operations: Mutation<R>[] | ObservablePatch | ObservableTransaction,\n options: FirstDocumentMutationOptions,\n ): Observable<SanityDocument<R>>\n /**\n * Perform mutation operations against the configured dataset.\n * Returns an observable that resolves to an array of the mutated documents.\n *\n * @param operations - Mutation operations to execute\n * @param options - Mutation options\n */\n mutate<R extends Record<string, Any> = Record<string, Any>>(\n operations: Mutation<R>[] | ObservablePatch | ObservableTransaction,\n options: AllDocumentsMutationOptions,\n ): Observable<SanityDocument<R>[]>\n /**\n * Perform mutation operations against the configured dataset\n * Returns an observable that resolves to a mutation result object containing the document ID of the first mutated document.\n *\n * @param operations - Mutation operations to execute\n * @param options - Mutation options\n */\n mutate<R extends Record<string, Any> = Record<string, Any>>(\n operations: Mutation<R>[] | ObservablePatch | ObservableTransaction,\n options: FirstDocumentIdMutationOptions,\n ): Observable<SingleMutationResult>\n /**\n * Perform mutation operations against the configured dataset\n * Returns an observable that resolves to a mutation result object containing the mutated document IDs.\n *\n * @param operations - Mutation operations to execute\n * @param options - Mutation options\n */\n mutate<R extends Record<string, Any> = Record<string, Any>>(\n operations: Mutation<R>[] | ObservablePatch | ObservableTransaction,\n options: AllDocumentIdsMutationOptions,\n ): Observable<MultipleMutationResult>\n /**\n * Perform mutation operations against the configured dataset\n * Returns an observable that resolves to the first mutated document.\n *\n * @param operations - Mutation operations to execute\n * @param options - Mutation options\n */\n mutate<R extends Record<string, Any> = Record<string, Any>>(\n operations: Mutation<R>[] | ObservablePatch | ObservableTransaction,\n options?: BaseMutationOptions,\n ): Observable<SanityDocument<R>>\n mutate<R extends Record<string, Any> = Record<string, Any>>(\n operations: Mutation<R>[] | ObservablePatch | ObservableTransaction,\n options?:\n | FirstDocumentMutationOptions\n | AllDocumentsMutationOptions\n | FirstDocumentIdMutationOptions\n | AllDocumentIdsMutationOptions\n | BaseMutationOptions,\n ): Observable<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n return dataMethods._mutate<R>(this, this.#httpRequest, operations, options)\n }\n\n /**\n * Create a new buildable patch of operations to perform\n *\n * @param documentId - Document ID to patch\n * @param operations - Optional object of patch operations to initialize the patch instance with\n * @returns Patch instance - call `.commit()` to perform the operations defined\n */\n patch(documentId: string, operations?: PatchOperations): ObservablePatch\n\n /**\n * Create a new buildable patch of operations to perform\n *\n * @param documentIds - Array of document IDs to patch\n * @param operations - Optional object of patch operations to initialize the patch instance with\n * @returns Patch instance - call `.commit()` to perform the operations defined\n */\n patch(documentIds: string[], operations?: PatchOperations): ObservablePatch\n\n /**\n * Create a new buildable patch of operations to perform\n *\n * @param selection - An object with `query` and optional `params`, defining which document(s) to patch\n * @param operations - Optional object of patch operations to initialize the patch instance with\n * @returns Patch instance - call `.commit()` to perform the operations defined\n */\n patch(selection: MutationSelection, operations?: PatchOperations): ObservablePatch\n\n /**\n * Create a new buildable patch of operations to perform\n *\n * @param selection - Document ID, an array of document IDs, or an object with `query` and optional `params`, defining which document(s) to patch\n * @param operations - Optional object of patch operations to initialize the patch instance with\n * @returns Patch instance - call `.commit()` to perform the operations defined\n */\n patch(selection: PatchSelection, operations?: PatchOperations): ObservablePatch {\n return new ObservablePatch(selection, operations, this)\n }\n\n /**\n * Create a new transaction of mutations\n *\n * @param operations - Optional array of mutation operations to initialize the transaction instance with\n */\n transaction<R extends Record<string, Any> = Record<string, Any>>(\n operations?: Mutation<R>[],\n ): ObservableTransaction {\n return new ObservableTransaction(operations, this)\n }\n\n /**\n * Perform action operations against the configured dataset\n *\n * @param operations - Action operation(s) to execute\n * @param options - Action options\n */\n action(\n operations: Action | Action[],\n options?: BaseActionOptions,\n ): Observable<SingleActionResult | MultipleActionResult> {\n return dataMethods._action(this, this.#httpRequest, operations, options)\n }\n\n /**\n * Perform an HTTP request against the Sanity API\n *\n * @param options - Request options\n */\n request<R = Any>(options: RawRequestOptions): Observable<R> {\n return dataMethods._request(this, this.#httpRequest, options)\n }\n\n /**\n * Get a Sanity API URL for the URI provided\n *\n * @param uri - URI/path to build URL for\n * @param canUseCdn - Whether or not to allow using the API CDN for this route\n */\n getUrl(uri: string, canUseCdn?: boolean): string {\n return dataMethods._getUrl(this, uri, canUseCdn)\n }\n\n /**\n * Get a Sanity API URL for the data operation and path provided\n *\n * @param operation - Data operation (eg `query`, `mutate`, `listen` or similar)\n * @param path - Path to append after the operation\n */\n getDataUrl(operation: string, path?: string): string {\n return dataMethods._getDataUrl(this, operation, path)\n }\n}\n\n/** @public */\nexport class SanityClient {\n assets: AssetsClient\n datasets: DatasetsClient\n live: LiveClient\n mediaLibrary: {\n video: MediaLibraryVideoClient\n }\n projects: ProjectsClient\n users: UsersClient\n agent: {\n action: AgentActionsClient\n }\n releases: ReleasesClient\n\n /**\n * Observable version of the Sanity client, with the same configuration as the promise-based one\n */\n observable: ObservableSanityClient\n\n /**\n * Private properties\n */\n #clientConfig: InitializedClientConfig\n #httpRequest: HttpRequest\n\n /**\n * Instance properties\n */\n listen = _listen\n\n constructor(httpRequest: HttpRequest, config: ClientConfig = defaultConfig) {\n this.config(config)\n\n this.#httpRequest = httpRequest\n\n this.assets = new AssetsClient(this, this.#httpRequest)\n this.datasets = new DatasetsClient(this, this.#httpRequest)\n this.live = new LiveClient(this)\n this.mediaLibrary = {\n video: new MediaLibraryVideoClient(this, this.#httpRequest),\n }\n this.projects = new ProjectsClient(this, this.#httpRequest)\n this.users = new UsersClient(this, this.#httpRequest)\n this.agent = {\n action: new AgentActionsClient(this, this.#httpRequest),\n }\n this.releases = new ReleasesClient(this, this.#httpRequest)\n\n this.observable = new ObservableSanityClient(httpRequest, config)\n }\n\n /**\n * Clone the client - returns a new instance\n */\n clone(): SanityClient {\n return new SanityClient(this.#httpRequest, this.config())\n }\n\n /**\n * Returns the current client configuration\n */\n config(): InitializedClientConfig\n /**\n * Reconfigure the client. Note that this _mutates_ the current client.\n */\n config(newConfig?: Partial<ClientConfig>): this\n config(newConfig?: Partial<ClientConfig>): ClientConfig | this {\n if (newConfig === undefined) {\n return {...this.#clientConfig}\n }\n\n if (this.#clientConfig && this.#clientConfig.allowReconfigure === false) {\n throw new Error(\n 'Existing client instance cannot be reconfigured - use `withConfig(newConfig)` to return a new client',\n )\n }\n\n if (this.observable) {\n this.observable.config(newConfig)\n }\n\n this.#clientConfig = initConfig(newConfig, this.#clientConfig || {})\n return this\n }\n\n /**\n * Clone the client with a new (partial) configuration.\n *\n * @param newConfig - New client configuration properties, shallowly merged with existing configuration\n */\n withConfig(newConfig?: Partial<ClientConfig>): SanityClient {\n const thisConfig = this.config()\n return new SanityClient(this.#httpRequest, {\n ...thisConfig,\n ...newConfig,\n stega: {\n ...(thisConfig.stega || {}),\n ...(typeof newConfig?.stega === 'boolean'\n ? {enabled: newConfig.stega}\n : newConfig?.stega || {}),\n },\n })\n }\n\n /**\n * Perform a GROQ-query against the configured dataset.\n *\n * @param query - GROQ-query to perform\n */\n fetch<\n R = Any,\n Q extends QueryWithoutParams = QueryWithoutParams,\n const G extends string = string,\n >(query: G, params?: Q | QueryWithoutParams): Promise<ClientReturn<G, R>>\n /**\n * Perform a GROQ-query against the configured dataset.\n *\n * @param query - GROQ-query to perform\n * @param params - Optional query parameters\n * @param options - Optional request options\n */\n fetch<\n R = Any,\n Q extends QueryWithoutParams | QueryParams = QueryParams,\n const G extends string = string,\n >(\n query: G,\n params: Q extends QueryWithoutParams ? QueryWithoutParams : Q,\n options?: FilteredResponseQueryOptions,\n ): Promise<ClientReturn<G, R>>\n /**\n * Perform a GROQ-query against the configured dataset.\n *\n * @param query - GROQ-query to perform\n * @param params - Optional query parameters\n * @param options - Request options\n */\n fetch<\n R = Any,\n Q extends QueryWithoutParams | QueryParams = QueryParams,\n const G extends string = string,\n >(\n query: G,\n params: Q extends QueryWithoutParams ? QueryWithoutParams : Q,\n options: UnfilteredResponseQueryOptions,\n ): Promise<RawQueryResponse<ClientReturn<G, R>>>\n /**\n * Perform a GROQ-query against the configured dataset.\n *\n * @param query - GROQ-query to perform\n * @param params - Optional query parameters\n * @param options - Request options\n */\n fetch<\n R = Any,\n Q extends QueryWithoutParams | QueryParams = QueryParams,\n const G extends string = string,\n >(\n query: G,\n params: Q extends QueryWithoutParams ? QueryWithoutParams : Q,\n options: UnfilteredResponseWithoutQuery,\n ): Promise<RawQuerylessQueryResponse<ClientReturn<G, R>>>\n fetch<R, Q, const G extends string>(\n query: G,\n params?: Q,\n options?: QueryOptions,\n ): Promise<RawQueryResponse<ClientReturn<G, R>> | ClientReturn<G, R>> {\n return lastValueFrom(\n dataMethods._fetch<ClientReturn<G, R>, Q>(\n this,\n this.#httpRequest,\n this.#clientConfig.stega,\n query,\n params,\n options,\n ),\n )\n }\n\n /**\n * Fetch a single document with the given ID.\n *\n * @param id - Document ID to fetch\n * @param options - Request options\n */\n getDocument<R extends Record<string, Any> = Record<string, Any>>(\n id: string,\n options: {\n signal?: AbortSignal\n tag?: string\n releaseId?: string\n includeAllVersions: true\n },\n ): Promise<SanityDocument<R>[]>\n /**\n * Fetch a single document with the given ID.\n *\n * @param id - Document ID to fetch\n * @param options - Request options\n */\n getDocument<R extends Record<string, Any> = Record<string, Any>>(\n id: string,\n options?: {\n signal?: AbortSignal\n tag?: string\n releaseId?: string\n includeAllVersions?: false\n },\n ): Promise<SanityDocument<R> | undefined>\n getDocument<R extends Record<string, Any> = Record<string, Any>>(\n id: string,\n options?: {\n signal?: AbortSignal\n tag?: string\n releaseId?: string\n includeAllVersions?: boolean\n },\n ): Promise<SanityDocument<R> | undefined | SanityDocument<R>[]> {\n // Implementation needs to handle union type safely\n if (options?.includeAllVersions === true) {\n return lastValueFrom(\n dataMethods._getDocument<R>(this, this.#httpRequest, id, {\n ...options,\n includeAllVersions: true,\n }),\n )\n }\n // When includeAllVersions is not true, pass options but only include includeAllVersions if it was explicitly set\n const opts = {\n signal: options?.signal,\n tag: options?.tag,\n releaseId: options?.releaseId,\n ...(options && 'includeAllVersions' in options ? {includeAllVersions: false as const} : {}),\n }\n return lastValueFrom(dataMethods._getDocument<R>(this, this.#httpRequest, id, opts))\n }\n\n /**\n * Fetch multiple documents in one request.\n * Should be used sparingly - performing a query is usually a better option.\n * The order/position of documents is preserved based on the original array of IDs.\n * If any of the documents are missing, they will be replaced by a `null` entry in the returned array\n *\n * @param ids - Document IDs to fetch\n * @param options - Request options\n */\n getDocuments<R extends Record<string, Any> = Record<string, Any>>(\n ids: string[],\n options?: {signal?: AbortSignal; tag?: string},\n ): Promise<(SanityDocument<R> | null)[]> {\n return lastValueFrom(dataMethods._getDocuments<R>(this, this.#httpRequest, ids, options))\n }\n\n /**\n * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.\n * Returns a promise that resolves to the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n create<R extends Record<string, Any> = Record<string, Any>>(\n document: SanityDocumentStub<R>,\n options: FirstDocumentMutationOptions,\n ): Promise<SanityDocument<R>>\n /**\n * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.\n * Returns a promise that resolves to an array containing the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n create<R extends Record<string, Any> = Record<string, Any>>(\n document: SanityDocumentStub<R>,\n options: AllDocumentsMutationOptions,\n ): Promise<SanityDocument<R>[]>\n /**\n * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.\n * Returns a promise that resolves to a mutation result object containing the ID of the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n create<R extends Record<string, Any> = Record<string, Any>>(\n document: SanityDocumentStub<R>,\n options: FirstDocumentIdMutationOptions,\n ): Promise<SingleMutationResult>\n /**\n * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.\n * Returns a promise that resolves to a mutation result object containing the ID of the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n create<R extends Record<string, Any> = Record<string, Any>>(\n document: SanityDocumentStub<R>,\n options: AllDocumentIdsMutationOptions,\n ): Promise<MultipleMutationResult>\n /**\n * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.\n * Returns a promise that resolves to the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n create<R extends Record<string, Any> = Record<string, Any>>(\n document: SanityDocumentStub<R>,\n options?: BaseMutationOptions,\n ): Promise<SanityDocument<R>>\n create<R extends Record<string, Any> = Record<string, Any>>(\n document: SanityDocumentStub<R>,\n options?:\n | AllDocumentIdsMutationOptions\n | AllDocumentsMutationOptions\n | BaseMutationOptions\n | FirstDocumentIdMutationOptions\n | FirstDocumentMutationOptions,\n ): Promise<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n return lastValueFrom(\n dataMethods._create<R>(this, this.#httpRequest, document, 'create', options),\n )\n }\n\n /**\n * Create a document if no document with the same ID already exists.\n * Returns a promise that resolves to the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: FirstDocumentMutationOptions,\n ): Promise<SanityDocument<R>>\n /**\n * Create a document if no document with the same ID already exists.\n * Returns a promise that resolves to an array containing the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: AllDocumentsMutationOptions,\n ): Promise<SanityDocument<R>[]>\n /**\n * Create a document if no document with the same ID already exists.\n * Returns a promise that resolves to a mutation result object containing the ID of the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: FirstDocumentIdMutationOptions,\n ): Promise<SingleMutationResult>\n /**\n * Create a document if no document with the same ID already exists.\n * Returns a promise that resolves to a mutation result object containing the ID of the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: AllDocumentIdsMutationOptions,\n ): Promise<MultipleMutationResult>\n /**\n * Create a document if no document with the same ID already exists.\n * Returns a promise that resolves to the created document.\n *\n * @param document - Document to create\n * @param options - Mutation options\n */\n createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options?: BaseMutationOptions,\n ): Promise<SanityDocument<R>>\n createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options?:\n | AllDocumentIdsMutationOptions\n | AllDocumentsMutationOptions\n | BaseMutationOptions\n | FirstDocumentIdMutationOptions\n | FirstDocumentMutationOptions,\n ): Promise<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n return lastValueFrom(\n dataMethods._createIfNotExists<R>(this, this.#httpRequest, document, options),\n )\n }\n\n /**\n * Create a document if it does not exist, or replace a document with the same document ID\n * Returns a promise that resolves to the created document.\n *\n * @param document - Document to either create or replace\n * @param options - Mutation options\n */\n createOrReplace<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: FirstDocumentMutationOptions,\n ): Promise<SanityDocument<R>>\n /**\n * Create a document if it does not exist, or replace a document with the same document ID\n * Returns a promise that resolves to an array containing the created document.\n *\n * @param document - Document to either create or replace\n * @param options - Mutation options\n */\n createOrReplace<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: AllDocumentsMutationOptions,\n ): Promise<SanityDocument<R>[]>\n /**\n * Create a document if it does not exist, or replace a document with the same document ID\n * Returns a promise that resolves to a mutation result object containing the ID of the created document.\n *\n * @param document - Document to either create or replace\n * @param options - Mutation options\n */\n createOrReplace<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: FirstDocumentIdMutationOptions,\n ): Promise<SingleMutationResult>\n /**\n * Create a document if it does not exist, or replace a document with the same document ID\n * Returns a promise that resolves to a mutation result object containing the created document ID.\n *\n * @param document - Document to either create or replace\n * @param options - Mutation options\n */\n createOrReplace<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options: AllDocumentIdsMutationOptions,\n ): Promise<MultipleMutationResult>\n /**\n * Create a document if it does not exist, or replace a document with the same document ID\n * Returns a promise that resolves to the created document.\n *\n * @param document - Document to either create or replace\n * @param options - Mutation options\n */\n createOrReplace<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options?: BaseMutationOptions,\n ): Promise<SanityDocument<R>>\n createOrReplace<R extends Record<string, Any> = Record<string, Any>>(\n document: IdentifiedSanityDocumentStub<R>,\n options?:\n | AllDocumentIdsMutationOptions\n | AllDocumentsMutationOptions\n | BaseMutationOptions\n | FirstDocumentIdMutationOptions\n | FirstDocumentMutationOptions,\n ): Promise<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n return lastValueFrom(\n dataMethods._createOrReplace<R>(this, this.#httpRequest, document, options),\n )\n }\n\n /**\n * @public\n *\n * Creates a new version of a published document.\n *\n * @remarks\n * * 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.\n * * If `document` is provided, it must have a `_type` property.\n * * Creating a version with no `releaseId` will create a new draft version of the published document.\n * * 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`.\n * * If the `document._id` is not defined, it will be generated from `publishedId` and `releaseId`.\n * * To create a version of an unpublished document, use the `client.create` method.\n *\n * @category Versions\n *\n * @param params - Version action parameters:\n * - `baseId` - The ID of the published document from which to create a new version from.\n * - `ifBaseRevisionId` - If `baseId` is provided, this ensures the `baseId`'s revision Id is as expected before creating the new version from it.\n * - `document` - The document to create as a new version (must include `_type`).\n * - `publishedId` - The ID of the published document being versioned.\n * - `releaseId` - The ID of the release to create the version for.\n * @param options - Additional action options.\n * @returns A promise that resolves to the `transactionId`.\n *\n * @example Creating a new version of a published document\n * ```ts\n * const transactionId = await client.createVersion({\n * baseId: 'myDocument',\n * publishedId: 'myDocument',\n * releaseId: 'myRelease',\n * })\n *\n * // The following document will be created:\n * // {\n * // _id: 'versions.myRelease.myDocument',\n * // _type: 'myDocument',\n * // title: 'My Document',\n * // }\n * ```\n *\n *\n * @example Creating a new draft version of a published document\n * ```ts\n * const transactionId = await client.createVersion({\n * baseId: 'myDocument',\n * publishedId: 'myDocument',\n * })\n *\n * // The following document will be created:\n * // {\n * // _id: 'drafts.myDocument',\n * // _type: 'myDocument',\n * // title: 'My Document',\n * // }\n * ```\n */\n createVersion<R extends Record<string, Any>>(\n args: {\n document: SanityDocumentStub<R>\n publishedId: string\n releaseId?: string\n },\n options?: BaseActionOptions,\n ): Promise<SingleActionResult | MultipleActionResult>\n createVersion<R extends Record<string, Any>>(\n args: {\n document: IdentifiedSanityDocumentStub<R>\n publishedId?: string\n releaseId?: string\n },\n options?: BaseActionOptions,\n ): Promise<SingleActionResult | MultipleActionResult>\n createVersion(\n args: {\n publishedId: string\n baseId: string\n releaseId?: string\n ifBaseRevisionId?: string\n },\n options?: BaseActionOptions,\n ): Promise<SingleActionResult | MultipleActionResult>\n createVersion<R extends Record<string, Any>>(\n {\n document,\n publishedId,\n releaseId,\n baseId,\n ifBaseRevisionId,\n }: {\n document?: SanityDocumentStub<R> | IdentifiedSanityDocumentStub<R>\n publishedId?: string\n releaseId?: string\n baseId?: string\n ifBaseRevisionId?: string\n },\n options?: BaseActionOptions,\n ): Promise<SingleActionResult | MultipleActionResult> {\n if (!document) {\n return firstValueFrom(\n dataMethods._createVersionFromBase(\n this,\n this.#httpRequest,\n publishedId,\n baseId,\n releaseId,\n ifBaseRevisionId,\n options,\n ),\n )\n }\n\n const documentVersionId = deriveDocumentVersionId('createVersion', {\n document,\n publishedId,\n releaseId,\n })\n\n const documentVersion = {...document, _id: documentVersionId}\n const versionPublishedId = publishedId || getPublishedId(document._id)\n\n return firstValueFrom(\n dataMethods._createVersion<R>(\n this,\n this.#httpRequest,\n documentVersion,\n versionPublishedId,\n options,\n ),\n )\n }\n\n /**\n * Deletes a document with the given document ID.\n * Returns a promise that resolves to the deleted document.\n *\n * @param id - Document ID to delete\n * @param options - Options for the mutation\n */\n delete<R extends Record<string, Any> = Record<string, Any>>(\n id: string,\n options: FirstDocumentMutationOptions,\n ): Promise<SanityDocument<R>>\n /**\n * Deletes a document with the given document ID.\n * Returns a promise that resolves to an array containing the deleted document.\n *\n * @param id - Document ID to delete\n * @param options - Options for the mutation\n */\n delete<R extends Record<string, Any> = Record<string, Any>>(\n id: string,\n options: AllDocumentsMutationOptions,\n ): Promise<SanityDocument<R>[]>\n /**\n * Deletes a document with the given document ID.\n * Returns a promise that resolves to a mutation result object containing the deleted document ID.\n *\n * @param id - Document ID to delete\n * @param options - Options for the mutation\n */\n delete(id: string, options: FirstDocumentIdMutationOptions): Promise<SingleMutationResult>\n /**\n * Deletes a document with the given document ID.\n * Returns a promise that resolves to a mutation result object containing the deleted document ID.\n *\n * @param id - Document ID to delete\n * @param options - Options for the mutation\n */\n delete(id: string, options: AllDocumentIdsMutationOptions): Promise<MultipleMutationResult>\n /**\n * Deletes a document with the given document ID.\n * Returns a promise that resolves to the deleted document.\n *\n * @param id - Document ID to delete\n * @param options - Options for the mutation\n */\n delete<R extends Record<string, Any> = Record<string, Any>>(\n id: string,\n options?: BaseMutationOptions,\n ): Promise<SanityDocument<R>>\n /**\n * Deletes one or more documents matching the given query or document ID.\n * Returns a promise that resolves to first deleted document.\n *\n * @param selection - An object with either an `id` or `query` key defining what to delete\n * @param options - Options for the mutation\n */\n delete<R extends Record<string, Any> = Record<string, Any>>(\n selection: MutationSelection,\n options: FirstDocumentMutationOptions,\n ): Promise<SanityDocument<R>>\n /**\n * Deletes one or more documents matching the given query or document ID.\n * Returns a promise that resolves to an array containing the deleted documents.\n *\n * @param selection - An object with either an `id` or `query` key defining what to delete\n * @param options - Options for the mutation\n */\n delete<R extends Record<string, Any> = Record<string, Any>>(\n selection: MutationSelection,\n options: AllDocumentsMutationOptions,\n ): Promise<SanityDocument<R>[]>\n /**\n * Deletes one or more documents matching the given query or document ID.\n * Returns a promise that resolves to a mutation result object containing the ID of the first deleted document.\n *\n * @param selection - An object with either an `id` or `query` key defining what to delete\n * @param options - Options for the mutation\n */\n delete(\n selection: MutationSelection,\n options: FirstDocumentIdMutationOptions,\n ): Promise<SingleMutationResult>\n /**\n * Deletes one or more documents matching the given query or document ID.\n * Returns a promise that resolves to a mutation result object containing the document IDs that were deleted.\n *\n * @param selection - An object with either an `id` or `query` key defining what to delete\n * @param options - Options for the mutation\n */\n delete(\n selection: MutationSelection,\n options: AllDocumentIdsMutationOptions,\n ): Promise<MultipleMutationResult>\n /**\n * Deletes one or more documents matching the given query or document ID.\n * Returns a promise that resolves to first deleted document.\n *\n * @param selection - An object with either an `id` or `query` key defining what to delete\n * @param options - Options for the mutation\n */\n delete<R extends Record<string, Any> = Record<string, Any>>(\n selection: MutationSelection,\n options?: BaseMutationOptions,\n ): Promise<SanityDocument<R>>\n delete<R extends Record<string, Any> = Record<string, Any>>(\n selection: string | MutationSelection,\n options?:\n | AllDocumentIdsMutationOptions\n | AllDocumentsMutationOptions\n | BaseMutationOptions\n | FirstDocumentIdMutationOptions\n | FirstDocumentMutationOptions,\n ): Promise<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n return lastValueFrom(dataMethods._delete<R>(this, this.#httpRequest, selection, options))\n }\n\n /**\n * @public\n *\n * Deletes the draft or release version of a document.\n *\n * @remarks\n * * Discarding a version with no `releaseId` will discard the draft version of the published document.\n * * If the draft or release version does not exist, any error will throw.\n *\n * @param params - Version action parameters:\n * - `releaseId` - The ID of the release to discard the document from.\n * - `publishedId` - The published ID of the document to discard.\n * @param purge - if `true` the document history is also discarded.\n * @param options - Additional action options.\n * @returns a promise that resolves to the `transactionId`.\n *\n * @example Discarding a release version of a document\n * ```ts\n * client.discardVersion({publishedId: 'myDocument', releaseId: 'myRelease'})\n * // The document with the ID `versions.myRelease.myDocument` will be discarded.\n * ```\n *\n * @example Discarding a draft version of a document\n * ```ts\n * client.discardVersion({publishedId: 'myDocument'})\n * // The document with the ID `drafts.myDocument` will be discarded.\n * ```\n */\n discardVersion(\n {releaseId, publishedId}: {releaseId?: string; publishedId: string},\n purge?: boolean,\n options?: BaseActionOptions,\n ): Promise<SingleActionResult | MultipleActionResult> {\n const documentVersionId = getDocumentVersionId(publishedId, releaseId)\n\n return lastValueFrom(\n dataMethods._discardVersion(this, this.#httpRequest, documentVersionId, purge, options),\n )\n }\n\n /**\n * @public\n *\n * Replaces an existing version document.\n *\n * @remarks\n * * Requires a document with a `_type` property.\n * * 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`.\n * * If the `document._id` is not defined, it will be generated from `publishedId` and `releaseId`.\n * * Replacing a version with no `releaseId` will replace the draft version of the published document.\n * * At least one of the **version** or **published** documents must exist.\n *\n * @param params - Version action parameters:\n * - `document` - The new document to replace the version with.\n * - `releaseId` - The ID of the release where the document version is replaced.\n * - `publishedId` - The ID of the published document to replace.\n * @param options - Additional action options.\n * @returns a promise that resolves to the `transactionId`.\n *\n * @example Replacing a release version of a published document with a generated version ID\n * ```ts\n * await client.replaceVersion({\n * document: {_type: 'myDocument', title: 'My Document'},\n * publishedId: 'myDocument',\n * releaseId: 'myRelease',\n * })\n *\n * // The following document will be patched:\n * // {\n * // _id: 'versions.myRelease.myDocument',\n * // _type: 'myDocument',\n * // title: 'My Document',\n * // }\n * ```\n *\n * @example Replacing a release version of a published document with a specified version ID\n * ```ts\n * await client.replaceVersion({\n * document: {_type: 'myDocument', _id: 'versions.myRelease.myDocument', title: 'My Document'},\n * // `publishedId` and `releaseId` are not required since `document._id` has been specified\n * })\n *\n * // The following document will be patched:\n * // {\n * // _id: 'versions.myRelease.myDocument',\n * // _type: 'myDocument',\n * // title: 'My Document',\n * // }\n * ```\n *\n * @example Replacing a draft version of a published document\n * ```ts\n * await client.replaceVersion({\n * document: {_type: 'myDocument', title: 'My Document'},\n * publishedId: 'myDocument',\n * })\n *\n * // The following document will be patched:\n * // {\n * // _id: 'drafts.myDocument',\n * // _type: 'myDocument',\n * // title: 'My Document',\n * // }\n * ```\n */\n\n replaceVersion<R extends Record<string, Any>>(\n args: {\n document: SanityDocumentStub<R>\n publishedId: string\n releaseId?: string\n },\n options?: BaseActionOptions,\n ): Promise<SingleActionResult | MultipleActionResult>\n replaceVersion<R extends Record<string, Any>>(\n args: {\n document: IdentifiedSanityDocumentStub<R>\n publishedId?: string\n releaseId?: string\n },\n options?: BaseActionOptions,\n ): Promise<SingleActionResult | MultipleActionResult>\n replaceVersion<R extends Record<string, Any>>(\n {\n document,\n publishedId,\n releaseId,\n }: {\n document: SanityDocumentStub<R> | IdentifiedSanityDocumentStub<R>\n publishedId?: string\n releaseId?: string\n },\n options?: BaseActionOptions,\n ): Promise<SingleActionResult | MultipleActionResult> {\n const documentVersionId = deriveDocumentVersionId('replaceVersion', {\n document,\n publishedId,\n releaseId,\n })\n\n const documentVersion = {...document, _id: documentVersionId}\n\n return firstValueFrom(\n dataMethods._replaceVersion<R>(this, this.#httpRequest, documentVersion, options),\n )\n }\n\n /**\n * @public\n *\n * Used to indicate when a document within a release should be unpublished when\n * the release is run.\n *\n * @remarks\n * * If the published document does not exist, an error will be thrown.\n *\n * @param params - Version action parameters:\n * - `releaseId` - The ID of the release to unpublish the document from.\n * - `publishedId` - The published ID of the document to unpublish.\n * @param options - Additional action options.\n * @returns a promise that resolves to the `transactionId`.\n *\n * @example Unpublishing a release version of a published document\n * ```ts\n * await client.unpublishVersion({publishedId: 'myDocument', releaseId: 'myRelease'})\n * // The document with the ID `versions.myRelease.myDocument` will be unpublished. when `myRelease` is run.\n * ```\n */\n unpublishVersion(\n {releaseId, publishedId}: {releaseId: string; publishedId: string},\n options?: BaseActionOptions,\n ): Promise<SingleActionResult | MultipleActionResult> {\n const versionId = getVersionId(publishedId, releaseId)\n\n return lastValueFrom(\n dataMethods._unpublishVersion(this, this.#httpRequest, versionId, publishedId, options),\n )\n }\n\n /**\n * Perform mutation operations against the configured dataset\n * Returns a promise that resolves to the first mutated document.\n *\n * @param operations - Mutation operations to execute\n * @param options - Mutation options\n */\n mutate<R extends Record<string, Any> = Record<string, Any>>(\n operations: Mutation<R>[] | Patch | Transaction,\n options: FirstDocumentMutationOptions,\n ): Promise<SanityDocument<R>>\n /**\n * Perform mutation operations against the configured dataset.\n * Returns a promise that resolves to an array of the mutated documents.\n *\n * @param operations - Mutation operations to execute\n * @param options - Mutation options\n */\n mutate<R extends Record<string, Any> = Record<string, Any>>(\n operations: Mutation<R>[] | Patch | Transaction,\n options: AllDocumentsMutationOptions,\n ): Promise<SanityDocument<R>[]>\n /**\n * Perform mutation operations against the configured dataset\n * Returns a promise that resolves to a mutation result object containing the document ID of the first mutated document.\n *\n * @param operations - Mutation operations to execute\n * @param options - Mutation options\n */\n mutate<R extends Record<string, Any> = Record<string, Any>>(\n operations: Mutation<R>[] | Patch | Transaction,\n options: FirstDocumentIdMutationOptions,\n ): Promise<SingleMutationResult>\n /**\n * Perform mutation operations against the configured dataset\n * Returns a promise that resolves to a mutation result object containing the mutated document IDs.\n *\n * @param operations - Mutation operations to execute\n * @param options - Mutation options\n */\n mutate<R extends Record<string, Any> = Record<string, Any>>(\n operations: Mutation<R>[] | Patch | Transaction,\n options: AllDocumentIdsMutationOptions,\n ): Promise<MultipleMutationResult>\n /**\n * Perform mutation operations against the configured dataset\n * Returns a promise that resolves to the first mutated document.\n *\n * @param operations - Mutation operations to execute\n * @param options - Mutation options\n */\n mutate<R extends Record<string, Any> = Record<string, Any>>(\n operations: Mutation<R>[] | Patch | Transaction,\n options?: BaseMutationOptions,\n ): Promise<SanityDocument<R>>\n mutate<R extends Record<string, Any> = Record<string, Any>>(\n operations: Mutation<R>[] | Patch | Transaction,\n options?:\n | FirstDocumentMutationOptions\n | AllDocumentsMutationOptions\n | FirstDocumentIdMutationOptions\n | AllDocumentIdsMutationOptions\n | BaseMutationOptions,\n ): Promise<\n SanityDocument<R> | SanityDocument<R>[] | SingleMutationResult | MultipleMutationResult\n > {\n return lastValueFrom(dataMethods._mutate<R>(this, this.#httpRequest, operations, options))\n }\n\n /**\n * Create a new buildable patch of operations to perform\n *\n * @param documentId - Document ID to patch\n * @param operations - Optional object of patch operations to initialize the patch instance with\n * @returns Patch instance - call `.commit()` to perform the operations defined\n */\n patch(documentId: string, operations?: PatchOperations): Patch\n\n /**\n * Create a new buildable patch of operations to perform\n *\n * @param documentIds - Array of document IDs to patch\n * @param operations - Optional object of patch operations to initialize the patch instance with\n * @returns Patch instance - call `.commit()` to perform the operations defined\n */\n patch(documentIds: string[], operations?: PatchOperations): Patch\n\n /**\n * Create a new buildable patch of operations to perform\n *\n * @param selection - An object with `query` and optional `params`, defining which document(s) to patch\n * @param operations - Optional object of patch operations to initialize the patch instance with\n * @returns Patch instance - call `.commit()` to perform the operations defined\n */\n patch(selection: MutationSelection, operations?: PatchOperations): Patch\n\n /**\n * Create a new buildable patch of operations to perform\n *\n * @param selection - Document ID, an array of document IDs, or an object with `query` and optional `params`, defining which document(s) to patch\n * @param operations - Optional object of patch operations to initialize the patch instance with\n * @returns Patch instance - call `.commit()` to perform the operations defined\n */\n patch(documentId: PatchSelection, operations?: PatchOperations): Patch {\n return new Patch(documentId, operations, this)\n }\n\n /**\n * Create a new transaction of mutations\n *\n * @param operations - Optional array of mutation operations to initialize the transaction instance with\n */\n transaction<R extends Record<string, Any> = Record<string, Any>>(\n operations?: Mutation<R>[],\n ): Transaction {\n return new Transaction(operations, this)\n }\n\n /**\n * Perform action operations against the configured dataset\n * Returns a promise that resolves to the transaction result\n *\n * @param operations - Action operation(s) to execute\n * @param options - Action options\n */\n action(\n operations: Action | Action[],\n options?: BaseActionOptions,\n ): Promise<SingleActionResult | MultipleActionResult> {\n return lastValueFrom(dataMethods._action(this, this.#httpRequest, operations, options))\n }\n\n /**\n * Perform a request against the Sanity API\n * NOTE: Only use this for Sanity API endpoints, not for your own APIs!\n *\n * @param options - Request options\n * @returns Promise resolving to the response body\n */\n request<R = Any>(options: RawRequestOptions): Promise<R> {\n return lastValueFrom(dataMethods._request<R>(this, this.#httpRequest, options))\n }\n\n /**\n * Perform an HTTP request a `/data` sub-endpoint\n * NOTE: Considered internal, thus marked as deprecated. Use `request` instead.\n *\n * @deprecated - Use `request()` or your own HTTP library instead\n * @param endpoint - Endpoint to hit (mutate, query etc)\n * @param body - Request body\n * @param options - Request options\n * @internal\n */\n dataRequest(endpoint: string, body: unknown, options?: BaseMutationOptions): Promise<Any> {\n return lastValueFrom(dataMethods._dataRequest(this, this.#httpRequest, endpoint, body, options))\n }\n\n /**\n * Get a Sanity API URL for the URI provided\n *\n * @param uri - URI/path to build URL for\n * @param canUseCdn - Whether or not to allow using the API CDN for this route\n */\n getUrl(uri: string, canUseCdn?: boolean): string {\n return dataMethods._getUrl(this, uri, canUseCdn)\n }\n\n /**\n * Get a Sanity API URL for the data operation and path provided\n *\n * @param operation - Data operation (eg `query`, `mutate`, `listen` or similar)\n * @param path - Path to append after the operation\n */\n getDataUrl(operation: string, path?: string): string {\n return dataMethods._getDataUrl(this, operation, path)\n }\n}\n","import type {Middlewares} from 'get-it'\n\nimport {defineHttpRequest} from './http/request'\nimport type {Any, ClientConfig, HttpRequest} from './types'\n\nexport {validateApiPerspective} from './config'\nexport {\n ChannelError,\n connectEventSource,\n ConnectionFailedError,\n DisconnectError,\n type EventSourceEvent,\n type EventSourceInstance,\n MessageError,\n MessageParseError,\n type ServerSentEvent,\n} from './data/eventsource'\nexport * from './data/patch'\nexport * from './data/transaction'\nexport {\n ClientError,\n CorsOriginError,\n formatQueryParseError,\n type HttpError,\n isHttpError,\n isQueryParseError,\n ServerError,\n} from './http/errors'\nexport * from './SanityClient'\nexport * from './types'\n\n/** @alpha */\nexport {adapter as unstable__adapter, environment as unstable__environment} from 'get-it'\n\n/**\n * Create the `requester` and `createClient` exports, that have environment specific middleware for node and browsers\n * @internal\n */\nexport default function defineCreateClientExports<\n SanityClientType,\n ClientConfigType extends ClientConfig,\n>(\n envMiddleware: Middlewares,\n ClassConstructor: new (httpRequest: HttpRequest, config: ClientConfigType) => SanityClientType,\n) {\n // Set the http client to use for requests, and its environment specific middleware\n const defaultRequester = defineHttpRequest(envMiddleware)\n\n const createClient = (config: ClientConfigType) => {\n const clientRequester = defineHttpRequest(envMiddleware, {\n ignoreWarnings: config.ignoreWarnings,\n })\n return new ClassConstructor(\n (options, requester) =>\n (requester || clientRequester)({\n maxRedirects: 0,\n maxRetries: config.maxRetries,\n retryDelay: config.retryDelay,\n lineage: config.lineage,\n ...options,\n } as Any),\n config,\n )\n }\n\n return {requester: defaultRequester, createClient}\n}\n","import {printNoDefaultExport} from './warnings'\n\n/* @internal */\nexport function defineDeprecatedCreateClient<SanityClientType, ClientConfigType>(\n createClient: (config: ClientConfigType) => SanityClientType,\n) {\n return function deprecatedCreateClient(config: ClientConfigType) {\n printNoDefaultExport()\n return createClient(config)\n }\n}\n","export default []\n","import defineCreateClientExports, {type ClientConfig, SanityClient} from './defineCreateClient'\nimport {defineDeprecatedCreateClient} from './defineDeprecatedCreateClient'\nimport envMiddleware from './http/browserMiddleware'\n\nexport * from './defineCreateClient'\n\nconst exp = defineCreateClientExports<SanityClient, ClientConfig>(envMiddleware, SanityClient)\n\n/** @public */\nexport const requester = exp.requester\n\n/** @public */\nexport const createClient = exp.createClient\n\n/**\n * @public\n * @deprecated Use the named export `createClient` instead of the `default` export\n */\nconst deprecatedCreateClient = defineDeprecatedCreateClient(createClient)\nexport default deprecatedCreateClient\n"],"names":["location","projectId","envMiddleware","isQuery","warnings.printNoApiVersionSpecifiedWarning","warnings.printDeprecatedResourceConfigWarning","resourceConfig","validate.resourceConfig","warnings.printCredentialedTokenWarning","warnings.printBrowserTokenWarning","warnings.printCdnWarning","validate.projectId","validate.dataset","validate.requestTag","warnings.printCdnAndWithCredentialsWarning","merge","validators.validateObject","validators.requireDocumentId","validators.validateDocumentId","validators.requireDocumentType","validators.resourceConfig","uri","validators.hasDataset","dataset","observable","validators.validateAssetType","defaults","EventSource","validate.resourceGuard","finalize","map","dataMethods._fetch","dataMethods._getDocument","dataMethods._getDocuments","dataMethods._create","dataMethods._createIfNotExists","dataMethods._createOrReplace","dataMethods._createVersionFromBase","dataMethods._createVersion","dataMethods._delete","dataMethods._discardVersion","dataMethods._replaceVersion","dataMethods._unpublishVersion","dataMethods._mutate","dataMethods._action","dataMethods._request","dataMethods._getUrl","dataMethods._getDataUrl","dataMethods._dataRequest","requester","createClient"],"mappings":";;;;;;;;AAwBA,MAAM,UAAU;AAkBA,SAAA,UAAU,OAAeA,WAAwB,SAA0B;AACzF,QAAM,QAAQ,MAAM,MAAM,OAAO,GAC3B,MAAM;AAAA,IACV,OAAO,aAAaA,UAAS,OAAO,KAAK;AAAA,IACzC,KAAKA,UAAS,MAAM,aAAaA,UAAS,KAAK,KAAK,IAAI;AAAA,EAGpD,GAAA,EAAC,OAAO,KAAK,YAAW,IAAI,eAAe,KAAK,KAAK,GAErD,iBAAiB,GAAG,GAAG,GAAG;AAEhC,SAAO,MACJ,MAAM,SAAS,GAAG,EAClB,MAAM,OAAO,GAAG,EAChB,IAAI,CAAC,MAAM,UAAU;AACd,UAAA,SAAS,QAAQ,IAAI,OAErB,SAAS,IADM,IAAI,MAAM,GAAG,MAAM,CAAC,cAAc,CACxB,MACzB,YAAY,YAAY,MAAM,GAC9B,iBAAiB,CA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