@sanity/client 6.23.0 → 6.24.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.d.cts CHANGED
@@ -390,7 +390,12 @@ export declare class ClientError extends Error {
390
390
  }
391
391
 
392
392
  /** @public */
393
- export declare type ClientPerspective = 'previewDrafts' | 'published' | 'raw'
393
+ export declare type ClientPerspective =
394
+ | 'previewDrafts'
395
+ | 'published'
396
+ | 'drafts'
397
+ | 'raw'
398
+ | ('published' | 'drafts' | ReleaseId)[]
394
399
 
395
400
  /** @public */
396
401
  export declare type ClientReturn<
@@ -2116,6 +2121,9 @@ export declare type ReconnectEvent = {
2116
2121
  type: 'reconnect'
2117
2122
  }
2118
2123
 
2124
+ /** @public */
2125
+ export declare type ReleaseId = `r${string}`
2126
+
2119
2127
  /**
2120
2128
  * Replaces an existing draft document.
2121
2129
  * At least one of the draft or published versions of the document must exist.
@@ -3132,6 +3140,11 @@ export declare class UsersClient {
3132
3140
  getById<T extends 'me' | string>(id: T): Promise<T extends 'me' ? CurrentSanityUser : SanityUser>
3133
3141
  }
3134
3142
 
3143
+ /**
3144
+ * @internal - it may have breaking changes in any release
3145
+ */
3146
+ export declare const validateApiPerspective: (perspective: unknown) => void
3147
+
3135
3148
  /**
3136
3149
  * The listener has been established, and will start receiving events.
3137
3150
  * Note that this is also emitted upon _reconnection_.
package/dist/index.d.ts CHANGED
@@ -390,7 +390,12 @@ export declare class ClientError extends Error {
390
390
  }
391
391
 
392
392
  /** @public */
393
- export declare type ClientPerspective = 'previewDrafts' | 'published' | 'raw'
393
+ export declare type ClientPerspective =
394
+ | 'previewDrafts'
395
+ | 'published'
396
+ | 'drafts'
397
+ | 'raw'
398
+ | ('published' | 'drafts' | ReleaseId)[]
394
399
 
395
400
  /** @public */
396
401
  export declare type ClientReturn<
@@ -2116,6 +2121,9 @@ export declare type ReconnectEvent = {
2116
2121
  type: 'reconnect'
2117
2122
  }
2118
2123
 
2124
+ /** @public */
2125
+ export declare type ReleaseId = `r${string}`
2126
+
2119
2127
  /**
2120
2128
  * Replaces an existing draft document.
2121
2129
  * At least one of the draft or published versions of the document must exist.
@@ -3132,6 +3140,11 @@ export declare class UsersClient {
3132
3140
  getById<T extends 'me' | string>(id: T): Promise<T extends 'me' ? CurrentSanityUser : SanityUser>
3133
3141
  }
3134
3142
 
3143
+ /**
3144
+ * @internal - it may have breaking changes in any release
3145
+ */
3146
+ export declare const validateApiPerspective: (perspective: unknown) => void
3147
+
3135
3148
  /**
3136
3149
  * The listener has been established, and will start receiving events.
3137
3150
  * Note that this is also emitted upon _reconnection_.
package/dist/index.js CHANGED
@@ -105,22 +105,9 @@ function shouldRetry(err, attempt, options) {
105
105
  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);
106
106
  return (isSafe || isQuery) && isRetriableResponse ? !0 : retry.shouldRetry(err, attempt, options);
107
107
  }
108
- function getSelection(sel) {
109
- if (typeof sel == "string")
110
- return { id: sel };
111
- if (Array.isArray(sel))
112
- return { query: "*[_id in $ids]", params: { ids: sel } };
113
- if (typeof sel == "object" && sel !== null && "query" in sel && typeof sel.query == "string")
114
- return "params" in sel && typeof sel.params == "object" && sel.params !== null ? { query: sel.query, params: sel.params } : { query: sel.query };
115
- const selectionOpts = [
116
- "* Document ID (<docId>)",
117
- "* Array of document IDs",
118
- "* Object containing `query`"
119
- ].join(`
120
- `);
121
- throw new Error(`Unknown selection - must be one of:
122
-
123
- ${selectionOpts}`);
108
+ const BASE_URL = "https://www.sanity.io/help/";
109
+ function generateHelpUrl(slug) {
110
+ return BASE_URL + slug;
124
111
  }
125
112
  const VALID_ASSET_TYPES = ["image", "file"], VALID_INSERT_LOCATIONS = ["before", "after", "replace"], dataset = (name2) => {
126
113
  if (!/^(~[a-z0-9]{1}[-\w]{0,63}|[a-z0-9]{1}[-\w]{0,63})$/.test(name2))
@@ -164,6 +151,124 @@ const VALID_ASSET_TYPES = ["image", "file"], VALID_INSERT_LOCATIONS = ["before",
164
151
  );
165
152
  return tag;
166
153
  };
154
+ function once(fn) {
155
+ let didCall = !1, returnValue;
156
+ return (...args) => (didCall || (returnValue = fn(...args), didCall = !0), returnValue);
157
+ }
158
+ const createWarningPrinter = (message) => (
159
+ // eslint-disable-next-line no-console
160
+ once((...args) => console.warn(message.join(" "), ...args))
161
+ ), printCdnAndWithCredentialsWarning = createWarningPrinter([
162
+ "Because you set `withCredentials` to true, we will override your `useCdn`",
163
+ "setting to be false since (cookie-based) credentials are never set on the CDN"
164
+ ]), printCdnWarning = createWarningPrinter([
165
+ "Since you haven't set a value for `useCdn`, we will deliver content using our",
166
+ "global, edge-cached API-CDN. If you wish to have content delivered faster, set",
167
+ "`useCdn: false` to use the Live API. Note: You may incur higher costs using the live API."
168
+ ]), printCdnPreviewDraftsWarning = createWarningPrinter([
169
+ "The Sanity client is configured with the `perspective` set to `previewDrafts`, which doesn't support the API-CDN.",
170
+ "The Live API will be used instead. Set `useCdn: false` in your configuration to hide this warning."
171
+ ]), printBrowserTokenWarning = createWarningPrinter([
172
+ "You have configured Sanity client to use a token in the browser. This may cause unintentional security issues.",
173
+ `See ${generateHelpUrl(
174
+ "js-client-browser-token"
175
+ )} for more information and how to hide this warning.`
176
+ ]), printNoApiVersionSpecifiedWarning = createWarningPrinter([
177
+ "Using the Sanity client without specifying an API version is deprecated.",
178
+ `See ${generateHelpUrl("js-client-api-version")}`
179
+ ]), printNoDefaultExport = createWarningPrinter([
180
+ "The default export of @sanity/client has been deprecated. Use the named export `createClient` instead."
181
+ ]), defaultCdnHost = "apicdn.sanity.io", defaultConfig = {
182
+ apiHost: "https://api.sanity.io",
183
+ apiVersion: "1",
184
+ useProjectHostname: !0,
185
+ stega: { enabled: !1 }
186
+ }, LOCALHOSTS = ["localhost", "127.0.0.1", "0.0.0.0"], isLocal = (host) => LOCALHOSTS.indexOf(host) !== -1;
187
+ function validateApiVersion(apiVersion) {
188
+ if (apiVersion === "1" || apiVersion === "X")
189
+ return;
190
+ const apiDate = new Date(apiVersion);
191
+ if (!(/^\d{4}-\d{2}-\d{2}$/.test(apiVersion) && apiDate instanceof Date && apiDate.getTime() > 0))
192
+ throw new Error("Invalid API version string, expected `1` or date in format `YYYY-MM-DD`");
193
+ }
194
+ const validateApiPerspective = function(perspective) {
195
+ if (Array.isArray(perspective)) {
196
+ for (const perspectiveValue of perspective)
197
+ if (perspectiveValue !== "published" && perspectiveValue !== "drafts" && !(typeof perspectiveValue == "string" && perspectiveValue.startsWith("r") && perspectiveValue !== "raw"))
198
+ throw new TypeError(
199
+ "Invalid API perspective value, expected `published`, `drafts` or a valid release identifier string"
200
+ );
201
+ return;
202
+ }
203
+ switch (perspective) {
204
+ case "previewDrafts":
205
+ case "drafts":
206
+ case "published":
207
+ case "raw":
208
+ return;
209
+ default:
210
+ throw new TypeError(
211
+ "Invalid API perspective string, expected `published`, `previewDrafts` or `raw`"
212
+ );
213
+ }
214
+ }, initConfig = (config, prevConfig) => {
215
+ const specifiedConfig = {
216
+ ...prevConfig,
217
+ ...config,
218
+ stega: {
219
+ ...typeof prevConfig.stega == "boolean" ? { enabled: prevConfig.stega } : prevConfig.stega || defaultConfig.stega,
220
+ ...typeof config.stega == "boolean" ? { enabled: config.stega } : config.stega || {}
221
+ }
222
+ };
223
+ specifiedConfig.apiVersion || printNoApiVersionSpecifiedWarning();
224
+ const newConfig = {
225
+ ...defaultConfig,
226
+ ...specifiedConfig
227
+ }, projectBased = newConfig.useProjectHostname;
228
+ if (typeof Promise > "u") {
229
+ const helpUrl = generateHelpUrl("js-client-promise-polyfill");
230
+ throw new Error(`No native Promise-implementation found, polyfill needed - see ${helpUrl}`);
231
+ }
232
+ if (projectBased && !newConfig.projectId)
233
+ throw new Error("Configuration must contain `projectId`");
234
+ if (typeof newConfig.perspective < "u" && validateApiPerspective(newConfig.perspective), "encodeSourceMap" in newConfig)
235
+ throw new Error(
236
+ "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'?"
237
+ );
238
+ if ("encodeSourceMapAtPath" in newConfig)
239
+ throw new Error(
240
+ "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'?"
241
+ );
242
+ if (typeof newConfig.stega.enabled != "boolean")
243
+ throw new Error(`stega.enabled must be a boolean, received ${newConfig.stega.enabled}`);
244
+ if (newConfig.stega.enabled && newConfig.stega.studioUrl === void 0)
245
+ throw new Error("stega.studioUrl must be defined when stega.enabled is true");
246
+ if (newConfig.stega.enabled && typeof newConfig.stega.studioUrl != "string" && typeof newConfig.stega.studioUrl != "function")
247
+ throw new Error(
248
+ `stega.studioUrl must be a string or a function, received ${newConfig.stega.studioUrl}`
249
+ );
250
+ const isBrowser = typeof window < "u" && window.location && window.location.hostname, isLocalhost = isBrowser && isLocal(window.location.hostname);
251
+ 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);
252
+ const hostParts = newConfig.apiHost.split("://", 2), protocol = hostParts[0], host = hostParts[1], cdnHost = newConfig.isDefaultApi ? defaultCdnHost : host;
253
+ 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;
254
+ };
255
+ function getSelection(sel) {
256
+ if (typeof sel == "string")
257
+ return { id: sel };
258
+ if (Array.isArray(sel))
259
+ return { query: "*[_id in $ids]", params: { ids: sel } };
260
+ if (typeof sel == "object" && sel !== null && "query" in sel && typeof sel.query == "string")
261
+ return "params" in sel && typeof sel.params == "object" && sel.params !== null ? { query: sel.query, params: sel.params } : { query: sel.query };
262
+ const selectionOpts = [
263
+ "* Document ID (<docId>)",
264
+ "* Array of document IDs",
265
+ "* Object containing `query`"
266
+ ].join(`
267
+ `);
268
+ throw new Error(`Unknown selection - must be one of:
269
+
270
+ ${selectionOpts}`);
271
+ }
167
272
  class BasePatch {
168
273
  selection;
169
274
  operations;
@@ -477,102 +582,7 @@ class ObservableTransaction extends BaseTransaction {
477
582
  return this._add({ patch: { id: patchOrDocumentId, ...patchOps } });
478
583
  }
479
584
  }
480
- const BASE_URL = "https://www.sanity.io/help/";
481
- function generateHelpUrl(slug) {
482
- return BASE_URL + slug;
483
- }
484
- function once(fn) {
485
- let didCall = !1, returnValue;
486
- return (...args) => (didCall || (returnValue = fn(...args), didCall = !0), returnValue);
487
- }
488
- const createWarningPrinter = (message) => (
489
- // eslint-disable-next-line no-console
490
- once((...args) => console.warn(message.join(" "), ...args))
491
- ), printCdnAndWithCredentialsWarning = createWarningPrinter([
492
- "Because you set `withCredentials` to true, we will override your `useCdn`",
493
- "setting to be false since (cookie-based) credentials are never set on the CDN"
494
- ]), printCdnWarning = createWarningPrinter([
495
- "Since you haven't set a value for `useCdn`, we will deliver content using our",
496
- "global, edge-cached API-CDN. If you wish to have content delivered faster, set",
497
- "`useCdn: false` to use the Live API. Note: You may incur higher costs using the live API."
498
- ]), printCdnPreviewDraftsWarning = createWarningPrinter([
499
- "The Sanity client is configured with the `perspective` set to `previewDrafts`, which doesn't support the API-CDN.",
500
- "The Live API will be used instead. Set `useCdn: false` in your configuration to hide this warning."
501
- ]), printBrowserTokenWarning = createWarningPrinter([
502
- "You have configured Sanity client to use a token in the browser. This may cause unintentional security issues.",
503
- `See ${generateHelpUrl(
504
- "js-client-browser-token"
505
- )} for more information and how to hide this warning.`
506
- ]), printNoApiVersionSpecifiedWarning = createWarningPrinter([
507
- "Using the Sanity client without specifying an API version is deprecated.",
508
- `See ${generateHelpUrl("js-client-api-version")}`
509
- ]), printNoDefaultExport = createWarningPrinter([
510
- "The default export of @sanity/client has been deprecated. Use the named export `createClient` instead."
511
- ]), defaultCdnHost = "apicdn.sanity.io", defaultConfig = {
512
- apiHost: "https://api.sanity.io",
513
- apiVersion: "1",
514
- useProjectHostname: !0,
515
- stega: { enabled: !1 }
516
- }, LOCALHOSTS = ["localhost", "127.0.0.1", "0.0.0.0"], isLocal = (host) => LOCALHOSTS.indexOf(host) !== -1;
517
- function validateApiVersion(apiVersion) {
518
- if (apiVersion === "1" || apiVersion === "X")
519
- return;
520
- const apiDate = new Date(apiVersion);
521
- if (!(/^\d{4}-\d{2}-\d{2}$/.test(apiVersion) && apiDate instanceof Date && apiDate.getTime() > 0))
522
- throw new Error("Invalid API version string, expected `1` or date in format `YYYY-MM-DD`");
523
- }
524
- const validateApiPerspective = function(perspective) {
525
- switch (perspective) {
526
- case "previewDrafts":
527
- case "published":
528
- case "raw":
529
- return;
530
- default:
531
- throw new TypeError(
532
- "Invalid API perspective string, expected `published`, `previewDrafts` or `raw`"
533
- );
534
- }
535
- }, initConfig = (config, prevConfig) => {
536
- const specifiedConfig = {
537
- ...prevConfig,
538
- ...config,
539
- stega: {
540
- ...typeof prevConfig.stega == "boolean" ? { enabled: prevConfig.stega } : prevConfig.stega || defaultConfig.stega,
541
- ...typeof config.stega == "boolean" ? { enabled: config.stega } : config.stega || {}
542
- }
543
- };
544
- specifiedConfig.apiVersion || printNoApiVersionSpecifiedWarning();
545
- const newConfig = {
546
- ...defaultConfig,
547
- ...specifiedConfig
548
- }, projectBased = newConfig.useProjectHostname;
549
- if (typeof Promise > "u") {
550
- const helpUrl = generateHelpUrl("js-client-promise-polyfill");
551
- throw new Error(`No native Promise-implementation found, polyfill needed - see ${helpUrl}`);
552
- }
553
- if (projectBased && !newConfig.projectId)
554
- throw new Error("Configuration must contain `projectId`");
555
- if (typeof newConfig.perspective == "string" && validateApiPerspective(newConfig.perspective), "encodeSourceMap" in newConfig)
556
- throw new Error(
557
- "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'?"
558
- );
559
- if ("encodeSourceMapAtPath" in newConfig)
560
- throw new Error(
561
- "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'?"
562
- );
563
- if (typeof newConfig.stega.enabled != "boolean")
564
- throw new Error(`stega.enabled must be a boolean, received ${newConfig.stega.enabled}`);
565
- if (newConfig.stega.enabled && newConfig.stega.studioUrl === void 0)
566
- throw new Error("stega.studioUrl must be defined when stega.enabled is true");
567
- if (newConfig.stega.enabled && typeof newConfig.stega.studioUrl != "string" && typeof newConfig.stega.studioUrl != "function")
568
- throw new Error(
569
- `stega.studioUrl must be a string or a function, received ${newConfig.stega.studioUrl}`
570
- );
571
- const isBrowser = typeof window < "u" && window.location && window.location.hostname, isLocalhost = isBrowser && isLocal(window.location.hostname);
572
- 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);
573
- const hostParts = newConfig.apiHost.split("://", 2), protocol = hostParts[0], host = hostParts[1], cdnHost = newConfig.isDefaultApi ? defaultCdnHost : host;
574
- 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;
575
- }, projectHeader = "X-Sanity-Project-ID";
585
+ const projectHeader = "X-Sanity-Project-ID";
576
586
  function requestOptions(config, overrides = {}) {
577
587
  const headers2 = {}, token = overrides.token || config.token;
578
588
  token && (headers2.Authorization = `Bearer ${token}`), !overrides.useGlobalApi && !config.useProjectHostname && config.projectId && (headers2[projectHeader] = config.projectId);
@@ -748,8 +758,11 @@ function _requestObservable(client, httpRequest, options) {
748
758
  if (tag && options.tag !== null && (options.query = { tag: requestTag(tag), ...options.query }), ["GET", "HEAD", "POST"].indexOf(options.method || "GET") >= 0 && uri.indexOf("/data/query/") === 0) {
749
759
  const resultSourceMap = options.resultSourceMap ?? config.resultSourceMap;
750
760
  resultSourceMap !== void 0 && resultSourceMap !== !1 && (options.query = { resultSourceMap, ...options.query });
751
- const perspective = options.perspective || config.perspective;
752
- typeof perspective == "string" && perspective !== "raw" && (validateApiPerspective(perspective), options.query = { perspective, ...options.query }, perspective === "previewDrafts" && useCdn && (useCdn = !1, printCdnPreviewDraftsWarning())), options.lastLiveEventId && (options.query = { ...options.query, lastLiveEventId: options.lastLiveEventId }), options.returnQuery === !1 && (options.query = { returnQuery: "false", ...options.query }), useCdn && options.cacheMode == "noStale" && (options.query = { cacheMode: "noStale", ...options.query });
761
+ const perspectiveOption = options.perspective || config.perspective;
762
+ typeof perspectiveOption < "u" && (validateApiPerspective(perspectiveOption), options.query = {
763
+ perspective: Array.isArray(perspectiveOption) ? perspectiveOption.join(",") : perspectiveOption,
764
+ ...options.query
765
+ }, perspectiveOption === "previewDrafts" && useCdn && (useCdn = !1, printCdnPreviewDraftsWarning())), options.lastLiveEventId && (options.query = { ...options.query, lastLiveEventId: options.lastLiveEventId }), options.returnQuery === !1 && (options.query = { returnQuery: "false", ...options.query }), useCdn && options.cacheMode == "noStale" && (options.query = { cacheMode: "noStale", ...options.query });
753
766
  }
754
767
  const reqOptions = requestOptions(
755
768
  config,
@@ -1551,7 +1564,7 @@ function defineDeprecatedCreateClient(createClient2) {
1551
1564
  return printNoDefaultExport(), createClient2(config);
1552
1565
  };
1553
1566
  }
1554
- var name = "@sanity/client", version = "6.23.0";
1567
+ var name = "@sanity/client", version = "6.24.0";
1555
1568
  const middleware = [
1556
1569
  debug({ verbose: !0, namespace: "sanity:client" }),
1557
1570
  headers({ "User-Agent": `${name} ${version}` }),
@@ -1585,6 +1598,7 @@ export {
1585
1598
  deprecatedCreateClient as default,
1586
1599
  requester,
1587
1600
  adapter as unstable__adapter,
1588
- environment as unstable__environment
1601
+ environment as unstable__environment,
1602
+ validateApiPerspective
1589
1603
  };
1590
1604
  //# sourceMappingURL=index.js.map