UNPKG

@sanity/client

Version:

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

163 lines (162 loc) • 6.18 kB
import { t as __exportAll } from "./rolldown-runtime-vyAXikos.js"; import { n as y } from "./dist-Z8cIRxoB.js"; import { S as toString, a as resolveMapping, b as reKeySegment, c as parseJsonPath, i as walkMap, n as resolveStudioBaseRoute, r as createEditUrl, s as jsonPathToStudioPath } from "./resolveEditInfo-Cz-smq3a.js"; /** * @internal */ function encodeIntoResult(result, csm, encoder) { return walkMap(result, (value, path) => { if (typeof value != "string") return value; let resolveMappingResult = resolveMapping(path, csm); if (!resolveMappingResult) return value; let { mapping, matchedPath } = resolveMappingResult; if (mapping.type !== "value" || mapping.source.type !== "documentValue") return value; let sourceDocument = csm.documents[mapping.source.document], sourcePath = csm.paths[mapping.source.path], matchPathSegments = parseJsonPath(matchedPath); return encoder({ sourcePath: parseJsonPath(sourcePath).concat(path.slice(matchPathSegments.length)), sourceDocument, resultPath: path, value }); }); } const filterDefault = ({ sourcePath, resultPath, value }) => { if (isValidDate(value) || isValidURL(value)) return !1; let endPath = sourcePath.at(-1); return !(sourcePath.at(-2) === "slug" && endPath === "current" || typeof endPath == "string" && (endPath.startsWith("_") || endPath.endsWith("Id")) || sourcePath.some((path) => path === "meta" || path === "metadata" || path === "openGraph" || path === "seo") || hasTypeLike(sourcePath) || hasTypeLike(resultPath) || typeof endPath == "string" && denylist.has(endPath)); }, denylist = /* @__PURE__ */ new Set(/* @__PURE__ */ "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".split(".")); function isValidDate(dateString) { return /^\d{4}-\d{2}-\d{2}/.test(dateString) ? !!Date.parse(dateString) : !1; } const allowedProtocols = /* @__PURE__ */ new Set([ "app:", "data:", "discord:", "file:", "ftp:", "ftps:", "geo:", "http:", "https:", "imap:", "javascript:", "magnet:", "mailto:", "maps:", "ms-excel:", "ms-powerpoint:", "ms-word:", "slack:", "sms:", "spotify:", "steam:", "teams:", "tel:", "vscode:", "zoom:" ]); function isValidURL(url) { try { let { protocol } = new URL(url, url.startsWith("/") ? "https://acme.com" : void 0); return allowedProtocols.has(protocol) || protocol.startsWith("web+"); } catch { return !1; } } function hasTypeLike(path) { return path.some((segment) => typeof segment == "string" && segment.match(/type/i) !== null); } var stegaEncodeSourceMap_exports = /* @__PURE__ */ __exportAll({ encodeIntoResult: () => encodeIntoResult, stegaEncodeSourceMap: () => stegaEncodeSourceMap }); /** * Uses `@vercel/stega` to embed edit info JSON into strings in your query result. * The JSON payloads are added using invisible characters so they don't show up visually. * The edit info is generated from the Content Source Map (CSM) that is returned from Sanity for the query. * @public */ function stegaEncodeSourceMap(result, resultSourceMap, config) { let { filter, logger, enabled } = config; if (!enabled) { let msg = "config.enabled must be true, don't call this function otherwise"; throw logger?.error?.(`[@sanity/client]: ${msg}`, { result, resultSourceMap, config }), TypeError(msg); } if (!resultSourceMap) return logger?.error?.("[@sanity/client]: Missing Content Source Map from response body", { result, resultSourceMap, config }), result; if (!config.studioUrl) { let msg = "config.studioUrl must be defined"; throw logger?.error?.(`[@sanity/client]: ${msg}`, { result, resultSourceMap, config }), TypeError(msg); } let report = { encoded: [], skipped: [] }, resultWithStega = encodeIntoResult(result, resultSourceMap, ({ sourcePath, sourceDocument, resultPath, value }) => { if ((typeof filter == "function" ? filter({ sourcePath, resultPath, filterDefault, sourceDocument, value }) : filterDefault({ sourcePath, resultPath, filterDefault, sourceDocument, value })) === !1) return logger && report.skipped.push({ path: prettyPathForLogging(sourcePath), value: `${value.slice(0, 20)}${value.length > 20 ? "..." : ""}`, length: value.length }), value; logger && report.encoded.push({ path: prettyPathForLogging(sourcePath), value: `${value.slice(0, 20)}${value.length > 20 ? "..." : ""}`, length: value.length }); let { baseUrl, workspace, tool } = resolveStudioBaseRoute(typeof config.studioUrl == "function" ? config.studioUrl(sourceDocument) : config.studioUrl); if (!baseUrl) return value; let { _id: id, _type: type, _projectId: projectId, _dataset: dataset } = sourceDocument; return y(value, { origin: "sanity.io", href: createEditUrl({ baseUrl, workspace, tool, id, type, path: sourcePath, ...!config.omitCrossDatasetReferenceData && { dataset, projectId } }) }, !1); }); if (logger) { let isSkipping = report.skipped.length, isEncoding = report.encoded.length; if ((isSkipping || isEncoding) && ((logger?.groupCollapsed || logger.log)?.("[@sanity/client]: Encoding source map into result"), logger.log?.(`[@sanity/client]: Paths encoded: ${report.encoded.length}, skipped: ${report.skipped.length}`)), report.encoded.length > 0 && (logger?.log?.("[@sanity/client]: Table of encoded paths"), (logger?.table || logger.log)?.(report.encoded)), report.skipped.length > 0) { let skipped = /* @__PURE__ */ new Set(); for (let { path } of report.skipped) skipped.add(path.replace(reKeySegment, "0").replace(/\[\d+\]/g, "[]")); logger?.log?.("[@sanity/client]: List of skipped paths", [...skipped.values()]); } (isSkipping || isEncoding) && logger?.groupEnd?.(); } return resultWithStega; } function prettyPathForLogging(path) { return toString(jsonPathToStudioPath(path)); } export { stegaEncodeSourceMap_exports as n, encodeIntoResult as r, stegaEncodeSourceMap as t }; //# sourceMappingURL=stegaEncodeSourceMap-YR3NQ3iz.js.map