@sanity/client 6.22.3 → 6.22.4
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/dist/_chunks-cjs/stegaEncodeSourceMap.cjs +2 -1
- package/dist/_chunks-cjs/stegaEncodeSourceMap.cjs.map +1 -1
- package/dist/_chunks-es/stegaEncodeSourceMap.js +2 -1
- package/dist/_chunks-es/stegaEncodeSourceMap.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/package.json +2 -2
- package/src/stega/filterDefault.ts +3 -2
- package/umd/sanityClient.js +2 -1
- package/umd/sanityClient.min.js +2 -2
|
@@ -186,7 +186,7 @@ const filterDefault = ({ sourcePath, resultPath, value }) => {
|
|
|
186
186
|
if (isValidDate(value) || isValidURL(value))
|
|
187
187
|
return !1;
|
|
188
188
|
const endPath = sourcePath.at(-1);
|
|
189
|
-
return !(sourcePath.at(-2) === "slug" && endPath === "current" || typeof endPath == "string" && endPath.startsWith("_") || typeof endPath == "number" && sourcePath.at(-2) === "marks" || endPath === "href" && typeof sourcePath.at(-2) == "number" && sourcePath.at(-3) === "markDefs" || endPath === "style" || endPath === "listItem" || sourcePath.some(
|
|
189
|
+
return !(sourcePath.at(-2) === "slug" && endPath === "current" || typeof endPath == "string" && (endPath.startsWith("_") || endPath.endsWith("Id")) || typeof endPath == "number" && sourcePath.at(-2) === "marks" || endPath === "href" && typeof sourcePath.at(-2) == "number" && sourcePath.at(-3) === "markDefs" || endPath === "style" || endPath === "listItem" || sourcePath.some(
|
|
190
190
|
(path) => path === "meta" || path === "metadata" || path === "openGraph" || path === "seo"
|
|
191
191
|
) || hasTypeLike(sourcePath) || hasTypeLike(resultPath) || typeof endPath == "string" && denylist.has(endPath));
|
|
192
192
|
}, denylist = /* @__PURE__ */ new Set([
|
|
@@ -223,6 +223,7 @@ const filterDefault = ({ sourcePath, resultPath, value }) => {
|
|
|
223
223
|
"template",
|
|
224
224
|
"theme",
|
|
225
225
|
"type",
|
|
226
|
+
"textTheme",
|
|
226
227
|
"unit",
|
|
227
228
|
"url",
|
|
228
229
|
"username",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stegaEncodeSourceMap.cjs","sources":["../../src/csm/studioPath.ts","../../src/csm/jsonPath.ts","../../src/csm/resolveMapping.ts","../../src/csm/isArray.ts","../../src/csm/isRecord.ts","../../src/csm/walkMap.ts","../../src/stega/encodeIntoResult.ts","../../src/csm/getPublishedId.ts","../../src/csm/createEditUrl.ts","../../src/csm/resolveEditInfo.ts","../../src/stega/filterDefault.ts","../../src/stega/stegaEncodeSourceMap.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","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 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 type {ContentSourceMap} from '@sanity/client/csm'\n\nimport {parseJsonPath} from '../csm/jsonPath'\nimport {resolveMapping} from '../csm/resolveMapping'\nimport {walkMap} from '../csm/walkMap'\nimport type {Encoder} from './types'\n\n/**\n * @internal\n */\nexport function encodeIntoResult<Result>(\n result: Result,\n csm: ContentSourceMap,\n encoder: Encoder,\n): Result {\n return walkMap(result, (value, path) => {\n // Only map strings, we could extend this in the future to support other types like integers...\n if (typeof value !== 'string') {\n return value\n }\n\n const resolveMappingResult = resolveMapping(path, csm)\n if (!resolveMappingResult) {\n return value\n }\n\n const {mapping, matchedPath} = resolveMappingResult\n if (mapping.type !== 'value') {\n return value\n }\n\n if (mapping.source.type !== 'documentValue') {\n return value\n }\n\n const sourceDocument = csm.documents[mapping.source.document!]\n const sourcePath = csm.paths[mapping.source.path]\n\n const matchPathSegments = parseJsonPath(matchedPath)\n const sourcePathSegments = parseJsonPath(sourcePath)\n const fullSourceSegments = sourcePathSegments.concat(path.slice(matchPathSegments.length))\n\n return encoder({\n sourcePath: fullSourceSegments,\n sourceDocument,\n resultPath: path,\n value,\n })\n }) as Result\n}\n","export const DRAFTS_PREFIX = 'drafts.'\n\n/** @internal */\nexport function getPublishedId(id: string): string {\n if (id.startsWith(DRAFTS_PREFIX)) {\n return id.slice(DRAFTS_PREFIX.length)\n }\n\n return id\n}\n","import {DRAFTS_PREFIX, getPublishedId} from './getPublishedId'\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 (_id.startsWith(DRAFTS_PREFIX)) {\n searchParams.set('isDraft', '')\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","import type {ContentSourceMapParsedPath, FilterDefault} from './types'\n\nexport const filterDefault: FilterDefault = ({sourcePath, resultPath, value}) => {\n // Skips encoding on URL or Date strings, similar to the `skip: 'auto'` parameter in vercelStegaCombine()\n if (isValidDate(value) || isValidURL(value)) {\n return false\n }\n\n const endPath = sourcePath.at(-1)\n // Never encode slugs\n if (sourcePath.at(-2) === 'slug' && endPath === 'current') {\n return false\n }\n\n // Skip underscored keys, needs better heuristics but it works for now\n if (typeof endPath === 'string' && endPath.startsWith('_')) {\n return false\n }\n\n /**\n * Best effort infer Portable Text paths that should not be encoded.\n * Nothing is for certain, and the below implementation may cause paths that aren't Portable Text and otherwise be safe to encode to be skipped.\n * However, that's ok as userland can always opt-in with the `encodeSourceMapAtPath` option and mark known safe paths as such, which will override this heuristic.\n */\n // If the path ends in marks[number] it's likely a PortableTextSpan: https://github.com/portabletext/types/blob/e54eb24f136d8efd51a46c6a190e7c46e79b5380/src/portableText.ts#LL154C16-L154C16\n if (typeof endPath === 'number' && sourcePath.at(-2) === 'marks') {\n return false\n }\n // Or if it's [number].markDefs[number].href it's likely a PortableTextLink: https://github.com/portabletext/types/blob/e54eb24f136d8efd51a46c6a190e7c46e79b5380/src/portableText.ts#L163\n if (\n endPath === 'href' &&\n typeof sourcePath.at(-2) === 'number' &&\n sourcePath.at(-3) === 'markDefs'\n ) {\n return false\n }\n // Otherwise we have to deal with special properties of PortableTextBlock, and we can't confidently know if it's actually a `_type: 'block'` array item or not.\n // All we know is that if it is indeed a block, and we encode the strings on these keys it'll for sure break the PortableText rendering and thus we skip encoding.\n // https://github.com/portabletext/types/blob/e54eb24f136d8efd51a46c6a190e7c46e79b5380/src/portableText.ts#L48-L58\n if (endPath === 'style' || endPath === 'listItem') {\n return false\n }\n\n // Don't encode into anything that is suggested it'll render for SEO in meta tags\n if (\n sourcePath.some(\n (path) => path === 'meta' || path === 'metadata' || path === 'openGraph' || path === 'seo',\n )\n ) {\n return false\n }\n\n // If the sourcePath or resultPath contains something that sounds like a type, like iconType, we skip encoding, as it's most\n // of the time used for logic that breaks if it contains stega characters\n if (hasTypeLike(sourcePath) || hasTypeLike(resultPath)) {\n return false\n }\n\n // Finally, we ignore a bunch of paths that are typically used for page building\n if (typeof endPath === 'string' && denylist.has(endPath)) {\n return false\n }\n\n return true\n}\n\nconst denylist = new Set([\n 'color',\n 'colour',\n 'currency',\n 'email',\n 'format',\n 'gid',\n 'hex',\n 'href',\n 'hsl',\n 'hsla',\n 'icon',\n 'id',\n 'index',\n 'key',\n 'language',\n 'layout',\n 'link',\n 'linkAction',\n 'locale',\n 'lqip',\n 'page',\n 'path',\n 'ref',\n 'rgb',\n 'rgba',\n 'route',\n 'secret',\n 'slug',\n 'status',\n 'tag',\n 'template',\n 'theme',\n 'type',\n 'unit',\n 'url',\n 'username',\n 'variant',\n 'website',\n])\n\nfunction isValidDate(dateString: string) {\n return /^\\d{4}-\\d{2}-\\d{2}/.test(dateString) ? Boolean(Date.parse(dateString)) : false\n}\n\nfunction isValidURL(url: string) {\n try {\n new URL(url, url.startsWith('/') ? 'https://acme.com' : undefined)\n } catch {\n return false\n }\n return true\n}\n\nfunction hasTypeLike(path: ContentSourceMapParsedPath): boolean {\n return path.some((segment) => typeof segment === 'string' && segment.match(/type/i) !== null)\n}\n","import {vercelStegaCombine} from '@vercel/stega'\n\nimport {createEditUrl} from '../csm/createEditUrl'\nimport {jsonPathToStudioPath} from '../csm/jsonPath'\nimport {resolveStudioBaseRoute} from '../csm/resolveEditInfo'\nimport {reKeySegment, toString as studioPathToString} from '../csm/studioPath'\nimport {encodeIntoResult} from './encodeIntoResult'\nimport {filterDefault} from './filterDefault'\nimport {ContentSourceMap, ContentSourceMapParsedPath, InitializedStegaConfig} from './types'\n\nconst TRUNCATE_LENGTH = 20\n\n/**\n * Uses `@vercel/stega` to embed edit info JSON into strings in your query result.\n * The JSON payloads are added using invisible characters so they don't show up visually.\n * The edit info is generated from the Content Source Map (CSM) that is returned from Sanity for the query.\n * @public\n */\nexport function stegaEncodeSourceMap<Result = unknown>(\n result: Result,\n resultSourceMap: ContentSourceMap | undefined,\n config: InitializedStegaConfig,\n): Result {\n const {filter, logger, enabled} = config\n if (!enabled) {\n const msg = \"config.enabled must be true, don't call this function otherwise\"\n logger?.error?.(`[@sanity/client]: ${msg}`, {result, resultSourceMap, config})\n throw new TypeError(msg)\n }\n\n if (!resultSourceMap) {\n logger?.error?.('[@sanity/client]: Missing Content Source Map from response body', {\n result,\n resultSourceMap,\n config,\n })\n return result\n }\n\n if (!config.studioUrl) {\n const msg = 'config.studioUrl must be defined'\n logger?.error?.(`[@sanity/client]: ${msg}`, {result, resultSourceMap, config})\n throw new TypeError(msg)\n }\n\n const report: Record<'encoded' | 'skipped', {path: string; length: number; value: string}[]> = {\n encoded: [],\n skipped: [],\n }\n\n const resultWithStega = encodeIntoResult(\n result,\n resultSourceMap,\n ({sourcePath, sourceDocument, resultPath, value}) => {\n // Allow userland to control when to opt-out of encoding\n if (\n (typeof filter === 'function'\n ? filter({sourcePath, resultPath, filterDefault, sourceDocument, value})\n : filterDefault({sourcePath, resultPath, filterDefault, sourceDocument, value})) === false\n ) {\n if (logger) {\n report.skipped.push({\n path: prettyPathForLogging(sourcePath),\n value: `${value.slice(0, TRUNCATE_LENGTH)}${\n value.length > TRUNCATE_LENGTH ? '...' : ''\n }`,\n length: value.length,\n })\n }\n return value\n }\n\n if (logger) {\n report.encoded.push({\n path: prettyPathForLogging(sourcePath),\n value: `${value.slice(0, TRUNCATE_LENGTH)}${value.length > TRUNCATE_LENGTH ? '...' : ''}`,\n length: value.length,\n })\n }\n\n const {baseUrl, workspace, tool} = resolveStudioBaseRoute(\n typeof config.studioUrl === 'function'\n ? config.studioUrl(sourceDocument)\n : config.studioUrl!,\n )\n if (!baseUrl) return value\n const {_id: id, _type: type, _projectId: projectId, _dataset: dataset} = sourceDocument\n\n return vercelStegaCombine(\n value,\n {\n origin: 'sanity.io',\n href: createEditUrl({\n baseUrl,\n workspace,\n tool,\n id,\n type,\n path: sourcePath,\n ...(!config.omitCrossDatasetReferenceData && {dataset, projectId}),\n }),\n },\n // We use custom logic to determine if we should skip encoding\n false,\n )\n },\n )\n\n if (logger) {\n const isSkipping = report.skipped.length\n const isEncoding = report.encoded.length\n if (isSkipping || isEncoding) {\n ;(logger?.groupCollapsed || logger.log)?.('[@sanity/client]: Encoding source map into result')\n logger.log?.(\n `[@sanity/client]: Paths encoded: ${report.encoded.length}, skipped: ${report.skipped.length}`,\n )\n }\n if (report.encoded.length > 0) {\n logger?.log?.(`[@sanity/client]: Table of encoded paths`)\n ;(logger?.table || logger.log)?.(report.encoded)\n }\n if (report.skipped.length > 0) {\n const skipped = new Set<string>()\n for (const {path} of report.skipped) {\n skipped.add(path.replace(reKeySegment, '0').replace(/\\[\\d+\\]/g, '[]'))\n }\n logger?.log?.(`[@sanity/client]: List of skipped paths`, [...skipped.values()])\n }\n\n if (isSkipping || isEncoding) {\n logger?.groupEnd?.()\n }\n }\n\n return resultWithStega\n}\n\nfunction prettyPathForLogging(path: ContentSourceMapParsedPath): string {\n return studioPathToString(jsonPathToStudioPath(path))\n}\n"],"names":["studioPath.toString","vercelStegaCombine","studioPathToString"],"mappings":";;AAeO,MAAM,eAAe;AASrB,SAAS,aAAa,SAA+C;AAC1E,SAAI,OAAO,WAAY,WACd,aAAa,KAAK,QAAQ,KAAK,CAAC,IAGlC,OAAO,WAAY,YAAY,UAAU;AAClD;AA8DO,SAAS,SAAS,MAAoB;AACvC,MAAA,CAAC,MAAM,QAAQ,IAAI;AACf,UAAA,IAAI,MAAM,sBAAsB;AAGxC,SAAO,KAAK,OAAe,CAAC,QAAQ,SAAS,MAAM;AACjD,UAAM,cAAc,OAAO;AAC3B,QAAI,gBAAgB;AACX,aAAA,GAAG,MAAM,IAAI,OAAO;AAG7B,QAAI,gBAAgB;AAEX,aAAA,GAAG,MAAM,GADE,MAAM,IAAI,KAAK,GACL,GAAG,OAAO;AAGpC,QAAA,aAAa,OAAO,KAAK,QAAQ;AACnC,aAAO,GAAG,MAAM,WAAW,QAAQ,IAAI;AAGrC,QAAA,MAAM,QAAQ,OAAO,GAAG;AACpB,YAAA,CAAC,MAAM,EAAE,IAAI;AACnB,aAAO,GAAG,MAAM,IAAI,IAAI,IAAI,EAAE;AAAA,IAAA;AAGhC,UAAM,IAAI,MAAM,8BAA8B,KAAK,UAAU,OAAO,CAAC,IAAI;AAAA,KACxE,EAAE;AACP;AC/GA,MAAM,SAAiC;AAAA,EACrC,MAAM;AAAA,EACN,MAAM;AAAA,EACN,MAAM;AAAA,EACN,KAAM;AAAA,EACN,KAAK;AAAA,EACL,MAAM;AACR,GAEM,WAAmC;AAAA,EACvC,OAAO;AAAA,EACP,OAAO;AAAA;AAAA,EACP,OAAO;AAAA,EACP,OAAO;AAAA,EACP,OAAO;AAAA,EACP,QAAQ;AACV;AAKO,SAAS,SAAS,MAAiE;AACjF,SAAA,IAAI,KACR,IAAI,CAAC,YACA,OAAO,WAAY,WAId,KAH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B,QAAQ,WAAW;AAAA,EAAA;AAIhB,SAAA;AACT;AAEA,SAAS,qBAAqB,MAA0C;AAC/D,SAAAC,SAAmB,qBAAqB,IAAI,CAAC;AACtD;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"stegaEncodeSourceMap.cjs","sources":["../../src/csm/studioPath.ts","../../src/csm/jsonPath.ts","../../src/csm/resolveMapping.ts","../../src/csm/isArray.ts","../../src/csm/isRecord.ts","../../src/csm/walkMap.ts","../../src/stega/encodeIntoResult.ts","../../src/csm/getPublishedId.ts","../../src/csm/createEditUrl.ts","../../src/csm/resolveEditInfo.ts","../../src/stega/filterDefault.ts","../../src/stega/stegaEncodeSourceMap.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","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 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 type {ContentSourceMap} from '@sanity/client/csm'\n\nimport {parseJsonPath} from '../csm/jsonPath'\nimport {resolveMapping} from '../csm/resolveMapping'\nimport {walkMap} from '../csm/walkMap'\nimport type {Encoder} from './types'\n\n/**\n * @internal\n */\nexport function encodeIntoResult<Result>(\n result: Result,\n csm: ContentSourceMap,\n encoder: Encoder,\n): Result {\n return walkMap(result, (value, path) => {\n // Only map strings, we could extend this in the future to support other types like integers...\n if (typeof value !== 'string') {\n return value\n }\n\n const resolveMappingResult = resolveMapping(path, csm)\n if (!resolveMappingResult) {\n return value\n }\n\n const {mapping, matchedPath} = resolveMappingResult\n if (mapping.type !== 'value') {\n return value\n }\n\n if (mapping.source.type !== 'documentValue') {\n return value\n }\n\n const sourceDocument = csm.documents[mapping.source.document!]\n const sourcePath = csm.paths[mapping.source.path]\n\n const matchPathSegments = parseJsonPath(matchedPath)\n const sourcePathSegments = parseJsonPath(sourcePath)\n const fullSourceSegments = sourcePathSegments.concat(path.slice(matchPathSegments.length))\n\n return encoder({\n sourcePath: fullSourceSegments,\n sourceDocument,\n resultPath: path,\n value,\n })\n }) as Result\n}\n","export const DRAFTS_PREFIX = 'drafts.'\n\n/** @internal */\nexport function getPublishedId(id: string): string {\n if (id.startsWith(DRAFTS_PREFIX)) {\n return id.slice(DRAFTS_PREFIX.length)\n }\n\n return id\n}\n","import {DRAFTS_PREFIX, getPublishedId} from './getPublishedId'\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 (_id.startsWith(DRAFTS_PREFIX)) {\n searchParams.set('isDraft', '')\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","import type {ContentSourceMapParsedPath, FilterDefault} from './types'\n\nexport const filterDefault: FilterDefault = ({sourcePath, resultPath, value}) => {\n // Skips encoding on URL or Date strings, similar to the `skip: 'auto'` parameter in vercelStegaCombine()\n if (isValidDate(value) || isValidURL(value)) {\n return false\n }\n\n const endPath = sourcePath.at(-1)\n // Never encode slugs\n if (sourcePath.at(-2) === 'slug' && endPath === 'current') {\n return false\n }\n\n // Skip underscored keys, and strings that end with `Id`, needs better heuristics but it works for now\n if (typeof endPath === 'string' && (endPath.startsWith('_') || endPath.endsWith('Id'))) {\n return false\n }\n\n /**\n * Best effort infer Portable Text paths that should not be encoded.\n * Nothing is for certain, and the below implementation may cause paths that aren't Portable Text and otherwise be safe to encode to be skipped.\n * However, that's ok as userland can always opt-in with the `encodeSourceMapAtPath` option and mark known safe paths as such, which will override this heuristic.\n */\n // If the path ends in marks[number] it's likely a PortableTextSpan: https://github.com/portabletext/types/blob/e54eb24f136d8efd51a46c6a190e7c46e79b5380/src/portableText.ts#LL154C16-L154C16\n if (typeof endPath === 'number' && sourcePath.at(-2) === 'marks') {\n return false\n }\n // Or if it's [number].markDefs[number].href it's likely a PortableTextLink: https://github.com/portabletext/types/blob/e54eb24f136d8efd51a46c6a190e7c46e79b5380/src/portableText.ts#L163\n if (\n endPath === 'href' &&\n typeof sourcePath.at(-2) === 'number' &&\n sourcePath.at(-3) === 'markDefs'\n ) {\n return false\n }\n // Otherwise we have to deal with special properties of PortableTextBlock, and we can't confidently know if it's actually a `_type: 'block'` array item or not.\n // All we know is that if it is indeed a block, and we encode the strings on these keys it'll for sure break the PortableText rendering and thus we skip encoding.\n // https://github.com/portabletext/types/blob/e54eb24f136d8efd51a46c6a190e7c46e79b5380/src/portableText.ts#L48-L58\n if (endPath === 'style' || endPath === 'listItem') {\n return false\n }\n\n // Don't encode into anything that is suggested it'll render for SEO in meta tags\n if (\n sourcePath.some(\n (path) => path === 'meta' || path === 'metadata' || path === 'openGraph' || path === 'seo',\n )\n ) {\n return false\n }\n\n // If the sourcePath or resultPath contains something that sounds like a type, like iconType, we skip encoding, as it's most\n // of the time used for logic that breaks if it contains stega characters\n if (hasTypeLike(sourcePath) || hasTypeLike(resultPath)) {\n return false\n }\n\n // Finally, we ignore a bunch of paths that are typically used for page building\n if (typeof endPath === 'string' && denylist.has(endPath)) {\n return false\n }\n\n return true\n}\n\nconst denylist = new Set([\n 'color',\n 'colour',\n 'currency',\n 'email',\n 'format',\n 'gid',\n 'hex',\n 'href',\n 'hsl',\n 'hsla',\n 'icon',\n 'id',\n 'index',\n 'key',\n 'language',\n 'layout',\n 'link',\n 'linkAction',\n 'locale',\n 'lqip',\n 'page',\n 'path',\n 'ref',\n 'rgb',\n 'rgba',\n 'route',\n 'secret',\n 'slug',\n 'status',\n 'tag',\n 'template',\n 'theme',\n 'type',\n 'textTheme',\n 'unit',\n 'url',\n 'username',\n 'variant',\n 'website',\n])\n\nfunction isValidDate(dateString: string) {\n return /^\\d{4}-\\d{2}-\\d{2}/.test(dateString) ? Boolean(Date.parse(dateString)) : false\n}\n\nfunction isValidURL(url: string) {\n try {\n new URL(url, url.startsWith('/') ? 'https://acme.com' : undefined)\n } catch {\n return false\n }\n return true\n}\n\nfunction hasTypeLike(path: ContentSourceMapParsedPath): boolean {\n return path.some((segment) => typeof segment === 'string' && segment.match(/type/i) !== null)\n}\n","import {vercelStegaCombine} from '@vercel/stega'\n\nimport {createEditUrl} from '../csm/createEditUrl'\nimport {jsonPathToStudioPath} from '../csm/jsonPath'\nimport {resolveStudioBaseRoute} from '../csm/resolveEditInfo'\nimport {reKeySegment, toString as studioPathToString} from '../csm/studioPath'\nimport {encodeIntoResult} from './encodeIntoResult'\nimport {filterDefault} from './filterDefault'\nimport {ContentSourceMap, ContentSourceMapParsedPath, InitializedStegaConfig} from './types'\n\nconst TRUNCATE_LENGTH = 20\n\n/**\n * Uses `@vercel/stega` to embed edit info JSON into strings in your query result.\n * The JSON payloads are added using invisible characters so they don't show up visually.\n * The edit info is generated from the Content Source Map (CSM) that is returned from Sanity for the query.\n * @public\n */\nexport function stegaEncodeSourceMap<Result = unknown>(\n result: Result,\n resultSourceMap: ContentSourceMap | undefined,\n config: InitializedStegaConfig,\n): Result {\n const {filter, logger, enabled} = config\n if (!enabled) {\n const msg = \"config.enabled must be true, don't call this function otherwise\"\n logger?.error?.(`[@sanity/client]: ${msg}`, {result, resultSourceMap, config})\n throw new TypeError(msg)\n }\n\n if (!resultSourceMap) {\n logger?.error?.('[@sanity/client]: Missing Content Source Map from response body', {\n result,\n resultSourceMap,\n config,\n })\n return result\n }\n\n if (!config.studioUrl) {\n const msg = 'config.studioUrl must be defined'\n logger?.error?.(`[@sanity/client]: ${msg}`, {result, resultSourceMap, config})\n throw new TypeError(msg)\n }\n\n const report: Record<'encoded' | 'skipped', {path: string; length: number; value: string}[]> = {\n encoded: [],\n skipped: [],\n }\n\n const resultWithStega = encodeIntoResult(\n result,\n resultSourceMap,\n ({sourcePath, sourceDocument, resultPath, value}) => {\n // Allow userland to control when to opt-out of encoding\n if (\n (typeof filter === 'function'\n ? filter({sourcePath, resultPath, filterDefault, sourceDocument, value})\n : filterDefault({sourcePath, resultPath, filterDefault, sourceDocument, value})) === false\n ) {\n if (logger) {\n report.skipped.push({\n path: prettyPathForLogging(sourcePath),\n value: `${value.slice(0, TRUNCATE_LENGTH)}${\n value.length > TRUNCATE_LENGTH ? '...' : ''\n }`,\n length: value.length,\n })\n }\n return value\n }\n\n if (logger) {\n report.encoded.push({\n path: prettyPathForLogging(sourcePath),\n value: `${value.slice(0, TRUNCATE_LENGTH)}${value.length > TRUNCATE_LENGTH ? '...' : ''}`,\n length: value.length,\n })\n }\n\n const {baseUrl, workspace, tool} = resolveStudioBaseRoute(\n typeof config.studioUrl === 'function'\n ? config.studioUrl(sourceDocument)\n : config.studioUrl!,\n )\n if (!baseUrl) return value\n const {_id: id, _type: type, _projectId: projectId, _dataset: dataset} = sourceDocument\n\n return vercelStegaCombine(\n value,\n {\n origin: 'sanity.io',\n href: createEditUrl({\n baseUrl,\n workspace,\n tool,\n id,\n type,\n path: sourcePath,\n ...(!config.omitCrossDatasetReferenceData && {dataset, projectId}),\n }),\n },\n // We use custom logic to determine if we should skip encoding\n false,\n )\n },\n )\n\n if (logger) {\n const isSkipping = report.skipped.length\n const isEncoding = report.encoded.length\n if (isSkipping || isEncoding) {\n ;(logger?.groupCollapsed || logger.log)?.('[@sanity/client]: Encoding source map into result')\n logger.log?.(\n `[@sanity/client]: Paths encoded: ${report.encoded.length}, skipped: ${report.skipped.length}`,\n )\n }\n if (report.encoded.length > 0) {\n logger?.log?.(`[@sanity/client]: Table of encoded paths`)\n ;(logger?.table || logger.log)?.(report.encoded)\n }\n if (report.skipped.length > 0) {\n const skipped = new Set<string>()\n for (const {path} of report.skipped) {\n skipped.add(path.replace(reKeySegment, '0').replace(/\\[\\d+\\]/g, '[]'))\n }\n logger?.log?.(`[@sanity/client]: List of skipped paths`, [...skipped.values()])\n }\n\n if (isSkipping || isEncoding) {\n logger?.groupEnd?.()\n }\n }\n\n return resultWithStega\n}\n\nfunction prettyPathForLogging(path: ContentSourceMapParsedPath): string {\n return studioPathToString(jsonPathToStudioPath(path))\n}\n"],"names":["studioPath.toString","vercelStegaCombine","studioPathToString"],"mappings":";;AAeO,MAAM,eAAe;AASrB,SAAS,aAAa,SAA+C;AAC1E,SAAI,OAAO,WAAY,WACd,aAAa,KAAK,QAAQ,KAAK,CAAC,IAGlC,OAAO,WAAY,YAAY,UAAU;AAClD;AA8DO,SAAS,SAAS,MAAoB;AACvC,MAAA,CAAC,MAAM,QAAQ,IAAI;AACf,UAAA,IAAI,MAAM,sBAAsB;AAGxC,SAAO,KAAK,OAAe,CAAC,QAAQ,SAAS,MAAM;AACjD,UAAM,cAAc,OAAO;AAC3B,QAAI,gBAAgB;AACX,aAAA,GAAG,MAAM,IAAI,OAAO;AAG7B,QAAI,gBAAgB;AAEX,aAAA,GAAG,MAAM,GADE,MAAM,IAAI,KAAK,GACL,GAAG,OAAO;AAGpC,QAAA,aAAa,OAAO,KAAK,QAAQ;AACnC,aAAO,GAAG,MAAM,WAAW,QAAQ,IAAI;AAGrC,QAAA,MAAM,QAAQ,OAAO,GAAG;AACpB,YAAA,CAAC,MAAM,EAAE,IAAI;AACnB,aAAO,GAAG,MAAM,IAAI,IAAI,IAAI,EAAE;AAAA,IAAA;AAGhC,UAAM,IAAI,MAAM,8BAA8B,KAAK,UAAU,OAAO,CAAC,IAAI;AAAA,KACxE,EAAE;AACP;AC/GA,MAAM,SAAiC;AAAA,EACrC,MAAM;AAAA,EACN,MAAM;AAAA,EACN,MAAM;AAAA,EACN,KAAM;AAAA,EACN,KAAK;AAAA,EACL,MAAM;AACR,GAEM,WAAmC;AAAA,EACvC,OAAO;AAAA,EACP,OAAO;AAAA;AAAA,EACP,OAAO;AAAA,EACP,OAAO;AAAA,EACP,OAAO;AAAA,EACP,QAAQ;AACV;AAKO,SAAS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AI,CAAC;AAEvE,cAAQ,MAAM,2CAA2C,CAAC,GAAG,QAAQ,OAAA,CAAQ,CAAC;AAAA,IAAA;AAG5E,KAAA,cAAc,eAChB,QAAQ,WAAW;AAAA,EAAA;AAIhB,SAAA;AACT;AAEA,SAAS,qBAAqB,MAA0C;AAC/D,SAAAC,SAAmB,qBAAqB,IAAI,CAAC;AACtD;;;;;;;;"}
|
|
@@ -185,7 +185,7 @@ const filterDefault = ({ sourcePath, resultPath, value }) => {
|
|
|
185
185
|
if (isValidDate(value) || isValidURL(value))
|
|
186
186
|
return !1;
|
|
187
187
|
const endPath = sourcePath.at(-1);
|
|
188
|
-
return !(sourcePath.at(-2) === "slug" && endPath === "current" || typeof endPath == "string" && endPath.startsWith("_") || typeof endPath == "number" && sourcePath.at(-2) === "marks" || endPath === "href" && typeof sourcePath.at(-2) == "number" && sourcePath.at(-3) === "markDefs" || endPath === "style" || endPath === "listItem" || sourcePath.some(
|
|
188
|
+
return !(sourcePath.at(-2) === "slug" && endPath === "current" || typeof endPath == "string" && (endPath.startsWith("_") || endPath.endsWith("Id")) || typeof endPath == "number" && sourcePath.at(-2) === "marks" || endPath === "href" && typeof sourcePath.at(-2) == "number" && sourcePath.at(-3) === "markDefs" || endPath === "style" || endPath === "listItem" || sourcePath.some(
|
|
189
189
|
(path) => path === "meta" || path === "metadata" || path === "openGraph" || path === "seo"
|
|
190
190
|
) || hasTypeLike(sourcePath) || hasTypeLike(resultPath) || typeof endPath == "string" && denylist.has(endPath));
|
|
191
191
|
}, denylist = /* @__PURE__ */ new Set([
|
|
@@ -222,6 +222,7 @@ const filterDefault = ({ sourcePath, resultPath, value }) => {
|
|
|
222
222
|
"template",
|
|
223
223
|
"theme",
|
|
224
224
|
"type",
|
|
225
|
+
"textTheme",
|
|
225
226
|
"unit",
|
|
226
227
|
"url",
|
|
227
228
|
"username",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stegaEncodeSourceMap.js","sources":["../../src/csm/studioPath.ts","../../src/csm/jsonPath.ts","../../src/csm/resolveMapping.ts","../../src/csm/isArray.ts","../../src/csm/isRecord.ts","../../src/csm/walkMap.ts","../../src/stega/encodeIntoResult.ts","../../src/csm/getPublishedId.ts","../../src/csm/createEditUrl.ts","../../src/csm/resolveEditInfo.ts","../../src/stega/filterDefault.ts","../../src/stega/stegaEncodeSourceMap.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","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 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 type {ContentSourceMap} from '@sanity/client/csm'\n\nimport {parseJsonPath} from '../csm/jsonPath'\nimport {resolveMapping} from '../csm/resolveMapping'\nimport {walkMap} from '../csm/walkMap'\nimport type {Encoder} from './types'\n\n/**\n * @internal\n */\nexport function encodeIntoResult<Result>(\n result: Result,\n csm: ContentSourceMap,\n encoder: Encoder,\n): Result {\n return walkMap(result, (value, path) => {\n // Only map strings, we could extend this in the future to support other types like integers...\n if (typeof value !== 'string') {\n return value\n }\n\n const resolveMappingResult = resolveMapping(path, csm)\n if (!resolveMappingResult) {\n return value\n }\n\n const {mapping, matchedPath} = resolveMappingResult\n if (mapping.type !== 'value') {\n return value\n }\n\n if (mapping.source.type !== 'documentValue') {\n return value\n }\n\n const sourceDocument = csm.documents[mapping.source.document!]\n const sourcePath = csm.paths[mapping.source.path]\n\n const matchPathSegments = parseJsonPath(matchedPath)\n const sourcePathSegments = parseJsonPath(sourcePath)\n const fullSourceSegments = sourcePathSegments.concat(path.slice(matchPathSegments.length))\n\n return encoder({\n sourcePath: fullSourceSegments,\n sourceDocument,\n resultPath: path,\n value,\n })\n }) as Result\n}\n","export const DRAFTS_PREFIX = 'drafts.'\n\n/** @internal */\nexport function getPublishedId(id: string): string {\n if (id.startsWith(DRAFTS_PREFIX)) {\n return id.slice(DRAFTS_PREFIX.length)\n }\n\n return id\n}\n","import {DRAFTS_PREFIX, getPublishedId} from './getPublishedId'\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 (_id.startsWith(DRAFTS_PREFIX)) {\n searchParams.set('isDraft', '')\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","import type {ContentSourceMapParsedPath, FilterDefault} from './types'\n\nexport const filterDefault: FilterDefault = ({sourcePath, resultPath, value}) => {\n // Skips encoding on URL or Date strings, similar to the `skip: 'auto'` parameter in vercelStegaCombine()\n if (isValidDate(value) || isValidURL(value)) {\n return false\n }\n\n const endPath = sourcePath.at(-1)\n // Never encode slugs\n if (sourcePath.at(-2) === 'slug' && endPath === 'current') {\n return false\n }\n\n // Skip underscored keys, needs better heuristics but it works for now\n if (typeof endPath === 'string' && endPath.startsWith('_')) {\n return false\n }\n\n /**\n * Best effort infer Portable Text paths that should not be encoded.\n * Nothing is for certain, and the below implementation may cause paths that aren't Portable Text and otherwise be safe to encode to be skipped.\n * However, that's ok as userland can always opt-in with the `encodeSourceMapAtPath` option and mark known safe paths as such, which will override this heuristic.\n */\n // If the path ends in marks[number] it's likely a PortableTextSpan: https://github.com/portabletext/types/blob/e54eb24f136d8efd51a46c6a190e7c46e79b5380/src/portableText.ts#LL154C16-L154C16\n if (typeof endPath === 'number' && sourcePath.at(-2) === 'marks') {\n return false\n }\n // Or if it's [number].markDefs[number].href it's likely a PortableTextLink: https://github.com/portabletext/types/blob/e54eb24f136d8efd51a46c6a190e7c46e79b5380/src/portableText.ts#L163\n if (\n endPath === 'href' &&\n typeof sourcePath.at(-2) === 'number' &&\n sourcePath.at(-3) === 'markDefs'\n ) {\n return false\n }\n // Otherwise we have to deal with special properties of PortableTextBlock, and we can't confidently know if it's actually a `_type: 'block'` array item or not.\n // All we know is that if it is indeed a block, and we encode the strings on these keys it'll for sure break the PortableText rendering and thus we skip encoding.\n // https://github.com/portabletext/types/blob/e54eb24f136d8efd51a46c6a190e7c46e79b5380/src/portableText.ts#L48-L58\n if (endPath === 'style' || endPath === 'listItem') {\n return false\n }\n\n // Don't encode into anything that is suggested it'll render for SEO in meta tags\n if (\n sourcePath.some(\n (path) => path === 'meta' || path === 'metadata' || path === 'openGraph' || path === 'seo',\n )\n ) {\n return false\n }\n\n // If the sourcePath or resultPath contains something that sounds like a type, like iconType, we skip encoding, as it's most\n // of the time used for logic that breaks if it contains stega characters\n if (hasTypeLike(sourcePath) || hasTypeLike(resultPath)) {\n return false\n }\n\n // Finally, we ignore a bunch of paths that are typically used for page building\n if (typeof endPath === 'string' && denylist.has(endPath)) {\n return false\n }\n\n return true\n}\n\nconst denylist = new Set([\n 'color',\n 'colour',\n 'currency',\n 'email',\n 'format',\n 'gid',\n 'hex',\n 'href',\n 'hsl',\n 'hsla',\n 'icon',\n 'id',\n 'index',\n 'key',\n 'language',\n 'layout',\n 'link',\n 'linkAction',\n 'locale',\n 'lqip',\n 'page',\n 'path',\n 'ref',\n 'rgb',\n 'rgba',\n 'route',\n 'secret',\n 'slug',\n 'status',\n 'tag',\n 'template',\n 'theme',\n 'type',\n 'unit',\n 'url',\n 'username',\n 'variant',\n 'website',\n])\n\nfunction isValidDate(dateString: string) {\n return /^\\d{4}-\\d{2}-\\d{2}/.test(dateString) ? Boolean(Date.parse(dateString)) : false\n}\n\nfunction isValidURL(url: string) {\n try {\n new URL(url, url.startsWith('/') ? 'https://acme.com' : undefined)\n } catch {\n return false\n }\n return true\n}\n\nfunction hasTypeLike(path: ContentSourceMapParsedPath): boolean {\n return path.some((segment) => typeof segment === 'string' && segment.match(/type/i) !== null)\n}\n","import {vercelStegaCombine} from '@vercel/stega'\n\nimport {createEditUrl} from '../csm/createEditUrl'\nimport {jsonPathToStudioPath} from '../csm/jsonPath'\nimport {resolveStudioBaseRoute} from '../csm/resolveEditInfo'\nimport {reKeySegment, toString as studioPathToString} from '../csm/studioPath'\nimport {encodeIntoResult} from './encodeIntoResult'\nimport {filterDefault} from './filterDefault'\nimport {ContentSourceMap, ContentSourceMapParsedPath, InitializedStegaConfig} from './types'\n\nconst TRUNCATE_LENGTH = 20\n\n/**\n * Uses `@vercel/stega` to embed edit info JSON into strings in your query result.\n * The JSON payloads are added using invisible characters so they don't show up visually.\n * The edit info is generated from the Content Source Map (CSM) that is returned from Sanity for the query.\n * @public\n */\nexport function stegaEncodeSourceMap<Result = unknown>(\n result: Result,\n resultSourceMap: ContentSourceMap | undefined,\n config: InitializedStegaConfig,\n): Result {\n const {filter, logger, enabled} = config\n if (!enabled) {\n const msg = \"config.enabled must be true, don't call this function otherwise\"\n logger?.error?.(`[@sanity/client]: ${msg}`, {result, resultSourceMap, config})\n throw new TypeError(msg)\n }\n\n if (!resultSourceMap) {\n logger?.error?.('[@sanity/client]: Missing Content Source Map from response body', {\n result,\n resultSourceMap,\n config,\n })\n return result\n }\n\n if (!config.studioUrl) {\n const msg = 'config.studioUrl must be defined'\n logger?.error?.(`[@sanity/client]: ${msg}`, {result, resultSourceMap, config})\n throw new TypeError(msg)\n }\n\n const report: Record<'encoded' | 'skipped', {path: string; length: number; value: string}[]> = {\n encoded: [],\n skipped: [],\n }\n\n const resultWithStega = encodeIntoResult(\n result,\n resultSourceMap,\n ({sourcePath, sourceDocument, resultPath, value}) => {\n // Allow userland to control when to opt-out of encoding\n if (\n (typeof filter === 'function'\n ? filter({sourcePath, resultPath, filterDefault, sourceDocument, value})\n : filterDefault({sourcePath, resultPath, filterDefault, sourceDocument, value})) === false\n ) {\n if (logger) {\n report.skipped.push({\n path: prettyPathForLogging(sourcePath),\n value: `${value.slice(0, TRUNCATE_LENGTH)}${\n value.length > TRUNCATE_LENGTH ? '...' : ''\n }`,\n length: value.length,\n })\n }\n return value\n }\n\n if (logger) {\n report.encoded.push({\n path: prettyPathForLogging(sourcePath),\n value: `${value.slice(0, TRUNCATE_LENGTH)}${value.length > TRUNCATE_LENGTH ? '...' : ''}`,\n length: value.length,\n })\n }\n\n const {baseUrl, workspace, tool} = resolveStudioBaseRoute(\n typeof config.studioUrl === 'function'\n ? config.studioUrl(sourceDocument)\n : config.studioUrl!,\n )\n if (!baseUrl) return value\n const {_id: id, _type: type, _projectId: projectId, _dataset: dataset} = sourceDocument\n\n return vercelStegaCombine(\n value,\n {\n origin: 'sanity.io',\n href: createEditUrl({\n baseUrl,\n workspace,\n tool,\n id,\n type,\n path: sourcePath,\n ...(!config.omitCrossDatasetReferenceData && {dataset, projectId}),\n }),\n },\n // We use custom logic to determine if we should skip encoding\n false,\n )\n },\n )\n\n if (logger) {\n const isSkipping = report.skipped.length\n const isEncoding = report.encoded.length\n if (isSkipping || isEncoding) {\n ;(logger?.groupCollapsed || logger.log)?.('[@sanity/client]: Encoding source map into result')\n logger.log?.(\n `[@sanity/client]: Paths encoded: ${report.encoded.length}, skipped: ${report.skipped.length}`,\n )\n }\n if (report.encoded.length > 0) {\n logger?.log?.(`[@sanity/client]: Table of encoded paths`)\n ;(logger?.table || logger.log)?.(report.encoded)\n }\n if (report.skipped.length > 0) {\n const skipped = new Set<string>()\n for (const {path} of report.skipped) {\n skipped.add(path.replace(reKeySegment, '0').replace(/\\[\\d+\\]/g, '[]'))\n }\n logger?.log?.(`[@sanity/client]: List of skipped paths`, [...skipped.values()])\n }\n\n if (isSkipping || isEncoding) {\n logger?.groupEnd?.()\n }\n }\n\n return resultWithStega\n}\n\nfunction prettyPathForLogging(path: ContentSourceMapParsedPath): string {\n return studioPathToString(jsonPathToStudioPath(path))\n}\n"],"names":["studioPath.toString","vercelStegaCombine","studioPathToString"],"mappings":";AAeO,MAAM,eAAe;AASrB,SAAS,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js","sources":["../../src/csm/studioPath.ts","../../src/csm/jsonPath.ts","../../src/csm/resolveMapping.ts","../../src/csm/isArray.ts","../../src/csm/isRecord.ts","../../src/csm/walkMap.ts","../../src/stega/encodeIntoResult.ts","../../src/csm/getPublishedId.ts","../../src/csm/createEditUrl.ts","../../src/csm/resolveEditInfo.ts","../../src/stega/filterDefault.ts","../../src/stega/stegaEncodeSourceMap.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","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 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 type {ContentSourceMap} from '@sanity/client/csm'\n\nimport {parseJsonPath} from '../csm/jsonPath'\nimport {resolveMapping} from '../csm/resolveMapping'\nimport {walkMap} from '../csm/walkMap'\nimport type {Encoder} from './types'\n\n/**\n * @internal\n */\nexport function encodeIntoResult<Result>(\n result: Result,\n csm: ContentSourceMap,\n encoder: Encoder,\n): Result {\n return walkMap(result, (value, path) => {\n // Only map strings, we could extend this in the future to support other types like integers...\n if (typeof value !== 'string') {\n return value\n }\n\n const resolveMappingResult = resolveMapping(path, csm)\n if (!resolveMappingResult) {\n return value\n }\n\n const {mapping, matchedPath} = resolveMappingResult\n if (mapping.type !== 'value') {\n return value\n }\n\n if (mapping.source.type !== 'documentValue') {\n return value\n }\n\n const sourceDocument = csm.documents[mapping.source.document!]\n const sourcePath = csm.paths[mapping.source.path]\n\n const matchPathSegments = parseJsonPath(matchedPath)\n const sourcePathSegments = parseJsonPath(sourcePath)\n const fullSourceSegments = sourcePathSegments.concat(path.slice(matchPathSegments.length))\n\n return encoder({\n sourcePath: fullSourceSegments,\n sourceDocument,\n resultPath: path,\n value,\n })\n }) as Result\n}\n","export const DRAFTS_PREFIX = 'drafts.'\n\n/** @internal */\nexport function getPublishedId(id: string): string {\n if (id.startsWith(DRAFTS_PREFIX)) {\n return id.slice(DRAFTS_PREFIX.length)\n }\n\n return id\n}\n","import {DRAFTS_PREFIX, getPublishedId} from './getPublishedId'\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 (_id.startsWith(DRAFTS_PREFIX)) {\n searchParams.set('isDraft', '')\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","import type {ContentSourceMapParsedPath, FilterDefault} from './types'\n\nexport const filterDefault: FilterDefault = ({sourcePath, resultPath, value}) => {\n // Skips encoding on URL or Date strings, similar to the `skip: 'auto'` parameter in vercelStegaCombine()\n if (isValidDate(value) || isValidURL(value)) {\n return false\n }\n\n const endPath = sourcePath.at(-1)\n // Never encode slugs\n if (sourcePath.at(-2) === 'slug' && endPath === 'current') {\n return false\n }\n\n // Skip underscored keys, and strings that end with `Id`, needs better heuristics but it works for now\n if (typeof endPath === 'string' && (endPath.startsWith('_') || endPath.endsWith('Id'))) {\n return false\n }\n\n /**\n * Best effort infer Portable Text paths that should not be encoded.\n * Nothing is for certain, and the below implementation may cause paths that aren't Portable Text and otherwise be safe to encode to be skipped.\n * However, that's ok as userland can always opt-in with the `encodeSourceMapAtPath` option and mark known safe paths as such, which will override this heuristic.\n */\n // If the path ends in marks[number] it's likely a PortableTextSpan: https://github.com/portabletext/types/blob/e54eb24f136d8efd51a46c6a190e7c46e79b5380/src/portableText.ts#LL154C16-L154C16\n if (typeof endPath === 'number' && sourcePath.at(-2) === 'marks') {\n return false\n }\n // Or if it's [number].markDefs[number].href it's likely a PortableTextLink: https://github.com/portabletext/types/blob/e54eb24f136d8efd51a46c6a190e7c46e79b5380/src/portableText.ts#L163\n if (\n endPath === 'href' &&\n typeof sourcePath.at(-2) === 'number' &&\n sourcePath.at(-3) === 'markDefs'\n ) {\n return false\n }\n // Otherwise we have to deal with special properties of PortableTextBlock, and we can't confidently know if it's actually a `_type: 'block'` array item or not.\n // All we know is that if it is indeed a block, and we encode the strings on these keys it'll for sure break the PortableText rendering and thus we skip encoding.\n // https://github.com/portabletext/types/blob/e54eb24f136d8efd51a46c6a190e7c46e79b5380/src/portableText.ts#L48-L58\n if (endPath === 'style' || endPath === 'listItem') {\n return false\n }\n\n // Don't encode into anything that is suggested it'll render for SEO in meta tags\n if (\n sourcePath.some(\n (path) => path === 'meta' || path === 'metadata' || path === 'openGraph' || path === 'seo',\n )\n ) {\n return false\n }\n\n // If the sourcePath or resultPath contains something that sounds like a type, like iconType, we skip encoding, as it's most\n // of the time used for logic that breaks if it contains stega characters\n if (hasTypeLike(sourcePath) || hasTypeLike(resultPath)) {\n return false\n }\n\n // Finally, we ignore a bunch of paths that are typically used for page building\n if (typeof endPath === 'string' && denylist.has(endPath)) {\n return false\n }\n\n return true\n}\n\nconst denylist = new Set([\n 'color',\n 'colour',\n 'currency',\n 'email',\n 'format',\n 'gid',\n 'hex',\n 'href',\n 'hsl',\n 'hsla',\n 'icon',\n 'id',\n 'index',\n 'key',\n 'language',\n 'layout',\n 'link',\n 'linkAction',\n 'locale',\n 'lqip',\n 'page',\n 'path',\n 'ref',\n 'rgb',\n 'rgba',\n 'route',\n 'secret',\n 'slug',\n 'status',\n 'tag',\n 'template',\n 'theme',\n 'type',\n 'textTheme',\n 'unit',\n 'url',\n 'username',\n 'variant',\n 'website',\n])\n\nfunction isValidDate(dateString: string) {\n return /^\\d{4}-\\d{2}-\\d{2}/.test(dateString) ? Boolean(Date.parse(dateString)) : false\n}\n\nfunction isValidURL(url: string) {\n try {\n new URL(url, url.startsWith('/') ? 'https://acme.com' : undefined)\n } catch {\n return false\n }\n return true\n}\n\nfunction hasTypeLike(path: ContentSourceMapParsedPath): boolean {\n return path.some((segment) => typeof segment === 'string' && segment.match(/type/i) !== null)\n}\n","import {vercelStegaCombine} from '@vercel/stega'\n\nimport {createEditUrl} from '../csm/createEditUrl'\nimport {jsonPathToStudioPath} from '../csm/jsonPath'\nimport {resolveStudioBaseRoute} from '../csm/resolveEditInfo'\nimport {reKeySegment, toString as studioPathToString} from '../csm/studioPath'\nimport {encodeIntoResult} from './encodeIntoResult'\nimport {filterDefault} from './filterDefault'\nimport {ContentSourceMap, ContentSourceMapParsedPath, InitializedStegaConfig} from './types'\n\nconst TRUNCATE_LENGTH = 20\n\n/**\n * Uses `@vercel/stega` to embed edit info JSON into strings in your query result.\n * The JSON payloads are added using invisible characters so they don't show up visually.\n * The edit info is generated from the Content Source Map (CSM) that is returned from Sanity for the query.\n * @public\n */\nexport function stegaEncodeSourceMap<Result = unknown>(\n result: Result,\n resultSourceMap: ContentSourceMap | undefined,\n config: InitializedStegaConfig,\n): Result {\n const {filter, logger, enabled} = config\n if (!enabled) {\n const msg = \"config.enabled must be true, don't call this function otherwise\"\n logger?.error?.(`[@sanity/client]: ${msg}`, {result, resultSourceMap, config})\n throw new TypeError(msg)\n }\n\n if (!resultSourceMap) {\n logger?.error?.('[@sanity/client]: Missing Content Source Map from response body', {\n result,\n resultSourceMap,\n config,\n })\n return result\n }\n\n if (!config.studioUrl) {\n const msg = 'config.studioUrl must be defined'\n logger?.error?.(`[@sanity/client]: ${msg}`, {result, resultSourceMap, config})\n throw new TypeError(msg)\n }\n\n const report: Record<'encoded' | 'skipped', {path: string; length: number; value: string}[]> = {\n encoded: [],\n skipped: [],\n }\n\n const resultWithStega = encodeIntoResult(\n result,\n resultSourceMap,\n ({sourcePath, sourceDocument, resultPath, value}) => {\n // Allow userland to control when to opt-out of encoding\n if (\n (typeof filter === 'function'\n ? filter({sourcePath, resultPath, filterDefault, sourceDocument, value})\n : filterDefault({sourcePath, resultPath, filterDefault, sourceDocument, value})) === false\n ) {\n if (logger) {\n report.skipped.push({\n path: prettyPathForLogging(sourcePath),\n value: `${value.slice(0, TRUNCATE_LENGTH)}${\n value.length > TRUNCATE_LENGTH ? '...' : ''\n }`,\n length: value.length,\n })\n }\n return value\n }\n\n if (logger) {\n report.encoded.push({\n path: prettyPathForLogging(sourcePath),\n value: `${value.slice(0, TRUNCATE_LENGTH)}${value.length > TRUNCATE_LENGTH ? '...' : ''}`,\n length: value.length,\n })\n }\n\n const {baseUrl, workspace, tool} = resolveStudioBaseRoute(\n typeof config.studioUrl === 'function'\n ? config.studioUrl(sourceDocument)\n : config.studioUrl!,\n )\n if (!baseUrl) return value\n const {_id: id, _type: type, _projectId: projectId, _dataset: dataset} = sourceDocument\n\n return vercelStegaCombine(\n value,\n {\n origin: 'sanity.io',\n href: createEditUrl({\n baseUrl,\n workspace,\n tool,\n id,\n type,\n path: sourcePath,\n ...(!config.omitCrossDatasetReferenceData && {dataset, projectId}),\n }),\n },\n // We use custom logic to determine if we should skip encoding\n false,\n )\n },\n )\n\n if (logger) {\n const isSkipping = report.skipped.length\n const isEncoding = report.encoded.length\n if (isSkipping || isEncoding) {\n ;(logger?.groupCollapsed || logger.log)?.('[@sanity/client]: Encoding source map into result')\n logger.log?.(\n `[@sanity/client]: Paths encoded: ${report.encoded.length}, skipped: ${report.skipped.length}`,\n )\n }\n if (report.encoded.length > 0) {\n logger?.log?.(`[@sanity/client]: Table of encoded paths`)\n ;(logger?.table || logger.log)?.(report.encoded)\n }\n if (report.skipped.length > 0) {\n const skipped = new Set<string>()\n for (const {path} of report.skipped) {\n skipped.add(path.replace(reKeySegment, '0').replace(/\\[\\d+\\]/g, '[]'))\n }\n logger?.log?.(`[@sanity/client]: List of skipped paths`, [...skipped.values()])\n }\n\n if (isSkipping || isEncoding) {\n logger?.groupEnd?.()\n }\n }\n\n return resultWithStega\n}\n\nfunction prettyPathForLogging(path: ContentSourceMapParsedPath): string {\n return studioPathToString(jsonPathToStudioPath(path))\n}\n"],"names":["studioPath.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0C;AAC/D,SAAAC,SAAmB,qBAAqB,IAAI,CAAC;AACtD;;;;;"}
|
package/dist/index.cjs
CHANGED
|
@@ -1568,7 +1568,7 @@ function defineDeprecatedCreateClient(createClient2) {
|
|
|
1568
1568
|
return printNoDefaultExport(), createClient2(config);
|
|
1569
1569
|
};
|
|
1570
1570
|
}
|
|
1571
|
-
var name = "@sanity/client", version = "6.22.
|
|
1571
|
+
var name = "@sanity/client", version = "6.22.4";
|
|
1572
1572
|
const middleware = [
|
|
1573
1573
|
middleware$1.debug({ verbose: !0, namespace: "sanity:client" }),
|
|
1574
1574
|
middleware$1.headers({ "User-Agent": `${name} ${version}` }),
|
package/dist/index.js
CHANGED
|
@@ -1550,7 +1550,7 @@ function defineDeprecatedCreateClient(createClient2) {
|
|
|
1550
1550
|
return printNoDefaultExport(), createClient2(config);
|
|
1551
1551
|
};
|
|
1552
1552
|
}
|
|
1553
|
-
var name = "@sanity/client", version = "6.22.
|
|
1553
|
+
var name = "@sanity/client", version = "6.22.4";
|
|
1554
1554
|
const middleware = [
|
|
1555
1555
|
debug({ verbose: !0, namespace: "sanity:client" }),
|
|
1556
1556
|
headers({ "User-Agent": `${name} ${version}` }),
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sanity/client",
|
|
3
|
-
"version": "6.22.
|
|
3
|
+
"version": "6.22.4",
|
|
4
4
|
"description": "Client for retrieving, creating and patching data from Sanity.io",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"sanity",
|
|
@@ -154,7 +154,7 @@
|
|
|
154
154
|
"vitest": "2.1.4",
|
|
155
155
|
"vitest-github-actions-reporter": "0.11.1"
|
|
156
156
|
},
|
|
157
|
-
"packageManager": "npm@10.
|
|
157
|
+
"packageManager": "npm@10.9.0",
|
|
158
158
|
"engines": {
|
|
159
159
|
"node": ">=14.18"
|
|
160
160
|
}
|
|
@@ -12,8 +12,8 @@ export const filterDefault: FilterDefault = ({sourcePath, resultPath, value}) =>
|
|
|
12
12
|
return false
|
|
13
13
|
}
|
|
14
14
|
|
|
15
|
-
// Skip underscored keys, needs better heuristics but it works for now
|
|
16
|
-
if (typeof endPath === 'string' && endPath.startsWith('_')) {
|
|
15
|
+
// Skip underscored keys, and strings that end with `Id`, needs better heuristics but it works for now
|
|
16
|
+
if (typeof endPath === 'string' && (endPath.startsWith('_') || endPath.endsWith('Id'))) {
|
|
17
17
|
return false
|
|
18
18
|
}
|
|
19
19
|
|
|
@@ -98,6 +98,7 @@ const denylist = new Set([
|
|
|
98
98
|
'template',
|
|
99
99
|
'theme',
|
|
100
100
|
'type',
|
|
101
|
+
'textTheme',
|
|
101
102
|
'unit',
|
|
102
103
|
'url',
|
|
103
104
|
'username',
|
package/umd/sanityClient.js
CHANGED
|
@@ -2812,7 +2812,7 @@ ${selectionOpts}`);
|
|
|
2812
2812
|
if (isValidDate(value) || isValidURL(value))
|
|
2813
2813
|
return !1;
|
|
2814
2814
|
const endPath = sourcePath.at(-1);
|
|
2815
|
-
return !(sourcePath.at(-2) === "slug" && endPath === "current" || typeof endPath == "string" && endPath.startsWith("_") || typeof endPath == "number" && sourcePath.at(-2) === "marks" || endPath === "href" && typeof sourcePath.at(-2) == "number" && sourcePath.at(-3) === "markDefs" || endPath === "style" || endPath === "listItem" || sourcePath.some(
|
|
2815
|
+
return !(sourcePath.at(-2) === "slug" && endPath === "current" || typeof endPath == "string" && (endPath.startsWith("_") || endPath.endsWith("Id")) || typeof endPath == "number" && sourcePath.at(-2) === "marks" || endPath === "href" && typeof sourcePath.at(-2) == "number" && sourcePath.at(-3) === "markDefs" || endPath === "style" || endPath === "listItem" || sourcePath.some(
|
|
2816
2816
|
(path) => path === "meta" || path === "metadata" || path === "openGraph" || path === "seo"
|
|
2817
2817
|
) || hasTypeLike(sourcePath) || hasTypeLike(resultPath) || typeof endPath == "string" && denylist.has(endPath));
|
|
2818
2818
|
}, denylist = /* @__PURE__ */ new Set([
|
|
@@ -2849,6 +2849,7 @@ ${selectionOpts}`);
|
|
|
2849
2849
|
"template",
|
|
2850
2850
|
"theme",
|
|
2851
2851
|
"type",
|
|
2852
|
+
"textTheme",
|
|
2852
2853
|
"unit",
|
|
2853
2854
|
"url",
|
|
2854
2855
|
"username",
|
package/umd/sanityClient.min.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).SanityClient={})}(this,(function(e){"use strict";const t=!(typeof navigator>"u")&&"ReactNative"===navigator.product,r={timeout:t?6e4:12e4},n=function(e){const n={...r,..."string"==typeof e?{url:e}:e};if(n.timeout=s(n.timeout),n.query){const{url:e,searchParams:r}=function(e){const r=e.indexOf("?");if(-1===r)return{url:e,searchParams:new URLSearchParams};const n=e.slice(0,r),s=e.slice(r+1);if(!t)return{url:n,searchParams:new URLSearchParams(s)};if("function"!=typeof decodeURIComponent)throw new Error("Broken `URLSearchParams` implementation, and `decodeURIComponent` is not defined");const i=new URLSearchParams;for(const e of s.split("&")){const[t,r]=e.split("=");t&&i.append(o(t),o(r||""))}return{url:n,searchParams:i}}(n.url);for(const[t,o]of Object.entries(n.query)){if(void 0!==o)if(Array.isArray(o))for(const e of o)r.append(t,e);else r.append(t,o);const s=r.toString();s&&(n.url=`${e}?${s}`)}}return n.method=n.body&&!n.method?"POST":(n.method||"GET").toUpperCase(),n};function o(e){return decodeURIComponent(e.replace(/\+/g," "))}function s(e){if(!1===e||0===e)return!1;if(e.connect||e.socket)return e;const t=Number(e);return isNaN(t)?s(r.timeout):{connect:t,socket:t}}const i=/^https?:\/\//i,a=function(e){if(!i.test(e.url))throw new Error(`"${e.url}" is not a valid URL`)};function c(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}const u=["request","response","progress","error","abort"],l=["processOptions","validateOptions","interceptRequest","finalizeOptions","onRequest","onResponse","onError","onReturn","onHeaders"];function h(e,t){const r=[],o=l.reduce(((e,t)=>(e[t]=e[t]||[],e)),{processOptions:[n],validateOptions:[a]});function s(e){const r=u.reduce(((e,t)=>(e[t]=function(){const e=Object.create(null);let t=0;return{publish:function(t){for(const r in e)e[r](t)},subscribe:function(r){const n=t++;return e[n]=r,function(){delete e[n]}}}}(),e)),{}),n=(e=>function(t,r,...n){const o="onError"===t;let s=r;for(let r=0;r<e[t].length&&(s=(0,e[t][r])(s,...n),!o||s);r++);return s})(o),s=n("processOptions",e);n("validateOptions",s);const i={options:s,channels:r,applyMiddleware:n};let a;const c=r.request.subscribe((e=>{a=t(e,((t,o)=>((e,t,o)=>{let s=e,i=t;if(!s)try{i=n("onResponse",t,o)}catch(e){i=null,s=e}s=s&&n("onError",s,o),s?r.error.publish(s):i&&r.response.publish(i)})(t,o,e)))}));r.abort.subscribe((()=>{c(),a&&a.abort()}));const l=n("onReturn",r,i);return l===r&&r.request.publish(i),l}return s.use=function(e){if(!e)throw new Error("Tried to add middleware that resolved to falsey value");if("function"==typeof e)throw new Error("Tried to add middleware that was a function. It probably expects you to pass options to it.");if(e.onReturn&&o.onReturn.length>0)throw new Error("Tried to add new middleware with `onReturn` handler, but another handler has already been registered for this event");return l.forEach((t=>{e[t]&&o[t].push(e[t])})),r.push(e),s},s.clone=()=>h(r,t),e.forEach(s.use),s}var p=function(e){return e.replace(/^\s+|\s+$/g,"")},f=c((function(e){if(!e)return{};for(var t={},r=p(e).split("\n"),n=0;n<r.length;n++){var o=r[n],s=o.indexOf(":"),i=p(o.slice(0,s)).toLowerCase(),a=p(o.slice(s+1));typeof t[i]>"u"?t[i]=a:(c=t[i],"[object Array]"===Object.prototype.toString.call(c)?t[i].push(a):t[i]=[t[i],a])}var c;return t}));let d=class{onabort;onerror;onreadystatechange;ontimeout;readyState=0;response;responseText="";responseType="";status;statusText;withCredentials;#e;#t;#r;#n={};#o;#s={};#i;open(e,t,r){this.#e=e,this.#t=t,this.#r="",this.readyState=1,this.onreadystatechange?.(),this.#o=void 0}abort(){this.#o&&this.#o.abort()}getAllResponseHeaders(){return this.#r}setRequestHeader(e,t){this.#n[e]=t}setInit(e,t=!0){this.#s=e,this.#i=t}send(e){const t="arraybuffer"!==this.responseType,r={...this.#s,method:this.#e,headers:this.#n,body:e};"function"==typeof AbortController&&this.#i&&(this.#o=new AbortController,typeof EventTarget<"u"&&this.#o.signal instanceof EventTarget&&(r.signal=this.#o.signal)),typeof document<"u"&&(r.credentials=this.withCredentials?"include":"omit"),fetch(this.#t,r).then((e=>(e.headers.forEach(((e,t)=>{this.#r+=`${t}: ${e}\r\n`})),this.status=e.status,this.statusText=e.statusText,this.readyState=3,this.onreadystatechange?.(),t?e.text():e.arrayBuffer()))).then((e=>{"string"==typeof e?this.responseText=e:this.response=e,this.readyState=4,this.onreadystatechange?.()})).catch((e=>{"AbortError"!==e.name?this.onerror?.(e):this.onabort?.()}))}};const y="function"==typeof XMLHttpRequest?"xhr":"fetch",g="xhr"===y?XMLHttpRequest:d,m=(e,t)=>{const r=e.options,n=e.applyMiddleware("finalizeOptions",r),o={},s=e.applyMiddleware("interceptRequest",void 0,{adapter:y,context:e});if(s){const e=setTimeout(t,0,null,s);return{abort:()=>clearTimeout(e)}}let i=new g;i instanceof d&&"object"==typeof n.fetch&&i.setInit(n.fetch,n.useAbortSignal??!0);const a=n.headers,c=n.timeout;let u=!1,l=!1,h=!1;if(i.onerror=e=>{b(i instanceof d?e instanceof Error?e:new Error(`Request error while attempting to reach is ${n.url}`,{cause:e}):new Error(`Request error while attempting to reach is ${n.url}${e.lengthComputable?`(${e.loaded} of ${e.total} bytes transferred)`:""}`))},i.ontimeout=e=>{b(new Error(`Request timeout while attempting to reach ${n.url}${e.lengthComputable?`(${e.loaded} of ${e.total} bytes transferred)`:""}`))},i.onabort=()=>{m(!0),u=!0},i.onreadystatechange=()=>{c&&(m(),o.socket=setTimeout((()=>p("ESOCKETTIMEDOUT")),c.socket)),!u&&4===i.readyState&&0!==i.status&&function(){if(!(u||l||h)){if(0===i.status)return void b(new Error("Unknown XHR error"));m(),l=!0,t(null,{body:i.response||(""===i.responseType||"text"===i.responseType?i.responseText:""),url:n.url,method:n.method,headers:f(i.getAllResponseHeaders()),statusCode:i.status,statusMessage:i.statusText})}}()},i.open(n.method,n.url,!0),i.withCredentials=!!n.withCredentials,a&&i.setRequestHeader)for(const e in a)a.hasOwnProperty(e)&&i.setRequestHeader(e,a[e]);return n.rawBody&&(i.responseType="arraybuffer"),e.applyMiddleware("onRequest",{options:n,adapter:y,request:i,context:e}),i.send(n.body||null),c&&(o.connect=setTimeout((()=>p("ETIMEDOUT")),c.connect)),{abort:function(){u=!0,i&&i.abort()}};function p(t){h=!0,i.abort();const r=new Error("ESOCKETTIMEDOUT"===t?`Socket timed out on request to ${n.url}`:`Connection timed out on request to ${n.url}`);r.code=t,e.channels.error.publish(r)}function m(e){(e||u||i.readyState>=2&&o.connect)&&clearTimeout(o.connect),o.socket&&clearTimeout(o.socket)}function b(e){if(l)return;m(!0),l=!0,i=null;const r=e||new Error(`Network error while attempting to reach ${n.url}`);r.isNetworkError=!0,r.request=n,t(r)}},b=(e=[],t=m)=>h(e,t);var v,w,C={exports:{}};var E=function(e){function t(e){let n,o,s,i=null;function a(...e){if(!a.enabled)return;const r=a,o=Number(new Date),s=o-(n||o);r.diff=s,r.prev=n,r.curr=o,n=o,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let i=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((n,o)=>{if("%%"===n)return"%";i++;const s=t.formatters[o];if("function"==typeof s){const t=e[i];n=s.call(r,t),e.splice(i,1),i--}return n})),t.formatArgs.call(r,e),(r.log||t.log).apply(r,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=r,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==i?i:(o!==t.namespaces&&(o=t.namespaces,s=t.enabled(e)),s),set:e=>{i=e}}),"function"==typeof t.init&&t.init(a),a}function r(e,r){const n=t(this.namespace+(typeof r>"u"?":":r)+e);return n.log=this.log,n}function n(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){return e instanceof Error?e.stack||e.message:e},t.disable=function(){const e=[...t.names.map(n),...t.skips.map(n).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let r;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const n=("string"==typeof e?e:"").split(/[\s,]+/),o=n.length;for(r=0;r<o;r++)n[r]&&("-"===(e=n[r].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.slice(1)+"$")):t.names.push(new RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;let r,n;for(r=0,n=t.skips.length;r<n;r++)if(t.skips[r].test(e))return!1;for(r=0,n=t.names.length;r<n;r++)if(t.names[r].test(e))return!0;return!1},t.humanize=function(){if(w)return v;w=1;var e=1e3,t=60*e,r=60*t,n=24*r,o=7*n;function s(e,t,r,n){var o=t>=1.5*r;return Math.round(e/r)+" "+n+(o?"s":"")}return v=function(i,a){a=a||{};var c,u,l=typeof i;if("string"===l&&i.length>0)return function(s){if(!((s=String(s)).length>100)){var i=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(s);if(i){var a=parseFloat(i[1]);switch((i[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*a;case"weeks":case"week":case"w":return a*o;case"days":case"day":case"d":return a*n;case"hours":case"hour":case"hrs":case"hr":case"h":return a*r;case"minutes":case"minute":case"mins":case"min":case"m":return a*t;case"seconds":case"second":case"secs":case"sec":case"s":return a*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return a;default:return}}}}(i);if("number"===l&&isFinite(i))return a.long?(c=i,(u=Math.abs(c))>=n?s(c,u,n,"day"):u>=r?s(c,u,r,"hour"):u>=t?s(c,u,t,"minute"):u>=e?s(c,u,e,"second"):c+" ms"):function(o){var s=Math.abs(o);return s>=n?Math.round(o/n)+"d":s>=r?Math.round(o/r)+"h":s>=t?Math.round(o/t)+"m":s>=e?Math.round(o/e)+"s":o+"ms"}(i);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(i))}}(),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((r=>{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t),r|=0;return t.colors[Math.abs(r)%t.colors.length]},t.enable(t.load()),t};!function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let n=0,o=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(n++,"%c"===e&&(o=n))})),t.splice(o,0,r)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch{}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch{}return!e&&typeof process<"u"&&"env"in process&&(e=process.env.DEBUG),e},t.useColors=function(){return!(!(typeof window<"u"&&window.process)||"renderer"!==window.process.type&&!window.process.__nwjs)||!(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&(typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},t.storage=function(){try{return localStorage}catch{}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=E(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(C,C.exports),c(C.exports);const x=typeof Buffer>"u"?()=>!1:e=>Buffer.isBuffer(e);function R(e){return"[object Object]"===Object.prototype.toString.call(e)}const S=["boolean","string","number"];function O(){return{processOptions:e=>{const t=e.body;return!t||"function"==typeof t.pipe||x(t)||-1===S.indexOf(typeof t)&&!Array.isArray(t)&&!function(e){if(!1===R(e))return!1;const t=e.constructor;if(void 0===t)return!0;const r=t.prototype;return!(!1===R(r)||!1===r.hasOwnProperty("isPrototypeOf"))}(t)?e:Object.assign({},e,{body:JSON.stringify(e.body),headers:Object.assign({},e.headers,{"Content-Type":"application/json"})})}}}function T(e){return{onResponse:e=>{const r=e.headers["content-type"]||"",n=-1!==r.indexOf("application/json");return e.body&&r&&n?Object.assign({},e,{body:t(e.body)}):e},processOptions:e=>Object.assign({},e,{headers:Object.assign({Accept:"application/json"},e.headers)})};function t(e){try{return JSON.parse(e)}catch(e){throw e.message=`Failed to parsed response body as JSON: ${e.message}`,e}}}let _={};typeof globalThis<"u"?_=globalThis:typeof window<"u"?_=window:typeof global<"u"?_=global:typeof self<"u"&&(_=self);var q=_;function j(e={}){const t=e.implementation||q.Observable;if(!t)throw new Error("`Observable` is not available in global scope, and no implementation was passed");return{onReturn:(e,r)=>new t((t=>(e.error.subscribe((e=>t.error(e))),e.progress.subscribe((e=>t.next(Object.assign({type:"progress"},e)))),e.response.subscribe((e=>{t.next(Object.assign({type:"response"},e)),t.complete()})),e.request.publish(r),()=>e.abort.publish())))}}var $=(e,t,r)=>("GET"===r.method||"HEAD"===r.method)&&(e.isNetworkError||!1);function A(e){return 100*Math.pow(2,e)+100*Math.random()}const I=(e={})=>(e=>{const t=e.maxRetries||5,r=e.retryDelay||A,n=e.shouldRetry;return{onError:(e,o)=>{const s=o.options,i=s.maxRetries||t,a=s.retryDelay||r,c=s.shouldRetry||n,u=s.attemptNumber||0;if(null!==(l=s.body)&&"object"==typeof l&&"function"==typeof l.pipe||!c(e,u,s)||u>=i)return e;var l;const h=Object.assign({},o,{options:Object.assign({},s,{attemptNumber:u+1})});return setTimeout((()=>o.channels.request.publish(h)),a(u)),null}}})({shouldRetry:$,...e});I.shouldRetry=$;var P=function(e,t){return P=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},P(e,t)};function k(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}P(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}function D(e,t,r,n){return new(r||(r=Promise))((function(o,s){function i(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(i,a)}c((n=n.apply(e,t||[])).next())}))}function F(e,t){var r,n,o,s,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(a){return function(c){return function(a){if(r)throw new TypeError("Generator is already executing.");for(;s&&(s=0,a[0]&&(i=0)),i;)try{if(r=1,n&&(o=2&a[0]?n.return:a[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,a[1])).done)return o;switch(n=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return i.label++,{value:a[1],done:!1};case 5:i.label++,n=a[1],a=[0];continue;case 7:a=i.ops.pop(),i.trys.pop();continue;default:if(!(o=i.trys,(o=o.length>0&&o[o.length-1])||6!==a[0]&&2!==a[0])){i=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]<o[3])){i.label=a[1];break}if(6===a[0]&&i.label<o[1]){i.label=o[1],o=a;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(a);break}o[2]&&i.ops.pop(),i.trys.pop();continue}a=t.call(e,i)}catch(e){a=[6,e],n=0}finally{r=o=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,c])}}}function M(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function U(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,o,s=r.call(e),i=[];try{for(;(void 0===t||t-- >0)&&!(n=s.next()).done;)i.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(r=s.return)&&r.call(s)}finally{if(o)throw o.error}}return i}function N(e,t,r){if(r||2===arguments.length)for(var n,o=0,s=t.length;o<s;o++)!n&&o in t||(n||(n=Array.prototype.slice.call(t,0,o)),n[o]=t[o]);return e.concat(n||Array.prototype.slice.call(t))}function L(e){return this instanceof L?(this.v=e,this):new L(e)}function z(e,t,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n,o=r.apply(e,t||[]),s=[];return n={},i("next"),i("throw"),i("return"),n[Symbol.asyncIterator]=function(){return this},n;function i(e){o[e]&&(n[e]=function(t){return new Promise((function(r,n){s.push([e,t,r,n])>1||a(e,t)}))})}function a(e,t){try{!function(e){e.value instanceof L?Promise.resolve(e.value.v).then(c,u):l(s[0][2],e)}(o[e](t))}catch(e){l(s[0][3],e)}}function c(e){a("next",e)}function u(e){a("throw",e)}function l(e,t){e(t),s.shift(),s.length&&a(s[0][0],s[0][1])}}function H(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e=M(e),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(r){t[r]=e[r]&&function(t){return new Promise((function(n,o){(function(e,t,r,n){Promise.resolve(n).then((function(t){e({value:t,done:r})}),t)})(n,o,(t=e[r](t)).done,t.value)}))}}}function B(e){return"function"==typeof e}function J(e){var t=e((function(e){Error.call(e),e.stack=(new Error).stack}));return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}"function"==typeof SuppressedError&&SuppressedError;var G=J((function(e){return function(t){e(this),this.message=t?t.length+" errors occurred during unsubscription:\n"+t.map((function(e,t){return t+1+") "+e.toString()})).join("\n "):"",this.name="UnsubscriptionError",this.errors=t}}));function V(e,t){if(e){var r=e.indexOf(t);0<=r&&e.splice(r,1)}}var X=function(){function e(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}var t;return e.prototype.unsubscribe=function(){var e,t,r,n,o;if(!this.closed){this.closed=!0;var s=this._parentage;if(s)if(this._parentage=null,Array.isArray(s))try{for(var i=M(s),a=i.next();!a.done;a=i.next()){a.value.remove(this)}}catch(t){e={error:t}}finally{try{a&&!a.done&&(t=i.return)&&t.call(i)}finally{if(e)throw e.error}}else s.remove(this);var c=this.initialTeardown;if(B(c))try{c()}catch(e){o=e instanceof G?e.errors:[e]}var u=this._finalizers;if(u){this._finalizers=null;try{for(var l=M(u),h=l.next();!h.done;h=l.next()){var p=h.value;try{W(p)}catch(e){o=null!=o?o:[],e instanceof G?o=N(N([],U(o)),U(e.errors)):o.push(e)}}}catch(e){r={error:e}}finally{try{h&&!h.done&&(n=l.return)&&n.call(l)}finally{if(r)throw r.error}}}if(o)throw new G(o)}},e.prototype.add=function(t){var r;if(t&&t!==this)if(this.closed)W(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=null!==(r=this._finalizers)&&void 0!==r?r:[]).push(t)}},e.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},e.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},e.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&V(t,e)},e.prototype.remove=function(t){var r=this._finalizers;r&&V(r,t),t instanceof e&&t._removeParent(this)},e.EMPTY=((t=new e).closed=!0,t),e}();function Q(e){return e instanceof X||e&&"closed"in e&&B(e.remove)&&B(e.add)&&B(e.unsubscribe)}function W(e){B(e)?e():e.unsubscribe()}X.EMPTY;var Y={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},K={setTimeout:function(e,t){for(var r=[],n=2;n<arguments.length;n++)r[n-2]=arguments[n];return setTimeout.apply(void 0,N([e,t],U(r)))},clearTimeout:function(e){var t=K.delegate;return((null==t?void 0:t.clearTimeout)||clearTimeout)(e)},delegate:void 0};function Z(e){K.setTimeout((function(){throw e}))}function ee(){}var te=function(e){function t(t){var r=e.call(this)||this;return r.isStopped=!1,t?(r.destination=t,Q(t)&&t.add(r)):r.destination=ae,r}return k(t,e),t.create=function(e,t,r){return new se(e,t,r)},t.prototype.next=function(e){this.isStopped||this._next(e)},t.prototype.error=function(e){this.isStopped||(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(e){this.destination.next(e)},t.prototype._error=function(e){try{this.destination.error(e)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t}(X),re=Function.prototype.bind;function ne(e,t){return re.call(e,t)}var oe=function(){function e(e){this.partialObserver=e}return e.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(e){ie(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){ie(e)}else ie(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){ie(e)}},e}(),se=function(e){function t(t,r,n){var o,s,i=e.call(this)||this;B(t)||!t?o={next:null!=t?t:void 0,error:null!=r?r:void 0,complete:null!=n?n:void 0}:i&&Y.useDeprecatedNextContext?((s=Object.create(t)).unsubscribe=function(){return i.unsubscribe()},o={next:t.next&&ne(t.next,s),error:t.error&&ne(t.error,s),complete:t.complete&&ne(t.complete,s)}):o=t;return i.destination=new oe(o),i}return k(t,e),t}(te);function ie(e){Z(e)}var ae={closed:!0,next:ee,error:function(e){throw e},complete:ee},ce="function"==typeof Symbol&&Symbol.observable||"@@observable";function ue(e){return e}function le(e){return 0===e.length?ue:1===e.length?e[0]:function(t){return e.reduce((function(e,t){return t(e)}),t)}}var he=function(){function e(e){e&&(this._subscribe=e)}return e.prototype.lift=function(t){var r=new e;return r.source=this,r.operator=t,r},e.prototype.subscribe=function(e,t,r){var n,o=this,s=(n=e)&&n instanceof te||function(e){return e&&B(e.next)&&B(e.error)&&B(e.complete)}(n)&&Q(n)?e:new se(e,t,r);return function(){var e=o,t=e.operator,r=e.source;s.add(t?t.call(s,r):r?o._subscribe(s):o._trySubscribe(s))}(),s},e.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},e.prototype.forEach=function(e,t){var r=this;return new(t=pe(t))((function(t,n){var o=new se({next:function(t){try{e(t)}catch(e){n(e),o.unsubscribe()}},error:n,complete:t});r.subscribe(o)}))},e.prototype._subscribe=function(e){var t;return null===(t=this.source)||void 0===t?void 0:t.subscribe(e)},e.prototype[ce]=function(){return this},e.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return le(e)(this)},e.prototype.toPromise=function(e){var t=this;return new(e=pe(e))((function(e,r){var n;t.subscribe((function(e){return n=e}),(function(e){return r(e)}),(function(){return e(n)}))}))},e.create=function(t){return new e(t)},e}();function pe(e){var t;return null!==(t=null!=e?e:Y.Promise)&&void 0!==t?t:Promise}function fe(e){return function(t){if(function(e){return B(null==e?void 0:e.lift)}(t))return t.lift((function(t){try{return e(t,this)}catch(e){this.error(e)}}));throw new TypeError("Unable to lift unknown Observable type")}}function de(e,t,r,n,o){return new ye(e,t,r,n,o)}var ye=function(e){function t(t,r,n,o,s,i){var a=e.call(this,t)||this;return a.onFinalize=s,a.shouldUnsubscribe=i,a._next=r?function(e){try{r(e)}catch(e){t.error(e)}}:e.prototype._next,a._error=o?function(e){try{o(e)}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._error,a._complete=n?function(){try{n()}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._complete,a}return k(t,e),t.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var r=this.closed;e.prototype.unsubscribe.call(this),!r&&(null===(t=this.onFinalize)||void 0===t||t.call(this))}},t}(te);var ge="function"==typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator";function me(e){if(e instanceof he)return e;if(null!=e){if(function(e){return B(e[ce])}(e))return s=e,new he((function(e){var t=s[ce]();if(B(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")}));if(function(e){return e&&"number"==typeof e.length&&"function"!=typeof e}(e))return o=e,new he((function(e){for(var t=0;t<o.length&&!e.closed;t++)e.next(o[t]);e.complete()}));if(B(null==(n=e)?void 0:n.then))return r=e,new he((function(e){r.then((function(t){e.closed||(e.next(t),e.complete())}),(function(t){return e.error(t)})).then(null,Z)}));if(function(e){return Symbol.asyncIterator&&B(null==e?void 0:e[Symbol.asyncIterator])}(e))return be(e);if(function(e){return B(null==e?void 0:e[ge])}(e))return t=e,new he((function(e){var r,n;try{for(var o=M(t),s=o.next();!s.done;s=o.next()){var i=s.value;if(e.next(i),e.closed)return}}catch(e){r={error:e}}finally{try{s&&!s.done&&(n=o.return)&&n.call(o)}finally{if(r)throw r.error}}e.complete()}));if(function(e){return B(null==e?void 0:e.getReader)}(e))return be(function(e){return z(this,arguments,(function(){var t,r,n;return F(this,(function(o){switch(o.label){case 0:t=e.getReader(),o.label=1;case 1:o.trys.push([1,,9,10]),o.label=2;case 2:return[4,L(t.read())];case 3:return r=o.sent(),n=r.value,r.done?[4,L(void 0)]:[3,5];case 4:return[2,o.sent()];case 5:return[4,L(n)];case 6:return[4,o.sent()];case 7:return o.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}}))}))}(e))}var t,r,n,o,s;throw function(e){return new TypeError("You provided "+(null!==e&&"object"==typeof e?"an invalid object":"'"+e+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}(e)}function be(e){return new he((function(t){(function(e,t){var r,n,o,s;return D(this,void 0,void 0,(function(){var i,a;return F(this,(function(c){switch(c.label){case 0:c.trys.push([0,5,6,11]),r=H(e),c.label=1;case 1:return[4,r.next()];case 2:if((n=c.sent()).done)return[3,4];if(i=n.value,t.next(i),t.closed)return[2];c.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return a=c.sent(),o={error:a},[3,11];case 6:return c.trys.push([6,,9,10]),n&&!n.done&&(s=r.return)?[4,s.call(r)]:[3,8];case 7:c.sent(),c.label=8;case 8:return[3,10];case 9:if(o)throw o.error;return[7];case 10:return[7];case 11:return t.complete(),[2]}}))}))})(e,t).catch((function(e){return t.error(e)}))}))}function ve(e,t){return me(e)}var we=J((function(e){return function(){e(this),this.name="EmptyError",this.message="no elements in sequence"}}));function Ce(e,t){return new Promise((function(t,r){var n,o=!1;e.subscribe({next:function(e){n=e,o=!0},error:r,complete:function(){o?t(n):r(new we)}})}))}function Ee(e,t){return fe((function(r,n){var o=0;r.subscribe(de(n,(function(r){n.next(e.call(t,r,o++))})))}))}var xe=Array.isArray;function Re(e){return Ee((function(t){return function(e,t){return xe(t)?e.apply(void 0,N([],U(t))):e(t)}(e,t)}))}function Se(e,t,r){t()}var Oe=Array.isArray;function Te(e,t){return fe((function(r,n){var o=0;r.subscribe(de(n,(function(r){return e.call(t,r,o++)&&n.next(r)})))}))}function _e(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r=function(e){return B((t=e)[t.length-1])?e.pop():void 0;var t}(e);return r?function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return le(e)}(_e.apply(void 0,N([],U(e))),Re(r)):fe((function(t,r){var n,o;(n=N([t],U(function(e){return 1===e.length&&Oe(e[0])?e[0]:e}(e))),void 0===o&&(o=ue),function(e){Se(0,(function(){for(var t=n.length,r=new Array(t),s=t,i=t,a=function(t){Se(0,(function(){var a=ve(n[t]),c=!1;a.subscribe(de(e,(function(n){r[t]=n,c||(c=!0,i--),i||e.next(o(r.slice()))}),(function(){--s||e.complete()})))}))},c=0;c<t;c++)a(c)}))})(r)}))}var qe={0:8203,1:8204,2:8205,3:8290,4:8291,5:8288,6:65279,7:8289,8:119155,9:119156,a:119157,b:119158,c:119159,d:119160,e:119161,f:119162},je={0:8203,1:8204,2:8205,3:65279},$e=new Array(4).fill(String.fromCodePoint(je[0])).join("");function Ae(e,t,r="auto"){return!0===r||"auto"===r&&(function(e){return!(!Number.isNaN(Number(e))||/[a-z]/i.test(e)&&!/\d+(?:[-:\/]\d+){2}(?:T\d+(?:[-:\/]\d+){1,2}(\.\d+)?Z?)?/.test(e)||!Date.parse(e))}(e)||function(e){try{new URL(e,e.startsWith("/")?"https://acme.com":void 0)}catch{return!1}return!0}(e))?e:`${e}${function(e){let t=JSON.stringify(e);return`${$e}${Array.from(t).map((e=>{let r=e.charCodeAt(0);if(r>255)throw new Error(`Only ASCII edit info can be encoded. Error attempting to encode ${t} on character ${e} (${r})`);return Array.from(r.toString(4).padStart(4,"0")).map((e=>String.fromCodePoint(je[e]))).join("")})).join("")}`}(t)}`}Object.fromEntries(Object.entries(je).map((e=>e.reverse()))),Object.fromEntries(Object.entries(qe).map((e=>e.reverse())));var Ie=`${Object.values(qe).map((e=>`\\u{${e.toString(16)}}`)).join("")}`,Pe=new RegExp(`[${Ie}]{4,}`,"gu");function ke(e){return e&&JSON.parse(function(e){var t;return{cleaned:e.replace(Pe,""),encoded:(null==(t=e.match(Pe))?void 0:t[0])||""}}(JSON.stringify(e)).cleaned)}class De extends Error{response;statusCode=400;responseBody;details;constructor(e){const t=Me(e);super(t.message),Object.assign(this,t)}}class Fe extends Error{response;statusCode=500;responseBody;details;constructor(e){const t=Me(e);super(t.message),Object.assign(this,t)}}function Me(e){const t=e.body,r={response:e,statusCode:e.statusCode,responseBody:Ne(t,e),message:"",details:void 0};if(t.error&&t.message)return r.message=`${t.error} - ${t.message}`,r;if(function(e){return Ue(e)&&Ue(e.error)&&"mutationError"===e.error.type&&"string"==typeof e.error.description}(t)||function(e){return Ue(e)&&Ue(e.error)&&"actionError"===e.error.type&&"string"==typeof e.error.description}(t)){const e=t.error.items||[],n=e.slice(0,5).map((e=>e.error?.description)).filter(Boolean);let o=n.length?`:\n- ${n.join("\n- ")}`:"";return e.length>5&&(o+=`\n...and ${e.length-5} more`),r.message=`${t.error.description}${o}`,r.details=t.error,r}return t.error&&t.error.description?(r.message=t.error.description,r.details=t.error,r):(r.message=t.error||t.message||function(e){const t=e.statusMessage?` ${e.statusMessage}`:"";return`${e.method}-request to ${e.url} resulted in HTTP ${e.statusCode}${t}`}(e),r)}function Ue(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Ne(e,t){return-1!==(t.headers["content-type"]||"").toLowerCase().indexOf("application/json")?JSON.stringify(e,null,2):e}class Le extends Error{projectId;addOriginUrl;constructor({projectId:e}){super("CorsOriginError"),this.name="CorsOriginError",this.projectId=e;const t=new URL(`https://sanity.io/manage/project/${e}/api`);if(typeof location<"u"){const{origin:e}=location;t.searchParams.set("cors","add"),t.searchParams.set("origin",e),this.addOriginUrl=t,this.message=`The current origin is not allowed to connect to the Live Content API. Add it here: ${t}`}else this.message=`The current origin is not allowed to connect to the Live Content API. Change your configuration here: ${t}`}}const ze={onResponse:e=>{if(e.statusCode>=500)throw new Fe(e);if(e.statusCode>=400)throw new De(e);return e}},He={onResponse:e=>{const t=e.headers["x-sanity-warning"];return(Array.isArray(t)?t:[t]).filter(Boolean).forEach((e=>console.warn(e))),e}};function Be(e,t,r){if(0===r.maxRetries)return!1;const n="GET"===r.method||"HEAD"===r.method,o=(r.uri||r.url).startsWith("/data/query"),s=e.response&&(429===e.response.statusCode||502===e.response.statusCode||503===e.response.statusCode);return!(!n&&!o||!s)||I.shouldRetry(e,t,r)}function Je(e){if("string"==typeof e)return{id:e};if(Array.isArray(e))return{query:"*[_id in $ids]",params:{ids:e}};if("object"==typeof e&&null!==e&&"query"in e&&"string"==typeof e.query)return"params"in e&&"object"==typeof e.params&&null!==e.params?{query:e.query,params:e.params}:{query:e.query};const t=["* Document ID (<docId>)","* Array of document IDs","* Object containing `query`"].join("\n");throw new Error(`Unknown selection - must be one of:\n\n${t}`)}const Ge=["image","file"],Ve=["before","after","replace"],Xe=e=>{if(!/^(~[a-z0-9]{1}[-\w]{0,63}|[a-z0-9]{1}[-\w]{0,63})$/.test(e))throw new Error("Datasets can only contain lowercase characters, numbers, underscores and dashes, and start with tilde, and be maximum 64 characters")},Qe=(e,t)=>{if(null===t||"object"!=typeof t||Array.isArray(t))throw new Error(`${e}() takes an object of properties`)},We=(e,t)=>{if("string"!=typeof t||!/^[a-z0-9_][a-z0-9_.-]{0,127}$/i.test(t)||t.includes(".."))throw new Error(`${e}(): "${t}" is not a valid document ID`)},Ye=(e,t)=>{if(!t._id)throw new Error(`${e}() requires that the document contains an ID ("_id" property)`);We(e,t._id)},Ke=e=>{if(!e.dataset)throw new Error("`dataset` must be provided to perform queries");return e.dataset||""},Ze=e=>{if("string"!=typeof e||!/^[a-z0-9._-]{1,75}$/i.test(e))throw new Error("Tag can only contain alphanumeric characters, underscores, dashes and dots, and be between one and 75 characters long.");return e};class et{selection;operations;constructor(e,t={}){this.selection=e,this.operations=t}set(e){return this._assign("set",e)}setIfMissing(e){return this._assign("setIfMissing",e)}diffMatchPatch(e){return Qe("diffMatchPatch",e),this._assign("diffMatchPatch",e)}unset(e){if(!Array.isArray(e))throw new Error("unset(attrs) takes an array of attributes to unset, non-array given");return this.operations=Object.assign({},this.operations,{unset:e}),this}inc(e){return this._assign("inc",e)}dec(e){return this._assign("dec",e)}insert(e,t,r){return((e,t,r)=>{const n="insert(at, selector, items)";if(-1===Ve.indexOf(e)){const e=Ve.map((e=>`"${e}"`)).join(", ");throw new Error(`${n} takes an "at"-argument which is one of: ${e}`)}if("string"!=typeof t)throw new Error(`${n} takes a "selector"-argument which must be a string`);if(!Array.isArray(r))throw new Error(`${n} takes an "items"-argument which must be an array`)})(e,t,r),this._assign("insert",{[e]:t,items:r})}append(e,t){return this.insert("after",`${e}[-1]`,t)}prepend(e,t){return this.insert("before",`${e}[0]`,t)}splice(e,t,r,n){const o=t<0?t-1:t,s=typeof r>"u"||-1===r?-1:Math.max(0,t+r),i=`${e}[${o}:${o<0&&s>=0?"":s}]`;return this.insert("replace",i,n||[])}ifRevisionId(e){return this.operations.ifRevisionID=e,this}serialize(){return{...Je(this.selection),...this.operations}}toJSON(){return this.serialize()}reset(){return this.operations={},this}_assign(e,t,r=!0){return Qe(e,t),this.operations=Object.assign({},this.operations,{[e]:Object.assign({},r&&this.operations[e]||{},t)}),this}_set(e,t){return this._assign(e,t,!1)}}class tt extends et{#a;constructor(e,t,r){super(e,t),this.#a=r}clone(){return new tt(this.selection,{...this.operations},this.#a)}commit(e){if(!this.#a)throw new Error("No `client` passed to patch, either provide one or pass the patch to a clients `mutate()` method");const t="string"==typeof this.selection,r=Object.assign({returnFirst:t,returnDocuments:!0},e);return this.#a.mutate({patch:this.serialize()},r)}}class rt extends et{#a;constructor(e,t,r){super(e,t),this.#a=r}clone(){return new rt(this.selection,{...this.operations},this.#a)}commit(e){if(!this.#a)throw new Error("No `client` passed to patch, either provide one or pass the patch to a clients `mutate()` method");const t="string"==typeof this.selection,r=Object.assign({returnFirst:t,returnDocuments:!0},e);return this.#a.mutate({patch:this.serialize()},r)}}const nt={returnDocuments:!1};class ot{operations;trxId;constructor(e=[],t){this.operations=e,this.trxId=t}create(e){return Qe("create",e),this._add({create:e})}createIfNotExists(e){const t="createIfNotExists";return Qe(t,e),Ye(t,e),this._add({[t]:e})}createOrReplace(e){const t="createOrReplace";return Qe(t,e),Ye(t,e),this._add({[t]:e})}delete(e){return We("delete",e),this._add({delete:{id:e}})}transactionId(e){return e?(this.trxId=e,this):this.trxId}serialize(){return[...this.operations]}toJSON(){return this.serialize()}reset(){return this.operations=[],this}_add(e){return this.operations.push(e),this}}class st extends ot{#a;constructor(e,t,r){super(e,r),this.#a=t}clone(){return new st([...this.operations],this.#a,this.trxId)}commit(e){if(!this.#a)throw new Error("No `client` passed to transaction, either provide one or pass the transaction to a clients `mutate()` method");return this.#a.mutate(this.serialize(),Object.assign({transactionId:this.trxId},nt,e||{}))}patch(e,t){const r="function"==typeof t;if("string"!=typeof e&&e instanceof rt)return this._add({patch:e.serialize()});if(r){const r=t(new rt(e,{},this.#a));if(!(r instanceof rt))throw new Error("function passed to `patch()` must return the patch");return this._add({patch:r.serialize()})}return this._add({patch:{id:e,...t}})}}class it extends ot{#a;constructor(e,t,r){super(e,r),this.#a=t}clone(){return new it([...this.operations],this.#a,this.trxId)}commit(e){if(!this.#a)throw new Error("No `client` passed to transaction, either provide one or pass the transaction to a clients `mutate()` method");return this.#a.mutate(this.serialize(),Object.assign({transactionId:this.trxId},nt,e||{}))}patch(e,t){const r="function"==typeof t;if("string"!=typeof e&&e instanceof tt)return this._add({patch:e.serialize()});if(r){const r=t(new tt(e,{},this.#a));if(!(r instanceof tt))throw new Error("function passed to `patch()` must return the patch");return this._add({patch:r.serialize()})}return this._add({patch:{id:e,...t}})}}function at(e){return"https://www.sanity.io/help/"+e}const ct=e=>function(e){let t,r=!1;return(...n)=>(r||(t=e(...n),r=!0),t)}(((...t)=>console.warn(e.join(" "),...t))),ut=ct(["Because you set `withCredentials` to true, we will override your `useCdn`","setting to be false since (cookie-based) credentials are never set on the CDN"]),lt=ct(["Since you haven't set a value for `useCdn`, we will deliver content using our","global, edge-cached API-CDN. If you wish to have content delivered faster, set","`useCdn: false` to use the Live API. Note: You may incur higher costs using the live API."]),ht=ct(["The Sanity client is configured with the `perspective` set to `previewDrafts`, which doesn't support the API-CDN.","The Live API will be used instead. Set `useCdn: false` in your configuration to hide this warning."]),pt=ct(["You have configured Sanity client to use a token in the browser. This may cause unintentional security issues.",`See ${at("js-client-browser-token")} for more information and how to hide this warning.`]),ft=ct(["Using the Sanity client without specifying an API version is deprecated.",`See ${at("js-client-api-version")}`]),dt=ct(["The default export of @sanity/client has been deprecated. Use the named export `createClient` instead."]),yt={apiHost:"https://api.sanity.io",apiVersion:"1",useProjectHostname:!0,stega:{enabled:!1}},gt=["localhost","127.0.0.1","0.0.0.0"];const mt=function(e){switch(e){case"previewDrafts":case"published":case"raw":return;default:throw new TypeError("Invalid API perspective string, expected `published`, `previewDrafts` or `raw`")}},bt=(e,t)=>{const r={...t,...e,stega:{..."boolean"==typeof t.stega?{enabled:t.stega}:t.stega||yt.stega,..."boolean"==typeof e.stega?{enabled:e.stega}:e.stega||{}}};r.apiVersion||ft();const n={...yt,...r},o=n.useProjectHostname;if(typeof Promise>"u"){const e=at("js-client-promise-polyfill");throw new Error(`No native Promise-implementation found, polyfill needed - see ${e}`)}if(o&&!n.projectId)throw new Error("Configuration must contain `projectId`");if("string"==typeof n.perspective&&mt(n.perspective),"encodeSourceMap"in n)throw new Error("It looks like you're using options meant for '@sanity/preview-kit/client'. 'encodeSourceMap' is not supported in '@sanity/client'. Did you mean 'stega.enabled'?");if("encodeSourceMapAtPath"in n)throw new Error("It looks like you're using options meant for '@sanity/preview-kit/client'. 'encodeSourceMapAtPath' is not supported in '@sanity/client'. Did you mean 'stega.filter'?");if("boolean"!=typeof n.stega.enabled)throw new Error(`stega.enabled must be a boolean, received ${n.stega.enabled}`);if(n.stega.enabled&&void 0===n.stega.studioUrl)throw new Error("stega.studioUrl must be defined when stega.enabled is true");if(n.stega.enabled&&"string"!=typeof n.stega.studioUrl&&"function"!=typeof n.stega.studioUrl)throw new Error(`stega.studioUrl must be a string or a function, received ${n.stega.studioUrl}`);const s=typeof window<"u"&&window.location&&window.location.hostname,i=s&&(e=>-1!==gt.indexOf(e))(window.location.hostname);s&&i&&n.token&&!0!==n.ignoreBrowserTokenWarning?pt():typeof n.useCdn>"u"&<(),o&&(e=>{if(!/^[-a-z0-9]+$/i.test(e))throw new Error("`projectId` can only contain only a-z, 0-9 and dashes")})(n.projectId),n.dataset&&Xe(n.dataset),"requestTagPrefix"in n&&(n.requestTagPrefix=n.requestTagPrefix?Ze(n.requestTagPrefix).replace(/\.+$/,""):void 0),n.apiVersion=`${n.apiVersion}`.replace(/^v/,""),n.isDefaultApi=n.apiHost===yt.apiHost,!0===n.useCdn&&n.withCredentials&&ut(),n.useCdn=!1!==n.useCdn&&!n.withCredentials,function(e){if("1"===e||"X"===e)return;const t=new Date(e);if(!(/^\d{4}-\d{2}-\d{2}$/.test(e)&&t instanceof Date&&t.getTime()>0))throw new Error("Invalid API version string, expected `1` or date in format `YYYY-MM-DD`")}(n.apiVersion);const a=n.apiHost.split("://",2),c=a[0],u=a[1],l=n.isDefaultApi?"apicdn.sanity.io":u;return n.useProjectHostname?(n.url=`${c}://${n.projectId}.${u}/v${n.apiVersion}`,n.cdnUrl=`${c}://${n.projectId}.${l}/v${n.apiVersion}`):(n.url=`${n.apiHost}/v${n.apiVersion}`,n.cdnUrl=n.url),n};const vt=({query:e,params:t={},options:r={}})=>{const n=new URLSearchParams,{tag:o,includeMutations:s,returnQuery:i,...a}=r;o&&n.append("tag",o),n.append("query",e);for(const[e,r]of Object.entries(t))n.append(`$${e}`,JSON.stringify(r));for(const[e,t]of Object.entries(a))t&&n.append(e,`${t}`);return!1===i&&n.append("returnQuery","false"),!1===s&&n.append("includeMutations","false"),`?${n}`},wt=(e={})=>{return{dryRun:e.dryRun,returnIds:!0,returnDocuments:(t=e.returnDocuments,r=!0,!1===t?void 0:typeof t>"u"?r:t),visibility:e.visibility||"sync",autoGenerateArrayKeys:e.autoGenerateArrayKeys,skipCrossDatasetReferenceValidation:e.skipCrossDatasetReferenceValidation};var t,r},Ct=e=>"response"===e.type,Et=e=>e.body;function xt(e,t,r,n,o={},s={}){const i="stega"in s?{...r||{},..."boolean"==typeof s.stega?{enabled:s.stega}:s.stega||{}}:r,a=i.enabled?ke(o):o,c=!1===s.filterResponse?e=>e:e=>e.result,{cache:u,next:l,...h}={useAbortSignal:typeof s.signal<"u",resultSourceMap:i.enabled?"withKeyArraySelector":s.resultSourceMap,...s,returnQuery:!1===s.filterResponse&&!1!==s.returnQuery},p=$t(e,t,"query",{query:n,params:a},typeof u<"u"||typeof l<"u"?{...h,fetch:{cache:u,next:l}}:h);return i.enabled?p.pipe(function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return _e.apply(void 0,N([],U(e)))}(ve(Promise.resolve().then((function(){return Or})).then((function(e){return e.stegaEncodeSourceMap$1})).then((({stegaEncodeSourceMap:e})=>e)))),Ee((([e,t])=>{const r=t(e.result,e.resultSourceMap,i);return c({...e,result:r})}))):p.pipe(Ee(c))}function Rt(e,t,r,n={}){return It(e,t,{uri:kt(e,"doc",r),json:!0,tag:n.tag,signal:n.signal}).pipe(Te(Ct),Ee((e=>e.body.documents&&e.body.documents[0])))}function St(e,t,r,n={}){return It(e,t,{uri:kt(e,"doc",r.join(",")),json:!0,tag:n.tag,signal:n.signal}).pipe(Te(Ct),Ee((e=>{const t=(n=e.body.documents||[],o=e=>e._id,n.reduce(((e,t)=>(e[o(t)]=t,e)),Object.create(null)));var n,o;return r.map((e=>t[e]||null))})))}function Ot(e,t,r,n){return Ye("createIfNotExists",r),At(e,t,r,"createIfNotExists",n)}function Tt(e,t,r,n){return Ye("createOrReplace",r),At(e,t,r,"createOrReplace",n)}function _t(e,t,r,n){return $t(e,t,"mutate",{mutations:[{delete:Je(r)}]},n)}function qt(e,t,r,n){let o;o=r instanceof rt||r instanceof tt?{patch:r.serialize()}:r instanceof st||r instanceof it?r.serialize():r;return $t(e,t,"mutate",{mutations:Array.isArray(o)?o:[o],transactionId:n&&n.transactionId||void 0},n)}function jt(e,t,r,n){return $t(e,t,"actions",{actions:Array.isArray(r)?r:[r],transactionId:n&&n.transactionId||void 0,skipCrossDatasetReferenceValidation:n&&n.skipCrossDatasetReferenceValidation||void 0,dryRun:n&&n.dryRun||void 0},n)}function $t(e,t,r,n,o={}){const s="mutate"===r,i="actions"===r,a="query"===r,c=s||i?"":vt(n),u=!s&&!i&&c.length<11264,l=u?c:"",h=o.returnFirst,{timeout:p,token:f,tag:d,headers:y,returnQuery:g,lastLiveEventId:m}=o;return It(e,t,{method:u?"GET":"POST",uri:kt(e,r,l),json:!0,body:u?void 0:n,query:s&&wt(o),timeout:p,headers:y,token:f,tag:d,returnQuery:g,perspective:o.perspective,resultSourceMap:o.resultSourceMap,lastLiveEventId:Array.isArray(m)?m[0]:m,canUseCdn:a,signal:o.signal,fetch:o.fetch,useAbortSignal:o.useAbortSignal,useCdn:o.useCdn}).pipe(Te(Ct),Ee(Et),Ee((e=>{if(!s)return e;const t=e.results||[];if(o.returnDocuments)return h?t[0]&&t[0].document:t.map((e=>e.document));const r=h?"documentId":"documentIds",n=h?t[0]&&t[0].id:t.map((e=>e.id));return{transactionId:e.transactionId,results:t,[r]:n}})))}function At(e,t,r,n,o={}){return $t(e,t,"mutate",{mutations:[{[n]:r}]},Object.assign({returnFirst:!0,returnDocuments:!0},o))}function It(e,t,r){const n=r.url||r.uri,o=e.config(),s=typeof r.canUseCdn>"u"?["GET","HEAD"].indexOf(r.method||"GET")>=0&&0===n.indexOf("/data/"):r.canUseCdn;let i=(r.useCdn??o.useCdn)&&s;const a=r.tag&&o.requestTagPrefix?[o.requestTagPrefix,r.tag].join("."):r.tag||o.requestTagPrefix;if(a&&null!==r.tag&&(r.query={tag:Ze(a),...r.query}),["GET","HEAD","POST"].indexOf(r.method||"GET")>=0&&0===n.indexOf("/data/query/")){const e=r.resultSourceMap??o.resultSourceMap;void 0!==e&&!1!==e&&(r.query={resultSourceMap:e,...r.query});const t=r.perspective||o.perspective;"string"==typeof t&&"raw"!==t&&(mt(t),r.query={perspective:t,...r.query},"previewDrafts"===t&&i&&(i=!1,ht())),r.lastLiveEventId&&(r.query={...r.query,lastLiveEventId:r.lastLiveEventId}),!1===r.returnQuery&&(r.query={returnQuery:"false",...r.query})}const c=function(e,t={}){const r={},n=t.token||e.token;n&&(r.Authorization=`Bearer ${n}`),!t.useGlobalApi&&!e.useProjectHostname&&e.projectId&&(r["X-Sanity-Project-ID"]=e.projectId);const o=!!(typeof t.withCredentials>"u"?e.token||e.withCredentials:t.withCredentials),s=typeof t.timeout>"u"?e.timeout:t.timeout;return Object.assign({},t,{headers:Object.assign({},r,t.headers||{}),timeout:typeof s>"u"?3e5:s,proxy:t.proxy||e.proxy,json:!0,withCredentials:o,fetch:"object"==typeof t.fetch&&"object"==typeof e.fetch?{...e.fetch,...t.fetch}:t.fetch||e.fetch})}(o,Object.assign({},r,{url:Dt(e,n,i)})),u=new he((e=>t(c,o.requester).subscribe(e)));return r.signal?u.pipe((l=r.signal,e=>new he((t=>{const r=()=>t.error(function(e){if(Ft)return new DOMException(e?.reason??"The operation was aborted.","AbortError");const t=new Error(e?.reason??"The operation was aborted.");return t.name="AbortError",t}(l));if(l&&l.aborted)return void r();const n=e.subscribe(t);return l.addEventListener("abort",r),()=>{l.removeEventListener("abort",r),n.unsubscribe()}})))):u;var l}function Pt(e,t,r){return It(e,t,r).pipe(Te((e=>"response"===e.type)),Ee((e=>e.body)))}function kt(e,t,r){const n=e.config(),o=`/${t}/${Ke(n)}`;return`/data${r?`${o}/${r}`:o}`.replace(/\/($|\?)/,"$1")}function Dt(e,t,r=!1){const{url:n,cdnUrl:o}=e.config();return`${r?o:n}/${t.replace(/^\//,"")}`}const Ft=!!globalThis.DOMException;class Mt{#a;#c;constructor(e,t){this.#a=e,this.#c=t}upload(e,t,r){return Nt(this.#a,this.#c,e,t,r)}}class Ut{#a;#c;constructor(e,t){this.#a=e,this.#c=t}upload(e,t,r){return Ce(Nt(this.#a,this.#c,e,t,r).pipe(Te((e=>"response"===e.type)),Ee((e=>e.body.document))))}}function Nt(e,t,r,n,o={}){(e=>{if(-1===Ge.indexOf(e))throw new Error(`Invalid asset type: ${e}. Must be one of ${Ge.join(", ")}`)})(r);let s=o.extract||void 0;s&&!s.length&&(s=["none"]);const i=Ke(e.config()),a="image"===r?"images":"files",c=function(e,t){return typeof File>"u"||!(t instanceof File)?e:Object.assign({filename:!1===e.preserveFilename?void 0:t.name,contentType:t.type},e)}(o,n),{tag:u,label:l,title:h,description:p,creditLine:f,filename:d,source:y}=c,g={label:l,title:h,description:p,filename:d,meta:s,creditLine:f};return y&&(g.sourceId=y.id,g.sourceName=y.name,g.sourceUrl=y.url),It(e,t,{tag:u,method:"POST",timeout:c.timeout||0,uri:`/assets/${a}/${i}`,headers:c.contentType?{"Content-Type":c.contentType}:{},query:g,body:n})}const Lt=["includePreviousRevision","includeResult","includeMutations","visibility","effectFormat","tag"],zt={includeResult:!0};function Ht(e,t,r={}){const{url:n,token:o,withCredentials:s,requestTagPrefix:i}=this.config(),a=r.tag&&i?[i,r.tag].join("."):r.tag,c={...(h=r,p=zt,Object.keys(p).concat(Object.keys(h)).reduce(((e,t)=>(e[t]=typeof h[t]>"u"?p[t]:h[t],e)),{})),tag:a},u=((e,t)=>t.reduce(((t,r)=>(typeof e[r]>"u"||(t[r]=e[r]),t)),{}))(c,Lt),l=`${n}${kt(this,"listen",vt({query:e,params:t,options:{tag:a,...u}}))}`;var h,p;if(l.length>14800)return new he((e=>e.error(new Error("Query too large for listener"))));const f=c.events?c.events:["mutation"],d=-1!==f.indexOf("reconnect"),y={};return(o||s)&&(y.withCredentials=!0),o&&(y.headers={Authorization:`Bearer ${o}`}),new he((e=>{let t,r,n=!1,o=!1;function s(){n||(d&&e.next({type:"reconnect"}),!n&&t.readyState===t.CLOSED&&(u(),clearTimeout(r),r=setTimeout(h,100)))}function i(t){e.error(function(e){if(e instanceof Error)return e;const t=Bt(e);return t instanceof Error?t:new Error(function(e){return e.error?e.error.description?e.error.description:"string"==typeof e.error?e.error:JSON.stringify(e.error,null,2):e.message||"Unknown listener error"}(t))}(t))}function a(t){const r=Bt(t);return r instanceof Error?e.error(r):e.next(r)}function c(){n=!0,u(),e.complete()}function u(){t&&(t.removeEventListener("error",s),t.removeEventListener("channelError",i),t.removeEventListener("disconnect",c),f.forEach((e=>t.removeEventListener(e,a))),t.close())}function h(){(async function(){const{default:e}=await Promise.resolve().then((function(){return Dr}));if(o)return;const t=new e(l,y);return t.addEventListener("error",s),t.addEventListener("channelError",i),t.addEventListener("disconnect",c),f.forEach((e=>t.addEventListener(e,a))),t})().then((e=>{e&&(t=e,o&&u())})).catch((t=>{e.error(t),p()}))}function p(){n=!0,u(),o=!0}return h(),p}))}function Bt(e){try{const t=e.data&&JSON.parse(e.data)||{};return Object.assign({type:e.type},t)}catch(e){return e}}const Jt="2021-03-26";class Gt{#a;constructor(e){this.#a=e}events({includeDrafts:e=!1,tag:t}={}){const{projectId:r,apiVersion:n,token:o,withCredentials:s,requestTagPrefix:i}=this.#a.config(),a=n.replace(/^v/,"");if("X"!==a&&a<Jt)throw new Error(`The live events API requires API version ${Jt} or later. The current API version is ${a}. Please update your API version to use this feature.`);if(e&&!o&&!s)throw new Error("The live events API requires a token or withCredentials when 'includeDrafts: true'. Please update your client configuration. The token should have the lowest possible access role.");if(e&&"X"!==a)throw new Error("The live events API requires API version X when 'includeDrafts: true'. This API is experimental and may change or even be removed.");const c=kt(this.#a,"live/events"),u=new URL(this.#a.getUrl(c,!1)),l=t&&i?[i,t].join("."):t;l&&u.searchParams.set("tag",l),e&&u.searchParams.set("includeDrafts","true");const h=["restart","message","welcome","reconnect"],p={};return e&&o&&(p.headers={Authorization:`Bearer ${o}`}),e&&s&&(p.withCredentials=!0),new he((e=>{let t,n,o=!1,s=!1;function i(r){if(!o){if("data"in r){const t=Vt(r);e.error(new Error(t.message,{cause:t}))}t.readyState===t.CLOSED&&(c(),clearTimeout(n),n=setTimeout(l,100))}}function a(t){const r=Vt(t);return r instanceof Error?e.error(r):e.next(r)}function c(){if(t){t.removeEventListener("error",i);for(const e of h)t.removeEventListener(e,a);t.close()}}function l(){(async function(){const e=typeof EventSource>"u"||p.headers||p.withCredentials?(await Promise.resolve().then((function(){return Dr}))).default:EventSource;if(s)return;try{if(await fetch(u,{method:"OPTIONS",mode:"cors",credentials:p.withCredentials?"include":"omit",headers:p.headers}),s)return}catch{throw new Le({projectId:r})}const t=new e(u.toString(),p);t.addEventListener("error",i);for(const e of h)t.addEventListener(e,a);return t})().then((e=>{e&&(t=e,s&&c())})).catch((t=>{e.error(t),f()}))}function f(){o=!0,c(),s=!0}return l(),f}))}}function Vt(e){try{const t=e.data&&JSON.parse(e.data)||{};return{type:e.type,id:e.lastEventId,...t}}catch(e){return e}}class Xt{#a;#c;constructor(e,t){this.#a=e,this.#c=t}create(e,t){return Wt(this.#a,this.#c,"PUT",e,t)}edit(e,t){return Wt(this.#a,this.#c,"PATCH",e,t)}delete(e){return Wt(this.#a,this.#c,"DELETE",e)}list(){return Pt(this.#a,this.#c,{uri:"/datasets",tag:null})}}class Qt{#a;#c;constructor(e,t){this.#a=e,this.#c=t}create(e,t){return Ce(Wt(this.#a,this.#c,"PUT",e,t))}edit(e,t){return Ce(Wt(this.#a,this.#c,"PATCH",e,t))}delete(e){return Ce(Wt(this.#a,this.#c,"DELETE",e))}list(){return Ce(Pt(this.#a,this.#c,{uri:"/datasets",tag:null}))}}function Wt(e,t,r,n,o){return Xe(n),Pt(e,t,{method:r,uri:`/datasets/${n}`,body:o,tag:null})}class Yt{#a;#c;constructor(e,t){this.#a=e,this.#c=t}list(e){const t=!1===e?.includeMembers?"/projects?includeMembers=false":"/projects";return Pt(this.#a,this.#c,{uri:t})}getById(e){return Pt(this.#a,this.#c,{uri:`/projects/${e}`})}}class Kt{#a;#c;constructor(e,t){this.#a=e,this.#c=t}list(e){const t=!1===e?.includeMembers?"/projects?includeMembers=false":"/projects";return Ce(Pt(this.#a,this.#c,{uri:t}))}getById(e){return Ce(Pt(this.#a,this.#c,{uri:`/projects/${e}`}))}}class Zt{#a;#c;constructor(e,t){this.#a=e,this.#c=t}getById(e){return Pt(this.#a,this.#c,{uri:`/users/${e}`})}}class er{#a;#c;constructor(e,t){this.#a=e,this.#c=t}getById(e){return Ce(Pt(this.#a,this.#c,{uri:`/users/${e}`}))}}class tr{assets;datasets;live;projects;users;#u;#c;listen=Ht;constructor(e,t=yt){this.config(t),this.#c=e,this.assets=new Mt(this,this.#c),this.datasets=new Xt(this,this.#c),this.live=new Gt(this),this.projects=new Yt(this,this.#c),this.users=new Zt(this,this.#c)}clone(){return new tr(this.#c,this.config())}config(e){if(void 0===e)return{...this.#u};if(this.#u&&!1===this.#u.allowReconfigure)throw new Error("Existing client instance cannot be reconfigured - use `withConfig(newConfig)` to return a new client");return this.#u=bt(e,this.#u||{}),this}withConfig(e){const t=this.config();return new tr(this.#c,{...t,...e,stega:{...t.stega||{},..."boolean"==typeof e?.stega?{enabled:e.stega}:e?.stega||{}}})}fetch(e,t,r){return xt(this,this.#c,this.#u.stega,e,t,r)}getDocument(e,t){return Rt(this,this.#c,e,t)}getDocuments(e,t){return St(this,this.#c,e,t)}create(e,t){return At(this,this.#c,e,"create",t)}createIfNotExists(e,t){return Ot(this,this.#c,e,t)}createOrReplace(e,t){return Tt(this,this.#c,e,t)}delete(e,t){return _t(this,this.#c,e,t)}mutate(e,t){return qt(this,this.#c,e,t)}patch(e,t){return new tt(e,t,this)}transaction(e){return new it(e,this)}action(e,t){return jt(this,this.#c,e,t)}request(e){return Pt(this,this.#c,e)}getUrl(e,t){return Dt(this,e,t)}getDataUrl(e,t){return kt(this,e,t)}}class rr{assets;datasets;live;projects;users;observable;#u;#c;listen=Ht;constructor(e,t=yt){this.config(t),this.#c=e,this.assets=new Ut(this,this.#c),this.datasets=new Qt(this,this.#c),this.live=new Gt(this),this.projects=new Kt(this,this.#c),this.users=new er(this,this.#c),this.observable=new tr(e,t)}clone(){return new rr(this.#c,this.config())}config(e){if(void 0===e)return{...this.#u};if(this.#u&&!1===this.#u.allowReconfigure)throw new Error("Existing client instance cannot be reconfigured - use `withConfig(newConfig)` to return a new client");return this.observable&&this.observable.config(e),this.#u=bt(e,this.#u||{}),this}withConfig(e){const t=this.config();return new rr(this.#c,{...t,...e,stega:{...t.stega||{},..."boolean"==typeof e?.stega?{enabled:e.stega}:e?.stega||{}}})}fetch(e,t,r){return Ce(xt(this,this.#c,this.#u.stega,e,t,r))}getDocument(e,t){return Ce(Rt(this,this.#c,e,t))}getDocuments(e,t){return Ce(St(this,this.#c,e,t))}create(e,t){return Ce(At(this,this.#c,e,"create",t))}createIfNotExists(e,t){return Ce(Ot(this,this.#c,e,t))}createOrReplace(e,t){return Ce(Tt(this,this.#c,e,t))}delete(e,t){return Ce(_t(this,this.#c,e,t))}mutate(e,t){return Ce(qt(this,this.#c,e,t))}patch(e,t){return new rt(e,t,this)}transaction(e){return new st(e,this)}action(e,t){return Ce(jt(this,this.#c,e,t))}request(e){return Ce(Pt(this,this.#c,e))}dataRequest(e,t,r){return Ce($t(this,this.#c,e,t,r))}getUrl(e,t){return Dt(this,e,t)}getDataUrl(e,t){return kt(this,e,t)}}const nr=function(e,t){const r=function(e){return b([I({shouldRetry:Be}),...e,He,O(),T(),{onRequest:e=>{if("xhr"!==e.adapter)return;const t=e.request,r=e.context;function n(e){return t=>{const n=t.lengthComputable?t.loaded/t.total*100:-1;r.channels.progress.publish({stage:e,percent:n,total:t.total,loaded:t.loaded,lengthComputable:t.lengthComputable})}}"upload"in t&&"onprogress"in t.upload&&(t.upload.onprogress=n("upload")),"onprogress"in t&&(t.onprogress=n("download"))}},ze,j({implementation:he})])}(e);return{requester:r,createClient:e=>new t(((t,n)=>(n||r)({maxRedirects:0,maxRetries:e.maxRetries,retryDelay:e.retryDelay,...t})),e)}}([],rr),or=nr.requester,sr=nr.createClient,ir=(ar=sr,function(e){return dt(),ar(e)});var ar;const cr=/_key\s*==\s*['"](.*)['"]/;function ur(e){if(!Array.isArray(e))throw new Error("Path is not an array");return e.reduce(((e,t,r)=>{const n=typeof t;if("number"===n)return`${e}[${t}]`;if("string"===n)return`${e}${0===r?"":"."}${t}`;if(function(e){return"string"==typeof e?cr.test(e.trim()):"object"==typeof e&&"_key"in e}(t)&&t._key)return`${e}[_key=="${t._key}"]`;if(Array.isArray(t)){const[r,n]=t;return`${e}[${r}:${n}]`}throw new Error(`Unsupported path segment \`${JSON.stringify(t)}\``)}),"")}const lr={"\f":"\\f","\n":"\\n","\r":"\\r","\t":"\\t","'":"\\'","\\":"\\\\"},hr={"\\f":"\f","\\n":"\n","\\r":"\r","\\t":"\t","\\'":"'","\\\\":"\\"};function pr(e){const t=[],r=/\['(.*?)'\]|\[(\d+)\]|\[\?\(@\._key=='(.*?)'\)\]/g;let n;for(;null!==(n=r.exec(e));)if(void 0===n[1])if(void 0===n[2])if(void 0===n[3]);else{const e=n[3].replace(/\\(\\')/g,(e=>hr[e]));t.push({_key:e,_index:-1})}else t.push(parseInt(n[2],10));else{const e=n[1].replace(/\\(\\|f|n|r|t|')/g,(e=>hr[e]));t.push(e)}return t}function fr(e){return e.map((e=>{if("string"==typeof e||"number"==typeof e)return e;if(""!==e._key)return{_key:e._key};if(-1!==e._index)return e._index;throw new Error(`invalid segment:${JSON.stringify(e)}`)}))}function dr(e,t){if(!t?.mappings)return;const r=function(e){return`$${e.map((e=>"string"==typeof e?`['${e.replace(/[\f\n\r\t'\\]/g,(e=>lr[e]))}']`:"number"==typeof e?`[${e}]`:""!==e._key?`[?(@._key=='${e._key.replace(/['\\]/g,(e=>lr[e]))}')]`:`[${e._index}]`)).join("")}`}(e.map((e=>{if("string"==typeof e||"number"==typeof e)return e;if(-1!==e._index)return e._index;throw new Error(`invalid segment:${JSON.stringify(e)}`)})));if(void 0!==t.mappings[r])return{mapping:t.mappings[r],matchedPath:r,pathSuffix:""};const n=Object.entries(t.mappings).filter((([e])=>r.startsWith(e))).sort((([e],[t])=>t.length-e.length));if(0==n.length)return;const[o,s]=n[0];return{mapping:s,matchedPath:o,pathSuffix:r.substring(o.length)}}function yr(e){return"object"==typeof e&&null!==e}function gr(e,t,r=[]){return function(e){return null!==e&&Array.isArray(e)}(e)?e.map(((e,n)=>{if(yr(e)){const o=e._key;if("string"==typeof o)return gr(e,t,r.concat({_key:o,_index:n}))}return gr(e,t,r.concat(n))})):yr(e)?Object.fromEntries(Object.entries(e).map((([e,n])=>[e,gr(n,t,r.concat(e))]))):t(e,r)}function mr(e,t,r){return gr(e,((e,n)=>{if("string"!=typeof e)return e;const o=dr(n,t);if(!o)return e;const{mapping:s,matchedPath:i}=o;if("value"!==s.type||"documentValue"!==s.source.type)return e;const a=t.documents[s.source.document],c=t.paths[s.source.path],u=pr(i),l=pr(c).concat(n.slice(u.length));return r({sourcePath:l,sourceDocument:a,resultPath:n,value:e})}))}const br="drafts.";function vr(e){const{baseUrl:t,workspace:r="default",tool:n="default",id:o,type:s,path:i,projectId:a,dataset:c}=e;if(!t)throw new Error("baseUrl is required");if(!i)throw new Error("path is required");if(!o)throw new Error("id is required");if("/"!==t&&t.endsWith("/"))throw new Error("baseUrl must not end with a slash");const u="default"===r?void 0:r,l="default"===n?void 0:n,h=function(e){return e.startsWith(br)?e.slice(7):e}(o),p=Array.isArray(i)?ur(fr(i)):i,f=new URLSearchParams({baseUrl:t,id:h,type:s,path:p});u&&f.set("workspace",u),l&&f.set("tool",l),a&&f.set("projectId",a),c&&f.set("dataset",c),o.startsWith(br)&&f.set("isDraft","");const d=["/"===t?"":t];u&&d.push(u);const y=["mode=presentation",`id=${h}`,`type=${s}`,`path=${encodeURIComponent(p)}`];return l&&y.push(`tool=${l}`),d.push("intent","edit",`${y.join(";")}?${f}`),d.join("/")}const wr=({sourcePath:e,resultPath:t,value:r})=>{if(/^\d{4}-\d{2}-\d{2}/.test(n=r)&&Date.parse(n)||function(e){try{new URL(e,e.startsWith("/")?"https://acme.com":void 0)}catch{return!1}return!0}(r))return!1;var n;const o=e.at(-1);return!("slug"===e.at(-2)&&"current"===o||"string"==typeof o&&o.startsWith("_")||"number"==typeof o&&"marks"===e.at(-2)||"href"===o&&"number"==typeof e.at(-2)&&"markDefs"===e.at(-3)||"style"===o||"listItem"===o||e.some((e=>"meta"===e||"metadata"===e||"openGraph"===e||"seo"===e))||Er(e)||Er(t)||"string"==typeof o&&Cr.has(o))},Cr=new Set(["color","colour","currency","email","format","gid","hex","href","hsl","hsla","icon","id","index","key","language","layout","link","linkAction","locale","lqip","page","path","ref","rgb","rgba","route","secret","slug","status","tag","template","theme","type","unit","url","username","variant","website"]);function Er(e){return e.some((e=>"string"==typeof e&&null!==e.match(/type/i)))}function xr(e,t,r){const{filter:n,logger:o,enabled:s}=r;if(!s){const n="config.enabled must be true, don't call this function otherwise";throw o?.error?.(`[@sanity/client]: ${n}`,{result:e,resultSourceMap:t,config:r}),new TypeError(n)}if(!t)return o?.error?.("[@sanity/client]: Missing Content Source Map from response body",{result:e,resultSourceMap:t,config:r}),e;if(!r.studioUrl){const n="config.studioUrl must be defined";throw o?.error?.(`[@sanity/client]: ${n}`,{result:e,resultSourceMap:t,config:r}),new TypeError(n)}const i={encoded:[],skipped:[]},a=mr(e,t,(({sourcePath:e,sourceDocument:t,resultPath:s,value:a})=>{if(!1===("function"==typeof n?n({sourcePath:e,resultPath:s,filterDefault:wr,sourceDocument:t,value:a}):wr({sourcePath:e,resultPath:s,filterDefault:wr,sourceDocument:t,value:a})))return o&&i.skipped.push({path:Rr(e),value:`${a.slice(0,20)}${a.length>20?"...":""}`,length:a.length}),a;o&&i.encoded.push({path:Rr(e),value:`${a.slice(0,20)}${a.length>20?"...":""}`,length:a.length});const{baseUrl:c,workspace:u,tool:l}=function(e){let t="string"==typeof e?e:e.baseUrl;return"/"!==t&&(t=t.replace(/\/$/,"")),"string"==typeof e?{baseUrl:t}:{...e,baseUrl:t}}("function"==typeof r.studioUrl?r.studioUrl(t):r.studioUrl);if(!c)return a;const{_id:h,_type:p,_projectId:f,_dataset:d}=t;return Ae(a,{origin:"sanity.io",href:vr({baseUrl:c,workspace:u,tool:l,id:h,type:p,path:e,...!r.omitCrossDatasetReferenceData&&{dataset:d,projectId:f}})},!1)}));if(o){const e=i.skipped.length,t=i.encoded.length;if((e||t)&&((o?.groupCollapsed||o.log)?.("[@sanity/client]: Encoding source map into result"),o.log?.(`[@sanity/client]: Paths encoded: ${i.encoded.length}, skipped: ${i.skipped.length}`)),i.encoded.length>0&&(o?.log?.("[@sanity/client]: Table of encoded paths"),(o?.table||o.log)?.(i.encoded)),i.skipped.length>0){const e=new Set;for(const{path:t}of i.skipped)e.add(t.replace(cr,"0").replace(/\[\d+\]/g,"[]"));o?.log?.("[@sanity/client]: List of skipped paths",[...e.values()])}(e||t)&&o?.groupEnd?.()}return a}function Rr(e){return ur(fr(e))}var Sr=Object.freeze({__proto__:null,stegaEncodeSourceMap:xr}),Or=Object.freeze({__proto__:null,encodeIntoResult:mr,stegaEncodeSourceMap:xr,stegaEncodeSourceMap$1:Sr});function Tr(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var _r,qr,jr,$r={exports:{}},Ar=$r.exports;
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).SanityClient={})}(this,(function(e){"use strict";const t=!(typeof navigator>"u")&&"ReactNative"===navigator.product,r={timeout:t?6e4:12e4},n=function(e){const n={...r,..."string"==typeof e?{url:e}:e};if(n.timeout=s(n.timeout),n.query){const{url:e,searchParams:r}=function(e){const r=e.indexOf("?");if(-1===r)return{url:e,searchParams:new URLSearchParams};const n=e.slice(0,r),s=e.slice(r+1);if(!t)return{url:n,searchParams:new URLSearchParams(s)};if("function"!=typeof decodeURIComponent)throw new Error("Broken `URLSearchParams` implementation, and `decodeURIComponent` is not defined");const i=new URLSearchParams;for(const e of s.split("&")){const[t,r]=e.split("=");t&&i.append(o(t),o(r||""))}return{url:n,searchParams:i}}(n.url);for(const[t,o]of Object.entries(n.query)){if(void 0!==o)if(Array.isArray(o))for(const e of o)r.append(t,e);else r.append(t,o);const s=r.toString();s&&(n.url=`${e}?${s}`)}}return n.method=n.body&&!n.method?"POST":(n.method||"GET").toUpperCase(),n};function o(e){return decodeURIComponent(e.replace(/\+/g," "))}function s(e){if(!1===e||0===e)return!1;if(e.connect||e.socket)return e;const t=Number(e);return isNaN(t)?s(r.timeout):{connect:t,socket:t}}const i=/^https?:\/\//i,a=function(e){if(!i.test(e.url))throw new Error(`"${e.url}" is not a valid URL`)};function c(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}const u=["request","response","progress","error","abort"],l=["processOptions","validateOptions","interceptRequest","finalizeOptions","onRequest","onResponse","onError","onReturn","onHeaders"];function h(e,t){const r=[],o=l.reduce(((e,t)=>(e[t]=e[t]||[],e)),{processOptions:[n],validateOptions:[a]});function s(e){const r=u.reduce(((e,t)=>(e[t]=function(){const e=Object.create(null);let t=0;return{publish:function(t){for(const r in e)e[r](t)},subscribe:function(r){const n=t++;return e[n]=r,function(){delete e[n]}}}}(),e)),{}),n=(e=>function(t,r,...n){const o="onError"===t;let s=r;for(let r=0;r<e[t].length&&(s=(0,e[t][r])(s,...n),!o||s);r++);return s})(o),s=n("processOptions",e);n("validateOptions",s);const i={options:s,channels:r,applyMiddleware:n};let a;const c=r.request.subscribe((e=>{a=t(e,((t,o)=>((e,t,o)=>{let s=e,i=t;if(!s)try{i=n("onResponse",t,o)}catch(e){i=null,s=e}s=s&&n("onError",s,o),s?r.error.publish(s):i&&r.response.publish(i)})(t,o,e)))}));r.abort.subscribe((()=>{c(),a&&a.abort()}));const l=n("onReturn",r,i);return l===r&&r.request.publish(i),l}return s.use=function(e){if(!e)throw new Error("Tried to add middleware that resolved to falsey value");if("function"==typeof e)throw new Error("Tried to add middleware that was a function. It probably expects you to pass options to it.");if(e.onReturn&&o.onReturn.length>0)throw new Error("Tried to add new middleware with `onReturn` handler, but another handler has already been registered for this event");return l.forEach((t=>{e[t]&&o[t].push(e[t])})),r.push(e),s},s.clone=()=>h(r,t),e.forEach(s.use),s}var p=function(e){return e.replace(/^\s+|\s+$/g,"")},d=c((function(e){if(!e)return{};for(var t={},r=p(e).split("\n"),n=0;n<r.length;n++){var o=r[n],s=o.indexOf(":"),i=p(o.slice(0,s)).toLowerCase(),a=p(o.slice(s+1));typeof t[i]>"u"?t[i]=a:(c=t[i],"[object Array]"===Object.prototype.toString.call(c)?t[i].push(a):t[i]=[t[i],a])}var c;return t}));let f=class{onabort;onerror;onreadystatechange;ontimeout;readyState=0;response;responseText="";responseType="";status;statusText;withCredentials;#e;#t;#r;#n={};#o;#s={};#i;open(e,t,r){this.#e=e,this.#t=t,this.#r="",this.readyState=1,this.onreadystatechange?.(),this.#o=void 0}abort(){this.#o&&this.#o.abort()}getAllResponseHeaders(){return this.#r}setRequestHeader(e,t){this.#n[e]=t}setInit(e,t=!0){this.#s=e,this.#i=t}send(e){const t="arraybuffer"!==this.responseType,r={...this.#s,method:this.#e,headers:this.#n,body:e};"function"==typeof AbortController&&this.#i&&(this.#o=new AbortController,typeof EventTarget<"u"&&this.#o.signal instanceof EventTarget&&(r.signal=this.#o.signal)),typeof document<"u"&&(r.credentials=this.withCredentials?"include":"omit"),fetch(this.#t,r).then((e=>(e.headers.forEach(((e,t)=>{this.#r+=`${t}: ${e}\r\n`})),this.status=e.status,this.statusText=e.statusText,this.readyState=3,this.onreadystatechange?.(),t?e.text():e.arrayBuffer()))).then((e=>{"string"==typeof e?this.responseText=e:this.response=e,this.readyState=4,this.onreadystatechange?.()})).catch((e=>{"AbortError"!==e.name?this.onerror?.(e):this.onabort?.()}))}};const y="function"==typeof XMLHttpRequest?"xhr":"fetch",g="xhr"===y?XMLHttpRequest:f,m=(e,t)=>{const r=e.options,n=e.applyMiddleware("finalizeOptions",r),o={},s=e.applyMiddleware("interceptRequest",void 0,{adapter:y,context:e});if(s){const e=setTimeout(t,0,null,s);return{abort:()=>clearTimeout(e)}}let i=new g;i instanceof f&&"object"==typeof n.fetch&&i.setInit(n.fetch,n.useAbortSignal??!0);const a=n.headers,c=n.timeout;let u=!1,l=!1,h=!1;if(i.onerror=e=>{b(i instanceof f?e instanceof Error?e:new Error(`Request error while attempting to reach is ${n.url}`,{cause:e}):new Error(`Request error while attempting to reach is ${n.url}${e.lengthComputable?`(${e.loaded} of ${e.total} bytes transferred)`:""}`))},i.ontimeout=e=>{b(new Error(`Request timeout while attempting to reach ${n.url}${e.lengthComputable?`(${e.loaded} of ${e.total} bytes transferred)`:""}`))},i.onabort=()=>{m(!0),u=!0},i.onreadystatechange=()=>{c&&(m(),o.socket=setTimeout((()=>p("ESOCKETTIMEDOUT")),c.socket)),!u&&4===i.readyState&&0!==i.status&&function(){if(!(u||l||h)){if(0===i.status)return void b(new Error("Unknown XHR error"));m(),l=!0,t(null,{body:i.response||(""===i.responseType||"text"===i.responseType?i.responseText:""),url:n.url,method:n.method,headers:d(i.getAllResponseHeaders()),statusCode:i.status,statusMessage:i.statusText})}}()},i.open(n.method,n.url,!0),i.withCredentials=!!n.withCredentials,a&&i.setRequestHeader)for(const e in a)a.hasOwnProperty(e)&&i.setRequestHeader(e,a[e]);return n.rawBody&&(i.responseType="arraybuffer"),e.applyMiddleware("onRequest",{options:n,adapter:y,request:i,context:e}),i.send(n.body||null),c&&(o.connect=setTimeout((()=>p("ETIMEDOUT")),c.connect)),{abort:function(){u=!0,i&&i.abort()}};function p(t){h=!0,i.abort();const r=new Error("ESOCKETTIMEDOUT"===t?`Socket timed out on request to ${n.url}`:`Connection timed out on request to ${n.url}`);r.code=t,e.channels.error.publish(r)}function m(e){(e||u||i.readyState>=2&&o.connect)&&clearTimeout(o.connect),o.socket&&clearTimeout(o.socket)}function b(e){if(l)return;m(!0),l=!0,i=null;const r=e||new Error(`Network error while attempting to reach ${n.url}`);r.isNetworkError=!0,r.request=n,t(r)}},b=(e=[],t=m)=>h(e,t);var v,w,C={exports:{}};var E=function(e){function t(e){let n,o,s,i=null;function a(...e){if(!a.enabled)return;const r=a,o=Number(new Date),s=o-(n||o);r.diff=s,r.prev=n,r.curr=o,n=o,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let i=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((n,o)=>{if("%%"===n)return"%";i++;const s=t.formatters[o];if("function"==typeof s){const t=e[i];n=s.call(r,t),e.splice(i,1),i--}return n})),t.formatArgs.call(r,e),(r.log||t.log).apply(r,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=r,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==i?i:(o!==t.namespaces&&(o=t.namespaces,s=t.enabled(e)),s),set:e=>{i=e}}),"function"==typeof t.init&&t.init(a),a}function r(e,r){const n=t(this.namespace+(typeof r>"u"?":":r)+e);return n.log=this.log,n}function n(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){return e instanceof Error?e.stack||e.message:e},t.disable=function(){const e=[...t.names.map(n),...t.skips.map(n).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let r;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const n=("string"==typeof e?e:"").split(/[\s,]+/),o=n.length;for(r=0;r<o;r++)n[r]&&("-"===(e=n[r].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.slice(1)+"$")):t.names.push(new RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;let r,n;for(r=0,n=t.skips.length;r<n;r++)if(t.skips[r].test(e))return!1;for(r=0,n=t.names.length;r<n;r++)if(t.names[r].test(e))return!0;return!1},t.humanize=function(){if(w)return v;w=1;var e=1e3,t=60*e,r=60*t,n=24*r,o=7*n;function s(e,t,r,n){var o=t>=1.5*r;return Math.round(e/r)+" "+n+(o?"s":"")}return v=function(i,a){a=a||{};var c,u,l=typeof i;if("string"===l&&i.length>0)return function(s){if(!((s=String(s)).length>100)){var i=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(s);if(i){var a=parseFloat(i[1]);switch((i[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*a;case"weeks":case"week":case"w":return a*o;case"days":case"day":case"d":return a*n;case"hours":case"hour":case"hrs":case"hr":case"h":return a*r;case"minutes":case"minute":case"mins":case"min":case"m":return a*t;case"seconds":case"second":case"secs":case"sec":case"s":return a*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return a;default:return}}}}(i);if("number"===l&&isFinite(i))return a.long?(c=i,(u=Math.abs(c))>=n?s(c,u,n,"day"):u>=r?s(c,u,r,"hour"):u>=t?s(c,u,t,"minute"):u>=e?s(c,u,e,"second"):c+" ms"):function(o){var s=Math.abs(o);return s>=n?Math.round(o/n)+"d":s>=r?Math.round(o/r)+"h":s>=t?Math.round(o/t)+"m":s>=e?Math.round(o/e)+"s":o+"ms"}(i);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(i))}}(),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((r=>{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t),r|=0;return t.colors[Math.abs(r)%t.colors.length]},t.enable(t.load()),t};!function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let n=0,o=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(n++,"%c"===e&&(o=n))})),t.splice(o,0,r)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch{}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch{}return!e&&typeof process<"u"&&"env"in process&&(e=process.env.DEBUG),e},t.useColors=function(){return!(!(typeof window<"u"&&window.process)||"renderer"!==window.process.type&&!window.process.__nwjs)||!(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&(typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},t.storage=function(){try{return localStorage}catch{}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=E(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(C,C.exports),c(C.exports);const x=typeof Buffer>"u"?()=>!1:e=>Buffer.isBuffer(e);function R(e){return"[object Object]"===Object.prototype.toString.call(e)}const S=["boolean","string","number"];function O(){return{processOptions:e=>{const t=e.body;return!t||"function"==typeof t.pipe||x(t)||-1===S.indexOf(typeof t)&&!Array.isArray(t)&&!function(e){if(!1===R(e))return!1;const t=e.constructor;if(void 0===t)return!0;const r=t.prototype;return!(!1===R(r)||!1===r.hasOwnProperty("isPrototypeOf"))}(t)?e:Object.assign({},e,{body:JSON.stringify(e.body),headers:Object.assign({},e.headers,{"Content-Type":"application/json"})})}}}function T(e){return{onResponse:e=>{const r=e.headers["content-type"]||"",n=-1!==r.indexOf("application/json");return e.body&&r&&n?Object.assign({},e,{body:t(e.body)}):e},processOptions:e=>Object.assign({},e,{headers:Object.assign({Accept:"application/json"},e.headers)})};function t(e){try{return JSON.parse(e)}catch(e){throw e.message=`Failed to parsed response body as JSON: ${e.message}`,e}}}let _={};typeof globalThis<"u"?_=globalThis:typeof window<"u"?_=window:typeof global<"u"?_=global:typeof self<"u"&&(_=self);var q=_;function j(e={}){const t=e.implementation||q.Observable;if(!t)throw new Error("`Observable` is not available in global scope, and no implementation was passed");return{onReturn:(e,r)=>new t((t=>(e.error.subscribe((e=>t.error(e))),e.progress.subscribe((e=>t.next(Object.assign({type:"progress"},e)))),e.response.subscribe((e=>{t.next(Object.assign({type:"response"},e)),t.complete()})),e.request.publish(r),()=>e.abort.publish())))}}var $=(e,t,r)=>("GET"===r.method||"HEAD"===r.method)&&(e.isNetworkError||!1);function A(e){return 100*Math.pow(2,e)+100*Math.random()}const I=(e={})=>(e=>{const t=e.maxRetries||5,r=e.retryDelay||A,n=e.shouldRetry;return{onError:(e,o)=>{const s=o.options,i=s.maxRetries||t,a=s.retryDelay||r,c=s.shouldRetry||n,u=s.attemptNumber||0;if(null!==(l=s.body)&&"object"==typeof l&&"function"==typeof l.pipe||!c(e,u,s)||u>=i)return e;var l;const h=Object.assign({},o,{options:Object.assign({},s,{attemptNumber:u+1})});return setTimeout((()=>o.channels.request.publish(h)),a(u)),null}}})({shouldRetry:$,...e});I.shouldRetry=$;var P=function(e,t){return P=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},P(e,t)};function k(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}P(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}function D(e,t,r,n){return new(r||(r=Promise))((function(o,s){function i(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(i,a)}c((n=n.apply(e,t||[])).next())}))}function F(e,t){var r,n,o,s,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(a){return function(c){return function(a){if(r)throw new TypeError("Generator is already executing.");for(;s&&(s=0,a[0]&&(i=0)),i;)try{if(r=1,n&&(o=2&a[0]?n.return:a[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,a[1])).done)return o;switch(n=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return i.label++,{value:a[1],done:!1};case 5:i.label++,n=a[1],a=[0];continue;case 7:a=i.ops.pop(),i.trys.pop();continue;default:if(!(o=i.trys,(o=o.length>0&&o[o.length-1])||6!==a[0]&&2!==a[0])){i=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]<o[3])){i.label=a[1];break}if(6===a[0]&&i.label<o[1]){i.label=o[1],o=a;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(a);break}o[2]&&i.ops.pop(),i.trys.pop();continue}a=t.call(e,i)}catch(e){a=[6,e],n=0}finally{r=o=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,c])}}}function M(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function U(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,o,s=r.call(e),i=[];try{for(;(void 0===t||t-- >0)&&!(n=s.next()).done;)i.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(r=s.return)&&r.call(s)}finally{if(o)throw o.error}}return i}function N(e,t,r){if(r||2===arguments.length)for(var n,o=0,s=t.length;o<s;o++)!n&&o in t||(n||(n=Array.prototype.slice.call(t,0,o)),n[o]=t[o]);return e.concat(n||Array.prototype.slice.call(t))}function L(e){return this instanceof L?(this.v=e,this):new L(e)}function z(e,t,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n,o=r.apply(e,t||[]),s=[];return n={},i("next"),i("throw"),i("return"),n[Symbol.asyncIterator]=function(){return this},n;function i(e){o[e]&&(n[e]=function(t){return new Promise((function(r,n){s.push([e,t,r,n])>1||a(e,t)}))})}function a(e,t){try{!function(e){e.value instanceof L?Promise.resolve(e.value.v).then(c,u):l(s[0][2],e)}(o[e](t))}catch(e){l(s[0][3],e)}}function c(e){a("next",e)}function u(e){a("throw",e)}function l(e,t){e(t),s.shift(),s.length&&a(s[0][0],s[0][1])}}function H(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e=M(e),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(r){t[r]=e[r]&&function(t){return new Promise((function(n,o){(function(e,t,r,n){Promise.resolve(n).then((function(t){e({value:t,done:r})}),t)})(n,o,(t=e[r](t)).done,t.value)}))}}}function B(e){return"function"==typeof e}function J(e){var t=e((function(e){Error.call(e),e.stack=(new Error).stack}));return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}"function"==typeof SuppressedError&&SuppressedError;var G=J((function(e){return function(t){e(this),this.message=t?t.length+" errors occurred during unsubscription:\n"+t.map((function(e,t){return t+1+") "+e.toString()})).join("\n "):"",this.name="UnsubscriptionError",this.errors=t}}));function V(e,t){if(e){var r=e.indexOf(t);0<=r&&e.splice(r,1)}}var X=function(){function e(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}var t;return e.prototype.unsubscribe=function(){var e,t,r,n,o;if(!this.closed){this.closed=!0;var s=this._parentage;if(s)if(this._parentage=null,Array.isArray(s))try{for(var i=M(s),a=i.next();!a.done;a=i.next()){a.value.remove(this)}}catch(t){e={error:t}}finally{try{a&&!a.done&&(t=i.return)&&t.call(i)}finally{if(e)throw e.error}}else s.remove(this);var c=this.initialTeardown;if(B(c))try{c()}catch(e){o=e instanceof G?e.errors:[e]}var u=this._finalizers;if(u){this._finalizers=null;try{for(var l=M(u),h=l.next();!h.done;h=l.next()){var p=h.value;try{Q(p)}catch(e){o=null!=o?o:[],e instanceof G?o=N(N([],U(o)),U(e.errors)):o.push(e)}}}catch(e){r={error:e}}finally{try{h&&!h.done&&(n=l.return)&&n.call(l)}finally{if(r)throw r.error}}}if(o)throw new G(o)}},e.prototype.add=function(t){var r;if(t&&t!==this)if(this.closed)Q(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=null!==(r=this._finalizers)&&void 0!==r?r:[]).push(t)}},e.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},e.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},e.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&V(t,e)},e.prototype.remove=function(t){var r=this._finalizers;r&&V(r,t),t instanceof e&&t._removeParent(this)},e.EMPTY=((t=new e).closed=!0,t),e}();function W(e){return e instanceof X||e&&"closed"in e&&B(e.remove)&&B(e.add)&&B(e.unsubscribe)}function Q(e){B(e)?e():e.unsubscribe()}X.EMPTY;var Y={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},K={setTimeout:function(e,t){for(var r=[],n=2;n<arguments.length;n++)r[n-2]=arguments[n];return setTimeout.apply(void 0,N([e,t],U(r)))},clearTimeout:function(e){var t=K.delegate;return((null==t?void 0:t.clearTimeout)||clearTimeout)(e)},delegate:void 0};function Z(e){K.setTimeout((function(){throw e}))}function ee(){}var te=function(e){function t(t){var r=e.call(this)||this;return r.isStopped=!1,t?(r.destination=t,W(t)&&t.add(r)):r.destination=ae,r}return k(t,e),t.create=function(e,t,r){return new se(e,t,r)},t.prototype.next=function(e){this.isStopped||this._next(e)},t.prototype.error=function(e){this.isStopped||(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(e){this.destination.next(e)},t.prototype._error=function(e){try{this.destination.error(e)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t}(X),re=Function.prototype.bind;function ne(e,t){return re.call(e,t)}var oe=function(){function e(e){this.partialObserver=e}return e.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(e){ie(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){ie(e)}else ie(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){ie(e)}},e}(),se=function(e){function t(t,r,n){var o,s,i=e.call(this)||this;B(t)||!t?o={next:null!=t?t:void 0,error:null!=r?r:void 0,complete:null!=n?n:void 0}:i&&Y.useDeprecatedNextContext?((s=Object.create(t)).unsubscribe=function(){return i.unsubscribe()},o={next:t.next&&ne(t.next,s),error:t.error&&ne(t.error,s),complete:t.complete&&ne(t.complete,s)}):o=t;return i.destination=new oe(o),i}return k(t,e),t}(te);function ie(e){Z(e)}var ae={closed:!0,next:ee,error:function(e){throw e},complete:ee},ce="function"==typeof Symbol&&Symbol.observable||"@@observable";function ue(e){return e}function le(e){return 0===e.length?ue:1===e.length?e[0]:function(t){return e.reduce((function(e,t){return t(e)}),t)}}var he=function(){function e(e){e&&(this._subscribe=e)}return e.prototype.lift=function(t){var r=new e;return r.source=this,r.operator=t,r},e.prototype.subscribe=function(e,t,r){var n,o=this,s=(n=e)&&n instanceof te||function(e){return e&&B(e.next)&&B(e.error)&&B(e.complete)}(n)&&W(n)?e:new se(e,t,r);return function(){var e=o,t=e.operator,r=e.source;s.add(t?t.call(s,r):r?o._subscribe(s):o._trySubscribe(s))}(),s},e.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},e.prototype.forEach=function(e,t){var r=this;return new(t=pe(t))((function(t,n){var o=new se({next:function(t){try{e(t)}catch(e){n(e),o.unsubscribe()}},error:n,complete:t});r.subscribe(o)}))},e.prototype._subscribe=function(e){var t;return null===(t=this.source)||void 0===t?void 0:t.subscribe(e)},e.prototype[ce]=function(){return this},e.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return le(e)(this)},e.prototype.toPromise=function(e){var t=this;return new(e=pe(e))((function(e,r){var n;t.subscribe((function(e){return n=e}),(function(e){return r(e)}),(function(){return e(n)}))}))},e.create=function(t){return new e(t)},e}();function pe(e){var t;return null!==(t=null!=e?e:Y.Promise)&&void 0!==t?t:Promise}function de(e){return function(t){if(function(e){return B(null==e?void 0:e.lift)}(t))return t.lift((function(t){try{return e(t,this)}catch(e){this.error(e)}}));throw new TypeError("Unable to lift unknown Observable type")}}function fe(e,t,r,n,o){return new ye(e,t,r,n,o)}var ye=function(e){function t(t,r,n,o,s,i){var a=e.call(this,t)||this;return a.onFinalize=s,a.shouldUnsubscribe=i,a._next=r?function(e){try{r(e)}catch(e){t.error(e)}}:e.prototype._next,a._error=o?function(e){try{o(e)}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._error,a._complete=n?function(){try{n()}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._complete,a}return k(t,e),t.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var r=this.closed;e.prototype.unsubscribe.call(this),!r&&(null===(t=this.onFinalize)||void 0===t||t.call(this))}},t}(te);var ge="function"==typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator";function me(e){if(e instanceof he)return e;if(null!=e){if(function(e){return B(e[ce])}(e))return s=e,new he((function(e){var t=s[ce]();if(B(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")}));if(function(e){return e&&"number"==typeof e.length&&"function"!=typeof e}(e))return o=e,new he((function(e){for(var t=0;t<o.length&&!e.closed;t++)e.next(o[t]);e.complete()}));if(B(null==(n=e)?void 0:n.then))return r=e,new he((function(e){r.then((function(t){e.closed||(e.next(t),e.complete())}),(function(t){return e.error(t)})).then(null,Z)}));if(function(e){return Symbol.asyncIterator&&B(null==e?void 0:e[Symbol.asyncIterator])}(e))return be(e);if(function(e){return B(null==e?void 0:e[ge])}(e))return t=e,new he((function(e){var r,n;try{for(var o=M(t),s=o.next();!s.done;s=o.next()){var i=s.value;if(e.next(i),e.closed)return}}catch(e){r={error:e}}finally{try{s&&!s.done&&(n=o.return)&&n.call(o)}finally{if(r)throw r.error}}e.complete()}));if(function(e){return B(null==e?void 0:e.getReader)}(e))return be(function(e){return z(this,arguments,(function(){var t,r,n;return F(this,(function(o){switch(o.label){case 0:t=e.getReader(),o.label=1;case 1:o.trys.push([1,,9,10]),o.label=2;case 2:return[4,L(t.read())];case 3:return r=o.sent(),n=r.value,r.done?[4,L(void 0)]:[3,5];case 4:return[2,o.sent()];case 5:return[4,L(n)];case 6:return[4,o.sent()];case 7:return o.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}}))}))}(e))}var t,r,n,o,s;throw function(e){return new TypeError("You provided "+(null!==e&&"object"==typeof e?"an invalid object":"'"+e+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}(e)}function be(e){return new he((function(t){(function(e,t){var r,n,o,s;return D(this,void 0,void 0,(function(){var i,a;return F(this,(function(c){switch(c.label){case 0:c.trys.push([0,5,6,11]),r=H(e),c.label=1;case 1:return[4,r.next()];case 2:if((n=c.sent()).done)return[3,4];if(i=n.value,t.next(i),t.closed)return[2];c.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return a=c.sent(),o={error:a},[3,11];case 6:return c.trys.push([6,,9,10]),n&&!n.done&&(s=r.return)?[4,s.call(r)]:[3,8];case 7:c.sent(),c.label=8;case 8:return[3,10];case 9:if(o)throw o.error;return[7];case 10:return[7];case 11:return t.complete(),[2]}}))}))})(e,t).catch((function(e){return t.error(e)}))}))}function ve(e,t){return me(e)}var we=J((function(e){return function(){e(this),this.name="EmptyError",this.message="no elements in sequence"}}));function Ce(e,t){return new Promise((function(t,r){var n,o=!1;e.subscribe({next:function(e){n=e,o=!0},error:r,complete:function(){o?t(n):r(new we)}})}))}function Ee(e,t){return de((function(r,n){var o=0;r.subscribe(fe(n,(function(r){n.next(e.call(t,r,o++))})))}))}var xe=Array.isArray;function Re(e){return Ee((function(t){return function(e,t){return xe(t)?e.apply(void 0,N([],U(t))):e(t)}(e,t)}))}function Se(e,t,r){t()}var Oe=Array.isArray;function Te(e,t){return de((function(r,n){var o=0;r.subscribe(fe(n,(function(r){return e.call(t,r,o++)&&n.next(r)})))}))}function _e(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r=function(e){return B((t=e)[t.length-1])?e.pop():void 0;var t}(e);return r?function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return le(e)}(_e.apply(void 0,N([],U(e))),Re(r)):de((function(t,r){var n,o;(n=N([t],U(function(e){return 1===e.length&&Oe(e[0])?e[0]:e}(e))),void 0===o&&(o=ue),function(e){Se(0,(function(){for(var t=n.length,r=new Array(t),s=t,i=t,a=function(t){Se(0,(function(){var a=ve(n[t]),c=!1;a.subscribe(fe(e,(function(n){r[t]=n,c||(c=!0,i--),i||e.next(o(r.slice()))}),(function(){--s||e.complete()})))}))},c=0;c<t;c++)a(c)}))})(r)}))}var qe={0:8203,1:8204,2:8205,3:8290,4:8291,5:8288,6:65279,7:8289,8:119155,9:119156,a:119157,b:119158,c:119159,d:119160,e:119161,f:119162},je={0:8203,1:8204,2:8205,3:65279},$e=new Array(4).fill(String.fromCodePoint(je[0])).join("");function Ae(e,t,r="auto"){return!0===r||"auto"===r&&(function(e){return!(!Number.isNaN(Number(e))||/[a-z]/i.test(e)&&!/\d+(?:[-:\/]\d+){2}(?:T\d+(?:[-:\/]\d+){1,2}(\.\d+)?Z?)?/.test(e)||!Date.parse(e))}(e)||function(e){try{new URL(e,e.startsWith("/")?"https://acme.com":void 0)}catch{return!1}return!0}(e))?e:`${e}${function(e){let t=JSON.stringify(e);return`${$e}${Array.from(t).map((e=>{let r=e.charCodeAt(0);if(r>255)throw new Error(`Only ASCII edit info can be encoded. Error attempting to encode ${t} on character ${e} (${r})`);return Array.from(r.toString(4).padStart(4,"0")).map((e=>String.fromCodePoint(je[e]))).join("")})).join("")}`}(t)}`}Object.fromEntries(Object.entries(je).map((e=>e.reverse()))),Object.fromEntries(Object.entries(qe).map((e=>e.reverse())));var Ie=`${Object.values(qe).map((e=>`\\u{${e.toString(16)}}`)).join("")}`,Pe=new RegExp(`[${Ie}]{4,}`,"gu");function ke(e){return e&&JSON.parse(function(e){var t;return{cleaned:e.replace(Pe,""),encoded:(null==(t=e.match(Pe))?void 0:t[0])||""}}(JSON.stringify(e)).cleaned)}class De extends Error{response;statusCode=400;responseBody;details;constructor(e){const t=Me(e);super(t.message),Object.assign(this,t)}}class Fe extends Error{response;statusCode=500;responseBody;details;constructor(e){const t=Me(e);super(t.message),Object.assign(this,t)}}function Me(e){const t=e.body,r={response:e,statusCode:e.statusCode,responseBody:Ne(t,e),message:"",details:void 0};if(t.error&&t.message)return r.message=`${t.error} - ${t.message}`,r;if(function(e){return Ue(e)&&Ue(e.error)&&"mutationError"===e.error.type&&"string"==typeof e.error.description}(t)||function(e){return Ue(e)&&Ue(e.error)&&"actionError"===e.error.type&&"string"==typeof e.error.description}(t)){const e=t.error.items||[],n=e.slice(0,5).map((e=>e.error?.description)).filter(Boolean);let o=n.length?`:\n- ${n.join("\n- ")}`:"";return e.length>5&&(o+=`\n...and ${e.length-5} more`),r.message=`${t.error.description}${o}`,r.details=t.error,r}return t.error&&t.error.description?(r.message=t.error.description,r.details=t.error,r):(r.message=t.error||t.message||function(e){const t=e.statusMessage?` ${e.statusMessage}`:"";return`${e.method}-request to ${e.url} resulted in HTTP ${e.statusCode}${t}`}(e),r)}function Ue(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Ne(e,t){return-1!==(t.headers["content-type"]||"").toLowerCase().indexOf("application/json")?JSON.stringify(e,null,2):e}class Le extends Error{projectId;addOriginUrl;constructor({projectId:e}){super("CorsOriginError"),this.name="CorsOriginError",this.projectId=e;const t=new URL(`https://sanity.io/manage/project/${e}/api`);if(typeof location<"u"){const{origin:e}=location;t.searchParams.set("cors","add"),t.searchParams.set("origin",e),this.addOriginUrl=t,this.message=`The current origin is not allowed to connect to the Live Content API. Add it here: ${t}`}else this.message=`The current origin is not allowed to connect to the Live Content API. Change your configuration here: ${t}`}}const ze={onResponse:e=>{if(e.statusCode>=500)throw new Fe(e);if(e.statusCode>=400)throw new De(e);return e}},He={onResponse:e=>{const t=e.headers["x-sanity-warning"];return(Array.isArray(t)?t:[t]).filter(Boolean).forEach((e=>console.warn(e))),e}};function Be(e,t,r){if(0===r.maxRetries)return!1;const n="GET"===r.method||"HEAD"===r.method,o=(r.uri||r.url).startsWith("/data/query"),s=e.response&&(429===e.response.statusCode||502===e.response.statusCode||503===e.response.statusCode);return!(!n&&!o||!s)||I.shouldRetry(e,t,r)}function Je(e){if("string"==typeof e)return{id:e};if(Array.isArray(e))return{query:"*[_id in $ids]",params:{ids:e}};if("object"==typeof e&&null!==e&&"query"in e&&"string"==typeof e.query)return"params"in e&&"object"==typeof e.params&&null!==e.params?{query:e.query,params:e.params}:{query:e.query};const t=["* Document ID (<docId>)","* Array of document IDs","* Object containing `query`"].join("\n");throw new Error(`Unknown selection - must be one of:\n\n${t}`)}const Ge=["image","file"],Ve=["before","after","replace"],Xe=e=>{if(!/^(~[a-z0-9]{1}[-\w]{0,63}|[a-z0-9]{1}[-\w]{0,63})$/.test(e))throw new Error("Datasets can only contain lowercase characters, numbers, underscores and dashes, and start with tilde, and be maximum 64 characters")},We=(e,t)=>{if(null===t||"object"!=typeof t||Array.isArray(t))throw new Error(`${e}() takes an object of properties`)},Qe=(e,t)=>{if("string"!=typeof t||!/^[a-z0-9_][a-z0-9_.-]{0,127}$/i.test(t)||t.includes(".."))throw new Error(`${e}(): "${t}" is not a valid document ID`)},Ye=(e,t)=>{if(!t._id)throw new Error(`${e}() requires that the document contains an ID ("_id" property)`);Qe(e,t._id)},Ke=e=>{if(!e.dataset)throw new Error("`dataset` must be provided to perform queries");return e.dataset||""},Ze=e=>{if("string"!=typeof e||!/^[a-z0-9._-]{1,75}$/i.test(e))throw new Error("Tag can only contain alphanumeric characters, underscores, dashes and dots, and be between one and 75 characters long.");return e};class et{selection;operations;constructor(e,t={}){this.selection=e,this.operations=t}set(e){return this._assign("set",e)}setIfMissing(e){return this._assign("setIfMissing",e)}diffMatchPatch(e){return We("diffMatchPatch",e),this._assign("diffMatchPatch",e)}unset(e){if(!Array.isArray(e))throw new Error("unset(attrs) takes an array of attributes to unset, non-array given");return this.operations=Object.assign({},this.operations,{unset:e}),this}inc(e){return this._assign("inc",e)}dec(e){return this._assign("dec",e)}insert(e,t,r){return((e,t,r)=>{const n="insert(at, selector, items)";if(-1===Ve.indexOf(e)){const e=Ve.map((e=>`"${e}"`)).join(", ");throw new Error(`${n} takes an "at"-argument which is one of: ${e}`)}if("string"!=typeof t)throw new Error(`${n} takes a "selector"-argument which must be a string`);if(!Array.isArray(r))throw new Error(`${n} takes an "items"-argument which must be an array`)})(e,t,r),this._assign("insert",{[e]:t,items:r})}append(e,t){return this.insert("after",`${e}[-1]`,t)}prepend(e,t){return this.insert("before",`${e}[0]`,t)}splice(e,t,r,n){const o=t<0?t-1:t,s=typeof r>"u"||-1===r?-1:Math.max(0,t+r),i=`${e}[${o}:${o<0&&s>=0?"":s}]`;return this.insert("replace",i,n||[])}ifRevisionId(e){return this.operations.ifRevisionID=e,this}serialize(){return{...Je(this.selection),...this.operations}}toJSON(){return this.serialize()}reset(){return this.operations={},this}_assign(e,t,r=!0){return We(e,t),this.operations=Object.assign({},this.operations,{[e]:Object.assign({},r&&this.operations[e]||{},t)}),this}_set(e,t){return this._assign(e,t,!1)}}class tt extends et{#a;constructor(e,t,r){super(e,t),this.#a=r}clone(){return new tt(this.selection,{...this.operations},this.#a)}commit(e){if(!this.#a)throw new Error("No `client` passed to patch, either provide one or pass the patch to a clients `mutate()` method");const t="string"==typeof this.selection,r=Object.assign({returnFirst:t,returnDocuments:!0},e);return this.#a.mutate({patch:this.serialize()},r)}}class rt extends et{#a;constructor(e,t,r){super(e,t),this.#a=r}clone(){return new rt(this.selection,{...this.operations},this.#a)}commit(e){if(!this.#a)throw new Error("No `client` passed to patch, either provide one or pass the patch to a clients `mutate()` method");const t="string"==typeof this.selection,r=Object.assign({returnFirst:t,returnDocuments:!0},e);return this.#a.mutate({patch:this.serialize()},r)}}const nt={returnDocuments:!1};class ot{operations;trxId;constructor(e=[],t){this.operations=e,this.trxId=t}create(e){return We("create",e),this._add({create:e})}createIfNotExists(e){const t="createIfNotExists";return We(t,e),Ye(t,e),this._add({[t]:e})}createOrReplace(e){const t="createOrReplace";return We(t,e),Ye(t,e),this._add({[t]:e})}delete(e){return Qe("delete",e),this._add({delete:{id:e}})}transactionId(e){return e?(this.trxId=e,this):this.trxId}serialize(){return[...this.operations]}toJSON(){return this.serialize()}reset(){return this.operations=[],this}_add(e){return this.operations.push(e),this}}class st extends ot{#a;constructor(e,t,r){super(e,r),this.#a=t}clone(){return new st([...this.operations],this.#a,this.trxId)}commit(e){if(!this.#a)throw new Error("No `client` passed to transaction, either provide one or pass the transaction to a clients `mutate()` method");return this.#a.mutate(this.serialize(),Object.assign({transactionId:this.trxId},nt,e||{}))}patch(e,t){const r="function"==typeof t;if("string"!=typeof e&&e instanceof rt)return this._add({patch:e.serialize()});if(r){const r=t(new rt(e,{},this.#a));if(!(r instanceof rt))throw new Error("function passed to `patch()` must return the patch");return this._add({patch:r.serialize()})}return this._add({patch:{id:e,...t}})}}class it extends ot{#a;constructor(e,t,r){super(e,r),this.#a=t}clone(){return new it([...this.operations],this.#a,this.trxId)}commit(e){if(!this.#a)throw new Error("No `client` passed to transaction, either provide one or pass the transaction to a clients `mutate()` method");return this.#a.mutate(this.serialize(),Object.assign({transactionId:this.trxId},nt,e||{}))}patch(e,t){const r="function"==typeof t;if("string"!=typeof e&&e instanceof tt)return this._add({patch:e.serialize()});if(r){const r=t(new tt(e,{},this.#a));if(!(r instanceof tt))throw new Error("function passed to `patch()` must return the patch");return this._add({patch:r.serialize()})}return this._add({patch:{id:e,...t}})}}function at(e){return"https://www.sanity.io/help/"+e}const ct=e=>function(e){let t,r=!1;return(...n)=>(r||(t=e(...n),r=!0),t)}(((...t)=>console.warn(e.join(" "),...t))),ut=ct(["Because you set `withCredentials` to true, we will override your `useCdn`","setting to be false since (cookie-based) credentials are never set on the CDN"]),lt=ct(["Since you haven't set a value for `useCdn`, we will deliver content using our","global, edge-cached API-CDN. If you wish to have content delivered faster, set","`useCdn: false` to use the Live API. Note: You may incur higher costs using the live API."]),ht=ct(["The Sanity client is configured with the `perspective` set to `previewDrafts`, which doesn't support the API-CDN.","The Live API will be used instead. Set `useCdn: false` in your configuration to hide this warning."]),pt=ct(["You have configured Sanity client to use a token in the browser. This may cause unintentional security issues.",`See ${at("js-client-browser-token")} for more information and how to hide this warning.`]),dt=ct(["Using the Sanity client without specifying an API version is deprecated.",`See ${at("js-client-api-version")}`]),ft=ct(["The default export of @sanity/client has been deprecated. Use the named export `createClient` instead."]),yt={apiHost:"https://api.sanity.io",apiVersion:"1",useProjectHostname:!0,stega:{enabled:!1}},gt=["localhost","127.0.0.1","0.0.0.0"];const mt=function(e){switch(e){case"previewDrafts":case"published":case"raw":return;default:throw new TypeError("Invalid API perspective string, expected `published`, `previewDrafts` or `raw`")}},bt=(e,t)=>{const r={...t,...e,stega:{..."boolean"==typeof t.stega?{enabled:t.stega}:t.stega||yt.stega,..."boolean"==typeof e.stega?{enabled:e.stega}:e.stega||{}}};r.apiVersion||dt();const n={...yt,...r},o=n.useProjectHostname;if(typeof Promise>"u"){const e=at("js-client-promise-polyfill");throw new Error(`No native Promise-implementation found, polyfill needed - see ${e}`)}if(o&&!n.projectId)throw new Error("Configuration must contain `projectId`");if("string"==typeof n.perspective&&mt(n.perspective),"encodeSourceMap"in n)throw new Error("It looks like you're using options meant for '@sanity/preview-kit/client'. 'encodeSourceMap' is not supported in '@sanity/client'. Did you mean 'stega.enabled'?");if("encodeSourceMapAtPath"in n)throw new Error("It looks like you're using options meant for '@sanity/preview-kit/client'. 'encodeSourceMapAtPath' is not supported in '@sanity/client'. Did you mean 'stega.filter'?");if("boolean"!=typeof n.stega.enabled)throw new Error(`stega.enabled must be a boolean, received ${n.stega.enabled}`);if(n.stega.enabled&&void 0===n.stega.studioUrl)throw new Error("stega.studioUrl must be defined when stega.enabled is true");if(n.stega.enabled&&"string"!=typeof n.stega.studioUrl&&"function"!=typeof n.stega.studioUrl)throw new Error(`stega.studioUrl must be a string or a function, received ${n.stega.studioUrl}`);const s=typeof window<"u"&&window.location&&window.location.hostname,i=s&&(e=>-1!==gt.indexOf(e))(window.location.hostname);s&&i&&n.token&&!0!==n.ignoreBrowserTokenWarning?pt():typeof n.useCdn>"u"&<(),o&&(e=>{if(!/^[-a-z0-9]+$/i.test(e))throw new Error("`projectId` can only contain only a-z, 0-9 and dashes")})(n.projectId),n.dataset&&Xe(n.dataset),"requestTagPrefix"in n&&(n.requestTagPrefix=n.requestTagPrefix?Ze(n.requestTagPrefix).replace(/\.+$/,""):void 0),n.apiVersion=`${n.apiVersion}`.replace(/^v/,""),n.isDefaultApi=n.apiHost===yt.apiHost,!0===n.useCdn&&n.withCredentials&&ut(),n.useCdn=!1!==n.useCdn&&!n.withCredentials,function(e){if("1"===e||"X"===e)return;const t=new Date(e);if(!(/^\d{4}-\d{2}-\d{2}$/.test(e)&&t instanceof Date&&t.getTime()>0))throw new Error("Invalid API version string, expected `1` or date in format `YYYY-MM-DD`")}(n.apiVersion);const a=n.apiHost.split("://",2),c=a[0],u=a[1],l=n.isDefaultApi?"apicdn.sanity.io":u;return n.useProjectHostname?(n.url=`${c}://${n.projectId}.${u}/v${n.apiVersion}`,n.cdnUrl=`${c}://${n.projectId}.${l}/v${n.apiVersion}`):(n.url=`${n.apiHost}/v${n.apiVersion}`,n.cdnUrl=n.url),n};const vt=({query:e,params:t={},options:r={}})=>{const n=new URLSearchParams,{tag:o,includeMutations:s,returnQuery:i,...a}=r;o&&n.append("tag",o),n.append("query",e);for(const[e,r]of Object.entries(t))n.append(`$${e}`,JSON.stringify(r));for(const[e,t]of Object.entries(a))t&&n.append(e,`${t}`);return!1===i&&n.append("returnQuery","false"),!1===s&&n.append("includeMutations","false"),`?${n}`},wt=(e={})=>{return{dryRun:e.dryRun,returnIds:!0,returnDocuments:(t=e.returnDocuments,r=!0,!1===t?void 0:typeof t>"u"?r:t),visibility:e.visibility||"sync",autoGenerateArrayKeys:e.autoGenerateArrayKeys,skipCrossDatasetReferenceValidation:e.skipCrossDatasetReferenceValidation};var t,r},Ct=e=>"response"===e.type,Et=e=>e.body;function xt(e,t,r,n,o={},s={}){const i="stega"in s?{...r||{},..."boolean"==typeof s.stega?{enabled:s.stega}:s.stega||{}}:r,a=i.enabled?ke(o):o,c=!1===s.filterResponse?e=>e:e=>e.result,{cache:u,next:l,...h}={useAbortSignal:typeof s.signal<"u",resultSourceMap:i.enabled?"withKeyArraySelector":s.resultSourceMap,...s,returnQuery:!1===s.filterResponse&&!1!==s.returnQuery},p=$t(e,t,"query",{query:n,params:a},typeof u<"u"||typeof l<"u"?{...h,fetch:{cache:u,next:l}}:h);return i.enabled?p.pipe(function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return _e.apply(void 0,N([],U(e)))}(ve(Promise.resolve().then((function(){return Or})).then((function(e){return e.stegaEncodeSourceMap$1})).then((({stegaEncodeSourceMap:e})=>e)))),Ee((([e,t])=>{const r=t(e.result,e.resultSourceMap,i);return c({...e,result:r})}))):p.pipe(Ee(c))}function Rt(e,t,r,n={}){return It(e,t,{uri:kt(e,"doc",r),json:!0,tag:n.tag,signal:n.signal}).pipe(Te(Ct),Ee((e=>e.body.documents&&e.body.documents[0])))}function St(e,t,r,n={}){return It(e,t,{uri:kt(e,"doc",r.join(",")),json:!0,tag:n.tag,signal:n.signal}).pipe(Te(Ct),Ee((e=>{const t=(n=e.body.documents||[],o=e=>e._id,n.reduce(((e,t)=>(e[o(t)]=t,e)),Object.create(null)));var n,o;return r.map((e=>t[e]||null))})))}function Ot(e,t,r,n){return Ye("createIfNotExists",r),At(e,t,r,"createIfNotExists",n)}function Tt(e,t,r,n){return Ye("createOrReplace",r),At(e,t,r,"createOrReplace",n)}function _t(e,t,r,n){return $t(e,t,"mutate",{mutations:[{delete:Je(r)}]},n)}function qt(e,t,r,n){let o;o=r instanceof rt||r instanceof tt?{patch:r.serialize()}:r instanceof st||r instanceof it?r.serialize():r;return $t(e,t,"mutate",{mutations:Array.isArray(o)?o:[o],transactionId:n&&n.transactionId||void 0},n)}function jt(e,t,r,n){return $t(e,t,"actions",{actions:Array.isArray(r)?r:[r],transactionId:n&&n.transactionId||void 0,skipCrossDatasetReferenceValidation:n&&n.skipCrossDatasetReferenceValidation||void 0,dryRun:n&&n.dryRun||void 0},n)}function $t(e,t,r,n,o={}){const s="mutate"===r,i="actions"===r,a="query"===r,c=s||i?"":vt(n),u=!s&&!i&&c.length<11264,l=u?c:"",h=o.returnFirst,{timeout:p,token:d,tag:f,headers:y,returnQuery:g,lastLiveEventId:m}=o;return It(e,t,{method:u?"GET":"POST",uri:kt(e,r,l),json:!0,body:u?void 0:n,query:s&&wt(o),timeout:p,headers:y,token:d,tag:f,returnQuery:g,perspective:o.perspective,resultSourceMap:o.resultSourceMap,lastLiveEventId:Array.isArray(m)?m[0]:m,canUseCdn:a,signal:o.signal,fetch:o.fetch,useAbortSignal:o.useAbortSignal,useCdn:o.useCdn}).pipe(Te(Ct),Ee(Et),Ee((e=>{if(!s)return e;const t=e.results||[];if(o.returnDocuments)return h?t[0]&&t[0].document:t.map((e=>e.document));const r=h?"documentId":"documentIds",n=h?t[0]&&t[0].id:t.map((e=>e.id));return{transactionId:e.transactionId,results:t,[r]:n}})))}function At(e,t,r,n,o={}){return $t(e,t,"mutate",{mutations:[{[n]:r}]},Object.assign({returnFirst:!0,returnDocuments:!0},o))}function It(e,t,r){const n=r.url||r.uri,o=e.config(),s=typeof r.canUseCdn>"u"?["GET","HEAD"].indexOf(r.method||"GET")>=0&&0===n.indexOf("/data/"):r.canUseCdn;let i=(r.useCdn??o.useCdn)&&s;const a=r.tag&&o.requestTagPrefix?[o.requestTagPrefix,r.tag].join("."):r.tag||o.requestTagPrefix;if(a&&null!==r.tag&&(r.query={tag:Ze(a),...r.query}),["GET","HEAD","POST"].indexOf(r.method||"GET")>=0&&0===n.indexOf("/data/query/")){const e=r.resultSourceMap??o.resultSourceMap;void 0!==e&&!1!==e&&(r.query={resultSourceMap:e,...r.query});const t=r.perspective||o.perspective;"string"==typeof t&&"raw"!==t&&(mt(t),r.query={perspective:t,...r.query},"previewDrafts"===t&&i&&(i=!1,ht())),r.lastLiveEventId&&(r.query={...r.query,lastLiveEventId:r.lastLiveEventId}),!1===r.returnQuery&&(r.query={returnQuery:"false",...r.query})}const c=function(e,t={}){const r={},n=t.token||e.token;n&&(r.Authorization=`Bearer ${n}`),!t.useGlobalApi&&!e.useProjectHostname&&e.projectId&&(r["X-Sanity-Project-ID"]=e.projectId);const o=!!(typeof t.withCredentials>"u"?e.token||e.withCredentials:t.withCredentials),s=typeof t.timeout>"u"?e.timeout:t.timeout;return Object.assign({},t,{headers:Object.assign({},r,t.headers||{}),timeout:typeof s>"u"?3e5:s,proxy:t.proxy||e.proxy,json:!0,withCredentials:o,fetch:"object"==typeof t.fetch&&"object"==typeof e.fetch?{...e.fetch,...t.fetch}:t.fetch||e.fetch})}(o,Object.assign({},r,{url:Dt(e,n,i)})),u=new he((e=>t(c,o.requester).subscribe(e)));return r.signal?u.pipe((l=r.signal,e=>new he((t=>{const r=()=>t.error(function(e){if(Ft)return new DOMException(e?.reason??"The operation was aborted.","AbortError");const t=new Error(e?.reason??"The operation was aborted.");return t.name="AbortError",t}(l));if(l&&l.aborted)return void r();const n=e.subscribe(t);return l.addEventListener("abort",r),()=>{l.removeEventListener("abort",r),n.unsubscribe()}})))):u;var l}function Pt(e,t,r){return It(e,t,r).pipe(Te((e=>"response"===e.type)),Ee((e=>e.body)))}function kt(e,t,r){const n=e.config(),o=`/${t}/${Ke(n)}`;return`/data${r?`${o}/${r}`:o}`.replace(/\/($|\?)/,"$1")}function Dt(e,t,r=!1){const{url:n,cdnUrl:o}=e.config();return`${r?o:n}/${t.replace(/^\//,"")}`}const Ft=!!globalThis.DOMException;class Mt{#a;#c;constructor(e,t){this.#a=e,this.#c=t}upload(e,t,r){return Nt(this.#a,this.#c,e,t,r)}}class Ut{#a;#c;constructor(e,t){this.#a=e,this.#c=t}upload(e,t,r){return Ce(Nt(this.#a,this.#c,e,t,r).pipe(Te((e=>"response"===e.type)),Ee((e=>e.body.document))))}}function Nt(e,t,r,n,o={}){(e=>{if(-1===Ge.indexOf(e))throw new Error(`Invalid asset type: ${e}. Must be one of ${Ge.join(", ")}`)})(r);let s=o.extract||void 0;s&&!s.length&&(s=["none"]);const i=Ke(e.config()),a="image"===r?"images":"files",c=function(e,t){return typeof File>"u"||!(t instanceof File)?e:Object.assign({filename:!1===e.preserveFilename?void 0:t.name,contentType:t.type},e)}(o,n),{tag:u,label:l,title:h,description:p,creditLine:d,filename:f,source:y}=c,g={label:l,title:h,description:p,filename:f,meta:s,creditLine:d};return y&&(g.sourceId=y.id,g.sourceName=y.name,g.sourceUrl=y.url),It(e,t,{tag:u,method:"POST",timeout:c.timeout||0,uri:`/assets/${a}/${i}`,headers:c.contentType?{"Content-Type":c.contentType}:{},query:g,body:n})}const Lt=["includePreviousRevision","includeResult","includeMutations","visibility","effectFormat","tag"],zt={includeResult:!0};function Ht(e,t,r={}){const{url:n,token:o,withCredentials:s,requestTagPrefix:i}=this.config(),a=r.tag&&i?[i,r.tag].join("."):r.tag,c={...(h=r,p=zt,Object.keys(p).concat(Object.keys(h)).reduce(((e,t)=>(e[t]=typeof h[t]>"u"?p[t]:h[t],e)),{})),tag:a},u=((e,t)=>t.reduce(((t,r)=>(typeof e[r]>"u"||(t[r]=e[r]),t)),{}))(c,Lt),l=`${n}${kt(this,"listen",vt({query:e,params:t,options:{tag:a,...u}}))}`;var h,p;if(l.length>14800)return new he((e=>e.error(new Error("Query too large for listener"))));const d=c.events?c.events:["mutation"],f=-1!==d.indexOf("reconnect"),y={};return(o||s)&&(y.withCredentials=!0),o&&(y.headers={Authorization:`Bearer ${o}`}),new he((e=>{let t,r,n=!1,o=!1;function s(){n||(f&&e.next({type:"reconnect"}),!n&&t.readyState===t.CLOSED&&(u(),clearTimeout(r),r=setTimeout(h,100)))}function i(t){e.error(function(e){if(e instanceof Error)return e;const t=Bt(e);return t instanceof Error?t:new Error(function(e){return e.error?e.error.description?e.error.description:"string"==typeof e.error?e.error:JSON.stringify(e.error,null,2):e.message||"Unknown listener error"}(t))}(t))}function a(t){const r=Bt(t);return r instanceof Error?e.error(r):e.next(r)}function c(){n=!0,u(),e.complete()}function u(){t&&(t.removeEventListener("error",s),t.removeEventListener("channelError",i),t.removeEventListener("disconnect",c),d.forEach((e=>t.removeEventListener(e,a))),t.close())}function h(){(async function(){const{default:e}=await Promise.resolve().then((function(){return Dr}));if(o)return;const t=new e(l,y);return t.addEventListener("error",s),t.addEventListener("channelError",i),t.addEventListener("disconnect",c),d.forEach((e=>t.addEventListener(e,a))),t})().then((e=>{e&&(t=e,o&&u())})).catch((t=>{e.error(t),p()}))}function p(){n=!0,u(),o=!0}return h(),p}))}function Bt(e){try{const t=e.data&&JSON.parse(e.data)||{};return Object.assign({type:e.type},t)}catch(e){return e}}const Jt="2021-03-26";class Gt{#a;constructor(e){this.#a=e}events({includeDrafts:e=!1,tag:t}={}){const{projectId:r,apiVersion:n,token:o,withCredentials:s,requestTagPrefix:i}=this.#a.config(),a=n.replace(/^v/,"");if("X"!==a&&a<Jt)throw new Error(`The live events API requires API version ${Jt} or later. The current API version is ${a}. Please update your API version to use this feature.`);if(e&&!o&&!s)throw new Error("The live events API requires a token or withCredentials when 'includeDrafts: true'. Please update your client configuration. The token should have the lowest possible access role.");if(e&&"X"!==a)throw new Error("The live events API requires API version X when 'includeDrafts: true'. This API is experimental and may change or even be removed.");const c=kt(this.#a,"live/events"),u=new URL(this.#a.getUrl(c,!1)),l=t&&i?[i,t].join("."):t;l&&u.searchParams.set("tag",l),e&&u.searchParams.set("includeDrafts","true");const h=["restart","message","welcome","reconnect"],p={};return e&&o&&(p.headers={Authorization:`Bearer ${o}`}),e&&s&&(p.withCredentials=!0),new he((e=>{let t,n,o=!1,s=!1;function i(r){if(!o){if("data"in r){const t=Vt(r);e.error(new Error(t.message,{cause:t}))}t.readyState===t.CLOSED&&(c(),clearTimeout(n),n=setTimeout(l,100))}}function a(t){const r=Vt(t);return r instanceof Error?e.error(r):e.next(r)}function c(){if(t){t.removeEventListener("error",i);for(const e of h)t.removeEventListener(e,a);t.close()}}function l(){(async function(){const e=typeof EventSource>"u"||p.headers||p.withCredentials?(await Promise.resolve().then((function(){return Dr}))).default:EventSource;if(s)return;try{if(await fetch(u,{method:"OPTIONS",mode:"cors",credentials:p.withCredentials?"include":"omit",headers:p.headers}),s)return}catch{throw new Le({projectId:r})}const t=new e(u.toString(),p);t.addEventListener("error",i);for(const e of h)t.addEventListener(e,a);return t})().then((e=>{e&&(t=e,s&&c())})).catch((t=>{e.error(t),d()}))}function d(){o=!0,c(),s=!0}return l(),d}))}}function Vt(e){try{const t=e.data&&JSON.parse(e.data)||{};return{type:e.type,id:e.lastEventId,...t}}catch(e){return e}}class Xt{#a;#c;constructor(e,t){this.#a=e,this.#c=t}create(e,t){return Qt(this.#a,this.#c,"PUT",e,t)}edit(e,t){return Qt(this.#a,this.#c,"PATCH",e,t)}delete(e){return Qt(this.#a,this.#c,"DELETE",e)}list(){return Pt(this.#a,this.#c,{uri:"/datasets",tag:null})}}class Wt{#a;#c;constructor(e,t){this.#a=e,this.#c=t}create(e,t){return Ce(Qt(this.#a,this.#c,"PUT",e,t))}edit(e,t){return Ce(Qt(this.#a,this.#c,"PATCH",e,t))}delete(e){return Ce(Qt(this.#a,this.#c,"DELETE",e))}list(){return Ce(Pt(this.#a,this.#c,{uri:"/datasets",tag:null}))}}function Qt(e,t,r,n,o){return Xe(n),Pt(e,t,{method:r,uri:`/datasets/${n}`,body:o,tag:null})}class Yt{#a;#c;constructor(e,t){this.#a=e,this.#c=t}list(e){const t=!1===e?.includeMembers?"/projects?includeMembers=false":"/projects";return Pt(this.#a,this.#c,{uri:t})}getById(e){return Pt(this.#a,this.#c,{uri:`/projects/${e}`})}}class Kt{#a;#c;constructor(e,t){this.#a=e,this.#c=t}list(e){const t=!1===e?.includeMembers?"/projects?includeMembers=false":"/projects";return Ce(Pt(this.#a,this.#c,{uri:t}))}getById(e){return Ce(Pt(this.#a,this.#c,{uri:`/projects/${e}`}))}}class Zt{#a;#c;constructor(e,t){this.#a=e,this.#c=t}getById(e){return Pt(this.#a,this.#c,{uri:`/users/${e}`})}}class er{#a;#c;constructor(e,t){this.#a=e,this.#c=t}getById(e){return Ce(Pt(this.#a,this.#c,{uri:`/users/${e}`}))}}class tr{assets;datasets;live;projects;users;#u;#c;listen=Ht;constructor(e,t=yt){this.config(t),this.#c=e,this.assets=new Mt(this,this.#c),this.datasets=new Xt(this,this.#c),this.live=new Gt(this),this.projects=new Yt(this,this.#c),this.users=new Zt(this,this.#c)}clone(){return new tr(this.#c,this.config())}config(e){if(void 0===e)return{...this.#u};if(this.#u&&!1===this.#u.allowReconfigure)throw new Error("Existing client instance cannot be reconfigured - use `withConfig(newConfig)` to return a new client");return this.#u=bt(e,this.#u||{}),this}withConfig(e){const t=this.config();return new tr(this.#c,{...t,...e,stega:{...t.stega||{},..."boolean"==typeof e?.stega?{enabled:e.stega}:e?.stega||{}}})}fetch(e,t,r){return xt(this,this.#c,this.#u.stega,e,t,r)}getDocument(e,t){return Rt(this,this.#c,e,t)}getDocuments(e,t){return St(this,this.#c,e,t)}create(e,t){return At(this,this.#c,e,"create",t)}createIfNotExists(e,t){return Ot(this,this.#c,e,t)}createOrReplace(e,t){return Tt(this,this.#c,e,t)}delete(e,t){return _t(this,this.#c,e,t)}mutate(e,t){return qt(this,this.#c,e,t)}patch(e,t){return new tt(e,t,this)}transaction(e){return new it(e,this)}action(e,t){return jt(this,this.#c,e,t)}request(e){return Pt(this,this.#c,e)}getUrl(e,t){return Dt(this,e,t)}getDataUrl(e,t){return kt(this,e,t)}}class rr{assets;datasets;live;projects;users;observable;#u;#c;listen=Ht;constructor(e,t=yt){this.config(t),this.#c=e,this.assets=new Ut(this,this.#c),this.datasets=new Wt(this,this.#c),this.live=new Gt(this),this.projects=new Kt(this,this.#c),this.users=new er(this,this.#c),this.observable=new tr(e,t)}clone(){return new rr(this.#c,this.config())}config(e){if(void 0===e)return{...this.#u};if(this.#u&&!1===this.#u.allowReconfigure)throw new Error("Existing client instance cannot be reconfigured - use `withConfig(newConfig)` to return a new client");return this.observable&&this.observable.config(e),this.#u=bt(e,this.#u||{}),this}withConfig(e){const t=this.config();return new rr(this.#c,{...t,...e,stega:{...t.stega||{},..."boolean"==typeof e?.stega?{enabled:e.stega}:e?.stega||{}}})}fetch(e,t,r){return Ce(xt(this,this.#c,this.#u.stega,e,t,r))}getDocument(e,t){return Ce(Rt(this,this.#c,e,t))}getDocuments(e,t){return Ce(St(this,this.#c,e,t))}create(e,t){return Ce(At(this,this.#c,e,"create",t))}createIfNotExists(e,t){return Ce(Ot(this,this.#c,e,t))}createOrReplace(e,t){return Ce(Tt(this,this.#c,e,t))}delete(e,t){return Ce(_t(this,this.#c,e,t))}mutate(e,t){return Ce(qt(this,this.#c,e,t))}patch(e,t){return new rt(e,t,this)}transaction(e){return new st(e,this)}action(e,t){return Ce(jt(this,this.#c,e,t))}request(e){return Ce(Pt(this,this.#c,e))}dataRequest(e,t,r){return Ce($t(this,this.#c,e,t,r))}getUrl(e,t){return Dt(this,e,t)}getDataUrl(e,t){return kt(this,e,t)}}const nr=function(e,t){const r=function(e){return b([I({shouldRetry:Be}),...e,He,O(),T(),{onRequest:e=>{if("xhr"!==e.adapter)return;const t=e.request,r=e.context;function n(e){return t=>{const n=t.lengthComputable?t.loaded/t.total*100:-1;r.channels.progress.publish({stage:e,percent:n,total:t.total,loaded:t.loaded,lengthComputable:t.lengthComputable})}}"upload"in t&&"onprogress"in t.upload&&(t.upload.onprogress=n("upload")),"onprogress"in t&&(t.onprogress=n("download"))}},ze,j({implementation:he})])}(e);return{requester:r,createClient:e=>new t(((t,n)=>(n||r)({maxRedirects:0,maxRetries:e.maxRetries,retryDelay:e.retryDelay,...t})),e)}}([],rr),or=nr.requester,sr=nr.createClient,ir=(ar=sr,function(e){return ft(),ar(e)});var ar;const cr=/_key\s*==\s*['"](.*)['"]/;function ur(e){if(!Array.isArray(e))throw new Error("Path is not an array");return e.reduce(((e,t,r)=>{const n=typeof t;if("number"===n)return`${e}[${t}]`;if("string"===n)return`${e}${0===r?"":"."}${t}`;if(function(e){return"string"==typeof e?cr.test(e.trim()):"object"==typeof e&&"_key"in e}(t)&&t._key)return`${e}[_key=="${t._key}"]`;if(Array.isArray(t)){const[r,n]=t;return`${e}[${r}:${n}]`}throw new Error(`Unsupported path segment \`${JSON.stringify(t)}\``)}),"")}const lr={"\f":"\\f","\n":"\\n","\r":"\\r","\t":"\\t","'":"\\'","\\":"\\\\"},hr={"\\f":"\f","\\n":"\n","\\r":"\r","\\t":"\t","\\'":"'","\\\\":"\\"};function pr(e){const t=[],r=/\['(.*?)'\]|\[(\d+)\]|\[\?\(@\._key=='(.*?)'\)\]/g;let n;for(;null!==(n=r.exec(e));)if(void 0===n[1])if(void 0===n[2])if(void 0===n[3]);else{const e=n[3].replace(/\\(\\')/g,(e=>hr[e]));t.push({_key:e,_index:-1})}else t.push(parseInt(n[2],10));else{const e=n[1].replace(/\\(\\|f|n|r|t|')/g,(e=>hr[e]));t.push(e)}return t}function dr(e){return e.map((e=>{if("string"==typeof e||"number"==typeof e)return e;if(""!==e._key)return{_key:e._key};if(-1!==e._index)return e._index;throw new Error(`invalid segment:${JSON.stringify(e)}`)}))}function fr(e,t){if(!t?.mappings)return;const r=function(e){return`$${e.map((e=>"string"==typeof e?`['${e.replace(/[\f\n\r\t'\\]/g,(e=>lr[e]))}']`:"number"==typeof e?`[${e}]`:""!==e._key?`[?(@._key=='${e._key.replace(/['\\]/g,(e=>lr[e]))}')]`:`[${e._index}]`)).join("")}`}(e.map((e=>{if("string"==typeof e||"number"==typeof e)return e;if(-1!==e._index)return e._index;throw new Error(`invalid segment:${JSON.stringify(e)}`)})));if(void 0!==t.mappings[r])return{mapping:t.mappings[r],matchedPath:r,pathSuffix:""};const n=Object.entries(t.mappings).filter((([e])=>r.startsWith(e))).sort((([e],[t])=>t.length-e.length));if(0==n.length)return;const[o,s]=n[0];return{mapping:s,matchedPath:o,pathSuffix:r.substring(o.length)}}function yr(e){return"object"==typeof e&&null!==e}function gr(e,t,r=[]){return function(e){return null!==e&&Array.isArray(e)}(e)?e.map(((e,n)=>{if(yr(e)){const o=e._key;if("string"==typeof o)return gr(e,t,r.concat({_key:o,_index:n}))}return gr(e,t,r.concat(n))})):yr(e)?Object.fromEntries(Object.entries(e).map((([e,n])=>[e,gr(n,t,r.concat(e))]))):t(e,r)}function mr(e,t,r){return gr(e,((e,n)=>{if("string"!=typeof e)return e;const o=fr(n,t);if(!o)return e;const{mapping:s,matchedPath:i}=o;if("value"!==s.type||"documentValue"!==s.source.type)return e;const a=t.documents[s.source.document],c=t.paths[s.source.path],u=pr(i),l=pr(c).concat(n.slice(u.length));return r({sourcePath:l,sourceDocument:a,resultPath:n,value:e})}))}const br="drafts.";function vr(e){const{baseUrl:t,workspace:r="default",tool:n="default",id:o,type:s,path:i,projectId:a,dataset:c}=e;if(!t)throw new Error("baseUrl is required");if(!i)throw new Error("path is required");if(!o)throw new Error("id is required");if("/"!==t&&t.endsWith("/"))throw new Error("baseUrl must not end with a slash");const u="default"===r?void 0:r,l="default"===n?void 0:n,h=function(e){return e.startsWith(br)?e.slice(7):e}(o),p=Array.isArray(i)?ur(dr(i)):i,d=new URLSearchParams({baseUrl:t,id:h,type:s,path:p});u&&d.set("workspace",u),l&&d.set("tool",l),a&&d.set("projectId",a),c&&d.set("dataset",c),o.startsWith(br)&&d.set("isDraft","");const f=["/"===t?"":t];u&&f.push(u);const y=["mode=presentation",`id=${h}`,`type=${s}`,`path=${encodeURIComponent(p)}`];return l&&y.push(`tool=${l}`),f.push("intent","edit",`${y.join(";")}?${d}`),f.join("/")}const wr=({sourcePath:e,resultPath:t,value:r})=>{if(/^\d{4}-\d{2}-\d{2}/.test(n=r)&&Date.parse(n)||function(e){try{new URL(e,e.startsWith("/")?"https://acme.com":void 0)}catch{return!1}return!0}(r))return!1;var n;const o=e.at(-1);return!("slug"===e.at(-2)&&"current"===o||"string"==typeof o&&(o.startsWith("_")||o.endsWith("Id"))||"number"==typeof o&&"marks"===e.at(-2)||"href"===o&&"number"==typeof e.at(-2)&&"markDefs"===e.at(-3)||"style"===o||"listItem"===o||e.some((e=>"meta"===e||"metadata"===e||"openGraph"===e||"seo"===e))||Er(e)||Er(t)||"string"==typeof o&&Cr.has(o))},Cr=new Set(["color","colour","currency","email","format","gid","hex","href","hsl","hsla","icon","id","index","key","language","layout","link","linkAction","locale","lqip","page","path","ref","rgb","rgba","route","secret","slug","status","tag","template","theme","type","textTheme","unit","url","username","variant","website"]);function Er(e){return e.some((e=>"string"==typeof e&&null!==e.match(/type/i)))}function xr(e,t,r){const{filter:n,logger:o,enabled:s}=r;if(!s){const n="config.enabled must be true, don't call this function otherwise";throw o?.error?.(`[@sanity/client]: ${n}`,{result:e,resultSourceMap:t,config:r}),new TypeError(n)}if(!t)return o?.error?.("[@sanity/client]: Missing Content Source Map from response body",{result:e,resultSourceMap:t,config:r}),e;if(!r.studioUrl){const n="config.studioUrl must be defined";throw o?.error?.(`[@sanity/client]: ${n}`,{result:e,resultSourceMap:t,config:r}),new TypeError(n)}const i={encoded:[],skipped:[]},a=mr(e,t,(({sourcePath:e,sourceDocument:t,resultPath:s,value:a})=>{if(!1===("function"==typeof n?n({sourcePath:e,resultPath:s,filterDefault:wr,sourceDocument:t,value:a}):wr({sourcePath:e,resultPath:s,filterDefault:wr,sourceDocument:t,value:a})))return o&&i.skipped.push({path:Rr(e),value:`${a.slice(0,20)}${a.length>20?"...":""}`,length:a.length}),a;o&&i.encoded.push({path:Rr(e),value:`${a.slice(0,20)}${a.length>20?"...":""}`,length:a.length});const{baseUrl:c,workspace:u,tool:l}=function(e){let t="string"==typeof e?e:e.baseUrl;return"/"!==t&&(t=t.replace(/\/$/,"")),"string"==typeof e?{baseUrl:t}:{...e,baseUrl:t}}("function"==typeof r.studioUrl?r.studioUrl(t):r.studioUrl);if(!c)return a;const{_id:h,_type:p,_projectId:d,_dataset:f}=t;return Ae(a,{origin:"sanity.io",href:vr({baseUrl:c,workspace:u,tool:l,id:h,type:p,path:e,...!r.omitCrossDatasetReferenceData&&{dataset:f,projectId:d}})},!1)}));if(o){const e=i.skipped.length,t=i.encoded.length;if((e||t)&&((o?.groupCollapsed||o.log)?.("[@sanity/client]: Encoding source map into result"),o.log?.(`[@sanity/client]: Paths encoded: ${i.encoded.length}, skipped: ${i.skipped.length}`)),i.encoded.length>0&&(o?.log?.("[@sanity/client]: Table of encoded paths"),(o?.table||o.log)?.(i.encoded)),i.skipped.length>0){const e=new Set;for(const{path:t}of i.skipped)e.add(t.replace(cr,"0").replace(/\[\d+\]/g,"[]"));o?.log?.("[@sanity/client]: List of skipped paths",[...e.values()])}(e||t)&&o?.groupEnd?.()}return a}function Rr(e){return ur(dr(e))}var Sr=Object.freeze({__proto__:null,stegaEncodeSourceMap:xr}),Or=Object.freeze({__proto__:null,encodeIntoResult:mr,stegaEncodeSourceMap:xr,stegaEncodeSourceMap$1:Sr});function Tr(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var _r,qr,jr,$r={exports:{}},Ar=$r.exports;
|
|
2
2
|
/** @license
|
|
3
3
|
* eventsource.js
|
|
4
4
|
* Available under MIT License (MIT)
|
|
5
5
|
* https://github.com/Yaffle/EventSource/
|
|
6
|
-
*/function Ir(){return _r||(_r=1,function(e,t){!function(r){var n=r.setTimeout,o=r.clearTimeout,s=r.XMLHttpRequest,i=r.XDomainRequest,a=r.ActiveXObject,c=r.EventSource,u=r.document,l=r.Promise,h=r.fetch,p=r.Response,f=r.TextDecoder,d=r.TextEncoder,y=r.AbortController;if("undefined"==typeof window||void 0===u||"readyState"in u||null!=u.body||(u.readyState="loading",window.addEventListener("load",(function(e){u.readyState="complete"}),!1)),null==s&&null!=a&&(s=function(){return new a("Microsoft.XMLHTTP")}),null==Object.create&&(Object.create=function(e){function t(){}return t.prototype=e,new t}),Date.now||(Date.now=function(){return(new Date).getTime()}),null==y){var g=h;h=function(e,t){var r=t.signal;return g(e,{headers:t.headers,credentials:t.credentials,cache:t.cache}).then((function(e){var t=e.body.getReader();return r._reader=t,r._aborted&&r._reader.cancel(),{status:e.status,statusText:e.statusText,headers:e.headers,body:{getReader:function(){return t}}}}))},y=function(){this.signal={_reader:null,_aborted:!1},this.abort=function(){null!=this.signal._reader&&this.signal._reader.cancel(),this.signal._aborted=!0}}}function m(){this.bitsNeeded=0,this.codePoint=0}m.prototype.decode=function(e){function t(e,t,r){if(1===r)return e>=128>>t&&e<<t<=2047;if(2===r)return e>=2048>>t&&e<<t<=55295||e>=57344>>t&&e<<t<=65535;if(3===r)return e>=65536>>t&&e<<t<=1114111;throw new Error}function r(e,t){if(6===e)return t>>6>15?3:t>31?2:1;if(12===e)return t>15?3:2;if(18===e)return 3;throw new Error}for(var n=65533,o="",s=this.bitsNeeded,i=this.codePoint,a=0;a<e.length;a+=1){var c=e[a];0!==s&&(c<128||c>191||!t(i<<6|63&c,s-6,r(s,i)))&&(s=0,i=n,o+=String.fromCharCode(i)),0===s?(c>=0&&c<=127?(s=0,i=c):c>=192&&c<=223?(s=6,i=31&c):c>=224&&c<=239?(s=12,i=15&c):c>=240&&c<=247?(s=18,i=7&c):(s=0,i=n),0===s||t(i,s,r(s,i))||(s=0,i=n)):(s-=6,i=i<<6|63&c),0===s&&(i<=65535?o+=String.fromCharCode(i):(o+=String.fromCharCode(55296+(i-65535-1>>10)),o+=String.fromCharCode(56320+(i-65535-1&1023))))}return this.bitsNeeded=s,this.codePoint=i,o};null!=f&&null!=d&&function(){try{return"test"===(new f).decode((new d).encode("test"),{stream:!0})}catch(e){console.debug("TextDecoder does not support streaming option. Using polyfill instead: "+e)}return!1}()||(f=m);var b=function(){};function v(e){this.withCredentials=!1,this.readyState=0,this.status=0,this.statusText="",this.responseText="",this.onprogress=b,this.onload=b,this.onerror=b,this.onreadystatechange=b,this._contentType="",this._xhr=e,this._sendTimeout=0,this._abort=b}function w(e){return e.replace(/[A-Z]/g,(function(e){return String.fromCharCode(e.charCodeAt(0)+32)}))}function C(e){for(var t=Object.create(null),r=e.split("\r\n"),n=0;n<r.length;n+=1){var o=r[n].split(": "),s=o.shift(),i=o.join(": ");t[w(s)]=i}this._map=t}function E(){}function x(e){this._headers=e}function R(){}function S(){this._listeners=Object.create(null)}function O(e){n((function(){throw e}),0)}function T(e){this.type=e,this.target=void 0}function _(e,t){T.call(this,e),this.data=t.data,this.lastEventId=t.lastEventId}function q(e,t){T.call(this,e),this.status=t.status,this.statusText=t.statusText,this.headers=t.headers}function j(e,t){T.call(this,e),this.error=t.error}v.prototype.open=function(e,t){this._abort(!0);var r=this,i=this._xhr,a=1,c=0;this._abort=function(e){0!==r._sendTimeout&&(o(r._sendTimeout),r._sendTimeout=0),1!==a&&2!==a&&3!==a||(a=4,i.onload=b,i.onerror=b,i.onabort=b,i.onprogress=b,i.onreadystatechange=b,i.abort(),0!==c&&(o(c),c=0),e||(r.readyState=4,r.onabort(null),r.onreadystatechange())),a=0};var u=function(){if(1===a){var e=0,t="",n=void 0;if("contentType"in i)e=200,t="OK",n=i.contentType;else try{e=i.status,t=i.statusText,n=i.getResponseHeader("Content-Type")}catch(r){e=0,t="",n=void 0}0!==e&&(a=2,r.readyState=2,r.status=e,r.statusText=t,r._contentType=n,r.onreadystatechange())}},l=function(){if(u(),2===a||3===a){a=3;var e="";try{e=i.responseText}catch(e){}r.readyState=3,r.responseText=e,r.onprogress()}},h=function(e,t){if(null!=t&&null!=t.preventDefault||(t={preventDefault:b}),l(),1===a||2===a||3===a){if(a=4,0!==c&&(o(c),c=0),r.readyState=4,"load"===e)r.onload(t);else if("error"===e)r.onerror(t);else{if("abort"!==e)throw new TypeError;r.onabort(t)}r.onreadystatechange()}},p=function(){c=n((function(){p()}),500),3===i.readyState&&l()};"onload"in i&&(i.onload=function(e){h("load",e)}),"onerror"in i&&(i.onerror=function(e){h("error",e)}),"onabort"in i&&(i.onabort=function(e){h("abort",e)}),"onprogress"in i&&(i.onprogress=l),"onreadystatechange"in i&&(i.onreadystatechange=function(e){!function(e){null!=i&&(4===i.readyState?"onload"in i&&"onerror"in i&&"onabort"in i||h(""===i.responseText?"error":"load",e):3===i.readyState?"onprogress"in i||l():2===i.readyState&&u())}(e)}),!("contentType"in i)&&"ontimeout"in s.prototype||(t+=(-1===t.indexOf("?")?"?":"&")+"padding=true"),i.open(e,t,!0),"readyState"in i&&(c=n((function(){p()}),0))},v.prototype.abort=function(){this._abort(!1)},v.prototype.getResponseHeader=function(e){return this._contentType},v.prototype.setRequestHeader=function(e,t){var r=this._xhr;"setRequestHeader"in r&&r.setRequestHeader(e,t)},v.prototype.getAllResponseHeaders=function(){return null!=this._xhr.getAllResponseHeaders&&this._xhr.getAllResponseHeaders()||""},v.prototype.send=function(){if("ontimeout"in s.prototype&&("sendAsBinary"in s.prototype||"mozAnon"in s.prototype)||null==u||null==u.readyState||"complete"===u.readyState){var e=this._xhr;"withCredentials"in e&&(e.withCredentials=this.withCredentials);try{e.send(void 0)}catch(e){throw e}}else{var t=this;t._sendTimeout=n((function(){t._sendTimeout=0,t.send()}),4)}},C.prototype.get=function(e){return this._map[w(e)]},null!=s&&null==s.HEADERS_RECEIVED&&(s.HEADERS_RECEIVED=2),E.prototype.open=function(e,t,r,n,o,i,a){e.open("GET",o);var c=0;for(var u in e.onprogress=function(){var t=e.responseText.slice(c);c+=t.length,r(t)},e.onerror=function(e){e.preventDefault(),n(new Error("NetworkError"))},e.onload=function(){n(null)},e.onabort=function(){n(null)},e.onreadystatechange=function(){if(e.readyState===s.HEADERS_RECEIVED){var r=e.status,n=e.statusText,o=e.getResponseHeader("Content-Type"),i=e.getAllResponseHeaders();t(r,n,o,new C(i))}},e.withCredentials=i,a)Object.prototype.hasOwnProperty.call(a,u)&&e.setRequestHeader(u,a[u]);return e.send(),e},x.prototype.get=function(e){return this._headers.get(e)},R.prototype.open=function(e,t,r,n,o,s,i){var a=null,c=new y,u=c.signal,p=new f;return h(o,{headers:i,credentials:s?"include":"same-origin",signal:u,cache:"no-store"}).then((function(e){return a=e.body.getReader(),t(e.status,e.statusText,e.headers.get("Content-Type"),new x(e.headers)),new l((function(e,t){var n=function(){a.read().then((function(t){if(t.done)e(void 0);else{var o=p.decode(t.value,{stream:!0});r(o),n()}})).catch((function(e){t(e)}))};n()}))})).catch((function(e){return"AbortError"===e.name?void 0:e})).then((function(e){n(e)})),{abort:function(){null!=a&&a.cancel(),c.abort()}}},S.prototype.dispatchEvent=function(e){e.target=this;var t=this._listeners[e.type];if(null!=t)for(var r=t.length,n=0;n<r;n+=1){var o=t[n];try{"function"==typeof o.handleEvent?o.handleEvent(e):o.call(this,e)}catch(e){O(e)}}},S.prototype.addEventListener=function(e,t){e=String(e);var r=this._listeners,n=r[e];null==n&&(n=[],r[e]=n);for(var o=!1,s=0;s<n.length;s+=1)n[s]===t&&(o=!0);o||n.push(t)},S.prototype.removeEventListener=function(e,t){e=String(e);var r=this._listeners,n=r[e];if(null!=n){for(var o=[],s=0;s<n.length;s+=1)n[s]!==t&&o.push(n[s]);0===o.length?delete r[e]:r[e]=o}},_.prototype=Object.create(T.prototype),q.prototype=Object.create(T.prototype),j.prototype=Object.create(T.prototype);var $=-1,A=-1,I=/^text\/event\-stream(;.*)?$/i,P=function(e,t){var r=null==e?t:parseInt(e,10);return r!=r&&(r=t),k(r)},k=function(e){return Math.min(Math.max(e,1e3),18e6)},D=function(e,t,r){try{"function"==typeof t&&t.call(e,r)}catch(e){O(e)}};function F(e,t){S.call(this),t=t||{},this.onopen=void 0,this.onmessage=void 0,this.onerror=void 0,this.url=void 0,this.readyState=void 0,this.withCredentials=void 0,this.headers=void 0,this._close=void 0,function(e,t,r){t=String(t);var a=Boolean(r.withCredentials),c=r.lastEventIdQueryParameterName||"lastEventId",u=k(1e3),l=P(r.heartbeatTimeout,45e3),h="",p=u,f=!1,d=0,y=r.headers||{},g=r.Transport,m=M&&null==g?void 0:new v(null!=g?new g:null!=s&&"withCredentials"in s.prototype||null==i?new s:new i),b=null!=g&&"string"!=typeof g?new g:null==m?new R:new E,w=void 0,C=0,x=$,S="",O="",T="",F="",U=0,N=0,L=0,z=function(t,r,n,o){if(0===x)if(200===t&&null!=n&&I.test(n)){x=1,f=Date.now(),p=u,e.readyState=1;var s=new q("open",{status:t,statusText:r,headers:o});e.dispatchEvent(s),D(e,e.onopen,s)}else{var i="";200!==t?(r&&(r=r.replace(/\s+/g," ")),i="EventSource's response has a status "+t+" "+r+" that is not 200. Aborting the connection."):i="EventSource's response has a Content-Type specifying an unsupported type: "+(null==n?"-":n.replace(/\s+/g," "))+". Aborting the connection.",J();s=new q("error",{status:t,statusText:r,headers:o});e.dispatchEvent(s),D(e,e.onerror,s),console.error(i)}},H=function(t){if(1===x){for(var r=-1,s=0;s<t.length;s+=1){(c=t.charCodeAt(s))!=="\n".charCodeAt(0)&&c!=="\r".charCodeAt(0)||(r=s)}var i=(-1!==r?F:"")+t.slice(0,r+1);F=(-1===r?F:"")+t.slice(r+1),""!==t&&(f=Date.now(),d+=t.length);for(var a=0;a<i.length;a+=1){var c=i.charCodeAt(a);if(U===A&&c==="\n".charCodeAt(0))U=0;else if(U===A&&(U=0),c==="\r".charCodeAt(0)||c==="\n".charCodeAt(0)){if(0!==U){1===U&&(L=a+1);var y=i.slice(N,L-1),g=i.slice(L+(L<a&&i.charCodeAt(L)===" ".charCodeAt(0)?1:0),a);"data"===y?(S+="\n",S+=g):"id"===y?O=g:"event"===y?T=g:"retry"===y?(u=P(g,u),p=u):"heartbeatTimeout"===y&&(l=P(g,l),0!==C&&(o(C),C=n((function(){G()}),l)))}if(0===U){if(""!==S){h=O,""===T&&(T="message");var m=new _(T,{data:S.slice(1),lastEventId:O});if(e.dispatchEvent(m),"open"===T?D(e,e.onopen,m):"message"===T?D(e,e.onmessage,m):"error"===T&&D(e,e.onerror,m),2===x)return}S="",T=""}U=c==="\r".charCodeAt(0)?A:0}else 0===U&&(N=a,U=1),1===U?c===":".charCodeAt(0)&&(L=a+1,U=2):2===U&&(U=3)}}},B=function(t){if(1===x||0===x){x=$,0!==C&&(o(C),C=0),C=n((function(){G()}),p),p=k(Math.min(16*u,2*p)),e.readyState=0;var r=new j("error",{error:t});e.dispatchEvent(r),D(e,e.onerror,r),null!=t&&console.error(t)}},J=function(){x=2,null!=w&&(w.abort(),w=void 0),0!==C&&(o(C),C=0),e.readyState=2},G=function(){if(C=0,x===$){f=!1,d=0,C=n((function(){G()}),l),x=0,S="",T="",O=h,F="",N=0,L=0,U=0;var r=t;if("data:"!==t.slice(0,5)&&"blob:"!==t.slice(0,5)&&""!==h){var o=t.indexOf("?");r=-1===o?t:t.slice(0,o+1)+t.slice(o+1).replace(/(?:^|&)([^=&]*)(?:=[^&]*)?/g,(function(e,t){return t===c?"":e})),r+=(-1===t.indexOf("?")?"?":"&")+c+"="+encodeURIComponent(h)}var s=e.withCredentials,i={Accept:"text/event-stream"},a=e.headers;if(null!=a)for(var u in a)Object.prototype.hasOwnProperty.call(a,u)&&(i[u]=a[u]);try{w=b.open(m,z,H,B,r,s,i)}catch(e){throw J(),e}}else if(f||null==w){var p=Math.max((f||Date.now())+l-Date.now(),1);f=!1,C=n((function(){G()}),p)}else B(new Error("No activity within "+l+" milliseconds. "+(0===x?"No response received.":d+" chars received.")+" Reconnecting.")),null!=w&&(w.abort(),w=void 0)};e.url=t,e.readyState=0,e.withCredentials=a,e.headers=y,e._close=J,G()}(this,e,t)}var M=null!=h&&null!=p&&"body"in p.prototype;F.prototype=Object.create(S.prototype),F.prototype.CONNECTING=0,F.prototype.OPEN=1,F.prototype.CLOSED=2,F.prototype.close=function(){this._close()},F.CONNECTING=0,F.OPEN=1,F.CLOSED=2,F.prototype.withCredentials=void 0;var U=c;null==s||null!=c&&"withCredentials"in c.prototype||(U=F),function(){var r=function(e){e.EventSourcePolyfill=F,e.NativeEventSource=c,e.EventSource=U}(t);void 0!==r&&(e.exports=r)}()}("undefined"==typeof globalThis?"undefined"!=typeof window?window:"undefined"!=typeof self?self:Ar:globalThis)}($r,$r.exports)),$r.exports}function Pr(){return jr?qr:(jr=1,qr=Ir().EventSourcePolyfill)}var kr=Tr(Pr()),Dr=Object.freeze({__proto__:null,default:kr});e.BasePatch=et,e.BaseTransaction=ot,e.ClientError=De,e.CorsOriginError=Le,e.ObservablePatch=tt,e.ObservableSanityClient=tr,e.ObservableTransaction=it,e.Patch=rt,e.SanityClient=rr,e.ServerError=Fe,e.Transaction=st,e.createClient=sr,e.default=ir,e.requester=or,e.unstable__adapter=y,e.unstable__environment="browser",Object.defineProperty(e,"__esModule",{value:!0})}));
|
|
6
|
+
*/function Ir(){return _r||(_r=1,function(e,t){!function(r){var n=r.setTimeout,o=r.clearTimeout,s=r.XMLHttpRequest,i=r.XDomainRequest,a=r.ActiveXObject,c=r.EventSource,u=r.document,l=r.Promise,h=r.fetch,p=r.Response,d=r.TextDecoder,f=r.TextEncoder,y=r.AbortController;if("undefined"==typeof window||void 0===u||"readyState"in u||null!=u.body||(u.readyState="loading",window.addEventListener("load",(function(e){u.readyState="complete"}),!1)),null==s&&null!=a&&(s=function(){return new a("Microsoft.XMLHTTP")}),null==Object.create&&(Object.create=function(e){function t(){}return t.prototype=e,new t}),Date.now||(Date.now=function(){return(new Date).getTime()}),null==y){var g=h;h=function(e,t){var r=t.signal;return g(e,{headers:t.headers,credentials:t.credentials,cache:t.cache}).then((function(e){var t=e.body.getReader();return r._reader=t,r._aborted&&r._reader.cancel(),{status:e.status,statusText:e.statusText,headers:e.headers,body:{getReader:function(){return t}}}}))},y=function(){this.signal={_reader:null,_aborted:!1},this.abort=function(){null!=this.signal._reader&&this.signal._reader.cancel(),this.signal._aborted=!0}}}function m(){this.bitsNeeded=0,this.codePoint=0}m.prototype.decode=function(e){function t(e,t,r){if(1===r)return e>=128>>t&&e<<t<=2047;if(2===r)return e>=2048>>t&&e<<t<=55295||e>=57344>>t&&e<<t<=65535;if(3===r)return e>=65536>>t&&e<<t<=1114111;throw new Error}function r(e,t){if(6===e)return t>>6>15?3:t>31?2:1;if(12===e)return t>15?3:2;if(18===e)return 3;throw new Error}for(var n=65533,o="",s=this.bitsNeeded,i=this.codePoint,a=0;a<e.length;a+=1){var c=e[a];0!==s&&(c<128||c>191||!t(i<<6|63&c,s-6,r(s,i)))&&(s=0,i=n,o+=String.fromCharCode(i)),0===s?(c>=0&&c<=127?(s=0,i=c):c>=192&&c<=223?(s=6,i=31&c):c>=224&&c<=239?(s=12,i=15&c):c>=240&&c<=247?(s=18,i=7&c):(s=0,i=n),0===s||t(i,s,r(s,i))||(s=0,i=n)):(s-=6,i=i<<6|63&c),0===s&&(i<=65535?o+=String.fromCharCode(i):(o+=String.fromCharCode(55296+(i-65535-1>>10)),o+=String.fromCharCode(56320+(i-65535-1&1023))))}return this.bitsNeeded=s,this.codePoint=i,o};null!=d&&null!=f&&function(){try{return"test"===(new d).decode((new f).encode("test"),{stream:!0})}catch(e){console.debug("TextDecoder does not support streaming option. Using polyfill instead: "+e)}return!1}()||(d=m);var b=function(){};function v(e){this.withCredentials=!1,this.readyState=0,this.status=0,this.statusText="",this.responseText="",this.onprogress=b,this.onload=b,this.onerror=b,this.onreadystatechange=b,this._contentType="",this._xhr=e,this._sendTimeout=0,this._abort=b}function w(e){return e.replace(/[A-Z]/g,(function(e){return String.fromCharCode(e.charCodeAt(0)+32)}))}function C(e){for(var t=Object.create(null),r=e.split("\r\n"),n=0;n<r.length;n+=1){var o=r[n].split(": "),s=o.shift(),i=o.join(": ");t[w(s)]=i}this._map=t}function E(){}function x(e){this._headers=e}function R(){}function S(){this._listeners=Object.create(null)}function O(e){n((function(){throw e}),0)}function T(e){this.type=e,this.target=void 0}function _(e,t){T.call(this,e),this.data=t.data,this.lastEventId=t.lastEventId}function q(e,t){T.call(this,e),this.status=t.status,this.statusText=t.statusText,this.headers=t.headers}function j(e,t){T.call(this,e),this.error=t.error}v.prototype.open=function(e,t){this._abort(!0);var r=this,i=this._xhr,a=1,c=0;this._abort=function(e){0!==r._sendTimeout&&(o(r._sendTimeout),r._sendTimeout=0),1!==a&&2!==a&&3!==a||(a=4,i.onload=b,i.onerror=b,i.onabort=b,i.onprogress=b,i.onreadystatechange=b,i.abort(),0!==c&&(o(c),c=0),e||(r.readyState=4,r.onabort(null),r.onreadystatechange())),a=0};var u=function(){if(1===a){var e=0,t="",n=void 0;if("contentType"in i)e=200,t="OK",n=i.contentType;else try{e=i.status,t=i.statusText,n=i.getResponseHeader("Content-Type")}catch(r){e=0,t="",n=void 0}0!==e&&(a=2,r.readyState=2,r.status=e,r.statusText=t,r._contentType=n,r.onreadystatechange())}},l=function(){if(u(),2===a||3===a){a=3;var e="";try{e=i.responseText}catch(e){}r.readyState=3,r.responseText=e,r.onprogress()}},h=function(e,t){if(null!=t&&null!=t.preventDefault||(t={preventDefault:b}),l(),1===a||2===a||3===a){if(a=4,0!==c&&(o(c),c=0),r.readyState=4,"load"===e)r.onload(t);else if("error"===e)r.onerror(t);else{if("abort"!==e)throw new TypeError;r.onabort(t)}r.onreadystatechange()}},p=function(){c=n((function(){p()}),500),3===i.readyState&&l()};"onload"in i&&(i.onload=function(e){h("load",e)}),"onerror"in i&&(i.onerror=function(e){h("error",e)}),"onabort"in i&&(i.onabort=function(e){h("abort",e)}),"onprogress"in i&&(i.onprogress=l),"onreadystatechange"in i&&(i.onreadystatechange=function(e){!function(e){null!=i&&(4===i.readyState?"onload"in i&&"onerror"in i&&"onabort"in i||h(""===i.responseText?"error":"load",e):3===i.readyState?"onprogress"in i||l():2===i.readyState&&u())}(e)}),!("contentType"in i)&&"ontimeout"in s.prototype||(t+=(-1===t.indexOf("?")?"?":"&")+"padding=true"),i.open(e,t,!0),"readyState"in i&&(c=n((function(){p()}),0))},v.prototype.abort=function(){this._abort(!1)},v.prototype.getResponseHeader=function(e){return this._contentType},v.prototype.setRequestHeader=function(e,t){var r=this._xhr;"setRequestHeader"in r&&r.setRequestHeader(e,t)},v.prototype.getAllResponseHeaders=function(){return null!=this._xhr.getAllResponseHeaders&&this._xhr.getAllResponseHeaders()||""},v.prototype.send=function(){if("ontimeout"in s.prototype&&("sendAsBinary"in s.prototype||"mozAnon"in s.prototype)||null==u||null==u.readyState||"complete"===u.readyState){var e=this._xhr;"withCredentials"in e&&(e.withCredentials=this.withCredentials);try{e.send(void 0)}catch(e){throw e}}else{var t=this;t._sendTimeout=n((function(){t._sendTimeout=0,t.send()}),4)}},C.prototype.get=function(e){return this._map[w(e)]},null!=s&&null==s.HEADERS_RECEIVED&&(s.HEADERS_RECEIVED=2),E.prototype.open=function(e,t,r,n,o,i,a){e.open("GET",o);var c=0;for(var u in e.onprogress=function(){var t=e.responseText.slice(c);c+=t.length,r(t)},e.onerror=function(e){e.preventDefault(),n(new Error("NetworkError"))},e.onload=function(){n(null)},e.onabort=function(){n(null)},e.onreadystatechange=function(){if(e.readyState===s.HEADERS_RECEIVED){var r=e.status,n=e.statusText,o=e.getResponseHeader("Content-Type"),i=e.getAllResponseHeaders();t(r,n,o,new C(i))}},e.withCredentials=i,a)Object.prototype.hasOwnProperty.call(a,u)&&e.setRequestHeader(u,a[u]);return e.send(),e},x.prototype.get=function(e){return this._headers.get(e)},R.prototype.open=function(e,t,r,n,o,s,i){var a=null,c=new y,u=c.signal,p=new d;return h(o,{headers:i,credentials:s?"include":"same-origin",signal:u,cache:"no-store"}).then((function(e){return a=e.body.getReader(),t(e.status,e.statusText,e.headers.get("Content-Type"),new x(e.headers)),new l((function(e,t){var n=function(){a.read().then((function(t){if(t.done)e(void 0);else{var o=p.decode(t.value,{stream:!0});r(o),n()}})).catch((function(e){t(e)}))};n()}))})).catch((function(e){return"AbortError"===e.name?void 0:e})).then((function(e){n(e)})),{abort:function(){null!=a&&a.cancel(),c.abort()}}},S.prototype.dispatchEvent=function(e){e.target=this;var t=this._listeners[e.type];if(null!=t)for(var r=t.length,n=0;n<r;n+=1){var o=t[n];try{"function"==typeof o.handleEvent?o.handleEvent(e):o.call(this,e)}catch(e){O(e)}}},S.prototype.addEventListener=function(e,t){e=String(e);var r=this._listeners,n=r[e];null==n&&(n=[],r[e]=n);for(var o=!1,s=0;s<n.length;s+=1)n[s]===t&&(o=!0);o||n.push(t)},S.prototype.removeEventListener=function(e,t){e=String(e);var r=this._listeners,n=r[e];if(null!=n){for(var o=[],s=0;s<n.length;s+=1)n[s]!==t&&o.push(n[s]);0===o.length?delete r[e]:r[e]=o}},_.prototype=Object.create(T.prototype),q.prototype=Object.create(T.prototype),j.prototype=Object.create(T.prototype);var $=-1,A=-1,I=/^text\/event\-stream(;.*)?$/i,P=function(e,t){var r=null==e?t:parseInt(e,10);return r!=r&&(r=t),k(r)},k=function(e){return Math.min(Math.max(e,1e3),18e6)},D=function(e,t,r){try{"function"==typeof t&&t.call(e,r)}catch(e){O(e)}};function F(e,t){S.call(this),t=t||{},this.onopen=void 0,this.onmessage=void 0,this.onerror=void 0,this.url=void 0,this.readyState=void 0,this.withCredentials=void 0,this.headers=void 0,this._close=void 0,function(e,t,r){t=String(t);var a=Boolean(r.withCredentials),c=r.lastEventIdQueryParameterName||"lastEventId",u=k(1e3),l=P(r.heartbeatTimeout,45e3),h="",p=u,d=!1,f=0,y=r.headers||{},g=r.Transport,m=M&&null==g?void 0:new v(null!=g?new g:null!=s&&"withCredentials"in s.prototype||null==i?new s:new i),b=null!=g&&"string"!=typeof g?new g:null==m?new R:new E,w=void 0,C=0,x=$,S="",O="",T="",F="",U=0,N=0,L=0,z=function(t,r,n,o){if(0===x)if(200===t&&null!=n&&I.test(n)){x=1,d=Date.now(),p=u,e.readyState=1;var s=new q("open",{status:t,statusText:r,headers:o});e.dispatchEvent(s),D(e,e.onopen,s)}else{var i="";200!==t?(r&&(r=r.replace(/\s+/g," ")),i="EventSource's response has a status "+t+" "+r+" that is not 200. Aborting the connection."):i="EventSource's response has a Content-Type specifying an unsupported type: "+(null==n?"-":n.replace(/\s+/g," "))+". Aborting the connection.",J();s=new q("error",{status:t,statusText:r,headers:o});e.dispatchEvent(s),D(e,e.onerror,s),console.error(i)}},H=function(t){if(1===x){for(var r=-1,s=0;s<t.length;s+=1){(c=t.charCodeAt(s))!=="\n".charCodeAt(0)&&c!=="\r".charCodeAt(0)||(r=s)}var i=(-1!==r?F:"")+t.slice(0,r+1);F=(-1===r?F:"")+t.slice(r+1),""!==t&&(d=Date.now(),f+=t.length);for(var a=0;a<i.length;a+=1){var c=i.charCodeAt(a);if(U===A&&c==="\n".charCodeAt(0))U=0;else if(U===A&&(U=0),c==="\r".charCodeAt(0)||c==="\n".charCodeAt(0)){if(0!==U){1===U&&(L=a+1);var y=i.slice(N,L-1),g=i.slice(L+(L<a&&i.charCodeAt(L)===" ".charCodeAt(0)?1:0),a);"data"===y?(S+="\n",S+=g):"id"===y?O=g:"event"===y?T=g:"retry"===y?(u=P(g,u),p=u):"heartbeatTimeout"===y&&(l=P(g,l),0!==C&&(o(C),C=n((function(){G()}),l)))}if(0===U){if(""!==S){h=O,""===T&&(T="message");var m=new _(T,{data:S.slice(1),lastEventId:O});if(e.dispatchEvent(m),"open"===T?D(e,e.onopen,m):"message"===T?D(e,e.onmessage,m):"error"===T&&D(e,e.onerror,m),2===x)return}S="",T=""}U=c==="\r".charCodeAt(0)?A:0}else 0===U&&(N=a,U=1),1===U?c===":".charCodeAt(0)&&(L=a+1,U=2):2===U&&(U=3)}}},B=function(t){if(1===x||0===x){x=$,0!==C&&(o(C),C=0),C=n((function(){G()}),p),p=k(Math.min(16*u,2*p)),e.readyState=0;var r=new j("error",{error:t});e.dispatchEvent(r),D(e,e.onerror,r),null!=t&&console.error(t)}},J=function(){x=2,null!=w&&(w.abort(),w=void 0),0!==C&&(o(C),C=0),e.readyState=2},G=function(){if(C=0,x===$){d=!1,f=0,C=n((function(){G()}),l),x=0,S="",T="",O=h,F="",N=0,L=0,U=0;var r=t;if("data:"!==t.slice(0,5)&&"blob:"!==t.slice(0,5)&&""!==h){var o=t.indexOf("?");r=-1===o?t:t.slice(0,o+1)+t.slice(o+1).replace(/(?:^|&)([^=&]*)(?:=[^&]*)?/g,(function(e,t){return t===c?"":e})),r+=(-1===t.indexOf("?")?"?":"&")+c+"="+encodeURIComponent(h)}var s=e.withCredentials,i={Accept:"text/event-stream"},a=e.headers;if(null!=a)for(var u in a)Object.prototype.hasOwnProperty.call(a,u)&&(i[u]=a[u]);try{w=b.open(m,z,H,B,r,s,i)}catch(e){throw J(),e}}else if(d||null==w){var p=Math.max((d||Date.now())+l-Date.now(),1);d=!1,C=n((function(){G()}),p)}else B(new Error("No activity within "+l+" milliseconds. "+(0===x?"No response received.":f+" chars received.")+" Reconnecting.")),null!=w&&(w.abort(),w=void 0)};e.url=t,e.readyState=0,e.withCredentials=a,e.headers=y,e._close=J,G()}(this,e,t)}var M=null!=h&&null!=p&&"body"in p.prototype;F.prototype=Object.create(S.prototype),F.prototype.CONNECTING=0,F.prototype.OPEN=1,F.prototype.CLOSED=2,F.prototype.close=function(){this._close()},F.CONNECTING=0,F.OPEN=1,F.CLOSED=2,F.prototype.withCredentials=void 0;var U=c;null==s||null!=c&&"withCredentials"in c.prototype||(U=F),function(){var r=function(e){e.EventSourcePolyfill=F,e.NativeEventSource=c,e.EventSource=U}(t);void 0!==r&&(e.exports=r)}()}("undefined"==typeof globalThis?"undefined"!=typeof window?window:"undefined"!=typeof self?self:Ar:globalThis)}($r,$r.exports)),$r.exports}function Pr(){return jr?qr:(jr=1,qr=Ir().EventSourcePolyfill)}var kr=Tr(Pr()),Dr=Object.freeze({__proto__:null,default:kr});e.BasePatch=et,e.BaseTransaction=ot,e.ClientError=De,e.CorsOriginError=Le,e.ObservablePatch=tt,e.ObservableSanityClient=tr,e.ObservableTransaction=it,e.Patch=rt,e.SanityClient=rr,e.ServerError=Fe,e.Transaction=st,e.createClient=sr,e.default=ir,e.requester=or,e.unstable__adapter=y,e.unstable__environment="browser",Object.defineProperty(e,"__esModule",{value:!0})}));
|