@sanity/client 5.0.0-esm.7 → 5.0.0-esm.9

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/README.md CHANGED
@@ -5,65 +5,111 @@
5
5
  [![gzip size][gzip-badge]][bundlephobia]
6
6
  [![size][size-badge]][bundlephobia]
7
7
 
8
- Javascript client for Sanity. Works in [Node.js](https://nodejs.org/en/), [Bun], [Deno], [Edge Runtime] and [modern browsers].
8
+ JavaScript client for Sanity. Works in modern browsers, as well as runtimes like [Node.js], [Bun], [Deno], and [Edge Runtime]
9
+
10
+ ## QuickStart
11
+
12
+ Install the client with a package manager:
13
+
14
+ ```sh
15
+ npm install @sanity/client
16
+ ```
17
+
18
+ Import and create a new client instance, and use its methods to interact with your project's [Content Lake]. Below are some simple examples in plain JavaScript. Read further for more comprehensive documentation.
19
+
20
+ ```js
21
+ // sanity.js
22
+ import {createClient} from '@sanity/client'
23
+ // Import using ESM URL imports in environments that supports it:
24
+ // import {createClient} from 'https://esm.sh/@sanity/client'
25
+
26
+ export const client = createClient({
27
+ projectId: 'your-project-id',
28
+ dataset: 'your-dataset-name',
29
+ useCdn: false, // set to `true` to fetch from edge cache
30
+ apiVersion: '2022-01-12', // use current date (YYYY-MM-DD) to target the latest API version
31
+ // token: process.env.SANITY_SECRET_TOKEN // Only if you want to update content with the client
32
+ })
33
+
34
+ // uses GROQ to query content: https://www.sanity.io/docs/groq
35
+ export async function getPosts() {
36
+ const posts = await client.fetch('*[_type == "post"]')
37
+ return posts
38
+ }
39
+
40
+ export async function createPost(post: Post) {
41
+ const result = client.create(post)
42
+ return result
43
+ }
44
+
45
+ export async function updateDocumentTitle(_id, title) {
46
+ const result = client.patch(_id).set({title})
47
+ return result
48
+ }
49
+ ```
9
50
 
10
51
  # Table of contents<!-- omit in toc -->
11
52
 
12
- - [@sanity/client](#sanityclient)
13
- - [Requirements](#requirements)
14
- - [Installation](#installation)
15
- - [API](#api)
16
- - [Creating a client instance](#creating-a-client-instance)
17
- - [ESM](#esm)
18
- - [CommonJS](#commonjs)
19
- - [TypeScript](#typescript)
20
- - [Bun](#bun)
21
- - [Deno](#deno)
22
- - [Edge Runtime](#edge-runtime)
23
- - [Browser ESM CDN](#browser-esm-cdn)
24
- - [UMD](#umd)
25
- - [Specifying API version](#specifying-api-version)
26
- - [Performing queries](#performing-queries)
27
- - [Listening to queries](#listening-to-queries)
28
- - [Fetch a single document](#fetch-a-single-document)
29
- - [Fetch multiple documents in one go](#fetch-multiple-documents-in-one-go)
30
- - [Creating documents](#creating-documents)
31
- - [Creating/replacing documents](#creatingreplacing-documents)
32
- - [Creating if not already present](#creating-if-not-already-present)
33
- - [Patch/update a document](#patchupdate-a-document)
34
- - [Setting a field only if not already present](#setting-a-field-only-if-not-already-present)
35
- - [Removing/unsetting fields](#removingunsetting-fields)
36
- - [Incrementing/decrementing numbers](#incrementingdecrementing-numbers)
37
- - [Patch a document only if revision matches](#patch-a-document-only-if-revision-matches)
38
- - [Adding elements to an array](#adding-elements-to-an-array)
39
- - [Appending/prepending elements to an array](#appendingprepending-elements-to-an-array)
40
- - [Deleting an element from an array](#deleting-an-element-from-an-array)
41
- - [Delete documents](#delete-documents)
42
- - [Multiple mutations in a transaction](#multiple-mutations-in-a-transaction)
43
- - [Clientless patches \& transactions](#clientless-patches--transactions)
44
- - [Uploading assets](#uploading-assets)
45
- - [Examples: Uploading assets from Node.js](#examples-uploading-assets-from-nodejs)
46
- - [Examples: Uploading assets from the Browser](#examples-uploading-assets-from-the-browser)
47
- - [Examples: Specify image metadata to extract](#examples-specify-image-metadata-to-extract)
48
- - [Deleting an asset](#deleting-an-asset)
49
- - [Mutation options](#mutation-options)
50
- - [Get client configuration](#get-client-configuration)
51
- - [Set client configuration](#set-client-configuration)
52
- - [Release new version](#release-new-version)
53
- - [License](#license)
54
- - [Migrate](#migrate)
55
- - [From `v4`](#from-v4)
53
+ - [QuickStart](#quickstart)
54
+ - [Requirements](#requirements)
55
+ - [Installation](#installation)
56
+ - [API](#api)
57
+ - [Creating a client instance](#creating-a-client-instance)
58
+ - [ESM](#esm)
59
+ - [CommonJS](#commonjs)
60
+ - [TypeScript](#typescript)
61
+ - [Bun](#bun)
62
+ - [Deno](#deno)
63
+ - [Edge Runtime](#edge-runtime)
64
+ - [Browser ESM CDN](#browser-esm-cdn)
65
+ - [UMD](#umd)
66
+ - [Specifying API version](#specifying-api-version)
67
+ - [Performing queries](#performing-queries)
68
+ - [Listening to queries](#listening-to-queries)
69
+ - [Fetch a single document](#fetch-a-single-document)
70
+ - [Fetch multiple documents in one go](#fetch-multiple-documents-in-one-go)
71
+ - [Creating documents](#creating-documents)
72
+ - [Creating/replacing documents](#creatingreplacing-documents)
73
+ - [Creating if not already present](#creating-if-not-already-present)
74
+ - [Patch/update a document](#patchupdate-a-document)
75
+ - [Setting a field only if not already present](#setting-a-field-only-if-not-already-present)
76
+ - [Removing/unsetting fields](#removingunsetting-fields)
77
+ - [Incrementing/decrementing numbers](#incrementingdecrementing-numbers)
78
+ - [Patch a document only if revision matches](#patch-a-document-only-if-revision-matches)
79
+ - [Adding elements to an array](#adding-elements-to-an-array)
80
+ - [Appending/prepending elements to an array](#appendingprepending-elements-to-an-array)
81
+ - [Deleting an element from an array](#deleting-an-element-from-an-array)
82
+ - [Delete documents](#delete-documents)
83
+ - [Multiple mutations in a transaction](#multiple-mutations-in-a-transaction)
84
+ - [Clientless patches \& transactions](#clientless-patches--transactions)
85
+ - [Uploading assets](#uploading-assets)
86
+ - [Examples: Uploading assets from Node.js](#examples-uploading-assets-from-nodejs)
87
+ - [Examples: Uploading assets from the Browser](#examples-uploading-assets-from-the-browser)
88
+ - [Examples: Specify image metadata to extract](#examples-specify-image-metadata-to-extract)
89
+ - [Deleting an asset](#deleting-an-asset)
90
+ - [Mutation options](#mutation-options)
91
+ - [Get client configuration](#get-client-configuration)
92
+ - [Set client configuration](#set-client-configuration)
93
+ - [Release new version](#release-new-version)
94
+ - [License](#license)
95
+ - [From `v4`](#from-v4)
56
96
 
57
97
  ## Requirements
58
98
 
59
- Sanity Client transpiles syntax for [modern browsers]. The JavaScript runtime must support ES6 features such as [class](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), [rest parameters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters), [spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and more. For ES5 environments you'll need to transpile `@sanity/client` and its `dependencies` with your own bundler, and have a global ES6-compliant `Promise` available. If your runtime environment doesn't provide a spec compliant `Promise` implementation, we recommend using [native-promise-only](https://www.npmjs.com/package/native-promise-only), [es6-promise](https://www.npmjs.com/package/es6-promise) or another [spec-compliant](https://promisesaplus.com/implementations) implementation. See [this article](https://www.sanity.io/help/js-client-promise-polyfill) for more information.
99
+ Sanity Client transpiles syntax for [modern browsers]. The JavaScript runtime must support ES6 features such as [class](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), [rest parameters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters), [spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and more. Most modern web frameworks, [browsers][modern browsers], and developer tooling supports ES6 today.
100
+
101
+ For legacy ES5 environments you'll need to transpile `@sanity/client` and its `dependencies` with your own bundler, and have a global ES6-compliant `Promise` available. If your runtime environment doesn't provide a spec compliant `Promise` implementation, we recommend using [native-promise-only](https://www.npmjs.com/package/native-promise-only), [es6-promise](https://www.npmjs.com/package/es6-promise) or another [spec-compliant](https://promisesaplus.com/implementations) implementation. See [this article](https://www.sanity.io/help/js-client-promise-polyfill) for more information.
60
102
 
61
103
  ## Installation
62
104
 
63
- The client can be installed from npm:
105
+ The client can be installed from [npm]:
64
106
 
65
- ```
107
+ ```sh
66
108
  npm install @sanity/client
109
+
110
+ # Alternative package managers
111
+ yarn add @sanity/client
112
+ pnpm install @sanity/client
67
113
  ```
68
114
 
69
115
  ## API
@@ -72,7 +118,7 @@ npm install @sanity/client
72
118
 
73
119
  `const client = createClient(options)`
74
120
 
75
- Initializes a new Sanity Client. Required options are `projectId`, `dataset`, and `apiVersion`. Setting a value for `useCdn` is encouraged.
121
+ Initializes a new Sanity Client. Required options are `projectId`, `dataset`, and `apiVersion`. Setting a value for `useCdn` is encouraged. Typically you want to have it as `false` in development to always fetch the freshest content and `true` in production environments so that content is fetched from the distributed cache. [You can learn more about the API CDN here][api-cdn].
76
122
 
77
123
  #### [ESM](https://hacks.mozilla.org/2018/03/es-modules-a-cartoon-deep-dive/)
78
124
 
@@ -90,7 +136,7 @@ const client = createClient({
90
136
  export default client
91
137
  ```
92
138
 
93
- #### [CommonJS](https://nodejs.org/api/modules.html#modules-commonjs-modules)
139
+ #### [CommonJS]
94
140
 
95
141
  ```js
96
142
  const {createClient} = require('@sanity/client')
@@ -106,7 +152,7 @@ const client = createClient({
106
152
  module.exports = client
107
153
  ```
108
154
 
109
- #### [TypeScript](https://www.typescriptlang.org/)
155
+ #### [TypeScript]
110
156
 
111
157
  ```ts
112
158
  import {createClient, type ClientConfig} from '@sanity/client'
@@ -302,8 +348,8 @@ The `require-unpkg` library lets you consume `npm` packages from `unpkg.com` sim
302
348
  projectId: 'your-project-id',
303
349
  dataset: 'bikeshop',
304
350
  apiVersion: '2021-03-25', // use current UTC date - see "specifying API version"!
305
- token: 'sanity-auth-token', // or leave blank for unauthenticated usage
306
351
  useCdn: true, // `false` if you want to ensure fresh data
352
+ token: 'sanity-secret-auth-token', // leave blank for unauthenticated usage
307
353
  })
308
354
 
309
355
  const data = await client.fetch(`count(*[])`)
@@ -314,7 +360,7 @@ The `require-unpkg` library lets you consume `npm` packages from `unpkg.com` sim
314
360
 
315
361
  ### Specifying API version
316
362
 
317
- Sanity uses ISO dates (YYYY-MM-DD) in UTC timezone for versioning. The explanation for this can be found [in the documentation](http://sanity.io/docs/api-versioning)
363
+ Sanity uses ISO dates (YYYY-MM-DD) in UTC timezone for versioning. The explanation for this can be found [in the documentation][api-versioning]
318
364
 
319
365
  In general, unless you know what API version you want to use, you'll want to statically set it to today's UTC date when starting a new project. By doing this, you'll get all the latest bugfixes and features, while locking the API to prevent breaking changes.
320
366
 
@@ -410,7 +456,7 @@ client.create(doc).then((res) => {
410
456
  })
411
457
  ```
412
458
 
413
- `client.create(doc)`
459
+ `client.create(doc)`
414
460
  `client.create(doc, mutationOptions)`
415
461
 
416
462
  Create a document. Argument is a plain JS object representing the document. It must contain a `_type` attribute. It _may_ contain an `_id`. If an ID is not specified, it will automatically be created.
@@ -432,7 +478,7 @@ client.createOrReplace(doc).then((res) => {
432
478
  })
433
479
  ```
434
480
 
435
- `client.createOrReplace(doc)`
481
+ `client.createOrReplace(doc)`
436
482
  `client.createOrReplace(doc, mutationOptions)`
437
483
 
438
484
  If you are not sure whether or not a document exists but want to overwrite it if it does, you can use the `createOrReplace()` method. When using this method, the document must contain an `_id` attribute.
@@ -452,7 +498,7 @@ client.createIfNotExists(doc).then((res) => {
452
498
  })
453
499
  ```
454
500
 
455
- `client.createIfNotExists(doc)`
501
+ `client.createIfNotExists(doc)`
456
502
  `client.createIfNotExists(doc, mutationOptions)`
457
503
 
458
504
  If you want to create a document if it does not already exist, but fall back without error if it does, you can use the `createIfNotExists()` method. When using this method, the document must contain an `_id` attribute.
@@ -561,7 +607,7 @@ client.patch('bike-123').unset(reviewsToRemove).commit()
561
607
 
562
608
  A single document can be deleted by specifying a document ID:
563
609
 
564
- `client.delete(docId)`
610
+ `client.delete(docId)`
565
611
  `client.delete(docId, mutationOptions)`
566
612
 
567
613
  ```js
@@ -1105,3 +1151,10 @@ client.createOrReplace(doc, options)
1105
1151
  [unpkg-dist]: https://unpkg.com/@sanity/client/umd/
1106
1152
  [bundlephobia]: https://bundlephobia.com/package/@sanity/client
1107
1153
  [esm.sh]: https://esm.sh
1154
+ [Node.js]: https://nodejs.org/en/
1155
+ [Content Lake]: https://www.sanity.io/docs/datastore
1156
+ [npm]: https://npmjs.com
1157
+ [api-cdn]: https://www.sanity.io/docs/api-cdn
1158
+ [CommonJS]: https://nodejs.org/api/modules.html#modules-commonjs-modules
1159
+ [TypeScript]: https://www.typescriptlang.org/
1160
+ [api-versioning]: http://sanity.io/docs/api-versioning
@@ -341,7 +341,7 @@ class BasePatch {
341
341
  * @param selector - Attribute or JSONPath expression for array
342
342
  * @param start - Index at which to start changing the array (with origin 0). If greater than the length of the array, actual starting index will be set to the length of the array. If negative, will begin that many elements from the end of the array (with origin -1) and will be set to 0 if absolute value is greater than the length of the array.x
343
343
  * @param deleteCount - An integer indicating the number of old array elements to remove.
344
- * @param items - The elements to add to the array, beginning at the start index. If you don't specify any elements, splice() will only remove elements from the array.
344
+ * @param items - The elements to add to the array, beginning at the start index. If you don't specify FIXME elements, splice() will only remove elements from the array.
345
345
  */
346
346
  splice(selector, start, deleteCount, items) {
347
347
  const delAll = typeof deleteCount === "undefined" || deleteCount === -1;
@@ -807,7 +807,9 @@ function _requestObservable(client, httpRequest, options) {
807
807
  const reqOptions = getRequestOptions(config, Object.assign({}, options, {
808
808
  url: _getUrl(client, uri, useCdn)
809
809
  }));
810
- return new rxjs.Observable(subscriber => httpRequest(reqOptions, config.requester).subscribe(subscriber));
810
+ return new rxjs.Observable(subscriber =>
811
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- the typings thinks it's optional because it's not required to specify it when calling createClient, but it's always defined in practice since SanityClient provides a default
812
+ httpRequest(reqOptions, config.requester).subscribe(subscriber));
811
813
  }
812
814
  function _request(client, httpRequest, options) {
813
815
  const observable = _requestObservable(client, httpRequest, options).pipe(operators.filter(event => event.type === "response"), operators.map(event => event.body));
@@ -1553,7 +1555,7 @@ const _ObservableSanityClient = class {
1553
1555
  * Fetch multiple documents in one request.
1554
1556
  * Should be used sparingly - performing a query is usually a better option.
1555
1557
  * The order/position of documents is preserved based on the original array of IDs.
1556
- * If a any of the documents are missing, they will be replaced by a `null` entry in the returned array
1558
+ * If a FIXME of the documents are missing, they will be replaced by a `null` entry in the returned array
1557
1559
  *
1558
1560
  * @param ids - Document IDs to fetch
1559
1561
  * @param options - Request options
@@ -1676,7 +1678,7 @@ const _SanityClient = class {
1676
1678
  * Fetch multiple documents in one request.
1677
1679
  * Should be used sparingly - performing a query is usually a better option.
1678
1680
  * The order/position of documents is preserved based on the original array of IDs.
1679
- * If a any of the documents are missing, they will be replaced by a `null` entry in the returned array
1681
+ * If a FIXME of the documents are missing, they will be replaced by a `null` entry in the returned array
1680
1682
  *
1681
1683
  * @param ids - Document IDs to fetch
1682
1684
  * @param options - Request options