@sanity/client 6.26.1 → 6.27.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/_chunks-cjs/config.cjs +163 -0
- package/dist/_chunks-cjs/config.cjs.map +1 -0
- package/dist/_chunks-es/config.js +164 -0
- package/dist/_chunks-es/config.js.map +1 -0
- package/dist/csm.cjs +40 -18
- package/dist/csm.cjs.map +1 -1
- package/dist/csm.d.cts +6 -3
- package/dist/csm.d.ts +6 -3
- package/dist/csm.js +42 -19
- package/dist/csm.js.map +1 -1
- package/dist/index.cjs +54 -202
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +11 -158
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/src/csm/applySourceDocuments.ts +10 -40
- package/src/csm/createSourceDocumentResolver.ts +54 -0
- package/src/csm/resolvePerspectives.ts +29 -0
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
const BASE_URL = "https://www.sanity.io/help/";
|
|
3
|
+
function generateHelpUrl(slug) {
|
|
4
|
+
return BASE_URL + slug;
|
|
5
|
+
}
|
|
6
|
+
const VALID_ASSET_TYPES = ["image", "file"], VALID_INSERT_LOCATIONS = ["before", "after", "replace"], dataset = (name) => {
|
|
7
|
+
if (!/^(~[a-z0-9]{1}[-\w]{0,63}|[a-z0-9]{1}[-\w]{0,63})$/.test(name))
|
|
8
|
+
throw new Error(
|
|
9
|
+
"Datasets can only contain lowercase characters, numbers, underscores and dashes, and start with tilde, and be maximum 64 characters"
|
|
10
|
+
);
|
|
11
|
+
}, projectId = (id) => {
|
|
12
|
+
if (!/^[-a-z0-9]+$/i.test(id))
|
|
13
|
+
throw new Error("`projectId` can only contain only a-z, 0-9 and dashes");
|
|
14
|
+
}, validateAssetType = (type) => {
|
|
15
|
+
if (VALID_ASSET_TYPES.indexOf(type) === -1)
|
|
16
|
+
throw new Error(`Invalid asset type: ${type}. Must be one of ${VALID_ASSET_TYPES.join(", ")}`);
|
|
17
|
+
}, validateObject = (op, val) => {
|
|
18
|
+
if (val === null || typeof val != "object" || Array.isArray(val))
|
|
19
|
+
throw new Error(`${op}() takes an object of properties`);
|
|
20
|
+
}, validateDocumentId = (op, id) => {
|
|
21
|
+
if (typeof id != "string" || !/^[a-z0-9_][a-z0-9_.-]{0,127}$/i.test(id) || id.includes(".."))
|
|
22
|
+
throw new Error(`${op}(): "${id}" is not a valid document ID`);
|
|
23
|
+
}, requireDocumentId = (op, doc) => {
|
|
24
|
+
if (!doc._id)
|
|
25
|
+
throw new Error(`${op}() requires that the document contains an ID ("_id" property)`);
|
|
26
|
+
validateDocumentId(op, doc._id);
|
|
27
|
+
}, validateInsert = (at, selector, items) => {
|
|
28
|
+
const signature = "insert(at, selector, items)";
|
|
29
|
+
if (VALID_INSERT_LOCATIONS.indexOf(at) === -1) {
|
|
30
|
+
const valid = VALID_INSERT_LOCATIONS.map((loc) => `"${loc}"`).join(", ");
|
|
31
|
+
throw new Error(`${signature} takes an "at"-argument which is one of: ${valid}`);
|
|
32
|
+
}
|
|
33
|
+
if (typeof selector != "string")
|
|
34
|
+
throw new Error(`${signature} takes a "selector"-argument which must be a string`);
|
|
35
|
+
if (!Array.isArray(items))
|
|
36
|
+
throw new Error(`${signature} takes an "items"-argument which must be an array`);
|
|
37
|
+
}, hasDataset = (config) => {
|
|
38
|
+
if (!config.dataset)
|
|
39
|
+
throw new Error("`dataset` must be provided to perform queries");
|
|
40
|
+
return config.dataset || "";
|
|
41
|
+
}, requestTag = (tag) => {
|
|
42
|
+
if (typeof tag != "string" || !/^[a-z0-9._-]{1,75}$/i.test(tag))
|
|
43
|
+
throw new Error(
|
|
44
|
+
"Tag can only contain alphanumeric characters, underscores, dashes and dots, and be between one and 75 characters long."
|
|
45
|
+
);
|
|
46
|
+
return tag;
|
|
47
|
+
};
|
|
48
|
+
function once(fn) {
|
|
49
|
+
let didCall = !1, returnValue;
|
|
50
|
+
return (...args) => (didCall || (returnValue = fn(...args), didCall = !0), returnValue);
|
|
51
|
+
}
|
|
52
|
+
const createWarningPrinter = (message) => (
|
|
53
|
+
// eslint-disable-next-line no-console
|
|
54
|
+
once((...args) => console.warn(message.join(" "), ...args))
|
|
55
|
+
), printCdnAndWithCredentialsWarning = createWarningPrinter([
|
|
56
|
+
"Because you set `withCredentials` to true, we will override your `useCdn`",
|
|
57
|
+
"setting to be false since (cookie-based) credentials are never set on the CDN"
|
|
58
|
+
]), printCdnWarning = createWarningPrinter([
|
|
59
|
+
"Since you haven't set a value for `useCdn`, we will deliver content using our",
|
|
60
|
+
"global, edge-cached API-CDN. If you wish to have content delivered faster, set",
|
|
61
|
+
"`useCdn: false` to use the Live API. Note: You may incur higher costs using the live API."
|
|
62
|
+
]), printCdnPreviewDraftsWarning = createWarningPrinter([
|
|
63
|
+
"The Sanity client is configured with the `perspective` set to `previewDrafts`, which doesn't support the API-CDN.",
|
|
64
|
+
"The Live API will be used instead. Set `useCdn: false` in your configuration to hide this warning."
|
|
65
|
+
]), printBrowserTokenWarning = createWarningPrinter([
|
|
66
|
+
"You have configured Sanity client to use a token in the browser. This may cause unintentional security issues.",
|
|
67
|
+
`See ${generateHelpUrl(
|
|
68
|
+
"js-client-browser-token"
|
|
69
|
+
)} for more information and how to hide this warning.`
|
|
70
|
+
]), printNoApiVersionSpecifiedWarning = createWarningPrinter([
|
|
71
|
+
"Using the Sanity client without specifying an API version is deprecated.",
|
|
72
|
+
`See ${generateHelpUrl("js-client-api-version")}`
|
|
73
|
+
]), printNoDefaultExport = createWarningPrinter([
|
|
74
|
+
"The default export of @sanity/client has been deprecated. Use the named export `createClient` instead."
|
|
75
|
+
]), defaultCdnHost = "apicdn.sanity.io", defaultConfig = {
|
|
76
|
+
apiHost: "https://api.sanity.io",
|
|
77
|
+
apiVersion: "1",
|
|
78
|
+
useProjectHostname: !0,
|
|
79
|
+
stega: { enabled: !1 }
|
|
80
|
+
}, LOCALHOSTS = ["localhost", "127.0.0.1", "0.0.0.0"], isLocal = (host) => LOCALHOSTS.indexOf(host) !== -1;
|
|
81
|
+
function validateApiVersion(apiVersion) {
|
|
82
|
+
if (apiVersion === "1" || apiVersion === "X")
|
|
83
|
+
return;
|
|
84
|
+
const apiDate = new Date(apiVersion);
|
|
85
|
+
if (!(/^\d{4}-\d{2}-\d{2}$/.test(apiVersion) && apiDate instanceof Date && apiDate.getTime() > 0))
|
|
86
|
+
throw new Error("Invalid API version string, expected `1` or date in format `YYYY-MM-DD`");
|
|
87
|
+
}
|
|
88
|
+
function validateApiPerspective(perspective) {
|
|
89
|
+
if (Array.isArray(perspective)) {
|
|
90
|
+
for (const perspectiveValue of perspective)
|
|
91
|
+
if (perspectiveValue !== "published" && perspectiveValue !== "drafts" && !(typeof perspectiveValue == "string" && perspectiveValue.startsWith("r") && perspectiveValue !== "raw"))
|
|
92
|
+
throw new TypeError(
|
|
93
|
+
"Invalid API perspective value, expected `published`, `drafts` or a valid release identifier string"
|
|
94
|
+
);
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
switch (perspective) {
|
|
98
|
+
case "previewDrafts":
|
|
99
|
+
case "drafts":
|
|
100
|
+
case "published":
|
|
101
|
+
case "raw":
|
|
102
|
+
return;
|
|
103
|
+
default:
|
|
104
|
+
throw new TypeError(
|
|
105
|
+
"Invalid API perspective string, expected `published`, `previewDrafts` or `raw`"
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
const initConfig = (config, prevConfig) => {
|
|
110
|
+
const specifiedConfig = {
|
|
111
|
+
...prevConfig,
|
|
112
|
+
...config,
|
|
113
|
+
stega: {
|
|
114
|
+
...typeof prevConfig.stega == "boolean" ? { enabled: prevConfig.stega } : prevConfig.stega || defaultConfig.stega,
|
|
115
|
+
...typeof config.stega == "boolean" ? { enabled: config.stega } : config.stega || {}
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
specifiedConfig.apiVersion || printNoApiVersionSpecifiedWarning();
|
|
119
|
+
const newConfig = {
|
|
120
|
+
...defaultConfig,
|
|
121
|
+
...specifiedConfig
|
|
122
|
+
}, projectBased = newConfig.useProjectHostname;
|
|
123
|
+
if (typeof Promise > "u") {
|
|
124
|
+
const helpUrl = generateHelpUrl("js-client-promise-polyfill");
|
|
125
|
+
throw new Error(`No native Promise-implementation found, polyfill needed - see ${helpUrl}`);
|
|
126
|
+
}
|
|
127
|
+
if (projectBased && !newConfig.projectId)
|
|
128
|
+
throw new Error("Configuration must contain `projectId`");
|
|
129
|
+
if (typeof newConfig.perspective < "u" && validateApiPerspective(newConfig.perspective), "encodeSourceMap" in newConfig)
|
|
130
|
+
throw new Error(
|
|
131
|
+
"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'?"
|
|
132
|
+
);
|
|
133
|
+
if ("encodeSourceMapAtPath" in newConfig)
|
|
134
|
+
throw new Error(
|
|
135
|
+
"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'?"
|
|
136
|
+
);
|
|
137
|
+
if (typeof newConfig.stega.enabled != "boolean")
|
|
138
|
+
throw new Error(`stega.enabled must be a boolean, received ${newConfig.stega.enabled}`);
|
|
139
|
+
if (newConfig.stega.enabled && newConfig.stega.studioUrl === void 0)
|
|
140
|
+
throw new Error("stega.studioUrl must be defined when stega.enabled is true");
|
|
141
|
+
if (newConfig.stega.enabled && typeof newConfig.stega.studioUrl != "string" && typeof newConfig.stega.studioUrl != "function")
|
|
142
|
+
throw new Error(
|
|
143
|
+
`stega.studioUrl must be a string or a function, received ${newConfig.stega.studioUrl}`
|
|
144
|
+
);
|
|
145
|
+
const isBrowser = typeof window < "u" && window.location && window.location.hostname, isLocalhost = isBrowser && isLocal(window.location.hostname);
|
|
146
|
+
isBrowser && isLocalhost && newConfig.token && newConfig.ignoreBrowserTokenWarning !== !0 ? printBrowserTokenWarning() : typeof newConfig.useCdn > "u" && printCdnWarning(), projectBased && projectId(newConfig.projectId), newConfig.dataset && dataset(newConfig.dataset), "requestTagPrefix" in newConfig && (newConfig.requestTagPrefix = newConfig.requestTagPrefix ? requestTag(newConfig.requestTagPrefix).replace(/\.+$/, "") : void 0), newConfig.apiVersion = `${newConfig.apiVersion}`.replace(/^v/, ""), newConfig.isDefaultApi = newConfig.apiHost === defaultConfig.apiHost, newConfig.useCdn === !0 && newConfig.withCredentials && printCdnAndWithCredentialsWarning(), newConfig.useCdn = newConfig.useCdn !== !1 && !newConfig.withCredentials, validateApiVersion(newConfig.apiVersion);
|
|
147
|
+
const hostParts = newConfig.apiHost.split("://", 2), protocol = hostParts[0], host = hostParts[1], cdnHost = newConfig.isDefaultApi ? defaultCdnHost : host;
|
|
148
|
+
return newConfig.useProjectHostname ? (newConfig.url = `${protocol}://${newConfig.projectId}.${host}/v${newConfig.apiVersion}`, newConfig.cdnUrl = `${protocol}://${newConfig.projectId}.${cdnHost}/v${newConfig.apiVersion}`) : (newConfig.url = `${newConfig.apiHost}/v${newConfig.apiVersion}`, newConfig.cdnUrl = newConfig.url), newConfig;
|
|
149
|
+
};
|
|
150
|
+
exports.dataset = dataset;
|
|
151
|
+
exports.defaultConfig = defaultConfig;
|
|
152
|
+
exports.hasDataset = hasDataset;
|
|
153
|
+
exports.initConfig = initConfig;
|
|
154
|
+
exports.printCdnPreviewDraftsWarning = printCdnPreviewDraftsWarning;
|
|
155
|
+
exports.printNoDefaultExport = printNoDefaultExport;
|
|
156
|
+
exports.requestTag = requestTag;
|
|
157
|
+
exports.requireDocumentId = requireDocumentId;
|
|
158
|
+
exports.validateApiPerspective = validateApiPerspective;
|
|
159
|
+
exports.validateAssetType = validateAssetType;
|
|
160
|
+
exports.validateDocumentId = validateDocumentId;
|
|
161
|
+
exports.validateInsert = validateInsert;
|
|
162
|
+
exports.validateObject = validateObject;
|
|
163
|
+
//# sourceMappingURL=config.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"config.cjs","sources":["../../src/generateHelpUrl.ts","../../src/validators.ts","../../src/util/once.ts","../../src/warnings.ts","../../src/config.ts"],"sourcesContent":["const BASE_URL = 'https://www.sanity.io/help/'\n\nexport function generateHelpUrl(slug: string) {\n return BASE_URL + slug\n}\n","import type {Any, InitializedClientConfig} from './types'\n\nconst VALID_ASSET_TYPES = ['image', 'file']\nconst VALID_INSERT_LOCATIONS = ['before', 'after', 'replace']\n\nexport const dataset = (name: string) => {\n if (!/^(~[a-z0-9]{1}[-\\w]{0,63}|[a-z0-9]{1}[-\\w]{0,63})$/.test(name)) {\n throw new Error(\n 'Datasets can only contain lowercase characters, numbers, underscores and dashes, and start with tilde, and be maximum 64 characters',\n )\n }\n}\n\nexport const projectId = (id: string) => {\n if (!/^[-a-z0-9]+$/i.test(id)) {\n throw new Error('`projectId` can only contain only a-z, 0-9 and dashes')\n }\n}\n\nexport const validateAssetType = (type: string) => {\n if (VALID_ASSET_TYPES.indexOf(type) === -1) {\n throw new Error(`Invalid asset type: ${type}. Must be one of ${VALID_ASSET_TYPES.join(', ')}`)\n }\n}\n\nexport const validateObject = (op: string, val: Any) => {\n if (val === null || typeof val !== 'object' || Array.isArray(val)) {\n throw new Error(`${op}() takes an object of properties`)\n }\n}\n\nexport const validateDocumentId = (op: string, id: string) => {\n if (typeof id !== 'string' || !/^[a-z0-9_][a-z0-9_.-]{0,127}$/i.test(id) || id.includes('..')) {\n throw new Error(`${op}(): \"${id}\" is not a valid document ID`)\n }\n}\n\nexport const requireDocumentId = (op: string, doc: Record<string, Any>) => {\n if (!doc._id) {\n throw new Error(`${op}() requires that the document contains an ID (\"_id\" property)`)\n }\n\n validateDocumentId(op, doc._id)\n}\n\nexport const validateInsert = (at: string, selector: string, items: Any[]) => {\n const signature = 'insert(at, selector, items)'\n if (VALID_INSERT_LOCATIONS.indexOf(at) === -1) {\n const valid = VALID_INSERT_LOCATIONS.map((loc) => `\"${loc}\"`).join(', ')\n throw new Error(`${signature} takes an \"at\"-argument which is one of: ${valid}`)\n }\n\n if (typeof selector !== 'string') {\n throw new Error(`${signature} takes a \"selector\"-argument which must be a string`)\n }\n\n if (!Array.isArray(items)) {\n throw new Error(`${signature} takes an \"items\"-argument which must be an array`)\n }\n}\n\nexport const hasDataset = (config: InitializedClientConfig): string => {\n if (!config.dataset) {\n throw new Error('`dataset` must be provided to perform queries')\n }\n\n return config.dataset || ''\n}\n\nexport const requestTag = (tag: string) => {\n if (typeof tag !== 'string' || !/^[a-z0-9._-]{1,75}$/i.test(tag)) {\n throw new Error(\n `Tag can only contain alphanumeric characters, underscores, dashes and dots, and be between one and 75 characters long.`,\n )\n }\n\n return tag\n}\n","import type {Any} from '../types'\n\nexport function once(fn: Any) {\n let didCall = false\n let returnValue: Any\n return (...args: Any[]) => {\n if (didCall) {\n return returnValue\n }\n returnValue = fn(...args)\n didCall = true\n return returnValue\n }\n}\n","import {generateHelpUrl} from './generateHelpUrl'\nimport {type Any} from './types'\nimport {once} from './util/once'\n\nconst createWarningPrinter = (message: string[]) =>\n // eslint-disable-next-line no-console\n once((...args: Any[]) => console.warn(message.join(' '), ...args))\n\nexport const printCdnAndWithCredentialsWarning = createWarningPrinter([\n `Because you set \\`withCredentials\\` to true, we will override your \\`useCdn\\``,\n `setting to be false since (cookie-based) credentials are never set on the CDN`,\n])\n\nexport const printCdnWarning = createWarningPrinter([\n `Since you haven't set a value for \\`useCdn\\`, we will deliver content using our`,\n `global, edge-cached API-CDN. If you wish to have content delivered faster, set`,\n `\\`useCdn: false\\` to use the Live API. Note: You may incur higher costs using the live API.`,\n])\n\nexport const printCdnPreviewDraftsWarning = createWarningPrinter([\n `The Sanity client is configured with the \\`perspective\\` set to \\`previewDrafts\\`, which doesn't support the API-CDN.`,\n `The Live API will be used instead. Set \\`useCdn: false\\` in your configuration to hide this warning.`,\n])\n\nexport const printBrowserTokenWarning = createWarningPrinter([\n 'You have configured Sanity client to use a token in the browser. This may cause unintentional security issues.',\n `See ${generateHelpUrl(\n 'js-client-browser-token',\n )} for more information and how to hide this warning.`,\n])\n\nexport const printNoApiVersionSpecifiedWarning = createWarningPrinter([\n 'Using the Sanity client without specifying an API version is deprecated.',\n `See ${generateHelpUrl('js-client-api-version')}`,\n])\n\nexport const printNoDefaultExport = createWarningPrinter([\n 'The default export of @sanity/client has been deprecated. Use the named export `createClient` instead.',\n])\n","import {generateHelpUrl} from './generateHelpUrl'\nimport type {ClientConfig, ClientPerspective, InitializedClientConfig} from './types'\nimport * as validate from './validators'\nimport * as warnings from './warnings'\n\nconst defaultCdnHost = 'apicdn.sanity.io'\nexport const defaultConfig = {\n apiHost: 'https://api.sanity.io',\n apiVersion: '1',\n useProjectHostname: true,\n stega: {enabled: false},\n} satisfies ClientConfig\n\nconst LOCALHOSTS = ['localhost', '127.0.0.1', '0.0.0.0']\nconst isLocal = (host: string) => LOCALHOSTS.indexOf(host) !== -1\n\nfunction validateApiVersion(apiVersion: string) {\n if (apiVersion === '1' || apiVersion === 'X') {\n return\n }\n\n const apiDate = new Date(apiVersion)\n const apiVersionValid =\n /^\\d{4}-\\d{2}-\\d{2}$/.test(apiVersion) && apiDate instanceof Date && apiDate.getTime() > 0\n\n if (!apiVersionValid) {\n throw new Error('Invalid API version string, expected `1` or date in format `YYYY-MM-DD`')\n }\n}\n\n/**\n * @internal - it may have breaking changes in any release\n */\nexport function validateApiPerspective(\n perspective: unknown,\n): asserts perspective is ClientPerspective {\n if (Array.isArray(perspective)) {\n for (const perspectiveValue of perspective) {\n if (perspectiveValue === 'published') {\n continue\n }\n if (perspectiveValue === 'drafts') {\n continue\n }\n if (\n typeof perspectiveValue === 'string' &&\n perspectiveValue.startsWith('r') &&\n perspectiveValue !== 'raw'\n ) {\n continue\n }\n throw new TypeError(\n 'Invalid API perspective value, expected `published`, `drafts` or a valid release identifier string',\n )\n }\n return\n }\n switch (perspective as ClientPerspective) {\n case 'previewDrafts':\n case 'drafts':\n case 'published':\n case 'raw':\n return\n default:\n throw new TypeError(\n 'Invalid API perspective string, expected `published`, `previewDrafts` or `raw`',\n )\n }\n}\n\nexport const initConfig = (\n config: Partial<ClientConfig>,\n prevConfig: Partial<ClientConfig>,\n): InitializedClientConfig => {\n const specifiedConfig = {\n ...prevConfig,\n ...config,\n stega: {\n ...(typeof prevConfig.stega === 'boolean'\n ? {enabled: prevConfig.stega}\n : prevConfig.stega || defaultConfig.stega),\n ...(typeof config.stega === 'boolean' ? {enabled: config.stega} : config.stega || {}),\n },\n }\n if (!specifiedConfig.apiVersion) {\n warnings.printNoApiVersionSpecifiedWarning()\n }\n\n const newConfig = {\n ...defaultConfig,\n ...specifiedConfig,\n } as InitializedClientConfig\n const projectBased = newConfig.useProjectHostname\n\n if (typeof Promise === 'undefined') {\n const helpUrl = generateHelpUrl('js-client-promise-polyfill')\n throw new Error(`No native Promise-implementation found, polyfill needed - see ${helpUrl}`)\n }\n\n if (projectBased && !newConfig.projectId) {\n throw new Error('Configuration must contain `projectId`')\n }\n\n if (typeof newConfig.perspective !== 'undefined') {\n validateApiPerspective(newConfig.perspective)\n }\n\n if ('encodeSourceMap' in newConfig) {\n throw new Error(\n `It looks like you're using options meant for '@sanity/preview-kit/client'. 'encodeSourceMap' is not supported in '@sanity/client'. Did you mean 'stega.enabled'?`,\n )\n }\n if ('encodeSourceMapAtPath' in newConfig) {\n throw new Error(\n `It looks like you're using options meant for '@sanity/preview-kit/client'. 'encodeSourceMapAtPath' is not supported in '@sanity/client'. Did you mean 'stega.filter'?`,\n )\n }\n if (typeof newConfig.stega.enabled !== 'boolean') {\n throw new Error(`stega.enabled must be a boolean, received ${newConfig.stega.enabled}`)\n }\n if (newConfig.stega.enabled && newConfig.stega.studioUrl === undefined) {\n throw new Error(`stega.studioUrl must be defined when stega.enabled is true`)\n }\n if (\n newConfig.stega.enabled &&\n typeof newConfig.stega.studioUrl !== 'string' &&\n typeof newConfig.stega.studioUrl !== 'function'\n ) {\n throw new Error(\n `stega.studioUrl must be a string or a function, received ${newConfig.stega.studioUrl}`,\n )\n }\n\n const isBrowser = typeof window !== 'undefined' && window.location && window.location.hostname\n const isLocalhost = isBrowser && isLocal(window.location.hostname)\n\n if (isBrowser && isLocalhost && newConfig.token && newConfig.ignoreBrowserTokenWarning !== true) {\n warnings.printBrowserTokenWarning()\n } else if (typeof newConfig.useCdn === 'undefined') {\n warnings.printCdnWarning()\n }\n\n if (projectBased) {\n validate.projectId(newConfig.projectId!)\n }\n\n if (newConfig.dataset) {\n validate.dataset(newConfig.dataset)\n }\n\n if ('requestTagPrefix' in newConfig) {\n // Allow setting and unsetting request tag prefix\n newConfig.requestTagPrefix = newConfig.requestTagPrefix\n ? validate.requestTag(newConfig.requestTagPrefix).replace(/\\.+$/, '')\n : undefined\n }\n\n newConfig.apiVersion = `${newConfig.apiVersion}`.replace(/^v/, '')\n newConfig.isDefaultApi = newConfig.apiHost === defaultConfig.apiHost\n\n if (newConfig.useCdn === true && newConfig.withCredentials) {\n warnings.printCdnAndWithCredentialsWarning()\n }\n\n // If `useCdn` is undefined, we treat it as `true`\n newConfig.useCdn = newConfig.useCdn !== false && !newConfig.withCredentials\n\n validateApiVersion(newConfig.apiVersion)\n\n const hostParts = newConfig.apiHost.split('://', 2)\n const protocol = hostParts[0]\n const host = hostParts[1]\n const cdnHost = newConfig.isDefaultApi ? defaultCdnHost : host\n\n if (newConfig.useProjectHostname) {\n newConfig.url = `${protocol}://${newConfig.projectId}.${host}/v${newConfig.apiVersion}`\n newConfig.cdnUrl = `${protocol}://${newConfig.projectId}.${cdnHost}/v${newConfig.apiVersion}`\n } else {\n newConfig.url = `${newConfig.apiHost}/v${newConfig.apiVersion}`\n newConfig.cdnUrl = newConfig.url\n }\n\n return newConfig\n}\n"],"names":["warnings.printNoApiVersionSpecifiedWarning","warnings.printBrowserTokenWarning","warnings.printCdnWarning","validate.projectId","validate.dataset","validate.requestTag","warnings.printCdnAndWithCredentialsWarning"],"mappings":";AAAA,MAAM,WAAW;AAEV,SAAS,gBAAgB,MAAc;AAC5C,SAAO,WAAW;AACpB;ACFA,MAAM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E1D,SAAI,UAAU,sBACZ,UAAU,MAAM,GAAG,QAAQ,MAAM,UAAU,SAAS,IAAI,IAAI,KAAK,UAAU,UAAU,IACrF,UAAU,SAAS,GAAG,QAAQ,MAAM,UAAU,SAAS,IAAI,OAAO,KAAK,UAAU,UAAU,OAE3F,UAAU,MAAM,GAAG,UAAU,OAAO,KAAK,UAAU,UAAU,IAC7D,UAAU,SAAS,UAAU,MAGxB;AACT;;;;;;;;;;;;;;"}
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
const BASE_URL = "https://www.sanity.io/help/";
|
|
2
|
+
function generateHelpUrl(slug) {
|
|
3
|
+
return BASE_URL + slug;
|
|
4
|
+
}
|
|
5
|
+
const VALID_ASSET_TYPES = ["image", "file"], VALID_INSERT_LOCATIONS = ["before", "after", "replace"], dataset = (name) => {
|
|
6
|
+
if (!/^(~[a-z0-9]{1}[-\w]{0,63}|[a-z0-9]{1}[-\w]{0,63})$/.test(name))
|
|
7
|
+
throw new Error(
|
|
8
|
+
"Datasets can only contain lowercase characters, numbers, underscores and dashes, and start with tilde, and be maximum 64 characters"
|
|
9
|
+
);
|
|
10
|
+
}, projectId = (id) => {
|
|
11
|
+
if (!/^[-a-z0-9]+$/i.test(id))
|
|
12
|
+
throw new Error("`projectId` can only contain only a-z, 0-9 and dashes");
|
|
13
|
+
}, validateAssetType = (type) => {
|
|
14
|
+
if (VALID_ASSET_TYPES.indexOf(type) === -1)
|
|
15
|
+
throw new Error(`Invalid asset type: ${type}. Must be one of ${VALID_ASSET_TYPES.join(", ")}`);
|
|
16
|
+
}, validateObject = (op, val) => {
|
|
17
|
+
if (val === null || typeof val != "object" || Array.isArray(val))
|
|
18
|
+
throw new Error(`${op}() takes an object of properties`);
|
|
19
|
+
}, validateDocumentId = (op, id) => {
|
|
20
|
+
if (typeof id != "string" || !/^[a-z0-9_][a-z0-9_.-]{0,127}$/i.test(id) || id.includes(".."))
|
|
21
|
+
throw new Error(`${op}(): "${id}" is not a valid document ID`);
|
|
22
|
+
}, requireDocumentId = (op, doc) => {
|
|
23
|
+
if (!doc._id)
|
|
24
|
+
throw new Error(`${op}() requires that the document contains an ID ("_id" property)`);
|
|
25
|
+
validateDocumentId(op, doc._id);
|
|
26
|
+
}, validateInsert = (at, selector, items) => {
|
|
27
|
+
const signature = "insert(at, selector, items)";
|
|
28
|
+
if (VALID_INSERT_LOCATIONS.indexOf(at) === -1) {
|
|
29
|
+
const valid = VALID_INSERT_LOCATIONS.map((loc) => `"${loc}"`).join(", ");
|
|
30
|
+
throw new Error(`${signature} takes an "at"-argument which is one of: ${valid}`);
|
|
31
|
+
}
|
|
32
|
+
if (typeof selector != "string")
|
|
33
|
+
throw new Error(`${signature} takes a "selector"-argument which must be a string`);
|
|
34
|
+
if (!Array.isArray(items))
|
|
35
|
+
throw new Error(`${signature} takes an "items"-argument which must be an array`);
|
|
36
|
+
}, hasDataset = (config) => {
|
|
37
|
+
if (!config.dataset)
|
|
38
|
+
throw new Error("`dataset` must be provided to perform queries");
|
|
39
|
+
return config.dataset || "";
|
|
40
|
+
}, requestTag = (tag) => {
|
|
41
|
+
if (typeof tag != "string" || !/^[a-z0-9._-]{1,75}$/i.test(tag))
|
|
42
|
+
throw new Error(
|
|
43
|
+
"Tag can only contain alphanumeric characters, underscores, dashes and dots, and be between one and 75 characters long."
|
|
44
|
+
);
|
|
45
|
+
return tag;
|
|
46
|
+
};
|
|
47
|
+
function once(fn) {
|
|
48
|
+
let didCall = !1, returnValue;
|
|
49
|
+
return (...args) => (didCall || (returnValue = fn(...args), didCall = !0), returnValue);
|
|
50
|
+
}
|
|
51
|
+
const createWarningPrinter = (message) => (
|
|
52
|
+
// eslint-disable-next-line no-console
|
|
53
|
+
once((...args) => console.warn(message.join(" "), ...args))
|
|
54
|
+
), printCdnAndWithCredentialsWarning = createWarningPrinter([
|
|
55
|
+
"Because you set `withCredentials` to true, we will override your `useCdn`",
|
|
56
|
+
"setting to be false since (cookie-based) credentials are never set on the CDN"
|
|
57
|
+
]), printCdnWarning = createWarningPrinter([
|
|
58
|
+
"Since you haven't set a value for `useCdn`, we will deliver content using our",
|
|
59
|
+
"global, edge-cached API-CDN. If you wish to have content delivered faster, set",
|
|
60
|
+
"`useCdn: false` to use the Live API. Note: You may incur higher costs using the live API."
|
|
61
|
+
]), printCdnPreviewDraftsWarning = createWarningPrinter([
|
|
62
|
+
"The Sanity client is configured with the `perspective` set to `previewDrafts`, which doesn't support the API-CDN.",
|
|
63
|
+
"The Live API will be used instead. Set `useCdn: false` in your configuration to hide this warning."
|
|
64
|
+
]), printBrowserTokenWarning = createWarningPrinter([
|
|
65
|
+
"You have configured Sanity client to use a token in the browser. This may cause unintentional security issues.",
|
|
66
|
+
`See ${generateHelpUrl(
|
|
67
|
+
"js-client-browser-token"
|
|
68
|
+
)} for more information and how to hide this warning.`
|
|
69
|
+
]), printNoApiVersionSpecifiedWarning = createWarningPrinter([
|
|
70
|
+
"Using the Sanity client without specifying an API version is deprecated.",
|
|
71
|
+
`See ${generateHelpUrl("js-client-api-version")}`
|
|
72
|
+
]), printNoDefaultExport = createWarningPrinter([
|
|
73
|
+
"The default export of @sanity/client has been deprecated. Use the named export `createClient` instead."
|
|
74
|
+
]), defaultCdnHost = "apicdn.sanity.io", defaultConfig = {
|
|
75
|
+
apiHost: "https://api.sanity.io",
|
|
76
|
+
apiVersion: "1",
|
|
77
|
+
useProjectHostname: !0,
|
|
78
|
+
stega: { enabled: !1 }
|
|
79
|
+
}, LOCALHOSTS = ["localhost", "127.0.0.1", "0.0.0.0"], isLocal = (host) => LOCALHOSTS.indexOf(host) !== -1;
|
|
80
|
+
function validateApiVersion(apiVersion) {
|
|
81
|
+
if (apiVersion === "1" || apiVersion === "X")
|
|
82
|
+
return;
|
|
83
|
+
const apiDate = new Date(apiVersion);
|
|
84
|
+
if (!(/^\d{4}-\d{2}-\d{2}$/.test(apiVersion) && apiDate instanceof Date && apiDate.getTime() > 0))
|
|
85
|
+
throw new Error("Invalid API version string, expected `1` or date in format `YYYY-MM-DD`");
|
|
86
|
+
}
|
|
87
|
+
function validateApiPerspective(perspective) {
|
|
88
|
+
if (Array.isArray(perspective)) {
|
|
89
|
+
for (const perspectiveValue of perspective)
|
|
90
|
+
if (perspectiveValue !== "published" && perspectiveValue !== "drafts" && !(typeof perspectiveValue == "string" && perspectiveValue.startsWith("r") && perspectiveValue !== "raw"))
|
|
91
|
+
throw new TypeError(
|
|
92
|
+
"Invalid API perspective value, expected `published`, `drafts` or a valid release identifier string"
|
|
93
|
+
);
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
switch (perspective) {
|
|
97
|
+
case "previewDrafts":
|
|
98
|
+
case "drafts":
|
|
99
|
+
case "published":
|
|
100
|
+
case "raw":
|
|
101
|
+
return;
|
|
102
|
+
default:
|
|
103
|
+
throw new TypeError(
|
|
104
|
+
"Invalid API perspective string, expected `published`, `previewDrafts` or `raw`"
|
|
105
|
+
);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
const initConfig = (config, prevConfig) => {
|
|
109
|
+
const specifiedConfig = {
|
|
110
|
+
...prevConfig,
|
|
111
|
+
...config,
|
|
112
|
+
stega: {
|
|
113
|
+
...typeof prevConfig.stega == "boolean" ? { enabled: prevConfig.stega } : prevConfig.stega || defaultConfig.stega,
|
|
114
|
+
...typeof config.stega == "boolean" ? { enabled: config.stega } : config.stega || {}
|
|
115
|
+
}
|
|
116
|
+
};
|
|
117
|
+
specifiedConfig.apiVersion || printNoApiVersionSpecifiedWarning();
|
|
118
|
+
const newConfig = {
|
|
119
|
+
...defaultConfig,
|
|
120
|
+
...specifiedConfig
|
|
121
|
+
}, projectBased = newConfig.useProjectHostname;
|
|
122
|
+
if (typeof Promise > "u") {
|
|
123
|
+
const helpUrl = generateHelpUrl("js-client-promise-polyfill");
|
|
124
|
+
throw new Error(`No native Promise-implementation found, polyfill needed - see ${helpUrl}`);
|
|
125
|
+
}
|
|
126
|
+
if (projectBased && !newConfig.projectId)
|
|
127
|
+
throw new Error("Configuration must contain `projectId`");
|
|
128
|
+
if (typeof newConfig.perspective < "u" && validateApiPerspective(newConfig.perspective), "encodeSourceMap" in newConfig)
|
|
129
|
+
throw new Error(
|
|
130
|
+
"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'?"
|
|
131
|
+
);
|
|
132
|
+
if ("encodeSourceMapAtPath" in newConfig)
|
|
133
|
+
throw new Error(
|
|
134
|
+
"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'?"
|
|
135
|
+
);
|
|
136
|
+
if (typeof newConfig.stega.enabled != "boolean")
|
|
137
|
+
throw new Error(`stega.enabled must be a boolean, received ${newConfig.stega.enabled}`);
|
|
138
|
+
if (newConfig.stega.enabled && newConfig.stega.studioUrl === void 0)
|
|
139
|
+
throw new Error("stega.studioUrl must be defined when stega.enabled is true");
|
|
140
|
+
if (newConfig.stega.enabled && typeof newConfig.stega.studioUrl != "string" && typeof newConfig.stega.studioUrl != "function")
|
|
141
|
+
throw new Error(
|
|
142
|
+
`stega.studioUrl must be a string or a function, received ${newConfig.stega.studioUrl}`
|
|
143
|
+
);
|
|
144
|
+
const isBrowser = typeof window < "u" && window.location && window.location.hostname, isLocalhost = isBrowser && isLocal(window.location.hostname);
|
|
145
|
+
isBrowser && isLocalhost && newConfig.token && newConfig.ignoreBrowserTokenWarning !== !0 ? printBrowserTokenWarning() : typeof newConfig.useCdn > "u" && printCdnWarning(), projectBased && projectId(newConfig.projectId), newConfig.dataset && dataset(newConfig.dataset), "requestTagPrefix" in newConfig && (newConfig.requestTagPrefix = newConfig.requestTagPrefix ? requestTag(newConfig.requestTagPrefix).replace(/\.+$/, "") : void 0), newConfig.apiVersion = `${newConfig.apiVersion}`.replace(/^v/, ""), newConfig.isDefaultApi = newConfig.apiHost === defaultConfig.apiHost, newConfig.useCdn === !0 && newConfig.withCredentials && printCdnAndWithCredentialsWarning(), newConfig.useCdn = newConfig.useCdn !== !1 && !newConfig.withCredentials, validateApiVersion(newConfig.apiVersion);
|
|
146
|
+
const hostParts = newConfig.apiHost.split("://", 2), protocol = hostParts[0], host = hostParts[1], cdnHost = newConfig.isDefaultApi ? defaultCdnHost : host;
|
|
147
|
+
return newConfig.useProjectHostname ? (newConfig.url = `${protocol}://${newConfig.projectId}.${host}/v${newConfig.apiVersion}`, newConfig.cdnUrl = `${protocol}://${newConfig.projectId}.${cdnHost}/v${newConfig.apiVersion}`) : (newConfig.url = `${newConfig.apiHost}/v${newConfig.apiVersion}`, newConfig.cdnUrl = newConfig.url), newConfig;
|
|
148
|
+
};
|
|
149
|
+
export {
|
|
150
|
+
dataset,
|
|
151
|
+
defaultConfig,
|
|
152
|
+
hasDataset,
|
|
153
|
+
initConfig,
|
|
154
|
+
printCdnPreviewDraftsWarning,
|
|
155
|
+
printNoDefaultExport,
|
|
156
|
+
requestTag,
|
|
157
|
+
requireDocumentId,
|
|
158
|
+
validateApiPerspective,
|
|
159
|
+
validateAssetType,
|
|
160
|
+
validateDocumentId,
|
|
161
|
+
validateInsert,
|
|
162
|
+
validateObject
|
|
163
|
+
};
|
|
164
|
+
//# sourceMappingURL=config.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"config.js","sources":["../../src/generateHelpUrl.ts","../../src/validators.ts","../../src/util/once.ts","../../src/warnings.ts","../../src/config.ts"],"sourcesContent":["const BASE_URL = 'https://www.sanity.io/help/'\n\nexport function generateHelpUrl(slug: string) {\n return BASE_URL + slug\n}\n","import type {Any, InitializedClientConfig} from './types'\n\nconst VALID_ASSET_TYPES = ['image', 'file']\nconst VALID_INSERT_LOCATIONS = ['before', 'after', 'replace']\n\nexport const dataset = (name: string) => {\n if (!/^(~[a-z0-9]{1}[-\\w]{0,63}|[a-z0-9]{1}[-\\w]{0,63})$/.test(name)) {\n throw new Error(\n 'Datasets can only contain lowercase characters, numbers, underscores and dashes, and start with tilde, and be maximum 64 characters',\n )\n }\n}\n\nexport const projectId = (id: string) => {\n if (!/^[-a-z0-9]+$/i.test(id)) {\n throw new Error('`projectId` can only contain only a-z, 0-9 and dashes')\n }\n}\n\nexport const validateAssetType = (type: string) => {\n if (VALID_ASSET_TYPES.indexOf(type) === -1) {\n throw new Error(`Invalid asset type: ${type}. Must be one of ${VALID_ASSET_TYPES.join(', ')}`)\n }\n}\n\nexport const validateObject = (op: string, val: Any) => {\n if (val === null || typeof val !== 'object' || Array.isArray(val)) {\n throw new Error(`${op}() takes an object of properties`)\n }\n}\n\nexport const validateDocumentId = (op: string, id: string) => {\n if (typeof id !== 'string' || !/^[a-z0-9_][a-z0-9_.-]{0,127}$/i.test(id) || id.includes('..')) {\n throw new Error(`${op}(): \"${id}\" is not a valid document ID`)\n }\n}\n\nexport const requireDocumentId = (op: string, doc: Record<string, Any>) => {\n if (!doc._id) {\n throw new Error(`${op}() requires that the document contains an ID (\"_id\" property)`)\n }\n\n validateDocumentId(op, doc._id)\n}\n\nexport const validateInsert = (at: string, selector: string, items: Any[]) => {\n const signature = 'insert(at, selector, items)'\n if (VALID_INSERT_LOCATIONS.indexOf(at) === -1) {\n const valid = VALID_INSERT_LOCATIONS.map((loc) => `\"${loc}\"`).join(', ')\n throw new Error(`${signature} takes an \"at\"-argument which is one of: ${valid}`)\n }\n\n if (typeof selector !== 'string') {\n throw new Error(`${signature} takes a \"selector\"-argument which must be a string`)\n }\n\n if (!Array.isArray(items)) {\n throw new Error(`${signature} takes an \"items\"-argument which must be an array`)\n }\n}\n\nexport const hasDataset = (config: InitializedClientConfig): string => {\n if (!config.dataset) {\n throw new Error('`dataset` must be provided to perform queries')\n }\n\n return config.dataset || ''\n}\n\nexport const requestTag = (tag: string) => {\n if (typeof tag !== 'string' || !/^[a-z0-9._-]{1,75}$/i.test(tag)) {\n throw new Error(\n `Tag can only contain alphanumeric characters, underscores, dashes and dots, and be between one and 75 characters long.`,\n )\n }\n\n return tag\n}\n","import type {Any} from '../types'\n\nexport function once(fn: Any) {\n let didCall = false\n let returnValue: Any\n return (...args: Any[]) => {\n if (didCall) {\n return returnValue\n }\n returnValue = fn(...args)\n didCall = true\n return returnValue\n }\n}\n","import {generateHelpUrl} from './generateHelpUrl'\nimport {type Any} from './types'\nimport {once} from './util/once'\n\nconst createWarningPrinter = (message: string[]) =>\n // eslint-disable-next-line no-console\n once((...args: Any[]) => console.warn(message.join(' '), ...args))\n\nexport const printCdnAndWithCredentialsWarning = createWarningPrinter([\n `Because you set \\`withCredentials\\` to true, we will override your \\`useCdn\\``,\n `setting to be false since (cookie-based) credentials are never set on the CDN`,\n])\n\nexport const printCdnWarning = createWarningPrinter([\n `Since you haven't set a value for \\`useCdn\\`, we will deliver content using our`,\n `global, edge-cached API-CDN. If you wish to have content delivered faster, set`,\n `\\`useCdn: false\\` to use the Live API. Note: You may incur higher costs using the live API.`,\n])\n\nexport const printCdnPreviewDraftsWarning = createWarningPrinter([\n `The Sanity client is configured with the \\`perspective\\` set to \\`previewDrafts\\`, which doesn't support the API-CDN.`,\n `The Live API will be used instead. Set \\`useCdn: false\\` in your configuration to hide this warning.`,\n])\n\nexport const printBrowserTokenWarning = createWarningPrinter([\n 'You have configured Sanity client to use a token in the browser. This may cause unintentional security issues.',\n `See ${generateHelpUrl(\n 'js-client-browser-token',\n )} for more information and how to hide this warning.`,\n])\n\nexport const printNoApiVersionSpecifiedWarning = createWarningPrinter([\n 'Using the Sanity client without specifying an API version is deprecated.',\n `See ${generateHelpUrl('js-client-api-version')}`,\n])\n\nexport const printNoDefaultExport = createWarningPrinter([\n 'The default export of @sanity/client has been deprecated. Use the named export `createClient` instead.',\n])\n","import {generateHelpUrl} from './generateHelpUrl'\nimport type {ClientConfig, ClientPerspective, InitializedClientConfig} from './types'\nimport * as validate from './validators'\nimport * as warnings from './warnings'\n\nconst defaultCdnHost = 'apicdn.sanity.io'\nexport const defaultConfig = {\n apiHost: 'https://api.sanity.io',\n apiVersion: '1',\n useProjectHostname: true,\n stega: {enabled: false},\n} satisfies ClientConfig\n\nconst LOCALHOSTS = ['localhost', '127.0.0.1', '0.0.0.0']\nconst isLocal = (host: string) => LOCALHOSTS.indexOf(host) !== -1\n\nfunction validateApiVersion(apiVersion: string) {\n if (apiVersion === '1' || apiVersion === 'X') {\n return\n }\n\n const apiDate = new Date(apiVersion)\n const apiVersionValid =\n /^\\d{4}-\\d{2}-\\d{2}$/.test(apiVersion) && apiDate instanceof Date && apiDate.getTime() > 0\n\n if (!apiVersionValid) {\n throw new Error('Invalid API version string, expected `1` or date in format `YYYY-MM-DD`')\n }\n}\n\n/**\n * @internal - it may have breaking changes in any release\n */\nexport function validateApiPerspective(\n perspective: unknown,\n): asserts perspective is ClientPerspective {\n if (Array.isArray(perspective)) {\n for (const perspectiveValue of perspective) {\n if (perspectiveValue === 'published') {\n continue\n }\n if (perspectiveValue === 'drafts') {\n continue\n }\n if (\n typeof perspectiveValue === 'string' &&\n perspectiveValue.startsWith('r') &&\n perspectiveValue !== 'raw'\n ) {\n continue\n }\n throw new TypeError(\n 'Invalid API perspective value, expected `published`, `drafts` or a valid release identifier string',\n )\n }\n return\n }\n switch (perspective as ClientPerspective) {\n case 'previewDrafts':\n case 'drafts':\n case 'published':\n case 'raw':\n return\n default:\n throw new TypeError(\n 'Invalid API perspective string, expected `published`, `previewDrafts` or `raw`',\n )\n }\n}\n\nexport const initConfig = (\n config: Partial<ClientConfig>,\n prevConfig: Partial<ClientConfig>,\n): InitializedClientConfig => {\n const specifiedConfig = {\n ...prevConfig,\n ...config,\n stega: {\n ...(typeof prevConfig.stega === 'boolean'\n ? {enabled: prevConfig.stega}\n : prevConfig.stega || defaultConfig.stega),\n ...(typeof config.stega === 'boolean' ? {enabled: config.stega} : config.stega || {}),\n },\n }\n if (!specifiedConfig.apiVersion) {\n warnings.printNoApiVersionSpecifiedWarning()\n }\n\n const newConfig = {\n ...defaultConfig,\n ...specifiedConfig,\n } as InitializedClientConfig\n const projectBased = newConfig.useProjectHostname\n\n if (typeof Promise === 'undefined') {\n const helpUrl = generateHelpUrl('js-client-promise-polyfill')\n throw new Error(`No native Promise-implementation found, polyfill needed - see ${helpUrl}`)\n }\n\n if (projectBased && !newConfig.projectId) {\n throw new Error('Configuration must contain `projectId`')\n }\n\n if (typeof newConfig.perspective !== 'undefined') {\n validateApiPerspective(newConfig.perspective)\n }\n\n if ('encodeSourceMap' in newConfig) {\n throw new Error(\n `It looks like you're using options meant for '@sanity/preview-kit/client'. 'encodeSourceMap' is not supported in '@sanity/client'. Did you mean 'stega.enabled'?`,\n )\n }\n if ('encodeSourceMapAtPath' in newConfig) {\n throw new Error(\n `It looks like you're using options meant for '@sanity/preview-kit/client'. 'encodeSourceMapAtPath' is not supported in '@sanity/client'. Did you mean 'stega.filter'?`,\n )\n }\n if (typeof newConfig.stega.enabled !== 'boolean') {\n throw new Error(`stega.enabled must be a boolean, received ${newConfig.stega.enabled}`)\n }\n if (newConfig.stega.enabled && newConfig.stega.studioUrl === undefined) {\n throw new Error(`stega.studioUrl must be defined when stega.enabled is true`)\n }\n if (\n newConfig.stega.enabled &&\n typeof newConfig.stega.studioUrl !== 'string' &&\n typeof newConfig.stega.studioUrl !== 'function'\n ) {\n throw new Error(\n `stega.studioUrl must be a string or a function, received ${newConfig.stega.studioUrl}`,\n )\n }\n\n const isBrowser = typeof window !== 'undefined' && window.location && window.location.hostname\n const isLocalhost = isBrowser && isLocal(window.location.hostname)\n\n if (isBrowser && isLocalhost && newConfig.token && newConfig.ignoreBrowserTokenWarning !== true) {\n warnings.printBrowserTokenWarning()\n } else if (typeof newConfig.useCdn === 'undefined') {\n warnings.printCdnWarning()\n }\n\n if (projectBased) {\n validate.projectId(newConfig.projectId!)\n }\n\n if (newConfig.dataset) {\n validate.dataset(newConfig.dataset)\n }\n\n if ('requestTagPrefix' in newConfig) {\n // Allow setting and unsetting request tag prefix\n newConfig.requestTagPrefix = newConfig.requestTagPrefix\n ? validate.requestTag(newConfig.requestTagPrefix).replace(/\\.+$/, '')\n : undefined\n }\n\n newConfig.apiVersion = `${newConfig.apiVersion}`.replace(/^v/, '')\n newConfig.isDefaultApi = newConfig.apiHost === defaultConfig.apiHost\n\n if (newConfig.useCdn === true && newConfig.withCredentials) {\n warnings.printCdnAndWithCredentialsWarning()\n }\n\n // If `useCdn` is undefined, we treat it as `true`\n newConfig.useCdn = newConfig.useCdn !== false && !newConfig.withCredentials\n\n validateApiVersion(newConfig.apiVersion)\n\n const hostParts = newConfig.apiHost.split('://', 2)\n const protocol = hostParts[0]\n const host = hostParts[1]\n const cdnHost = newConfig.isDefaultApi ? defaultCdnHost : host\n\n if (newConfig.useProjectHostname) {\n newConfig.url = `${protocol}://${newConfig.projectId}.${host}/v${newConfig.apiVersion}`\n newConfig.cdnUrl = `${protocol}://${newConfig.projectId}.${cdnHost}/v${newConfig.apiVersion}`\n } else {\n newConfig.url = `${newConfig.apiHost}/v${newConfig.apiVersion}`\n newConfig.cdnUrl = newConfig.url\n }\n\n return newConfig\n}\n"],"names":["warnings.printNoApiVersionSpecifiedWarning","warnings.printBrowserTokenWarning","warnings.printCdnWarning","validate.projectId","validate.dataset","validate.requestTag","warnings.printCdnAndWithCredentialsWarning"],"mappings":"AAAA,MAAM,WAAW;AAEV,SAAS,gBAAgB,MAAc;AAC5C,SAAO,WAAW;AACpB;ACFA,MAAM,oBAAoB,CAAC,SAAS,MAAM,GACpC,yBAAyB,CAAC,UAAU,SAAS,SAAS,GAE/C,UAAU,CAAC,SAAiB;AACnC,MAAA,CAAC,qDAAqD,KAAK,IAAI;AACjE,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAEJ,GAEa,YAAY,CAAC,OAAe;AACnC,MAAA,CAAC,gBAAgB,KAAK,EAAE;AACpB,UAAA,IAAI,MAAM,uDAAuD;AAE3E,GAEa,oBAAoB,CAAC,SAAiB;AAC7C,MAAA,kBAAkB,QAAQ,IAAI,MAAM;AAChC,UAAA,IAAI,MAAM,uBAAuB,IAAI,oBAAoB,kBAAkB,KAAK,IAAI,C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cjs/resolveEditInfo.cjs");
|
|
4
|
-
|
|
5
|
-
|
|
3
|
+
var resolveEditInfo = require("./_chunks-cjs/resolveEditInfo.cjs"), config = require("./_chunks-cjs/config.cjs");
|
|
4
|
+
function resolvePerspectives(perspective) {
|
|
5
|
+
if (config.validateApiPerspective(perspective), Array.isArray(perspective))
|
|
6
|
+
return perspective.includes("published") ? perspective : [...perspective, "published"];
|
|
7
|
+
switch (perspective) {
|
|
8
|
+
case "previewDrafts":
|
|
9
|
+
case "drafts":
|
|
10
|
+
return ["drafts", "published"];
|
|
11
|
+
case "published":
|
|
12
|
+
default:
|
|
13
|
+
return ["published"];
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
function createSourceDocumentResolver(getCachedDocument, _perspective) {
|
|
17
|
+
const perspectives = resolvePerspectives(_perspective);
|
|
18
|
+
function findDocument(sourceDocument) {
|
|
19
|
+
for (const perspective of perspectives) {
|
|
20
|
+
let match = null;
|
|
21
|
+
if (perspective.startsWith("r") && (match = getCachedDocument({
|
|
22
|
+
...sourceDocument,
|
|
23
|
+
_id: resolveEditInfo.getVersionId(sourceDocument._id, perspective)
|
|
24
|
+
})), perspective === "drafts" && (match = getCachedDocument({
|
|
25
|
+
...sourceDocument,
|
|
26
|
+
_id: resolveEditInfo.getDraftId(sourceDocument._id)
|
|
27
|
+
})), perspective === "published" && (match = getCachedDocument({
|
|
28
|
+
...sourceDocument,
|
|
29
|
+
_id: resolveEditInfo.getPublishedId(sourceDocument._id)
|
|
30
|
+
})), match)
|
|
31
|
+
return { ...match, _id: resolveEditInfo.getPublishedId(match._id), _originalId: match._id };
|
|
32
|
+
}
|
|
33
|
+
return null;
|
|
34
|
+
}
|
|
35
|
+
return function(sourceDocument) {
|
|
36
|
+
return findDocument(sourceDocument);
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
function applySourceDocuments(result, resultSourceMap, getCachedDocument, updateFn, perspective) {
|
|
6
40
|
if (!resultSourceMap) return result;
|
|
7
|
-
|
|
8
|
-
throw new Error(`Unknown perspective "${perspective}"`);
|
|
41
|
+
const resolveDocument = createSourceDocumentResolver(getCachedDocument, perspective), cachedDocuments = resultSourceMap.documents.map(resolveDocument);
|
|
9
42
|
return resolveEditInfo.walkMap(JSON.parse(JSON.stringify(result)), (value, path) => {
|
|
10
43
|
const resolveMappingResult = resolveEditInfo.resolveMapping(path, resultSourceMap);
|
|
11
44
|
if (!resolveMappingResult)
|
|
@@ -15,19 +48,8 @@ function applySourceDocuments(result, resultSourceMap, getCachedDocument, update
|
|
|
15
48
|
return value;
|
|
16
49
|
const sourceDocument = resultSourceMap.documents[mapping.source.document], sourcePath = resultSourceMap.paths[mapping.source.path];
|
|
17
50
|
if (sourceDocument) {
|
|
18
|
-
const parsedPath = resolveEditInfo.parseJsonPath(sourcePath + pathSuffix), stringifiedPath = resolveEditInfo.toString(parsedPath);
|
|
19
|
-
if (
|
|
20
|
-
return value;
|
|
21
|
-
let cachedDocument;
|
|
22
|
-
if (perspective === "previewDrafts" ? (cachedDocument = getCachedDocument(
|
|
23
|
-
resolveEditInfo.isDraftId(sourceDocument._id) ? sourceDocument : { ...sourceDocument, _id: resolveEditInfo.getDraftId(sourceDocument._id) }
|
|
24
|
-
), cachedDocument || (cachedDocument = getCachedDocument(
|
|
25
|
-
resolveEditInfo.isDraftId(sourceDocument._id) ? { ...sourceDocument, _id: resolveEditInfo.getPublishedId(sourceDocument._id) } : sourceDocument
|
|
26
|
-
)), cachedDocument && (cachedDocument = {
|
|
27
|
-
...cachedDocument,
|
|
28
|
-
_id: resolveEditInfo.getPublishedId(sourceDocument._id),
|
|
29
|
-
_originalId: sourceDocument._id
|
|
30
|
-
})) : cachedDocument = getCachedDocument(sourceDocument), !cachedDocument)
|
|
51
|
+
const parsedPath = resolveEditInfo.parseJsonPath(sourcePath + pathSuffix), stringifiedPath = resolveEditInfo.toString(parsedPath), cachedDocument = cachedDocuments[mapping.source.document];
|
|
52
|
+
if (!cachedDocument)
|
|
31
53
|
return value;
|
|
32
54
|
const changedValue = cachedDocument ? resolveEditInfo.get(cachedDocument, stringifiedPath, value) : value;
|
|
33
55
|
return value === changedValue ? value : updateFn(changedValue, {
|
package/dist/csm.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"csm.cjs","sources":["../src/csm/applySourceDocuments.ts","../src/csm/resolvedKeyedSourcePath.ts","../src/csm/resolveEditUrl.ts"],"sourcesContent":["import {getDraftId, getPublishedId,
|
|
1
|
+
{"version":3,"file":"csm.cjs","sources":["../src/csm/resolvePerspectives.ts","../src/csm/createSourceDocumentResolver.ts","../src/csm/applySourceDocuments.ts","../src/csm/resolvedKeyedSourcePath.ts","../src/csm/resolveEditUrl.ts"],"sourcesContent":["import {validateApiPerspective} from '../config'\nimport type {ReleaseId} from '../types'\nimport type {ClientPerspective} from './types'\n\n/**\n * This resolves the perspectives to how documents should be resolved when applying optimistic updates,\n * like in `applySourceDocuments`.\n * @internal\n */\nexport function resolvePerspectives(\n perspective: Exclude<ClientPerspective, 'raw'>,\n): ('published' | 'drafts' | ReleaseId)[] {\n validateApiPerspective(perspective)\n\n if (Array.isArray(perspective)) {\n if (!perspective.includes('published')) {\n return [...perspective, 'published']\n }\n return perspective\n }\n switch (perspective) {\n case 'previewDrafts':\n case 'drafts':\n return ['drafts', 'published']\n case 'published':\n default:\n return ['published']\n }\n}\n","import {getDraftId, getPublishedId, getVersionId} from './draftUtils'\nimport {resolvePerspectives} from './resolvePerspectives'\nimport type {ClientPerspective, ContentSourceMapDocuments, SanityDocument} from './types'\n\n/** @internal */\nexport type ResolvedDocument = Partial<SanityDocument> &\n Required<Pick<SanityDocument, '_id' | '_type'>>\n\n/** @internal */\nexport type MatchedDocument = Partial<SanityDocument> &\n Required<Pick<SanityDocument, '_id' | '_type' | '_originalId'>>\n\n/** @internal */\nexport function createSourceDocumentResolver(\n getCachedDocument: (\n sourceDocument: ContentSourceMapDocuments[number],\n ) => ResolvedDocument | null | undefined,\n _perspective: Exclude<ClientPerspective, 'raw'>,\n) {\n const perspectives = resolvePerspectives(_perspective)\n function findDocument(sourceDocument: ContentSourceMapDocuments[number]) {\n for (const perspective of perspectives) {\n let match: ReturnType<typeof getCachedDocument> = null\n if (perspective.startsWith('r')) {\n match = getCachedDocument({\n ...sourceDocument,\n _id: getVersionId(sourceDocument._id, perspective),\n })\n }\n if (perspective === 'drafts') {\n match = getCachedDocument({\n ...sourceDocument,\n _id: getDraftId(sourceDocument._id),\n })\n }\n if (perspective === 'published') {\n match = getCachedDocument({\n ...sourceDocument,\n _id: getPublishedId(sourceDocument._id),\n })\n }\n if (match) {\n return {...match, _id: getPublishedId(match._id), _originalId: match._id}\n }\n }\n return null\n }\n // define resolver that loops over source documents and perspectives\n return function resolveSourceDocument(\n sourceDocument: ContentSourceMapDocuments[number],\n ): MatchedDocument | null {\n return findDocument(sourceDocument)\n }\n}\n","import {createSourceDocumentResolver} from './createSourceDocumentResolver'\nimport {parseJsonPath} from './jsonPath'\nimport {resolveMapping} from './resolveMapping'\nimport * as paths from './studioPath'\nimport type {\n Any,\n ApplySourceDocumentsUpdateFunction,\n ClientPerspective,\n ContentSourceMap,\n ContentSourceMapDocuments,\n Path,\n SanityDocument,\n} from './types'\nimport {walkMap} from './walkMap'\n\n/**\n * Optimistically applies source documents to a result, using the content source map to trace fields.\n * Can be used to apply mutations to documents being edited in a Studio, or any mutation on Content Lake, to a result with extremely low latency.\n * @alpha\n */\nexport function applySourceDocuments<Result = unknown>(\n result: Result,\n resultSourceMap: ContentSourceMap | undefined,\n getCachedDocument: (\n sourceDocument: ContentSourceMapDocuments[number],\n ) =>\n | (Partial<SanityDocument> & Required<Pick<SanityDocument, '_id' | '_type'>>)\n | null\n | undefined,\n updateFn: ApplySourceDocumentsUpdateFunction,\n perspective: Exclude<ClientPerspective, 'raw'>,\n): Result {\n if (!resultSourceMap) return result\n\n const resolveDocument = createSourceDocumentResolver(getCachedDocument, perspective)\n const cachedDocuments = resultSourceMap.documents.map(resolveDocument)\n\n return walkMap(JSON.parse(JSON.stringify(result)), (value, path) => {\n const resolveMappingResult = resolveMapping(path, resultSourceMap)\n if (!resolveMappingResult) {\n return value\n }\n\n const {mapping, pathSuffix} = 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 = resultSourceMap.documents[mapping.source.document]\n const sourcePath = resultSourceMap.paths[mapping.source.path]\n\n if (sourceDocument) {\n const parsedPath = parseJsonPath(sourcePath + pathSuffix)\n const stringifiedPath = paths.toString(parsedPath as Path)\n const cachedDocument = cachedDocuments[mapping.source.document]\n\n if (!cachedDocument) {\n return value\n }\n\n const changedValue = cachedDocument\n ? paths.get<Result[keyof Result]>(cachedDocument, stringifiedPath, value)\n : value\n return value === changedValue\n ? value\n : updateFn<Result[keyof Result]>(changedValue as Any, {\n cachedDocument,\n previousValue: value as Result[keyof Result],\n sourceDocument,\n sourcePath: parsedPath,\n })\n }\n\n return value\n }) as Result\n}\n","import {jsonPath, parseJsonPath} from './jsonPath'\nimport type {ContentSourceMapParsedPath} from './types'\n\n/**\n * @internal\n */\nexport function resolvedKeyedSourcePath(options: {\n keyedResultPath: ContentSourceMapParsedPath\n pathSuffix?: string\n sourceBasePath: string\n}): ContentSourceMapParsedPath {\n const {keyedResultPath, pathSuffix, sourceBasePath} = options\n\n const inferredResultPath = pathSuffix === undefined ? [] : parseJsonPath(pathSuffix)\n\n const inferredPath = keyedResultPath.slice(keyedResultPath.length - inferredResultPath.length)\n\n const inferredPathSuffix = inferredPath.length ? jsonPath(inferredPath).slice(1) : ''\n\n return parseJsonPath(sourceBasePath + inferredPathSuffix)\n}\n","import {createEditUrl} from './createEditUrl'\nimport {studioPathToJsonPath} from './jsonPath'\nimport {resolveEditInfo} from './resolveEditInfo'\nimport type {ResolveEditUrlOptions} from './types'\n\n/** @alpha */\nexport function resolveEditUrl(\n options: ResolveEditUrlOptions,\n): ReturnType<typeof createEditUrl> | undefined {\n const {resultSourceMap, studioUrl} = options\n const resultPath = studioPathToJsonPath(options.resultPath)\n\n const editInfo = resolveEditInfo({\n resultPath,\n resultSourceMap,\n studioUrl,\n })\n if (!editInfo) {\n return undefined\n }\n\n return createEditUrl(editInfo)\n}\n"],"names":["validateApiPerspective","getVersionId","getDraftId","getPublishedId","walkMap","resolveMapping","parseJsonPath","paths.toString","paths.get","jsonPath","studioPathToJsonPath","resolveEditInfo","createEditUrl"],"mappings":";;;AASO,SAAS,oBACd,aACwC;AAGxC,MAFAA,OAAuB,uBAAA,WAAW,GAE9B,MAAM,QAAQ,WAAW;AACtB,WAAA,YAAY,SAAS,WAAW,IAG9B,cAFE,CAAC,GAAG,aAAa,WAAW;AAIvC,UAAQ,aAAa;AAAA,IACnB,KAAK;AAAA,IACL,KAAK;AACI,aAAA,CAAC,UAAU,WAAW;AAAA,IAC/B,KAAK;AAAA,IACL;AACE,aAAO,CAAC,WAAW;AAAA,EAAA;AAEzB;ACfgB,SAAA,6BACd,mBAGA,cACA;AACM,QAAA,eAAe,oBAAoB,YAAY;AACrD,WAAS,aAAa,gBAAmD;AACvE,eAAW,eAAe,cAAc;AACtC,UAAI,QAA8C;AAmBlD,UAlBI,YAAY,WAAW,GAAG,MAC5B,QAAQ,kBAAkB;AAAA,QACxB,GAAG;AAAA,QACH,KAAKC,gBAAA,aAAa,eAAe,KAAK,WAAW;AAAA,MAClD,CAAA,IAEC,gBAAgB,aAClB,QAAQ,kBAAkB;AAAA,QACxB,GAAG;AAAA,QACH,KAAKC,gBAAAA,WAAW,eAAe,GAAG;AAAA,MACnC,CAAA,IAEC,gBAAgB,gBAClB,QAAQ,kBAAkB;AAAA,QACxB,GAAG;AAAA,QACH,KAAKC,gBAAAA,eAAe,eAAe,GAAG;AAAA,MACvC,CAAA,IAEC;AACK,eAAA,EAAC,GAAG,OAAO,KAAKA,gBAAA,eAAe,MAAM,GAAG,GAAG,aAAa,MAAM,IAAG;AAAA,IAAA;AAGrE,WAAA;AAAA,EAAA;AAGT,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AY,EAAE,MAAM,CAAC,IAAI;AAE5E,SAAAH,gBAAA,cAAc,iBAAiB,kBAAkB;AAC1D;ACdO,SAAS,eACd,SAC8C;AACxC,QAAA,EAAC,iBAAiB,UAAa,IAAA,SAC/B,aAAaI,gBAAA,qBAAqB,QAAQ,UAAU,GAEpD,WAAWC,gBAAAA,gBAAgB;AAAA,IAC/B;AAAA,IACA;AAAA,IACA;AAAA,EAAA,CACD;AACI,MAAA;AAIL,WAAOC,gBAAAA,cAAc,QAAQ;AAC/B;;;;;;;;;;;;;;;;;;;;;;"}
|
package/dist/csm.d.cts
CHANGED
|
@@ -14,9 +14,12 @@ export declare function applySourceDocuments<Result = unknown>(
|
|
|
14
14
|
resultSourceMap: ContentSourceMap | undefined,
|
|
15
15
|
getCachedDocument: (
|
|
16
16
|
sourceDocument: ContentSourceMapDocuments[number],
|
|
17
|
-
) =>
|
|
18
|
-
|
|
19
|
-
|
|
17
|
+
) =>
|
|
18
|
+
| (Partial<SanityDocument> & Required<Pick<SanityDocument, '_id' | '_type'>>)
|
|
19
|
+
| null
|
|
20
|
+
| undefined,
|
|
21
|
+
updateFn: ApplySourceDocumentsUpdateFunction,
|
|
22
|
+
perspective: Exclude<ClientPerspective, 'raw'>,
|
|
20
23
|
): Result
|
|
21
24
|
|
|
22
25
|
/**
|
package/dist/csm.d.ts
CHANGED
|
@@ -14,9 +14,12 @@ export declare function applySourceDocuments<Result = unknown>(
|
|
|
14
14
|
resultSourceMap: ContentSourceMap | undefined,
|
|
15
15
|
getCachedDocument: (
|
|
16
16
|
sourceDocument: ContentSourceMapDocuments[number],
|
|
17
|
-
) =>
|
|
18
|
-
|
|
19
|
-
|
|
17
|
+
) =>
|
|
18
|
+
| (Partial<SanityDocument> & Required<Pick<SanityDocument, '_id' | '_type'>>)
|
|
19
|
+
| null
|
|
20
|
+
| undefined,
|
|
21
|
+
updateFn: ApplySourceDocumentsUpdateFunction,
|
|
22
|
+
perspective: Exclude<ClientPerspective, 'raw'>,
|
|
20
23
|
): Result
|
|
21
24
|
|
|
22
25
|
/**
|