@sanity/client 6.4.5 → 6.4.6-canary.1

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sanity/client",
3
- "version": "6.4.5",
3
+ "version": "6.4.6-canary.1",
4
4
  "description": "Client for retrieving, creating and patching data from Sanity.io",
5
5
  "keywords": [
6
6
  "sanity",
@@ -1,6 +1,7 @@
1
1
  import {type MonoTypeOperatorFunction, Observable} from 'rxjs'
2
2
  import {filter, map} from 'rxjs/operators'
3
3
 
4
+ import {validateApiPerspective} from '../config'
4
5
  import {requestOptions} from '../http/requestOptions'
5
6
  import type {ObservableSanityClient, SanityClient} from '../SanityClient'
6
7
  import type {
@@ -229,6 +230,8 @@ export function _dataRequest(
229
230
  headers,
230
231
  token,
231
232
  tag,
233
+ perspective: options.perspective,
234
+ resultSourceMap: options.resultSourceMap,
232
235
  canUseCdn: isQuery,
233
236
  signal: options.signal,
234
237
  fetch: options.fetch,
@@ -313,11 +316,13 @@ export function _requestObservable<R>(
313
316
  ['GET', 'HEAD', 'POST'].indexOf(options.method || 'GET') >= 0 &&
314
317
  uri.indexOf('/data/query/') === 0
315
318
  ) {
316
- if (config.resultSourceMap) {
319
+ if (options.resultSourceMap ?? config.resultSourceMap) {
317
320
  options.query = {resultSourceMap: true, ...options.query}
318
321
  }
319
- if (typeof config.perspective === 'string' && config.perspective !== 'raw') {
320
- options.query = {perspective: config.perspective, ...options.query}
322
+ const perspective = options.perspective || config.perspective
323
+ if (typeof perspective === 'string' && perspective !== 'raw') {
324
+ validateApiPerspective(perspective)
325
+ options.query = {perspective, ...options.query}
321
326
  }
322
327
  }
323
328
 
package/src/types.ts CHANGED
@@ -293,6 +293,8 @@ export interface RequestObservableOptions extends Omit<RequestOptions, 'url'> {
293
293
  uri?: string
294
294
  canUseCdn?: boolean
295
295
  tag?: string
296
+ resultSourceMap?: boolean
297
+ perspective?: ClientPerspective
296
298
  }
297
299
 
298
300
  /** @public */
@@ -500,6 +502,8 @@ export interface ListenOptions {
500
502
 
501
503
  /** @public */
502
504
  export type ResponseQueryOptions<T = 'next'> = RequestOptions & {
505
+ perspective?: ClientPerspective
506
+ resultSourceMap?: boolean
503
507
  cache?: RequestInit['cache']
504
508
  next?: T extends keyof RequestInit ? RequestInit[T] : never
505
509
  }
@@ -2277,47 +2277,9 @@
2277
2277
  if ((isSafe || isQuery) && isRetriableResponse) return true;
2278
2278
  return retry.shouldRetry(err, attempt, options);
2279
2279
  }
2280
- const projectHeader = "X-Sanity-Project-ID";
2281
- function requestOptions(config) {
2282
- let overrides = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
2283
- const headers = {};
2284
- const token = overrides.token || config.token;
2285
- if (token) {
2286
- headers.Authorization = "Bearer ".concat(token);
2287
- }
2288
- if (!overrides.useGlobalApi && !config.useProjectHostname && config.projectId) {
2289
- headers[projectHeader] = config.projectId;
2290
- }
2291
- const withCredentials = Boolean(typeof overrides.withCredentials === "undefined" ? config.token || config.withCredentials : overrides.withCredentials);
2292
- const timeout = typeof overrides.timeout === "undefined" ? config.timeout : overrides.timeout;
2293
- return Object.assign({}, overrides, {
2294
- headers: Object.assign({}, headers, overrides.headers || {}),
2295
- timeout: typeof timeout === "undefined" ? 5 * 60 * 1e3 : timeout,
2296
- proxy: overrides.proxy || config.proxy,
2297
- json: true,
2298
- withCredentials,
2299
- fetch: typeof overrides.fetch === "object" && typeof config.fetch === "object" ? {
2300
- ...config.fetch,
2301
- ...overrides.fetch
2302
- } : overrides.fetch || config.fetch
2303
- });
2304
- }
2305
- function getSelection(sel) {
2306
- if (typeof sel === "string" || Array.isArray(sel)) {
2307
- return {
2308
- id: sel
2309
- };
2310
- }
2311
- if (typeof sel === "object" && sel !== null && "query" in sel && typeof sel.query === "string") {
2312
- return "params" in sel && typeof sel.params === "object" && sel.params !== null ? {
2313
- query: sel.query,
2314
- params: sel.params
2315
- } : {
2316
- query: sel.query
2317
- };
2318
- }
2319
- const selectionOpts = ["* Document ID (<docId>)", "* Array of document IDs", "* Object containing `query`"].join("\n");
2320
- throw new Error("Unknown selection - must be one of:\n\n".concat(selectionOpts));
2280
+ const BASE_URL = "https://www.sanity.io/help/";
2281
+ function generateHelpUrl(slug) {
2282
+ return BASE_URL + slug;
2321
2283
  }
2322
2284
  const VALID_ASSET_TYPES = ["image", "file"];
2323
2285
  const VALID_INSERT_LOCATIONS = ["before", "after", "replace"];
@@ -2377,6 +2339,153 @@
2377
2339
  }
2378
2340
  return tag;
2379
2341
  };
2342
+ function once(fn) {
2343
+ let didCall = false;
2344
+ let returnValue;
2345
+ return function () {
2346
+ if (didCall) {
2347
+ return returnValue;
2348
+ }
2349
+ returnValue = fn(...arguments);
2350
+ didCall = true;
2351
+ return returnValue;
2352
+ };
2353
+ }
2354
+ const createWarningPrinter = message =>
2355
+ // eslint-disable-next-line no-console
2356
+ once(function () {
2357
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
2358
+ args[_key] = arguments[_key];
2359
+ }
2360
+ return console.warn(message.join(" "), ...args);
2361
+ });
2362
+ const printCdnWarning = createWarningPrinter(["Since you haven't set a value for `useCdn`, we will deliver content using our", "global, edge-cached API-CDN. If you wish to have content delivered faster, set", "`useCdn: false` to use the Live API. Note: You may incur higher costs using the live API."]);
2363
+ const printBrowserTokenWarning = createWarningPrinter(["You have configured Sanity client to use a token in the browser. This may cause unintentional security issues.", "See ".concat(generateHelpUrl("js-client-browser-token"), " for more information and how to hide this warning.")]);
2364
+ const printNoApiVersionSpecifiedWarning = createWarningPrinter(["Using the Sanity client without specifying an API version is deprecated.", "See ".concat(generateHelpUrl("js-client-api-version"))]);
2365
+ const printNoDefaultExport = createWarningPrinter(["The default export of @sanity/client has been deprecated. Use the named export `createClient` instead."]);
2366
+ const defaultCdnHost = "apicdn.sanity.io";
2367
+ const defaultConfig = {
2368
+ apiHost: "https://api.sanity.io",
2369
+ apiVersion: "1",
2370
+ useProjectHostname: true
2371
+ };
2372
+ const LOCALHOSTS = ["localhost", "127.0.0.1", "0.0.0.0"];
2373
+ const isLocal = host => LOCALHOSTS.indexOf(host) !== -1;
2374
+ const validateApiVersion = function validateApiVersion2(apiVersion) {
2375
+ if (apiVersion === "1" || apiVersion === "X") {
2376
+ return;
2377
+ }
2378
+ const apiDate = new Date(apiVersion);
2379
+ const apiVersionValid = /^\d{4}-\d{2}-\d{2}$/.test(apiVersion) && apiDate instanceof Date && apiDate.getTime() > 0;
2380
+ if (!apiVersionValid) {
2381
+ throw new Error("Invalid API version string, expected `1` or date in format `YYYY-MM-DD`");
2382
+ }
2383
+ };
2384
+ const validateApiPerspective = function validateApiPerspective2(perspective) {
2385
+ switch (perspective) {
2386
+ case "previewDrafts":
2387
+ case "published":
2388
+ case "raw":
2389
+ return;
2390
+ default:
2391
+ throw new TypeError("Invalid API perspective string, expected `published`, `previewDrafts` or `raw`");
2392
+ }
2393
+ };
2394
+ const initConfig = (config, prevConfig) => {
2395
+ const specifiedConfig = Object.assign({}, prevConfig, config);
2396
+ if (!specifiedConfig.apiVersion) {
2397
+ printNoApiVersionSpecifiedWarning();
2398
+ }
2399
+ const newConfig = Object.assign({}, defaultConfig, specifiedConfig);
2400
+ const projectBased = newConfig.useProjectHostname;
2401
+ if (typeof Promise === "undefined") {
2402
+ const helpUrl = generateHelpUrl("js-client-promise-polyfill");
2403
+ throw new Error("No native Promise-implementation found, polyfill needed - see ".concat(helpUrl));
2404
+ }
2405
+ if (projectBased && !newConfig.projectId) {
2406
+ throw new Error("Configuration must contain `projectId`");
2407
+ }
2408
+ if (typeof newConfig.perspective === "string") {
2409
+ validateApiPerspective(newConfig.perspective);
2410
+ }
2411
+ if ("encodeSourceMapAtPath" in newConfig || "encodeSourceMap" in newConfig || "studioUrl" in newConfig || "logger" in newConfig) {
2412
+ throw new Error("It looks like you're using options meant for '@sanity/preview-kit/client', such as 'encodeSourceMapAtPath', 'encodeSourceMap', 'studioUrl' and 'logger'. Make sure you're using the right import.");
2413
+ }
2414
+ const isBrowser = typeof window !== "undefined" && window.location && window.location.hostname;
2415
+ const isLocalhost = isBrowser && isLocal(window.location.hostname);
2416
+ if (isBrowser && isLocalhost && newConfig.token && newConfig.ignoreBrowserTokenWarning !== true) {
2417
+ printBrowserTokenWarning();
2418
+ } else if (typeof newConfig.useCdn === "undefined") {
2419
+ printCdnWarning();
2420
+ }
2421
+ if (projectBased) {
2422
+ projectId(newConfig.projectId);
2423
+ }
2424
+ if (newConfig.dataset) {
2425
+ dataset(newConfig.dataset);
2426
+ }
2427
+ if ("requestTagPrefix" in newConfig) {
2428
+ newConfig.requestTagPrefix = newConfig.requestTagPrefix ? requestTag(newConfig.requestTagPrefix).replace(/\.+$/, "") : void 0;
2429
+ }
2430
+ newConfig.apiVersion = "".concat(newConfig.apiVersion).replace(/^v/, "");
2431
+ newConfig.isDefaultApi = newConfig.apiHost === defaultConfig.apiHost;
2432
+ newConfig.useCdn = newConfig.useCdn !== false && !newConfig.withCredentials;
2433
+ validateApiVersion(newConfig.apiVersion);
2434
+ const hostParts = newConfig.apiHost.split("://", 2);
2435
+ const protocol = hostParts[0];
2436
+ const host = hostParts[1];
2437
+ const cdnHost = newConfig.isDefaultApi ? defaultCdnHost : host;
2438
+ if (newConfig.useProjectHostname) {
2439
+ newConfig.url = "".concat(protocol, "://").concat(newConfig.projectId, ".").concat(host, "/v").concat(newConfig.apiVersion);
2440
+ newConfig.cdnUrl = "".concat(protocol, "://").concat(newConfig.projectId, ".").concat(cdnHost, "/v").concat(newConfig.apiVersion);
2441
+ } else {
2442
+ newConfig.url = "".concat(newConfig.apiHost, "/v").concat(newConfig.apiVersion);
2443
+ newConfig.cdnUrl = newConfig.url;
2444
+ }
2445
+ return newConfig;
2446
+ };
2447
+ const projectHeader = "X-Sanity-Project-ID";
2448
+ function requestOptions(config) {
2449
+ let overrides = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
2450
+ const headers = {};
2451
+ const token = overrides.token || config.token;
2452
+ if (token) {
2453
+ headers.Authorization = "Bearer ".concat(token);
2454
+ }
2455
+ if (!overrides.useGlobalApi && !config.useProjectHostname && config.projectId) {
2456
+ headers[projectHeader] = config.projectId;
2457
+ }
2458
+ const withCredentials = Boolean(typeof overrides.withCredentials === "undefined" ? config.token || config.withCredentials : overrides.withCredentials);
2459
+ const timeout = typeof overrides.timeout === "undefined" ? config.timeout : overrides.timeout;
2460
+ return Object.assign({}, overrides, {
2461
+ headers: Object.assign({}, headers, overrides.headers || {}),
2462
+ timeout: typeof timeout === "undefined" ? 5 * 60 * 1e3 : timeout,
2463
+ proxy: overrides.proxy || config.proxy,
2464
+ json: true,
2465
+ withCredentials,
2466
+ fetch: typeof overrides.fetch === "object" && typeof config.fetch === "object" ? {
2467
+ ...config.fetch,
2468
+ ...overrides.fetch
2469
+ } : overrides.fetch || config.fetch
2470
+ });
2471
+ }
2472
+ function getSelection(sel) {
2473
+ if (typeof sel === "string" || Array.isArray(sel)) {
2474
+ return {
2475
+ id: sel
2476
+ };
2477
+ }
2478
+ if (typeof sel === "object" && sel !== null && "query" in sel && typeof sel.query === "string") {
2479
+ return "params" in sel && typeof sel.params === "object" && sel.params !== null ? {
2480
+ query: sel.query,
2481
+ params: sel.params
2482
+ } : {
2483
+ query: sel.query
2484
+ };
2485
+ }
2486
+ const selectionOpts = ["* Document ID (<docId>)", "* Array of document IDs", "* Object containing `query`"].join("\n");
2487
+ throw new Error("Unknown selection - must be one of:\n\n".concat(selectionOpts));
2488
+ }
2380
2489
  const encodeQueryString = _ref2 => {
2381
2490
  let {
2382
2491
  query,
@@ -2984,6 +3093,8 @@
2984
3093
  headers,
2985
3094
  token,
2986
3095
  tag,
3096
+ perspective: options.perspective,
3097
+ resultSourceMap: options.resultSourceMap,
2987
3098
  canUseCdn: isQuery,
2988
3099
  signal: options.signal,
2989
3100
  fetch: options.fetch
@@ -3019,6 +3130,7 @@
3019
3130
  }, opts);
3020
3131
  }
3021
3132
  function _requestObservable(client, httpRequest, options) {
3133
+ var _a;
3022
3134
  const uri = options.url || options.uri;
3023
3135
  const config = client.config();
3024
3136
  const canUseCdn = typeof options.canUseCdn === "undefined" ? ["GET", "HEAD"].indexOf(options.method || "GET") >= 0 && uri.indexOf("/data/") === 0 : options.canUseCdn;
@@ -3031,15 +3143,17 @@
3031
3143
  };
3032
3144
  }
3033
3145
  if (["GET", "HEAD", "POST"].indexOf(options.method || "GET") >= 0 && uri.indexOf("/data/query/") === 0) {
3034
- if (config.resultSourceMap) {
3146
+ if ((_a = options.resultSourceMap) != null ? _a : config.resultSourceMap) {
3035
3147
  options.query = {
3036
3148
  resultSourceMap: true,
3037
3149
  ...options.query
3038
3150
  };
3039
3151
  }
3040
- if (typeof config.perspective === "string" && config.perspective !== "raw") {
3152
+ const perspective = options.perspective || config.perspective;
3153
+ if (typeof perspective === "string" && perspective !== "raw") {
3154
+ validateApiPerspective(perspective);
3041
3155
  options.query = {
3042
- perspective: config.perspective,
3156
+ perspective,
3043
3157
  ...options.query
3044
3158
  };
3045
3159
  }
@@ -3194,115 +3308,6 @@
3194
3308
  contentType: file.type
3195
3309
  }, opts);
3196
3310
  }
3197
- const BASE_URL = "https://www.sanity.io/help/";
3198
- function generateHelpUrl(slug) {
3199
- return BASE_URL + slug;
3200
- }
3201
- function once(fn) {
3202
- let didCall = false;
3203
- let returnValue;
3204
- return function () {
3205
- if (didCall) {
3206
- return returnValue;
3207
- }
3208
- returnValue = fn(...arguments);
3209
- didCall = true;
3210
- return returnValue;
3211
- };
3212
- }
3213
- const createWarningPrinter = message =>
3214
- // eslint-disable-next-line no-console
3215
- once(function () {
3216
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
3217
- args[_key] = arguments[_key];
3218
- }
3219
- return console.warn(message.join(" "), ...args);
3220
- });
3221
- const printCdnWarning = createWarningPrinter(["Since you haven't set a value for `useCdn`, we will deliver content using our", "global, edge-cached API-CDN. If you wish to have content delivered faster, set", "`useCdn: false` to use the Live API. Note: You may incur higher costs using the live API."]);
3222
- const printBrowserTokenWarning = createWarningPrinter(["You have configured Sanity client to use a token in the browser. This may cause unintentional security issues.", "See ".concat(generateHelpUrl("js-client-browser-token"), " for more information and how to hide this warning.")]);
3223
- const printNoApiVersionSpecifiedWarning = createWarningPrinter(["Using the Sanity client without specifying an API version is deprecated.", "See ".concat(generateHelpUrl("js-client-api-version"))]);
3224
- const printNoDefaultExport = createWarningPrinter(["The default export of @sanity/client has been deprecated. Use the named export `createClient` instead."]);
3225
- const defaultCdnHost = "apicdn.sanity.io";
3226
- const defaultConfig = {
3227
- apiHost: "https://api.sanity.io",
3228
- apiVersion: "1",
3229
- useProjectHostname: true
3230
- };
3231
- const LOCALHOSTS = ["localhost", "127.0.0.1", "0.0.0.0"];
3232
- const isLocal = host => LOCALHOSTS.indexOf(host) !== -1;
3233
- const validateApiVersion = function validateApiVersion2(apiVersion) {
3234
- if (apiVersion === "1" || apiVersion === "X") {
3235
- return;
3236
- }
3237
- const apiDate = new Date(apiVersion);
3238
- const apiVersionValid = /^\d{4}-\d{2}-\d{2}$/.test(apiVersion) && apiDate instanceof Date && apiDate.getTime() > 0;
3239
- if (!apiVersionValid) {
3240
- throw new Error("Invalid API version string, expected `1` or date in format `YYYY-MM-DD`");
3241
- }
3242
- };
3243
- const validateApiPerspective = function validateApiPerspective2(perspective) {
3244
- switch (perspective) {
3245
- case "previewDrafts":
3246
- case "published":
3247
- case "raw":
3248
- return;
3249
- default:
3250
- throw new TypeError("Invalid API perspective string, expected `published`, `previewDrafts` or `raw`");
3251
- }
3252
- };
3253
- const initConfig = (config, prevConfig) => {
3254
- const specifiedConfig = Object.assign({}, prevConfig, config);
3255
- if (!specifiedConfig.apiVersion) {
3256
- printNoApiVersionSpecifiedWarning();
3257
- }
3258
- const newConfig = Object.assign({}, defaultConfig, specifiedConfig);
3259
- const projectBased = newConfig.useProjectHostname;
3260
- if (typeof Promise === "undefined") {
3261
- const helpUrl = generateHelpUrl("js-client-promise-polyfill");
3262
- throw new Error("No native Promise-implementation found, polyfill needed - see ".concat(helpUrl));
3263
- }
3264
- if (projectBased && !newConfig.projectId) {
3265
- throw new Error("Configuration must contain `projectId`");
3266
- }
3267
- if (typeof newConfig.perspective === "string") {
3268
- validateApiPerspective(newConfig.perspective);
3269
- }
3270
- if ("encodeSourceMapAtPath" in newConfig || "encodeSourceMap" in newConfig || "studioUrl" in newConfig || "logger" in newConfig) {
3271
- throw new Error("It looks like you're using options meant for '@sanity/preview-kit/client', such as 'encodeSourceMapAtPath', 'encodeSourceMap', 'studioUrl' and 'logger'. Make sure you're using the right import.");
3272
- }
3273
- const isBrowser = typeof window !== "undefined" && window.location && window.location.hostname;
3274
- const isLocalhost = isBrowser && isLocal(window.location.hostname);
3275
- if (isBrowser && isLocalhost && newConfig.token && newConfig.ignoreBrowserTokenWarning !== true) {
3276
- printBrowserTokenWarning();
3277
- } else if (typeof newConfig.useCdn === "undefined") {
3278
- printCdnWarning();
3279
- }
3280
- if (projectBased) {
3281
- projectId(newConfig.projectId);
3282
- }
3283
- if (newConfig.dataset) {
3284
- dataset(newConfig.dataset);
3285
- }
3286
- if ("requestTagPrefix" in newConfig) {
3287
- newConfig.requestTagPrefix = newConfig.requestTagPrefix ? requestTag(newConfig.requestTagPrefix).replace(/\.+$/, "") : void 0;
3288
- }
3289
- newConfig.apiVersion = "".concat(newConfig.apiVersion).replace(/^v/, "");
3290
- newConfig.isDefaultApi = newConfig.apiHost === defaultConfig.apiHost;
3291
- newConfig.useCdn = newConfig.useCdn !== false && !newConfig.withCredentials;
3292
- validateApiVersion(newConfig.apiVersion);
3293
- const hostParts = newConfig.apiHost.split("://", 2);
3294
- const protocol = hostParts[0];
3295
- const host = hostParts[1];
3296
- const cdnHost = newConfig.isDefaultApi ? defaultCdnHost : host;
3297
- if (newConfig.useProjectHostname) {
3298
- newConfig.url = "".concat(protocol, "://").concat(newConfig.projectId, ".").concat(host, "/v").concat(newConfig.apiVersion);
3299
- newConfig.cdnUrl = "".concat(protocol, "://").concat(newConfig.projectId, ".").concat(cdnHost, "/v").concat(newConfig.apiVersion);
3300
- } else {
3301
- newConfig.url = "".concat(newConfig.apiHost, "/v").concat(newConfig.apiVersion);
3302
- newConfig.cdnUrl = newConfig.url;
3303
- }
3304
- return newConfig;
3305
- };
3306
3311
  var defaults = (obj, defaults) => Object.keys(defaults).concat(Object.keys(obj)).reduce((target, prop) => {
3307
3312
  target[prop] = typeof obj[prop] === "undefined" ? defaults[prop] : obj[prop];
3308
3313
  return target;