@sanity/client 7.1.0-views.0 → 7.1.0-views.2
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 +810 -40
- package/dist/_chunks-cjs/config.cjs +14 -0
- package/dist/_chunks-cjs/config.cjs.map +1 -1
- package/dist/_chunks-cjs/dataMethods.cjs +197 -32
- package/dist/_chunks-cjs/dataMethods.cjs.map +1 -1
- package/dist/_chunks-cjs/isRecord.cjs +6 -0
- package/dist/_chunks-cjs/isRecord.cjs.map +1 -0
- package/dist/_chunks-cjs/resolveEditInfo.cjs +3 -5
- package/dist/_chunks-cjs/resolveEditInfo.cjs.map +1 -1
- package/dist/_chunks-cjs/stegaClean.cjs +4 -0
- package/dist/_chunks-cjs/stegaClean.cjs.map +1 -1
- package/dist/_chunks-cjs/stegaEncodeSourceMap.cjs +2 -5
- package/dist/_chunks-cjs/stegaEncodeSourceMap.cjs.map +1 -1
- package/dist/_chunks-es/config.js +15 -1
- package/dist/_chunks-es/config.js.map +1 -1
- package/dist/_chunks-es/dataMethods.js +200 -33
- package/dist/_chunks-es/dataMethods.js.map +1 -1
- package/dist/_chunks-es/isRecord.js +7 -0
- package/dist/_chunks-es/isRecord.js.map +1 -0
- package/dist/_chunks-es/resolveEditInfo.js +1 -3
- package/dist/_chunks-es/resolveEditInfo.js.map +1 -1
- package/dist/_chunks-es/stegaClean.js +4 -0
- package/dist/_chunks-es/stegaClean.js.map +1 -1
- package/dist/_chunks-es/stegaEncodeSourceMap.js +1 -4
- package/dist/_chunks-es/stegaEncodeSourceMap.js.map +1 -1
- package/dist/index.browser.cjs +1019 -59
- package/dist/index.browser.cjs.map +1 -1
- package/dist/index.browser.d.cts +1950 -149
- package/dist/index.browser.d.ts +1950 -149
- package/dist/index.browser.js +1021 -60
- package/dist/index.browser.js.map +1 -1
- package/dist/index.cjs +825 -29
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1950 -149
- package/dist/index.d.ts +1950 -149
- package/dist/index.js +826 -31
- package/dist/index.js.map +1 -1
- package/dist/stega.browser.d.cts +1950 -149
- package/dist/stega.browser.d.ts +1950 -149
- package/dist/stega.d.cts +1950 -149
- package/dist/stega.d.ts +1950 -149
- package/dist/views.cjs +21 -5
- package/dist/views.cjs.map +1 -1
- package/dist/views.d.cts +54 -36
- package/dist/views.d.ts +54 -36
- package/dist/views.js +22 -5
- package/dist/views.js.map +1 -1
- package/package.json +2 -1
- package/src/SanityClient.ts +652 -12
- package/src/agent/actions/AgentActionsClient.ts +29 -2
- package/src/agent/actions/commonTypes.ts +57 -17
- package/src/agent/actions/generate.ts +36 -2
- package/src/agent/actions/patch.ts +136 -0
- package/src/agent/actions/prompt.ts +145 -0
- package/src/agent/actions/transform.ts +105 -7
- package/src/agent/actions/translate.ts +5 -2
- package/src/config.ts +3 -1
- package/src/csm/walkMap.ts +1 -1
- package/src/data/dataMethods.ts +170 -12
- package/src/data/encodeQueryString.ts +1 -1
- package/src/data/eventsource.ts +16 -7
- package/src/data/listen.ts +10 -4
- package/src/data/live.ts +13 -5
- package/src/datasets/DatasetsClient.ts +4 -1
- package/src/defineCreateClient.ts +7 -1
- package/src/http/errors.ts +92 -27
- package/src/http/request.ts +3 -3
- package/src/http/requestOptions.ts +4 -0
- package/src/projects/ProjectsClient.ts +6 -2
- package/src/releases/ReleasesClient.ts +693 -0
- package/src/releases/createRelease.ts +53 -0
- package/src/types.ts +293 -10
- package/src/users/UsersClient.ts +7 -3
- package/src/util/codeFrame.ts +174 -0
- package/src/util/createVersionId.ts +79 -0
- package/src/{csm → util}/isRecord.ts +1 -1
- package/src/validators.ts +23 -1
- package/src/views/index.ts +65 -15
- package/umd/sanityClient.js +1067 -61
- package/umd/sanityClient.min.js +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dataMethods.js","sources":["../../src/http/errors.ts","../../src/http/request.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"],"sourcesContent":["import type {ActionError, Any, ErrorProps, MutationError} from '../types'\n\nconst MAX_ITEMS_IN_ERROR_MESSAGE = 5\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) {\n const props = extractErrorProps(res)\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): 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 // API/Boom style errors ({statusCode, error, message})\n if (body.error && body.message) {\n props.message = `${body.error} - ${body.message}`\n return props\n }\n\n // Mutation errors (specifically)\n if (isMutationError(body) || isActionError(body)) {\n const allItems = body.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 = `${body.error.description}${itemsStr}`\n props.details = body.error\n return props\n }\n\n // Query/database errors ({error: {description, other, arb, props}})\n if (body.error && body.error.description) {\n props.message = body.error.description\n props.details = body.error\n return props\n }\n\n // Other, more arbitrary errors\n props.message = body.error || body.message || httpErrorMessage(res)\n return props\n}\n\nfunction isMutationError(body: Any): body is MutationError {\n return (\n isPlainObject(body) &&\n isPlainObject(body.error) &&\n body.error.type === 'mutationError' &&\n typeof body.error.description === 'string'\n )\n}\n\nfunction isActionError(body: Any): body is ActionError {\n return (\n isPlainObject(body) &&\n isPlainObject(body.error) &&\n body.error.type === 'actionError' &&\n typeof body.error.description === 'string'\n )\n}\n\nfunction isPlainObject(obj: Any): obj is Record<string, unknown> {\n return typeof obj === 'object' && obj !== null && !Array.isArray(obj)\n}\n\nfunction httpErrorMessage(res: Any) {\n const statusMessage = res.statusMessage ? ` ${res.statusMessage}` : ''\n return `${res.method}-request to ${res.url} resulted in HTTP ${res.statusCode}${statusMessage}`\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\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 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) => {\n if (res.statusCode >= 500) {\n throw new ServerError(res)\n } else if (res.statusCode >= 400) {\n throw new ClientError(res)\n }\n\n return res\n },\n}\n\nfunction printWarnings() {\n const seen: Record<string, boolean> = {}\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 seen[msg] = true\n console.warn(msg) // eslint-disable-line no-console\n }\n return res\n },\n }\n}\n\n/** @internal */\nexport function defineHttpRequest(envMiddleware: Middlewares): Requester {\n return getIt([\n retry({shouldRetry}),\n ...envMiddleware,\n printWarnings(),\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","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 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 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 {from, type MonoTypeOperatorFunction, Observable} from 'rxjs'\nimport {combineLatestWith, filter, map} from 'rxjs/operators'\n\nimport {validateApiPerspective} from '../config'\nimport {requestOptions} from '../http/requestOptions'\nimport {stegaClean} from '../stega/stegaClean'\nimport type {\n Action,\n AllDocumentIdsMutationOptions,\n AllDocumentsMutationOptions,\n Any,\n BaseActionOptions,\n BaseMutationOptions,\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 RequestObservableOptions,\n RequestOptions,\n SanityDocument,\n SingleActionResult,\n SingleMutationResult,\n} from '../types'\nimport {getSelection} from '../util/getSelection'\nimport * as validate from '../validators'\nimport * as validators from '../validators'\nimport {printCdnPreviewDraftsWarning, printPreviewDraftsDeprecationWarning} from '../warnings'\nimport {encodeQueryString} from './encodeQueryString'\nimport {ObservablePatch, Patch} from './patch'\nimport {ObservableTransaction, Transaction} from './transaction'\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 config: InitializedClientConfig,\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(config, 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 config: InitializedClientConfig,\n httpRequest: HttpRequest,\n id: string,\n opts: {signal?: AbortSignal; tag?: string} = {},\n): Observable<SanityDocument<R> | undefined> {\n const options = {\n uri: _getDataUrl(config, 'doc', id),\n json: true,\n tag: opts.tag,\n signal: opts.signal,\n }\n return _requestObservable<SanityDocument<R> | undefined>(config, httpRequest, options).pipe(\n filter(isResponse),\n map((event) => event.body.documents && event.body.documents[0]),\n )\n}\n\n/** @internal */\nexport function _getDocuments<R extends Record<string, Any>>(\n config: InitializedClientConfig,\n httpRequest: HttpRequest,\n ids: string[],\n opts: {signal?: AbortSignal; tag?: string} = {},\n): Observable<(SanityDocument<R> | null)[]> {\n const options = {\n uri: _getDataUrl(config, 'doc', ids.join(',')),\n json: true,\n tag: opts.tag,\n signal: opts.signal,\n }\n return _requestObservable<(SanityDocument<R> | null)[]>(config, 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 _createIfNotExists<R extends Record<string, Any>>(\n config: InitializedClientConfig,\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>(config, httpRequest, doc, 'createIfNotExists', options)\n}\n\n/** @internal */\nexport function _createOrReplace<R extends Record<string, Any>>(\n config: InitializedClientConfig,\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>(config, httpRequest, doc, 'createOrReplace', options)\n}\n\n/** @internal */\nexport function _delete<R extends Record<string, Any>>(\n config: InitializedClientConfig,\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 config,\n httpRequest,\n 'mutate',\n {mutations: [{delete: getSelection(selection)}]},\n options,\n )\n}\n\n/** @internal */\nexport function _mutate<R extends Record<string, Any>>(\n config: InitializedClientConfig,\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(config, httpRequest, 'mutate', {mutations: muts, transactionId}, options)\n}\n\n/**\n * @internal\n */\nexport function _action(\n config: InitializedClientConfig,\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 config,\n httpRequest,\n 'actions',\n {actions: acts, transactionId, skipCrossDatasetReferenceValidation, dryRun},\n options,\n )\n}\n\n/**\n * @internal\n */\nexport function _dataRequest(\n config: InitializedClientConfig,\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(config, 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(config, 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 config: InitializedClientConfig,\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(config, httpRequest, 'mutate', {mutations: [mutation]}, opts)\n}\n\nconst hasDataConfig = (config: InitializedClientConfig) =>\n (config.dataset !== undefined && config.projectId !== undefined) ||\n config['~experimental_resource'] !== undefined\n\nconst isQuery = (config: InitializedClientConfig, uri: string) =>\n hasDataConfig(config) && uri.startsWith(_getDataUrl(config, 'query'))\n\nconst isViewQuery = (config: InitializedClientConfig, uri: string) =>\n hasDataConfig(config) && uri.startsWith(_getDataUrl(config, 'views'))\n\nconst isMutate = (config: InitializedClientConfig, uri: string) =>\n hasDataConfig(config) && uri.startsWith(_getDataUrl(config, 'mutate'))\n\nconst isDoc = (config: InitializedClientConfig, uri: string) =>\n hasDataConfig(config) && uri.startsWith(_getDataUrl(config, 'doc', ''))\n\nconst isListener = (config: InitializedClientConfig, uri: string) =>\n hasDataConfig(config) && uri.startsWith(_getDataUrl(config, 'listen'))\n\nconst isHistory = (config: InitializedClientConfig, uri: string) =>\n hasDataConfig(config) && uri.startsWith(_getDataUrl(config, 'history', ''))\n\nconst isData = (config: InitializedClientConfig, uri: string) =>\n uri.startsWith('/data/') ||\n isQuery(config, uri) ||\n isMutate(config, uri) ||\n isDoc(config, uri) ||\n isListener(config, uri) ||\n isHistory(config, uri) ||\n isViewQuery(config, uri)\n\n/**\n * @internal\n */\nexport function _requestObservable<R>(\n config: InitializedClientConfig,\n httpRequest: HttpRequest,\n options: RequestObservableOptions,\n): Observable<HttpRequestEvent<R>> {\n const uri = options.url || (options.uri as string)\n\n // If the `canUseCdn`-option is not set we detect it automatically based on the method + URL.\n // The /data endpoint and view query endpoints are available through API-CDN.\n const canUseCdn =\n typeof options.canUseCdn === 'undefined'\n ? ['GET', 'HEAD'].indexOf(options.method || 'GET') >= 0 && isData(config, uri)\n : options.canUseCdn\n\n let useCdn = (options.useCdn ?? config.useCdn) && canUseCdn\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(config, 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(config, 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>(config: InitializedClientConfig, httpRequest: HttpRequest, options: Any): Observable<R> {\n const observable = _requestObservable<R>(config, 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(config: InitializedClientConfig, operation: string, path?: string): string {\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(config: InitializedClientConfig, uri: string, canUseCdn = false, options: {forceApiUrl?: boolean} = {}): string {\n const {url, cdnUrl} = 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 case 'view': {\n return `/views/${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"],"names":["isQuery","validators.validateObject","validators.requireDocumentId","validators.validateDocumentId","validate.requestTag","validators.resourceConfig","uri","validators.hasDataset"],"mappings":";;;;;;AAKO,MAAM,oBAAoB,MAAM;AAAA,EACrC;AAAA,EACA,aAAuC;AAAA,EACvC;AAAA,EACA;AAAA,EAEA,YAAY,KAAU;AACd,UAAA,QAAQ,kBAAkB,GAAG;AACnC,UAAM,MAAM,OAAO,GACnB,OAAO,OAAO,MAAM,KAAK;AAAA,EAAA;AAE7B;AAGO,MAAM,oBAAoB,MAAM;AAAA,EACrC;AAAA,EACA,aAAuC;AAAA,EACvC;AAAA,EACA;AAAA,EAEA,YAAY,KAAU;AACd,UAAA,QAAQ,kBAAkB,GAAG;AACnC,UAAM,MAAM,OAAO,GACnB,OAAO,OAAO,MAAM,KAAK;AAAA,EAAA;AAE7B;AAEA,SAAS,kBAAkB,KAAsB;AACzC,QAAA,OAAO,IAAI,MACX,QAAQ;AAAA,IACZ,UAAU;AAAA,IACV,YAAY,IAAI;AAAA,IAChB,cAAc,cAAc,MAAM,GAAG;AAAA,IACrC,SAAS;AAAA,IACT,SAAS;AAAA,EACX;AAGI,MAAA,KAAK,SAAS,KAAK;AACrB,WAAA,MAAM,UAAU,GAAG,KAAK,KAAK,MAAM,KAAK,O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;AAChE,MAAA,CAAC,OAAO,wBAAwB;AAC5B,UAAA,IAAI,MAAM,yDAAyD;AAE3E,QAAM,EAAC,MAAM,OAAM,OAAO,wBAAwB;AAElD,UAAQ,MAAM;AAAA,IACZ,KAAK,WAAW;AACR,YAAA,WAAW,GAAG,MAAM,GAAG;AAC7B,UAAI,SAAS,WAAW;AAChB,cAAA,IAAI,MAAM,oDAAoD;AAEtE,aAAO,aAAa,SAAS,CAAC,CAAC,aAAa,SAAS,CAAC,CAAC;AAAA,IAAA;AAAA,IAEzD,KAAK;AACH,aAAO,aAAa,EAAE;AAAA,IAExB,KAAK;AACH,aAAO,oBAAoB,EAAE;AAAA,IAE/B,KAAK;AACH,aAAO,eAAe,EAAE;AAAA,IAE1B,KAAK;AACH,aAAO,UAAU,EAAE;AAAA,IAErB;AAEE,YAAM,IAAI,MAAM,8BAA8B,KAAK,SAAU,CAAA,EAAE;AAAA,EAAA;AAErE;"}
|
|
1
|
+
{"version":3,"file":"dataMethods.js","sources":["../../src/util/codeFrame.ts","../../src/http/errors.ts","../../src/http/request.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"],"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/** @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() {\n const seen: Record<string, boolean> = {}\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 seen[msg] = true\n console.warn(msg) // eslint-disable-line no-console\n }\n return res\n },\n }\n}\n\n/** @internal */\nexport function defineHttpRequest(envMiddleware: Middlewares): Requester {\n return getIt([\n retry({shouldRetry}),\n ...envMiddleware,\n printWarnings(),\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","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 {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 {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 {printCdnPreviewDraftsWarning, printPreviewDraftsDeprecationWarning} from '../warnings'\nimport {encodeQueryString} from './encodeQueryString'\nimport {ObservablePatch, Patch} from './patch'\nimport {ObservableTransaction, Transaction} from './transaction'\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 config: InitializedClientConfig,\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, useEmulate, connections, ...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\n // Only use emulate if explicitly asked for\n useEmulate: false,\n\n // Having connections is a special case for views\n connections: undefined,\n\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 // Use 'emulate' endpoint for view emulation, otherwise use 'query'\n const endpoint = useEmulate ? 'emulate' : 'query'\n const requestBody = useEmulate\n ? {\n query,\n params,\n connections: connections,\n }\n : {query, params}\n\n const $request = _dataRequest(config, httpRequest, endpoint, requestBody, 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 config: InitializedClientConfig,\n httpRequest: HttpRequest,\n id: string,\n opts: {signal?: AbortSignal; tag?: string; releaseId?: string} = {},\n): Observable<SanityDocument<R> | undefined> {\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(config, 'doc', docId),\n json: true,\n tag: opts.tag,\n signal: opts.signal,\n }\n return _requestObservable<SanityDocument<R> | undefined>(config, httpRequest, options).pipe(\n filter(isResponse),\n map((event) => event.body.documents && event.body.documents[0]),\n )\n}\n\n/** @internal */\nexport function _getDocuments<R extends Record<string, Any>>(\n config: InitializedClientConfig,\n httpRequest: HttpRequest,\n ids: string[],\n opts: {signal?: AbortSignal; tag?: string} = {},\n): Observable<(SanityDocument<R> | null)[]> {\n const options = {\n uri: _getDataUrl(config, 'doc', ids.join(',')),\n json: true,\n tag: opts.tag,\n signal: opts.signal,\n }\n return _requestObservable<(SanityDocument<R> | null)[]>(config, 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 config: InitializedClientConfig,\n httpRequest: HttpRequest,\n releaseId: string,\n opts: BaseMutationOptions = {},\n): Observable<RawQueryResponse<SanityDocument<R>[]>> {\n return _dataRequest(\n config,\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 config: InitializedClientConfig,\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>(config, httpRequest, doc, 'createIfNotExists', options)\n}\n\n/** @internal */\nexport function _createOrReplace<R extends Record<string, Any>>(\n config: InitializedClientConfig,\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>(config, httpRequest, doc, 'createOrReplace', options)\n}\n\n/** @internal */\nexport function _createVersion<R extends Record<string, Any>>(\n config: InitializedClientConfig,\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\n const createVersionAction: CreateVersionAction = {\n actionType: 'sanity.action.document.version.create',\n publishedId,\n document: doc,\n }\n\n return _action(config, httpRequest, createVersionAction, options)\n}\n\n/** @internal */\nexport function _delete<R extends Record<string, Any>>(\n config: InitializedClientConfig,\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 config,\n httpRequest,\n 'mutate',\n {mutations: [{delete: getSelection(selection)}]},\n options,\n )\n}\n\n/** @internal */\nexport function _discardVersion(\n config: InitializedClientConfig,\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(config, httpRequest, discardVersionAction, options)\n}\n\n/** @internal */\nexport function _replaceVersion<R extends Record<string, Any>>(\n config: InitializedClientConfig,\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(config, httpRequest, replaceVersionAction, options)\n}\n\n/** @internal */\nexport function _unpublishVersion(\n config: InitializedClientConfig,\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(config, httpRequest, unpublishVersionAction, options)\n}\n\n/** @internal */\nexport function _mutate<R extends Record<string, Any>>(\n config: InitializedClientConfig,\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(config, httpRequest, 'mutate', {mutations: muts, transactionId}, options)\n}\n\n/**\n * @internal\n */\nexport function _action(\n config: InitializedClientConfig,\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 config,\n httpRequest,\n 'actions',\n {actions: acts, transactionId, skipCrossDatasetReferenceValidation, dryRun},\n options,\n )\n}\n\n/**\n * @internal\n */\nexport function _dataRequest(\n config: InitializedClientConfig,\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 const isEmulate = endpoint === 'emulate'\n\n // Check if the query string is within a configured threshold,\n // in which case we can use GET. Otherwise, use POST.\n // Emulate endpoint always uses POST\n const strQuery = isMutation || isAction || isEmulate ? '' : encodeQueryString(body)\n const useGet = !isMutation && !isAction && !isEmulate && 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(config, 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(config, 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 config: InitializedClientConfig,\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(config, httpRequest, 'mutate', {mutations: [mutation]}, opts)\n}\n\nconst hasDataConfig = (config: InitializedClientConfig) =>\n (config.dataset !== undefined && config.projectId !== undefined) ||\n config['~experimental_resource'] !== undefined\n\nconst isQuery = (config: InitializedClientConfig, uri: string) =>\n hasDataConfig(config) && uri.startsWith(_getDataUrl(config, 'query'))\n\nconst isViewQuery = (config: InitializedClientConfig, uri: string) =>\n hasDataConfig(config) && uri.startsWith(_getDataUrl(config, 'views'))\n\nconst isEmulate = (config: InitializedClientConfig, uri: string) =>\n hasDataConfig(config) && uri.startsWith(_getDataUrl(config, 'emulate'))\n\nconst isMutate = (config: InitializedClientConfig, uri: string) =>\n hasDataConfig(config) && uri.startsWith(_getDataUrl(config, 'mutate'))\n\nconst isDoc = (config: InitializedClientConfig, uri: string) =>\n hasDataConfig(config) && uri.startsWith(_getDataUrl(config, 'doc', ''))\n\nconst isListener = (config: InitializedClientConfig, uri: string) =>\n hasDataConfig(config) && uri.startsWith(_getDataUrl(config, 'listen'))\n\nconst isHistory = (config: InitializedClientConfig, uri: string) =>\n hasDataConfig(config) && uri.startsWith(_getDataUrl(config, 'history', ''))\n\nconst isData = (config: InitializedClientConfig, uri: string) =>\n uri.startsWith('/data/') ||\n isQuery(config, uri) ||\n isMutate(config, uri) ||\n isDoc(config, uri) ||\n isListener(config, uri) ||\n isHistory(config, uri) ||\n isViewQuery(config, uri) ||\n isEmulate(config, uri)\n\n/**\n * @internal\n */\nexport function _requestObservable<R>(\n config: InitializedClientConfig,\n httpRequest: HttpRequest,\n options: RequestObservableOptions,\n): Observable<HttpRequestEvent<R>> {\n const uri = options.url || (options.uri as string)\n\n // If the `canUseCdn`-option is not set we detect it automatically based on the method + URL.\n // The /data endpoint and view query endpoints are available through API-CDN.\n const canUseCdn =\n typeof options.canUseCdn === 'undefined'\n ? ['GET', 'HEAD'].indexOf(options.method || 'GET') >= 0 && isData(config, uri)\n : options.canUseCdn\n\n let useCdn = (options.useCdn ?? config.useCdn) && canUseCdn\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 (applies to both query and emulate endpoints)\n if (\n ['GET', 'HEAD', 'POST'].indexOf(options.method || 'GET') >= 0 &&\n (isQuery(config, uri) || isEmulate(config, uri))\n ) {\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(config, 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>(\n config: InitializedClientConfig,\n httpRequest: HttpRequest,\n options: Any,\n): Observable<R> {\n const observable = _requestObservable<R>(config, 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(\n config: InitializedClientConfig,\n operation: string,\n path?: string,\n): string {\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(config: InitializedClientConfig, uri: string, canUseCdn = false): string {\n const {url, cdnUrl} = 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 case 'view': {\n return `/views/${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"],"names":["location","isQuery","validators.validateObject","validators.requireDocumentId","validators.validateDocumentId","validators.requireDocumentType","isEmulate","validate.requestTag","validators.resourceConfig","uri","validators.hasDataset"],"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,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AA,UAAU,OAAO,SAAS;AACtB,YAAA;AACN;AAAA,IAAA;AAEI,UAAA,eAAe,MAAM,UAAU,QAAQ;AAC7C,WAAA,OAAO,iBAAiB,SAAS,KAAK,GAC/B,MAAM;AACX,aAAO,oBAAoB,SAAS,KAAK,GACzC,aAAa,YAAY;AAAA,IAC3B;AAAA,EAAA,CACD;AAEL;AAGA,MAAM,0BAA0B,EAAQ,WAAW;AAQnD,SAAS,kBAAkB,QAAsB;AAK3C,MAAA;AACF,WAAO,IAAI,aAAa,QAAQ,UAAU,8BAA8B,YAAY;AAItF,QAAM,QAAQ,IAAI,MAAM,QAAQ,UAAU,4BAA4B;AACtE,SAAA,MAAM,OAAO,cAEN;AACT;AAEA,MAAM,mBAAmB,CAAC,WAA4C;AAChE,MAAA,CAAC,OAAO,wBAAwB;AAC5B,UAAA,IAAI,MAAM,yDAAyD;AAE3E,QAAM,EAAC,MAAM,OAAM,OAAO,wBAAwB;AAElD,UAAQ,MAAM;AAAA,IACZ,KAAK,WAAW;AACR,YAAA,WAAW,GAAG,MAAM,GAAG;AAC7B,UAAI,SAAS,WAAW;AAChB,cAAA,IAAI,MAAM,oDAAoD;AAEtE,aAAO,aAAa,SAAS,CAAC,CAAC,aAAa,SAAS,CAAC,CAAC;AAAA,IAAA;AAAA,IAEzD,KAAK;AACH,aAAO,aAAa,EAAE;AAAA,IAExB,KAAK;AACH,aAAO,oBAAoB,EAAE;AAAA,IAE/B,KAAK;AACH,aAAO,eAAe,EAAE;AAAA,IAE1B,KAAK;AACH,aAAO,UAAU,EAAE;AAAA,IAErB;AAEE,YAAM,IAAI,MAAM,8BAA8B,KAAK,SAAU,CAAA,EAAE;AAAA,EAAA;AAErE;"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"isRecord.js","sources":["../../src/util/isRecord.ts"],"sourcesContent":["/** @internal */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n"],"names":[],"mappings":"AACO,SAAS,SAAS,OAAkD;AAClE,SAAA,OAAO,SAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { isRecord } from "./isRecord.js";
|
|
1
2
|
const rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g, reKeySegment = /_key\s*==\s*['"](.*)['"]/, reIndexTuple = /^\d*:\d*$/;
|
|
2
3
|
function isIndexSegment(segment) {
|
|
3
4
|
return typeof segment == "number" || typeof segment == "string" && /^\[\d+\]$/.test(segment);
|
|
@@ -212,9 +213,6 @@ function resolveMapping(resultPath, csm) {
|
|
|
212
213
|
function isArray(value) {
|
|
213
214
|
return value !== null && Array.isArray(value);
|
|
214
215
|
}
|
|
215
|
-
function isRecord(value) {
|
|
216
|
-
return typeof value == "object" && value !== null;
|
|
217
|
-
}
|
|
218
216
|
function walkMap(value, mappingFn, path = []) {
|
|
219
217
|
if (isArray(value))
|
|
220
218
|
return value.map((v, idx) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolveEditInfo.js","sources":["../../src/csm/studioPath.ts","../../src/csm/draftUtils.ts","../../src/csm/jsonPath.ts","../../src/csm/resolveMapping.ts","../../src/csm/isArray.ts","../../src/csm/isRecord.ts","../../src/csm/walkMap.ts","../../src/csm/createEditUrl.ts","../../src/csm/resolveEditInfo.ts"],"sourcesContent":["/** @alpha */\nexport type KeyedSegment = {_key: string}\n\n/** @alpha */\nexport type IndexTuple = [number | '', number | '']\n\n/** @alpha */\nexport type PathSegment = string | number | KeyedSegment | IndexTuple\n\n/** @alpha */\nexport type Path = PathSegment[]\n\nconst rePropName =\n /[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))/g\n/** @internal */\nexport const reKeySegment = /_key\\s*==\\s*['\"](.*)['\"]/\nconst reIndexTuple = /^\\d*:\\d*$/\n\n/** @internal */\nexport function isIndexSegment(segment: PathSegment): segment is number {\n return typeof segment === 'number' || (typeof segment === 'string' && /^\\[\\d+\\]$/.test(segment))\n}\n\n/** @internal */\nexport function isKeySegment(segment: PathSegment): segment is KeyedSegment {\n if (typeof segment === 'string') {\n return reKeySegment.test(segment.trim())\n }\n\n return typeof segment === 'object' && '_key' in segment\n}\n\n/** @internal */\nexport function isIndexTuple(segment: PathSegment): segment is IndexTuple {\n if (typeof segment === 'string' && reIndexTuple.test(segment)) {\n return true\n }\n\n if (!Array.isArray(segment) || segment.length !== 2) {\n return false\n }\n\n const [from, to] = segment\n return (typeof from === 'number' || from === '') && (typeof to === 'number' || to === '')\n}\n\n/** @internal */\nexport function get<Result = unknown, Fallback = unknown>(\n obj: unknown,\n path: Path | string,\n defaultVal?: Fallback,\n): Result | typeof defaultVal {\n const select = typeof path === 'string' ? fromString(path) : path\n if (!Array.isArray(select)) {\n throw new Error('Path must be an array or a string')\n }\n\n let acc: unknown | undefined = obj\n for (let i = 0; i < select.length; i++) {\n const segment = select[i]\n if (isIndexSegment(segment)) {\n if (!Array.isArray(acc)) {\n return defaultVal\n }\n\n acc = acc[segment]\n }\n\n if (isKeySegment(segment)) {\n if (!Array.isArray(acc)) {\n return defaultVal\n }\n\n acc = acc.find((item) => item._key === segment._key)\n }\n\n if (typeof segment === 'string') {\n acc =\n typeof acc === 'object' && acc !== null\n ? ((acc as Record<string, unknown>)[segment] as Result)\n : undefined\n }\n\n if (typeof acc === 'undefined') {\n return defaultVal\n }\n }\n\n return acc as Result\n}\n\n/** @alpha */\nexport function toString(path: Path): string {\n if (!Array.isArray(path)) {\n throw new Error('Path is not an array')\n }\n\n return path.reduce<string>((target, segment, i) => {\n const segmentType = typeof segment\n if (segmentType === 'number') {\n return `${target}[${segment}]`\n }\n\n if (segmentType === 'string') {\n const separator = i === 0 ? '' : '.'\n return `${target}${separator}${segment}`\n }\n\n if (isKeySegment(segment) && segment._key) {\n return `${target}[_key==\"${segment._key}\"]`\n }\n\n if (Array.isArray(segment)) {\n const [from, to] = segment\n return `${target}[${from}:${to}]`\n }\n\n throw new Error(`Unsupported path segment \\`${JSON.stringify(segment)}\\``)\n }, '')\n}\n\n/** @alpha */\nexport function fromString(path: string): Path {\n if (typeof path !== 'string') {\n throw new Error('Path is not a string')\n }\n\n const segments = path.match(rePropName)\n if (!segments) {\n throw new Error('Invalid path string')\n }\n\n return segments.map(parsePathSegment)\n}\n\nfunction parsePathSegment(segment: string): PathSegment {\n if (isIndexSegment(segment)) {\n return parseIndexSegment(segment)\n }\n\n if (isKeySegment(segment)) {\n return parseKeySegment(segment)\n }\n\n if (isIndexTuple(segment)) {\n return parseIndexTupleSegment(segment)\n }\n\n return segment\n}\n\nfunction parseIndexSegment(segment: string): PathSegment {\n return Number(segment.replace(/[^\\d]/g, ''))\n}\n\nfunction parseKeySegment(segment: string): KeyedSegment {\n const segments = segment.match(reKeySegment)\n return {_key: segments![1]}\n}\n\nfunction parseIndexTupleSegment(segment: string): IndexTuple {\n const [from, to] = segment.split(':').map((seg) => (seg === '' ? seg : Number(seg)))\n return [from, to]\n}\n","// nominal/opaque type hack\ntype Opaque<T, K> = T & {__opaqueId__: K}\n\n/** @internal */\nexport type DraftId = Opaque<string, 'draftId'>\n\n/** @internal */\nexport type PublishedId = Opaque<string, 'publishedId'>\n\n/** @internal */\nexport const DRAFTS_FOLDER = 'drafts'\n\n/** @internal */\nexport const VERSION_FOLDER = 'versions'\n\nconst PATH_SEPARATOR = '.'\nconst DRAFTS_PREFIX = `${DRAFTS_FOLDER}${PATH_SEPARATOR}`\nconst VERSION_PREFIX = `${VERSION_FOLDER}${PATH_SEPARATOR}`\n\n/** @internal */\nexport function isDraftId(id: string): id is DraftId {\n return id.startsWith(DRAFTS_PREFIX)\n}\n\n/** @internal */\nexport function isVersionId(id: string): boolean {\n return id.startsWith(VERSION_PREFIX)\n}\n\n/** @internal */\nexport function isPublishedId(id: string): id is PublishedId {\n return !isDraftId(id) && !isVersionId(id)\n}\n\n/** @internal */\nexport function getDraftId(id: string): DraftId {\n if (isVersionId(id)) {\n const publishedId = getPublishedId(id)\n return (DRAFTS_PREFIX + publishedId) as DraftId\n }\n\n return isDraftId(id) ? id : ((DRAFTS_PREFIX + id) as DraftId)\n}\n\n/** @internal */\nexport function getVersionId(id: string, version: string): string {\n if (version === 'drafts' || version === 'published') {\n throw new Error('Version can not be \"published\" or \"drafts\"')\n }\n\n return `${VERSION_PREFIX}${version}${PATH_SEPARATOR}${getPublishedId(id)}`\n}\n\n/**\n * @internal\n * Given an id, returns the versionId if it exists.\n * e.g. `versions.summer-drop.foo` = `summer-drop`\n * e.g. `drafts.foo` = `undefined`\n * e.g. `foo` = `undefined`\n */\nexport function getVersionFromId(id: string): string | undefined {\n if (!isVersionId(id)) return undefined\n // eslint-disable-next-line unused-imports/no-unused-vars\n const [_versionPrefix, versionId, ..._publishedId] = id.split(PATH_SEPARATOR)\n\n return versionId\n}\n\n/** @internal */\nexport function getPublishedId(id: string): PublishedId {\n if (isVersionId(id)) {\n // make sure to only remove the versions prefix and the bundle name\n return id.split(PATH_SEPARATOR).slice(2).join(PATH_SEPARATOR) as PublishedId as PublishedId\n }\n\n if (isDraftId(id)) {\n return id.slice(DRAFTS_PREFIX.length) as PublishedId\n }\n\n return id as PublishedId\n}\n","import * as studioPath from './studioPath'\nimport type {\n ContentSourceMapParsedPath,\n ContentSourceMapParsedPathKeyedSegment,\n ContentSourceMapPaths,\n Path,\n} from './types'\n\nconst ESCAPE: Record<string, string> = {\n '\\f': '\\\\f',\n '\\n': '\\\\n',\n '\\r': '\\\\r',\n '\\t': '\\\\t',\n \"'\": \"\\\\'\",\n '\\\\': '\\\\\\\\',\n}\n\nconst UNESCAPE: Record<string, string> = {\n '\\\\f': '\\f',\n '\\\\n': '\\n',\n '\\\\r': '\\r',\n '\\\\t': '\\t',\n \"\\\\'\": \"'\",\n '\\\\\\\\': '\\\\',\n}\n\n/**\n * @internal\n */\nexport function jsonPath(path: ContentSourceMapParsedPath): ContentSourceMapPaths[number] {\n return `$${path\n .map((segment) => {\n if (typeof segment === 'string') {\n const escapedKey = segment.replace(/[\\f\\n\\r\\t'\\\\]/g, (match) => {\n return ESCAPE[match]\n })\n return `['${escapedKey}']`\n }\n\n if (typeof segment === 'number') {\n return `[${segment}]`\n }\n\n if (segment._key !== '') {\n const escapedKey = segment._key.replace(/['\\\\]/g, (match) => {\n return ESCAPE[match]\n })\n return `[?(@._key=='${escapedKey}')]`\n }\n\n return `[${segment._index}]`\n })\n .join('')}`\n}\n\n/**\n * @internal\n */\nexport function parseJsonPath(path: ContentSourceMapPaths[number]): ContentSourceMapParsedPath {\n const parsed: ContentSourceMapParsedPath = []\n\n const parseRe = /\\['(.*?)'\\]|\\[(\\d+)\\]|\\[\\?\\(@\\._key=='(.*?)'\\)\\]/g\n let match: RegExpExecArray | null\n\n while ((match = parseRe.exec(path)) !== null) {\n if (match[1] !== undefined) {\n const key = match[1].replace(/\\\\(\\\\|f|n|r|t|')/g, (m) => {\n return UNESCAPE[m]\n })\n\n parsed.push(key)\n continue\n }\n\n if (match[2] !== undefined) {\n parsed.push(parseInt(match[2], 10))\n continue\n }\n\n if (match[3] !== undefined) {\n const _key = match[3].replace(/\\\\(\\\\')/g, (m) => {\n return UNESCAPE[m]\n })\n\n parsed.push({\n _key,\n _index: -1,\n })\n continue\n }\n }\n\n return parsed\n}\n\n/**\n * @internal\n */\nexport function jsonPathToStudioPath(path: ContentSourceMapParsedPath): Path {\n return path.map((segment) => {\n if (typeof segment === 'string') {\n return segment\n }\n\n if (typeof segment === 'number') {\n return segment\n }\n\n if (segment._key !== '') {\n return {_key: segment._key}\n }\n\n if (segment._index !== -1) {\n return segment._index\n }\n\n throw new Error(`invalid segment:${JSON.stringify(segment)}`)\n })\n}\n\n/**\n * @internal\n */\nexport function studioPathToJsonPath(path: Path | string): ContentSourceMapParsedPath {\n const parsedPath = typeof path === 'string' ? studioPath.fromString(path) : path\n\n return parsedPath.map((segment) => {\n if (typeof segment === 'string') {\n return segment\n }\n\n if (typeof segment === 'number') {\n return segment\n }\n\n if (Array.isArray(segment)) {\n throw new Error(`IndexTuple segments aren't supported:${JSON.stringify(segment)}`)\n }\n\n if (isContentSourceMapParsedPathKeyedSegment(segment)) {\n return segment\n }\n\n if (segment._key) {\n return {_key: segment._key, _index: -1}\n }\n\n throw new Error(`invalid segment:${JSON.stringify(segment)}`)\n })\n}\n\nfunction isContentSourceMapParsedPathKeyedSegment(\n segment: studioPath.PathSegment | ContentSourceMapParsedPath[number],\n): segment is ContentSourceMapParsedPathKeyedSegment {\n return typeof segment === 'object' && '_key' in segment && '_index' in segment\n}\n\n/**\n * @internal\n */\nexport function jsonPathToMappingPath(path: ContentSourceMapParsedPath): (string | number)[] {\n return path.map((segment) => {\n if (typeof segment === 'string') {\n return segment\n }\n\n if (typeof segment === 'number') {\n return segment\n }\n\n if (segment._index !== -1) {\n return segment._index\n }\n\n throw new Error(`invalid segment:${JSON.stringify(segment)}`)\n })\n}\n","import {jsonPath, jsonPathToMappingPath} from './jsonPath'\nimport type {ContentSourceMap, ContentSourceMapMapping, ContentSourceMapParsedPath} from './types'\n\n/**\n * @internal\n */\nexport function resolveMapping(\n resultPath: ContentSourceMapParsedPath,\n csm?: ContentSourceMap,\n):\n | {\n mapping: ContentSourceMapMapping\n matchedPath: string\n pathSuffix: string\n }\n | undefined {\n if (!csm?.mappings) {\n return undefined\n }\n const resultMappingPath = jsonPath(jsonPathToMappingPath(resultPath))\n\n if (csm.mappings[resultMappingPath] !== undefined) {\n return {\n mapping: csm.mappings[resultMappingPath],\n matchedPath: resultMappingPath,\n pathSuffix: '',\n }\n }\n\n const mappings = Object.entries(csm.mappings)\n .filter(([key]) => resultMappingPath.startsWith(key))\n .sort(([key1], [key2]) => key2.length - key1.length)\n\n if (mappings.length == 0) {\n return undefined\n }\n\n const [matchedPath, mapping] = mappings[0]\n const pathSuffix = resultMappingPath.substring(matchedPath.length)\n return {mapping, matchedPath, pathSuffix}\n}\n","/** @internal */\nexport function isArray(value: unknown): value is Array<unknown> {\n return value !== null && Array.isArray(value)\n}\n","/** @internal */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null\n}\n","import {isArray} from './isArray'\nimport {isRecord} from './isRecord'\nimport type {ContentSourceMapParsedPath, WalkMapFn} from './types'\n\n/**\n * generic way to walk a nested object or array and apply a mapping function to each value\n * @internal\n */\nexport function walkMap(\n value: unknown,\n mappingFn: WalkMapFn,\n path: ContentSourceMapParsedPath = [],\n): unknown {\n if (isArray(value)) {\n return value.map((v, idx) => {\n if (isRecord(v)) {\n const _key = v['_key']\n if (typeof _key === 'string') {\n return walkMap(v, mappingFn, path.concat({_key, _index: idx}))\n }\n }\n\n return walkMap(v, mappingFn, path.concat(idx))\n })\n }\n\n if (isRecord(value)) {\n // Handle Portable Text in a faster way\n if (value._type === 'block' || value._type === 'span') {\n const result = {...value}\n if (value._type === 'block') {\n result.children = walkMap(value.children, mappingFn, path.concat('children'))\n } else if (value._type === 'span') {\n result.text = walkMap(value.text, mappingFn, path.concat('text'))\n }\n return result\n }\n\n return Object.fromEntries(\n Object.entries(value).map(([k, v]) => [k, walkMap(v, mappingFn, path.concat(k))]),\n )\n }\n\n return mappingFn(value, path)\n}\n","import {getPublishedId, getVersionFromId, isPublishedId, isVersionId} from './draftUtils'\nimport {jsonPathToStudioPath} from './jsonPath'\nimport * as studioPath from './studioPath'\nimport type {CreateEditUrlOptions, EditIntentUrl, StudioBaseUrl} from './types'\n\n/** @internal */\nexport function createEditUrl(options: CreateEditUrlOptions): `${StudioBaseUrl}${EditIntentUrl}` {\n const {\n baseUrl,\n workspace: _workspace = 'default',\n tool: _tool = 'default',\n id: _id,\n type,\n path,\n projectId,\n dataset,\n } = options\n\n if (!baseUrl) {\n throw new Error('baseUrl is required')\n }\n if (!path) {\n throw new Error('path is required')\n }\n if (!_id) {\n throw new Error('id is required')\n }\n if (baseUrl !== '/' && baseUrl.endsWith('/')) {\n throw new Error('baseUrl must not end with a slash')\n }\n\n const workspace = _workspace === 'default' ? undefined : _workspace\n const tool = _tool === 'default' ? undefined : _tool\n const id = getPublishedId(_id)\n const stringifiedPath = Array.isArray(path)\n ? studioPath.toString(jsonPathToStudioPath(path))\n : path\n\n // eslint-disable-next-line no-warning-comments\n // @TODO Using searchParams as a temporary workaround until `@sanity/overlays` can decode state from the path reliably\n const searchParams = new URLSearchParams({\n baseUrl,\n id,\n type,\n path: stringifiedPath,\n })\n if (workspace) {\n searchParams.set('workspace', workspace)\n }\n if (tool) {\n searchParams.set('tool', tool)\n }\n if (projectId) {\n searchParams.set('projectId', projectId)\n }\n if (dataset) {\n searchParams.set('dataset', dataset)\n }\n if (isPublishedId(_id)) {\n searchParams.set('perspective', 'published')\n } else if (isVersionId(_id)) {\n const versionId = getVersionFromId(_id)!\n searchParams.set('perspective', versionId)\n }\n\n const segments = [baseUrl === '/' ? '' : baseUrl]\n if (workspace) {\n segments.push(workspace)\n }\n const routerParams = [\n 'mode=presentation',\n `id=${id}`,\n `type=${type}`,\n `path=${encodeURIComponent(stringifiedPath)}`,\n ]\n if (tool) {\n routerParams.push(`tool=${tool}`)\n }\n segments.push('intent', 'edit', `${routerParams.join(';')}?${searchParams}`)\n return segments.join('/') as unknown as `${StudioBaseUrl}${EditIntentUrl}`\n}\n","import {parseJsonPath} from './jsonPath'\nimport {resolveMapping} from './resolveMapping'\nimport type {\n CreateEditUrlOptions,\n ResolveEditInfoOptions,\n StudioBaseRoute,\n StudioBaseUrl,\n StudioUrl,\n} from './types'\n\n/** @internal */\nexport function resolveEditInfo(options: ResolveEditInfoOptions): CreateEditUrlOptions | undefined {\n const {resultSourceMap: csm, resultPath} = options\n const {mapping, pathSuffix} = resolveMapping(resultPath, csm) || {}\n\n if (!mapping) {\n // console.warn('no mapping for path', { path: resultPath, sourceMap: csm })\n return undefined\n }\n\n if (mapping.source.type === 'literal') {\n return undefined\n }\n\n if (mapping.source.type === 'unknown') {\n return undefined\n }\n\n const sourceDoc = csm.documents[mapping.source.document]\n const sourcePath = csm.paths[mapping.source.path]\n\n if (sourceDoc && sourcePath) {\n const {baseUrl, workspace, tool} = resolveStudioBaseRoute(\n typeof options.studioUrl === 'function' ? options.studioUrl(sourceDoc) : options.studioUrl,\n )\n if (!baseUrl) return undefined\n const {_id, _type, _projectId, _dataset} = sourceDoc\n return {\n baseUrl,\n workspace,\n tool,\n id: _id,\n type: _type,\n path: parseJsonPath(sourcePath + pathSuffix),\n projectId: _projectId,\n dataset: _dataset,\n } satisfies CreateEditUrlOptions\n }\n\n return undefined\n}\n\n/** @internal */\nexport function resolveStudioBaseRoute(studioUrl: StudioUrl): StudioBaseRoute {\n let baseUrl: StudioBaseUrl = typeof studioUrl === 'string' ? studioUrl : studioUrl.baseUrl\n if (baseUrl !== '/') {\n baseUrl = baseUrl.replace(/\\/$/, '')\n }\n if (typeof studioUrl === 'string') {\n return {baseUrl}\n }\n return {...studioUrl, baseUrl}\n}\n"],"names":["studioPath.fromString","studioPath.toString"],"mappings":"AAYA,MAAM,aACJ,oGAEW,eAAe,4BACtB,eAAe;AAGd,SAAS,eAAe,SAAyC;AAC/D,SAAA,OAAO,WAAY,YAAa,OAAO,WAAY,YAAY,YAAY,KAAK,OAAO;AAChG;AAGO,SAAS,aAAa,SAA+C;AAC1E,SAAI,OAAO,WAAY,WACd,aAAa,KAAK,QAAQ,KAAK,CAAC,IAGlC,OAAO,WAAY,YAAY,UAAU;AAClD;AAGO,SAAS,aAAa,SAA6C;AACxE,MAAI,OAAO,WAAY,YAAY,aAAa,KAAK,OAAO;AACnD,WAAA;AAGT,MAAI,CAAC,MAAM,QAAQ,OAAO,KAAK,QAAQ,WAAW;AACzC,WAAA;AAGH,QAAA,CAAC,MAAM,EAAE,IAAI;AACX,UAAA,OAAO,QAA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,GACjD,aAAa,IAAI,MAAM,QAAQ,OAAO,IAAI;AAEhD,MAAI,aAAa,YAAY;AAC3B,UAAM,EAAC,SAAS,WAAW,KAAQ,IAAA;AAAA,MACjC,OAAO,QAAQ,aAAc,aAAa,QAAQ,UAAU,SAAS,IAAI,QAAQ;AAAA,IACnF;AACA,QAAI,CAAC,QAAS;AACd,UAAM,EAAC,KAAK,OAAO,YAAY,SAAY,IAAA;AACpC,WAAA;AAAA,MACL;AAAA,MACA;AAAA,MACA;AAAA,MACA,IAAI;AAAA,MACJ,MAAM;AAAA,MACN,MAAM,cAAc,aAAa,UAAU;AAAA,MAC3C,WAAW;AAAA,MACX,SAAS;AAAA,IACX;AAAA,EAAA;AAIJ;AAGO,SAAS,uBAAuB,WAAuC;AAC5E,MAAI,UAAyB,OAAO,aAAc,WAAW,YAAY,UAAU;AAInF,SAHI,YAAY,QACd,UAAU,QAAQ,QAAQ,OAAO,EAAE,IAEjC,OAAO,aAAc,WAChB,EAAC,YAEH,EAAC,GAAG,WAAW,QAAO;AAC/B;"}
|
|
1
|
+
{"version":3,"file":"resolveEditInfo.js","sources":["../../src/csm/studioPath.ts","../../src/csm/draftUtils.ts","../../src/csm/jsonPath.ts","../../src/csm/resolveMapping.ts","../../src/csm/isArray.ts","../../src/csm/walkMap.ts","../../src/csm/createEditUrl.ts","../../src/csm/resolveEditInfo.ts"],"sourcesContent":["/** @alpha */\nexport type KeyedSegment = {_key: string}\n\n/** @alpha */\nexport type IndexTuple = [number | '', number | '']\n\n/** @alpha */\nexport type PathSegment = string | number | KeyedSegment | IndexTuple\n\n/** @alpha */\nexport type Path = PathSegment[]\n\nconst rePropName =\n /[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))/g\n/** @internal */\nexport const reKeySegment = /_key\\s*==\\s*['\"](.*)['\"]/\nconst reIndexTuple = /^\\d*:\\d*$/\n\n/** @internal */\nexport function isIndexSegment(segment: PathSegment): segment is number {\n return typeof segment === 'number' || (typeof segment === 'string' && /^\\[\\d+\\]$/.test(segment))\n}\n\n/** @internal */\nexport function isKeySegment(segment: PathSegment): segment is KeyedSegment {\n if (typeof segment === 'string') {\n return reKeySegment.test(segment.trim())\n }\n\n return typeof segment === 'object' && '_key' in segment\n}\n\n/** @internal */\nexport function isIndexTuple(segment: PathSegment): segment is IndexTuple {\n if (typeof segment === 'string' && reIndexTuple.test(segment)) {\n return true\n }\n\n if (!Array.isArray(segment) || segment.length !== 2) {\n return false\n }\n\n const [from, to] = segment\n return (typeof from === 'number' || from === '') && (typeof to === 'number' || to === '')\n}\n\n/** @internal */\nexport function get<Result = unknown, Fallback = unknown>(\n obj: unknown,\n path: Path | string,\n defaultVal?: Fallback,\n): Result | typeof defaultVal {\n const select = typeof path === 'string' ? fromString(path) : path\n if (!Array.isArray(select)) {\n throw new Error('Path must be an array or a string')\n }\n\n let acc: unknown | undefined = obj\n for (let i = 0; i < select.length; i++) {\n const segment = select[i]\n if (isIndexSegment(segment)) {\n if (!Array.isArray(acc)) {\n return defaultVal\n }\n\n acc = acc[segment]\n }\n\n if (isKeySegment(segment)) {\n if (!Array.isArray(acc)) {\n return defaultVal\n }\n\n acc = acc.find((item) => item._key === segment._key)\n }\n\n if (typeof segment === 'string') {\n acc =\n typeof acc === 'object' && acc !== null\n ? ((acc as Record<string, unknown>)[segment] as Result)\n : undefined\n }\n\n if (typeof acc === 'undefined') {\n return defaultVal\n }\n }\n\n return acc as Result\n}\n\n/** @alpha */\nexport function toString(path: Path): string {\n if (!Array.isArray(path)) {\n throw new Error('Path is not an array')\n }\n\n return path.reduce<string>((target, segment, i) => {\n const segmentType = typeof segment\n if (segmentType === 'number') {\n return `${target}[${segment}]`\n }\n\n if (segmentType === 'string') {\n const separator = i === 0 ? '' : '.'\n return `${target}${separator}${segment}`\n }\n\n if (isKeySegment(segment) && segment._key) {\n return `${target}[_key==\"${segment._key}\"]`\n }\n\n if (Array.isArray(segment)) {\n const [from, to] = segment\n return `${target}[${from}:${to}]`\n }\n\n throw new Error(`Unsupported path segment \\`${JSON.stringify(segment)}\\``)\n }, '')\n}\n\n/** @alpha */\nexport function fromString(path: string): Path {\n if (typeof path !== 'string') {\n throw new Error('Path is not a string')\n }\n\n const segments = path.match(rePropName)\n if (!segments) {\n throw new Error('Invalid path string')\n }\n\n return segments.map(parsePathSegment)\n}\n\nfunction parsePathSegment(segment: string): PathSegment {\n if (isIndexSegment(segment)) {\n return parseIndexSegment(segment)\n }\n\n if (isKeySegment(segment)) {\n return parseKeySegment(segment)\n }\n\n if (isIndexTuple(segment)) {\n return parseIndexTupleSegment(segment)\n }\n\n return segment\n}\n\nfunction parseIndexSegment(segment: string): PathSegment {\n return Number(segment.replace(/[^\\d]/g, ''))\n}\n\nfunction parseKeySegment(segment: string): KeyedSegment {\n const segments = segment.match(reKeySegment)\n return {_key: segments![1]}\n}\n\nfunction parseIndexTupleSegment(segment: string): IndexTuple {\n const [from, to] = segment.split(':').map((seg) => (seg === '' ? seg : Number(seg)))\n return [from, to]\n}\n","// nominal/opaque type hack\ntype Opaque<T, K> = T & {__opaqueId__: K}\n\n/** @internal */\nexport type DraftId = Opaque<string, 'draftId'>\n\n/** @internal */\nexport type PublishedId = Opaque<string, 'publishedId'>\n\n/** @internal */\nexport const DRAFTS_FOLDER = 'drafts'\n\n/** @internal */\nexport const VERSION_FOLDER = 'versions'\n\nconst PATH_SEPARATOR = '.'\nconst DRAFTS_PREFIX = `${DRAFTS_FOLDER}${PATH_SEPARATOR}`\nconst VERSION_PREFIX = `${VERSION_FOLDER}${PATH_SEPARATOR}`\n\n/** @internal */\nexport function isDraftId(id: string): id is DraftId {\n return id.startsWith(DRAFTS_PREFIX)\n}\n\n/** @internal */\nexport function isVersionId(id: string): boolean {\n return id.startsWith(VERSION_PREFIX)\n}\n\n/** @internal */\nexport function isPublishedId(id: string): id is PublishedId {\n return !isDraftId(id) && !isVersionId(id)\n}\n\n/** @internal */\nexport function getDraftId(id: string): DraftId {\n if (isVersionId(id)) {\n const publishedId = getPublishedId(id)\n return (DRAFTS_PREFIX + publishedId) as DraftId\n }\n\n return isDraftId(id) ? id : ((DRAFTS_PREFIX + id) as DraftId)\n}\n\n/** @internal */\nexport function getVersionId(id: string, version: string): string {\n if (version === 'drafts' || version === 'published') {\n throw new Error('Version can not be \"published\" or \"drafts\"')\n }\n\n return `${VERSION_PREFIX}${version}${PATH_SEPARATOR}${getPublishedId(id)}`\n}\n\n/**\n * @internal\n * Given an id, returns the versionId if it exists.\n * e.g. `versions.summer-drop.foo` = `summer-drop`\n * e.g. `drafts.foo` = `undefined`\n * e.g. `foo` = `undefined`\n */\nexport function getVersionFromId(id: string): string | undefined {\n if (!isVersionId(id)) return undefined\n // eslint-disable-next-line unused-imports/no-unused-vars\n const [_versionPrefix, versionId, ..._publishedId] = id.split(PATH_SEPARATOR)\n\n return versionId\n}\n\n/** @internal */\nexport function getPublishedId(id: string): PublishedId {\n if (isVersionId(id)) {\n // make sure to only remove the versions prefix and the bundle name\n return id.split(PATH_SEPARATOR).slice(2).join(PATH_SEPARATOR) as PublishedId as PublishedId\n }\n\n if (isDraftId(id)) {\n return id.slice(DRAFTS_PREFIX.length) as PublishedId\n }\n\n return id as PublishedId\n}\n","import * as studioPath from './studioPath'\nimport type {\n ContentSourceMapParsedPath,\n ContentSourceMapParsedPathKeyedSegment,\n ContentSourceMapPaths,\n Path,\n} from './types'\n\nconst ESCAPE: Record<string, string> = {\n '\\f': '\\\\f',\n '\\n': '\\\\n',\n '\\r': '\\\\r',\n '\\t': '\\\\t',\n \"'\": \"\\\\'\",\n '\\\\': '\\\\\\\\',\n}\n\nconst UNESCAPE: Record<string, string> = {\n '\\\\f': '\\f',\n '\\\\n': '\\n',\n '\\\\r': '\\r',\n '\\\\t': '\\t',\n \"\\\\'\": \"'\",\n '\\\\\\\\': '\\\\',\n}\n\n/**\n * @internal\n */\nexport function jsonPath(path: ContentSourceMapParsedPath): ContentSourceMapPaths[number] {\n return `$${path\n .map((segment) => {\n if (typeof segment === 'string') {\n const escapedKey = segment.replace(/[\\f\\n\\r\\t'\\\\]/g, (match) => {\n return ESCAPE[match]\n })\n return `['${escapedKey}']`\n }\n\n if (typeof segment === 'number') {\n return `[${segment}]`\n }\n\n if (segment._key !== '') {\n const escapedKey = segment._key.replace(/['\\\\]/g, (match) => {\n return ESCAPE[match]\n })\n return `[?(@._key=='${escapedKey}')]`\n }\n\n return `[${segment._index}]`\n })\n .join('')}`\n}\n\n/**\n * @internal\n */\nexport function parseJsonPath(path: ContentSourceMapPaths[number]): ContentSourceMapParsedPath {\n const parsed: ContentSourceMapParsedPath = []\n\n const parseRe = /\\['(.*?)'\\]|\\[(\\d+)\\]|\\[\\?\\(@\\._key=='(.*?)'\\)\\]/g\n let match: RegExpExecArray | null\n\n while ((match = parseRe.exec(path)) !== null) {\n if (match[1] !== undefined) {\n const key = match[1].replace(/\\\\(\\\\|f|n|r|t|')/g, (m) => {\n return UNESCAPE[m]\n })\n\n parsed.push(key)\n continue\n }\n\n if (match[2] !== undefined) {\n parsed.push(parseInt(match[2], 10))\n continue\n }\n\n if (match[3] !== undefined) {\n const _key = match[3].replace(/\\\\(\\\\')/g, (m) => {\n return UNESCAPE[m]\n })\n\n parsed.push({\n _key,\n _index: -1,\n })\n continue\n }\n }\n\n return parsed\n}\n\n/**\n * @internal\n */\nexport function jsonPathToStudioPath(path: ContentSourceMapParsedPath): Path {\n return path.map((segment) => {\n if (typeof segment === 'string') {\n return segment\n }\n\n if (typeof segment === 'number') {\n return segment\n }\n\n if (segment._key !== '') {\n return {_key: segment._key}\n }\n\n if (segment._index !== -1) {\n return segment._index\n }\n\n throw new Error(`invalid segment:${JSON.stringify(segment)}`)\n })\n}\n\n/**\n * @internal\n */\nexport function studioPathToJsonPath(path: Path | string): ContentSourceMapParsedPath {\n const parsedPath = typeof path === 'string' ? studioPath.fromString(path) : path\n\n return parsedPath.map((segment) => {\n if (typeof segment === 'string') {\n return segment\n }\n\n if (typeof segment === 'number') {\n return segment\n }\n\n if (Array.isArray(segment)) {\n throw new Error(`IndexTuple segments aren't supported:${JSON.stringify(segment)}`)\n }\n\n if (isContentSourceMapParsedPathKeyedSegment(segment)) {\n return segment\n }\n\n if (segment._key) {\n return {_key: segment._key, _index: -1}\n }\n\n throw new Error(`invalid segment:${JSON.stringify(segment)}`)\n })\n}\n\nfunction isContentSourceMapParsedPathKeyedSegment(\n segment: studioPath.PathSegment | ContentSourceMapParsedPath[number],\n): segment is ContentSourceMapParsedPathKeyedSegment {\n return typeof segment === 'object' && '_key' in segment && '_index' in segment\n}\n\n/**\n * @internal\n */\nexport function jsonPathToMappingPath(path: ContentSourceMapParsedPath): (string | number)[] {\n return path.map((segment) => {\n if (typeof segment === 'string') {\n return segment\n }\n\n if (typeof segment === 'number') {\n return segment\n }\n\n if (segment._index !== -1) {\n return segment._index\n }\n\n throw new Error(`invalid segment:${JSON.stringify(segment)}`)\n })\n}\n","import {jsonPath, jsonPathToMappingPath} from './jsonPath'\nimport type {ContentSourceMap, ContentSourceMapMapping, ContentSourceMapParsedPath} from './types'\n\n/**\n * @internal\n */\nexport function resolveMapping(\n resultPath: ContentSourceMapParsedPath,\n csm?: ContentSourceMap,\n):\n | {\n mapping: ContentSourceMapMapping\n matchedPath: string\n pathSuffix: string\n }\n | undefined {\n if (!csm?.mappings) {\n return undefined\n }\n const resultMappingPath = jsonPath(jsonPathToMappingPath(resultPath))\n\n if (csm.mappings[resultMappingPath] !== undefined) {\n return {\n mapping: csm.mappings[resultMappingPath],\n matchedPath: resultMappingPath,\n pathSuffix: '',\n }\n }\n\n const mappings = Object.entries(csm.mappings)\n .filter(([key]) => resultMappingPath.startsWith(key))\n .sort(([key1], [key2]) => key2.length - key1.length)\n\n if (mappings.length == 0) {\n return undefined\n }\n\n const [matchedPath, mapping] = mappings[0]\n const pathSuffix = resultMappingPath.substring(matchedPath.length)\n return {mapping, matchedPath, pathSuffix}\n}\n","/** @internal */\nexport function isArray(value: unknown): value is Array<unknown> {\n return value !== null && Array.isArray(value)\n}\n","import {isRecord} from '../util/isRecord'\nimport {isArray} from './isArray'\nimport type {ContentSourceMapParsedPath, WalkMapFn} from './types'\n\n/**\n * generic way to walk a nested object or array and apply a mapping function to each value\n * @internal\n */\nexport function walkMap(\n value: unknown,\n mappingFn: WalkMapFn,\n path: ContentSourceMapParsedPath = [],\n): unknown {\n if (isArray(value)) {\n return value.map((v, idx) => {\n if (isRecord(v)) {\n const _key = v['_key']\n if (typeof _key === 'string') {\n return walkMap(v, mappingFn, path.concat({_key, _index: idx}))\n }\n }\n\n return walkMap(v, mappingFn, path.concat(idx))\n })\n }\n\n if (isRecord(value)) {\n // Handle Portable Text in a faster way\n if (value._type === 'block' || value._type === 'span') {\n const result = {...value}\n if (value._type === 'block') {\n result.children = walkMap(value.children, mappingFn, path.concat('children'))\n } else if (value._type === 'span') {\n result.text = walkMap(value.text, mappingFn, path.concat('text'))\n }\n return result\n }\n\n return Object.fromEntries(\n Object.entries(value).map(([k, v]) => [k, walkMap(v, mappingFn, path.concat(k))]),\n )\n }\n\n return mappingFn(value, path)\n}\n","import {getPublishedId, getVersionFromId, isPublishedId, isVersionId} from './draftUtils'\nimport {jsonPathToStudioPath} from './jsonPath'\nimport * as studioPath from './studioPath'\nimport type {CreateEditUrlOptions, EditIntentUrl, StudioBaseUrl} from './types'\n\n/** @internal */\nexport function createEditUrl(options: CreateEditUrlOptions): `${StudioBaseUrl}${EditIntentUrl}` {\n const {\n baseUrl,\n workspace: _workspace = 'default',\n tool: _tool = 'default',\n id: _id,\n type,\n path,\n projectId,\n dataset,\n } = options\n\n if (!baseUrl) {\n throw new Error('baseUrl is required')\n }\n if (!path) {\n throw new Error('path is required')\n }\n if (!_id) {\n throw new Error('id is required')\n }\n if (baseUrl !== '/' && baseUrl.endsWith('/')) {\n throw new Error('baseUrl must not end with a slash')\n }\n\n const workspace = _workspace === 'default' ? undefined : _workspace\n const tool = _tool === 'default' ? undefined : _tool\n const id = getPublishedId(_id)\n const stringifiedPath = Array.isArray(path)\n ? studioPath.toString(jsonPathToStudioPath(path))\n : path\n\n // eslint-disable-next-line no-warning-comments\n // @TODO Using searchParams as a temporary workaround until `@sanity/overlays` can decode state from the path reliably\n const searchParams = new URLSearchParams({\n baseUrl,\n id,\n type,\n path: stringifiedPath,\n })\n if (workspace) {\n searchParams.set('workspace', workspace)\n }\n if (tool) {\n searchParams.set('tool', tool)\n }\n if (projectId) {\n searchParams.set('projectId', projectId)\n }\n if (dataset) {\n searchParams.set('dataset', dataset)\n }\n if (isPublishedId(_id)) {\n searchParams.set('perspective', 'published')\n } else if (isVersionId(_id)) {\n const versionId = getVersionFromId(_id)!\n searchParams.set('perspective', versionId)\n }\n\n const segments = [baseUrl === '/' ? '' : baseUrl]\n if (workspace) {\n segments.push(workspace)\n }\n const routerParams = [\n 'mode=presentation',\n `id=${id}`,\n `type=${type}`,\n `path=${encodeURIComponent(stringifiedPath)}`,\n ]\n if (tool) {\n routerParams.push(`tool=${tool}`)\n }\n segments.push('intent', 'edit', `${routerParams.join(';')}?${searchParams}`)\n return segments.join('/') as unknown as `${StudioBaseUrl}${EditIntentUrl}`\n}\n","import {parseJsonPath} from './jsonPath'\nimport {resolveMapping} from './resolveMapping'\nimport type {\n CreateEditUrlOptions,\n ResolveEditInfoOptions,\n StudioBaseRoute,\n StudioBaseUrl,\n StudioUrl,\n} from './types'\n\n/** @internal */\nexport function resolveEditInfo(options: ResolveEditInfoOptions): CreateEditUrlOptions | undefined {\n const {resultSourceMap: csm, resultPath} = options\n const {mapping, pathSuffix} = resolveMapping(resultPath, csm) || {}\n\n if (!mapping) {\n // console.warn('no mapping for path', { path: resultPath, sourceMap: csm })\n return undefined\n }\n\n if (mapping.source.type === 'literal') {\n return undefined\n }\n\n if (mapping.source.type === 'unknown') {\n return undefined\n }\n\n const sourceDoc = csm.documents[mapping.source.document]\n const sourcePath = csm.paths[mapping.source.path]\n\n if (sourceDoc && sourcePath) {\n const {baseUrl, workspace, tool} = resolveStudioBaseRoute(\n typeof options.studioUrl === 'function' ? options.studioUrl(sourceDoc) : options.studioUrl,\n )\n if (!baseUrl) return undefined\n const {_id, _type, _projectId, _dataset} = sourceDoc\n return {\n baseUrl,\n workspace,\n tool,\n id: _id,\n type: _type,\n path: parseJsonPath(sourcePath + pathSuffix),\n projectId: _projectId,\n dataset: _dataset,\n } satisfies CreateEditUrlOptions\n }\n\n return undefined\n}\n\n/** @internal */\nexport function resolveStudioBaseRoute(studioUrl: StudioUrl): StudioBaseRoute {\n let baseUrl: StudioBaseUrl = typeof studioUrl === 'string' ? studioUrl : studioUrl.baseUrl\n if (baseUrl !== '/') {\n baseUrl = baseUrl.replace(/\\/$/, '')\n }\n if (typeof studioUrl === 'string') {\n return {baseUrl}\n }\n return {...studioUrl, baseUrl}\n}\n"],"names":["studioPath.fromString","studioPath.toString"],"mappings":";AAYA,MAAM,aACJ,oGAEW,eAAe,4BACtB,eAAe;AAGd,SAAS,eAAe,SAAyC;AAC/D,SAAA,OAAO,WAAY,YAAa,OAAO,WAAY,YAAY,YAAY,KAAK,OAAO;AAChG;AAGO,SAAS,aAAa,SAA+C;AAC1E,SAAI,OAAO,WAAY,WACd,aAAa,KAAK,QAAQ,KAAK,CAAC,IAGlC,OAAO,WAAY,YAAY,UAAU;AAClD;AAGO,SAAS,aAAa,SAA6C;AACxE,MAAI,OAAO,WAAY,YAAY,aAAa,KAAK,OAAO;AACnD,WAAA;AAGT,MAAI,CAAC,MAAM,QAAQ,OAAO,KAAK,QAAQ,WAAW;AACzC,WAAA;AAGH,QAAA,CAAC,MAAM,EAAE,IAAI;AACX,UAAA,OAAO,QAAS,YAAY,SAAS,QAAQ,OAAO,MAAO,YAAY,OAAO;AACxF;AAGgB,SAAA,IACd,KACA,MACA,YAC4B;AAC5B,QAAM,SAAS,OAAO,QAAS,WAAW,WAAW,IAAI,IAAI;AACzD,MAAA,CAAC,MAAM,QAAQ,MAA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