@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/index.js CHANGED
@@ -4,6 +4,7 @@ import { retry, jsonRequest, jsonResponse, progress, observable, debug, headers,
4
4
  import { Observable, defer, isObservable, of, mergeMap, from, lastValueFrom, shareReplay, catchError, concat, timer, throwError, EMPTY } from "rxjs";
5
5
  import { stegaClean } from "./_chunks-es/stegaClean.js";
6
6
  import { combineLatestWith, map, filter } from "rxjs/operators";
7
+ import { validateObject, validateInsert, requireDocumentId, validateDocumentId, requestTag, validateApiPerspective, printCdnPreviewDraftsWarning, hasDataset, validateAssetType, dataset, defaultConfig, initConfig, printNoDefaultExport } from "./_chunks-es/config.js";
7
8
  class ClientError extends Error {
8
9
  response;
9
10
  statusCode = 400;
@@ -63,9 +64,9 @@ function stringifyBody(body, res) {
63
64
  class CorsOriginError extends Error {
64
65
  projectId;
65
66
  addOriginUrl;
66
- constructor({ projectId: projectId2 }) {
67
- super("CorsOriginError"), this.name = "CorsOriginError", this.projectId = projectId2;
68
- const url = new URL(`https://sanity.io/manage/project/${projectId2}/api`);
67
+ constructor({ projectId }) {
68
+ super("CorsOriginError"), this.name = "CorsOriginError", this.projectId = projectId;
69
+ const url = new URL(`https://sanity.io/manage/project/${projectId}/api`);
69
70
  if (typeof location < "u") {
70
71
  const { origin } = location;
71
72
  url.searchParams.set("cors", "add"), url.searchParams.set("origin", origin), this.addOriginUrl = url, this.message = `The current origin is not allowed to connect to the Live Content API. Add it here: ${url}`;
@@ -110,154 +111,6 @@ function shouldRetry(err, attempt, options) {
110
111
  const isSafe = options.method === "GET" || options.method === "HEAD", isQuery = (options.uri || options.url).startsWith("/data/query"), isRetriableResponse = err.response && (err.response.statusCode === 429 || err.response.statusCode === 502 || err.response.statusCode === 503);
111
112
  return (isSafe || isQuery) && isRetriableResponse ? !0 : retry.shouldRetry(err, attempt, options);
112
113
  }
113
- const BASE_URL = "https://www.sanity.io/help/";
114
- function generateHelpUrl(slug) {
115
- return BASE_URL + slug;
116
- }
117
- const VALID_ASSET_TYPES = ["image", "file"], VALID_INSERT_LOCATIONS = ["before", "after", "replace"], dataset = (name2) => {
118
- if (!/^(~[a-z0-9]{1}[-\w]{0,63}|[a-z0-9]{1}[-\w]{0,63})$/.test(name2))
119
- throw new Error(
120
- "Datasets can only contain lowercase characters, numbers, underscores and dashes, and start with tilde, and be maximum 64 characters"
121
- );
122
- }, projectId = (id) => {
123
- if (!/^[-a-z0-9]+$/i.test(id))
124
- throw new Error("`projectId` can only contain only a-z, 0-9 and dashes");
125
- }, validateAssetType = (type) => {
126
- if (VALID_ASSET_TYPES.indexOf(type) === -1)
127
- throw new Error(`Invalid asset type: ${type}. Must be one of ${VALID_ASSET_TYPES.join(", ")}`);
128
- }, validateObject = (op, val) => {
129
- if (val === null || typeof val != "object" || Array.isArray(val))
130
- throw new Error(`${op}() takes an object of properties`);
131
- }, validateDocumentId = (op, id) => {
132
- if (typeof id != "string" || !/^[a-z0-9_][a-z0-9_.-]{0,127}$/i.test(id) || id.includes(".."))
133
- throw new Error(`${op}(): "${id}" is not a valid document ID`);
134
- }, requireDocumentId = (op, doc) => {
135
- if (!doc._id)
136
- throw new Error(`${op}() requires that the document contains an ID ("_id" property)`);
137
- validateDocumentId(op, doc._id);
138
- }, validateInsert = (at, selector, items) => {
139
- const signature = "insert(at, selector, items)";
140
- if (VALID_INSERT_LOCATIONS.indexOf(at) === -1) {
141
- const valid = VALID_INSERT_LOCATIONS.map((loc) => `"${loc}"`).join(", ");
142
- throw new Error(`${signature} takes an "at"-argument which is one of: ${valid}`);
143
- }
144
- if (typeof selector != "string")
145
- throw new Error(`${signature} takes a "selector"-argument which must be a string`);
146
- if (!Array.isArray(items))
147
- throw new Error(`${signature} takes an "items"-argument which must be an array`);
148
- }, hasDataset = (config) => {
149
- if (!config.dataset)
150
- throw new Error("`dataset` must be provided to perform queries");
151
- return config.dataset || "";
152
- }, requestTag = (tag) => {
153
- if (typeof tag != "string" || !/^[a-z0-9._-]{1,75}$/i.test(tag))
154
- throw new Error(
155
- "Tag can only contain alphanumeric characters, underscores, dashes and dots, and be between one and 75 characters long."
156
- );
157
- return tag;
158
- };
159
- function once(fn) {
160
- let didCall = !1, returnValue;
161
- return (...args) => (didCall || (returnValue = fn(...args), didCall = !0), returnValue);
162
- }
163
- const createWarningPrinter = (message) => (
164
- // eslint-disable-next-line no-console
165
- once((...args) => console.warn(message.join(" "), ...args))
166
- ), printCdnAndWithCredentialsWarning = createWarningPrinter([
167
- "Because you set `withCredentials` to true, we will override your `useCdn`",
168
- "setting to be false since (cookie-based) credentials are never set on the CDN"
169
- ]), printCdnWarning = createWarningPrinter([
170
- "Since you haven't set a value for `useCdn`, we will deliver content using our",
171
- "global, edge-cached API-CDN. If you wish to have content delivered faster, set",
172
- "`useCdn: false` to use the Live API. Note: You may incur higher costs using the live API."
173
- ]), printCdnPreviewDraftsWarning = createWarningPrinter([
174
- "The Sanity client is configured with the `perspective` set to `previewDrafts`, which doesn't support the API-CDN.",
175
- "The Live API will be used instead. Set `useCdn: false` in your configuration to hide this warning."
176
- ]), printBrowserTokenWarning = createWarningPrinter([
177
- "You have configured Sanity client to use a token in the browser. This may cause unintentional security issues.",
178
- `See ${generateHelpUrl(
179
- "js-client-browser-token"
180
- )} for more information and how to hide this warning.`
181
- ]), printNoApiVersionSpecifiedWarning = createWarningPrinter([
182
- "Using the Sanity client without specifying an API version is deprecated.",
183
- `See ${generateHelpUrl("js-client-api-version")}`
184
- ]), printNoDefaultExport = createWarningPrinter([
185
- "The default export of @sanity/client has been deprecated. Use the named export `createClient` instead."
186
- ]), defaultCdnHost = "apicdn.sanity.io", defaultConfig = {
187
- apiHost: "https://api.sanity.io",
188
- apiVersion: "1",
189
- useProjectHostname: !0,
190
- stega: { enabled: !1 }
191
- }, LOCALHOSTS = ["localhost", "127.0.0.1", "0.0.0.0"], isLocal = (host) => LOCALHOSTS.indexOf(host) !== -1;
192
- function validateApiVersion(apiVersion) {
193
- if (apiVersion === "1" || apiVersion === "X")
194
- return;
195
- const apiDate = new Date(apiVersion);
196
- if (!(/^\d{4}-\d{2}-\d{2}$/.test(apiVersion) && apiDate instanceof Date && apiDate.getTime() > 0))
197
- throw new Error("Invalid API version string, expected `1` or date in format `YYYY-MM-DD`");
198
- }
199
- function validateApiPerspective(perspective) {
200
- if (Array.isArray(perspective)) {
201
- for (const perspectiveValue of perspective)
202
- if (perspectiveValue !== "published" && perspectiveValue !== "drafts" && !(typeof perspectiveValue == "string" && perspectiveValue.startsWith("r") && perspectiveValue !== "raw"))
203
- throw new TypeError(
204
- "Invalid API perspective value, expected `published`, `drafts` or a valid release identifier string"
205
- );
206
- return;
207
- }
208
- switch (perspective) {
209
- case "previewDrafts":
210
- case "drafts":
211
- case "published":
212
- case "raw":
213
- return;
214
- default:
215
- throw new TypeError(
216
- "Invalid API perspective string, expected `published`, `previewDrafts` or `raw`"
217
- );
218
- }
219
- }
220
- const initConfig = (config, prevConfig) => {
221
- const specifiedConfig = {
222
- ...prevConfig,
223
- ...config,
224
- stega: {
225
- ...typeof prevConfig.stega == "boolean" ? { enabled: prevConfig.stega } : prevConfig.stega || defaultConfig.stega,
226
- ...typeof config.stega == "boolean" ? { enabled: config.stega } : config.stega || {}
227
- }
228
- };
229
- specifiedConfig.apiVersion || printNoApiVersionSpecifiedWarning();
230
- const newConfig = {
231
- ...defaultConfig,
232
- ...specifiedConfig
233
- }, projectBased = newConfig.useProjectHostname;
234
- if (typeof Promise > "u") {
235
- const helpUrl = generateHelpUrl("js-client-promise-polyfill");
236
- throw new Error(`No native Promise-implementation found, polyfill needed - see ${helpUrl}`);
237
- }
238
- if (projectBased && !newConfig.projectId)
239
- throw new Error("Configuration must contain `projectId`");
240
- if (typeof newConfig.perspective < "u" && validateApiPerspective(newConfig.perspective), "encodeSourceMap" in newConfig)
241
- throw new Error(
242
- "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'?"
243
- );
244
- if ("encodeSourceMapAtPath" in newConfig)
245
- throw new Error(
246
- "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'?"
247
- );
248
- if (typeof newConfig.stega.enabled != "boolean")
249
- throw new Error(`stega.enabled must be a boolean, received ${newConfig.stega.enabled}`);
250
- if (newConfig.stega.enabled && newConfig.stega.studioUrl === void 0)
251
- throw new Error("stega.studioUrl must be defined when stega.enabled is true");
252
- if (newConfig.stega.enabled && typeof newConfig.stega.studioUrl != "string" && typeof newConfig.stega.studioUrl != "function")
253
- throw new Error(
254
- `stega.studioUrl must be a string or a function, received ${newConfig.stega.studioUrl}`
255
- );
256
- const isBrowser = typeof window < "u" && window.location && window.location.hostname, isLocalhost = isBrowser && isLocal(window.location.hostname);
257
- 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);
258
- const hostParts = newConfig.apiHost.split("://", 2), protocol = hostParts[0], host = hostParts[1], cdnHost = newConfig.isDefaultApi ? defaultCdnHost : host;
259
- 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;
260
- };
261
114
  class ConnectionFailedError extends Error {
262
115
  name = "ConnectionFailedError";
263
116
  }
@@ -1040,7 +893,7 @@ class LiveClient {
1040
893
  tag: _tag
1041
894
  } = {}) {
1042
895
  const {
1043
- projectId: projectId2,
896
+ projectId,
1044
897
  apiVersion: _apiVersion,
1045
898
  token,
1046
899
  withCredentials,
@@ -1089,7 +942,7 @@ class LiveClient {
1089
942
  }).pipe(
1090
943
  mergeMap(() => EMPTY),
1091
944
  catchError(() => {
1092
- throw new CorsOriginError({ projectId: projectId2 });
945
+ throw new CorsOriginError({ projectId });
1093
946
  })
1094
947
  );
1095
948
  return concat(checkCors, events);
@@ -1218,8 +1071,8 @@ class ObservableProjectsClient {
1218
1071
  *
1219
1072
  * @param projectId - ID of the project to fetch
1220
1073
  */
1221
- getById(projectId2) {
1222
- return _request(this.#client, this.#httpRequest, { uri: `/projects/${projectId2}` });
1074
+ getById(projectId) {
1075
+ return _request(this.#client, this.#httpRequest, { uri: `/projects/${projectId}` });
1223
1076
  }
1224
1077
  }
1225
1078
  class ProjectsClient {
@@ -1237,9 +1090,9 @@ class ProjectsClient {
1237
1090
  *
1238
1091
  * @param projectId - ID of the project to fetch
1239
1092
  */
1240
- getById(projectId2) {
1093
+ getById(projectId) {
1241
1094
  return lastValueFrom(
1242
- _request(this.#client, this.#httpRequest, { uri: `/projects/${projectId2}` })
1095
+ _request(this.#client, this.#httpRequest, { uri: `/projects/${projectId}` })
1243
1096
  );
1244
1097
  }
1245
1098
  }
@@ -1626,7 +1479,7 @@ function defineDeprecatedCreateClient(createClient2) {
1626
1479
  return printNoDefaultExport(), createClient2(config);
1627
1480
  };
1628
1481
  }
1629
- var name = "@sanity/client", version = "6.26.1";
1482
+ var name = "@sanity/client", version = "6.27.0";
1630
1483
  const middleware = [
1631
1484
  debug({ verbose: !0, namespace: "sanity:client" }),
1632
1485
  headers({ "User-Agent": `${name} ${version}` }),