@sanity/sdk-react 0.0.0-alpha.17 → 0.0.0-alpha.19

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/hooks.d.ts DELETED
@@ -1,4365 +0,0 @@
1
- import {ActionsResult} from '@sanity/sdk'
2
- import {ApplyActionsOptions} from '@sanity/sdk'
3
- import {AuthProvider} from '@sanity/sdk'
4
- import {AuthState} from '@sanity/sdk'
5
- import {ClientOptions} from '@sanity/sdk'
6
- import {CurrentUser} from '@sanity/sdk'
7
- import {DocumentAction} from '@sanity/sdk'
8
- import {DocumentEvent} from '@sanity/sdk'
9
- import {DocumentHandle} from '@sanity/sdk'
10
- import {FrameMessage} from '@sanity/sdk'
11
- import {JsonMatch} from '@sanity/sdk'
12
- import {JsonMatchPath} from '@sanity/sdk'
13
- import {Observable} from 'rxjs'
14
- import {PermissionsResult} from '@sanity/sdk'
15
- import {PreviewValue} from '@sanity/sdk'
16
- import {QueryOptions} from '@sanity/sdk'
17
- import {Requester} from 'get-it'
18
- import {ResourceId} from '@sanity/sdk'
19
- import {ResourceType} from '@sanity/sdk'
20
- import {SanityDocument} from '@sanity/types'
21
- import {SanityInstance} from '@sanity/sdk'
22
- import {SanityProject as SanityProject_2} from '@sanity/sdk'
23
- import {SanityUser as SanityUser_2} from '@sanity/sdk'
24
- import {SortOrderingItem} from '@sanity/types'
25
- import {ValidProjection} from '@sanity/sdk'
26
- import {WindowMessage} from '@sanity/sdk'
27
-
28
- /** @public */
29
- declare type Action =
30
- | CreateAction
31
- | ReplaceDraftAction
32
- | EditAction
33
- | DeleteAction
34
- | DiscardAction
35
- | PublishAction
36
- | UnpublishAction
37
-
38
- /** @internal */
39
- declare type AllDocumentIdsMutationOptions = BaseMutationOptions & {
40
- returnFirst: false
41
- returnDocuments: false
42
- }
43
-
44
- /** @internal */
45
- declare type AllDocumentsMutationOptions = BaseMutationOptions & {
46
- returnFirst: false
47
- returnDocuments?: true
48
- }
49
-
50
- /**
51
- * Used to tag types that is set to `any` as a temporary measure, but should be replaced with proper typings in the future
52
- * @internal
53
- */
54
- declare type Any = any
55
-
56
- /** @public */
57
- declare type AssetMetadataType =
58
- | 'location'
59
- | 'exif'
60
- | 'image'
61
- | 'palette'
62
- | 'lqip'
63
- | 'blurhash'
64
- | 'none'
65
-
66
- /** @internal */
67
- declare class AssetsClient {
68
- #private
69
- constructor(client: SanityClient, httpRequest: HttpRequest)
70
- /**
71
- * Uploads a file asset to the configured dataset
72
- *
73
- * @param assetType - Asset type (file)
74
- * @param body - Asset content - can be a browser File instance, a Blob, a Node.js Buffer instance or a Node.js ReadableStream.
75
- * @param options - Options to use for the upload
76
- */
77
- upload(
78
- assetType: 'file',
79
- body: UploadBody,
80
- options?: UploadClientConfig,
81
- ): Promise<SanityAssetDocument>
82
- /**
83
- * Uploads an image asset to the configured dataset
84
- *
85
- * @param assetType - Asset type (image)
86
- * @param body - Asset content - can be a browser File instance, a Blob, a Node.js Buffer instance or a Node.js ReadableStream.
87
- * @param options - Options to use for the upload
88
- */
89
- upload(
90
- assetType: 'image',
91
- body: UploadBody,
92
- options?: UploadClientConfig,
93
- ): Promise<SanityImageAssetDocument>
94
- /**
95
- * Uploads a file or an image asset to the configured dataset
96
- *
97
- * @param assetType - Asset type (file/image)
98
- * @param body - Asset content - can be a browser File instance, a Blob, a Node.js Buffer instance or a Node.js ReadableStream.
99
- * @param options - Options to use for the upload
100
- */
101
- upload(
102
- assetType: 'file' | 'image',
103
- body: UploadBody,
104
- options?: UploadClientConfig,
105
- ): Promise<SanityAssetDocument | SanityImageAssetDocument>
106
- }
107
-
108
- /** @internal */
109
- declare type AttributeSet = {
110
- [key: string]: Any
111
- }
112
-
113
- /** @internal */
114
- declare type BaseActionOptions = RequestOptions & {
115
- transactionId?: string
116
- skipCrossDatasetReferenceValidation?: boolean
117
- dryRun?: boolean
118
- }
119
-
120
- /** @internal */
121
- declare type BaseMutationOptions = RequestOptions & {
122
- visibility?: 'sync' | 'async' | 'deferred'
123
- returnDocuments?: boolean
124
- returnFirst?: boolean
125
- dryRun?: boolean
126
- autoGenerateArrayKeys?: boolean
127
- skipCrossDatasetReferenceValidation?: boolean
128
- transactionId?: string
129
- }
130
-
131
- /** @internal */
132
- declare class BasePatch {
133
- protected selection: PatchSelection
134
- protected operations: PatchOperations
135
- constructor(selection: PatchSelection, operations?: PatchOperations)
136
- /**
137
- * Sets the given attributes to the document. Does NOT merge objects.
138
- * The operation is added to the current patch, ready to be commited by `commit()`
139
- *
140
- * @param attrs - Attributes to set. To set a deep attribute, use JSONMatch, eg: \{"nested.prop": "value"\}
141
- */
142
- set(attrs: AttributeSet): this
143
- /**
144
- * Sets the given attributes to the document if they are not currently set. Does NOT merge objects.
145
- * The operation is added to the current patch, ready to be commited by `commit()`
146
- *
147
- * @param attrs - Attributes to set. To set a deep attribute, use JSONMatch, eg: \{"nested.prop": "value"\}
148
- */
149
- setIfMissing(attrs: AttributeSet): this
150
- /**
151
- * Performs a "diff-match-patch" operation on the string attributes provided.
152
- * The operation is added to the current patch, ready to be commited by `commit()`
153
- *
154
- * @param attrs - Attributes to perform operation on. To set a deep attribute, use JSONMatch, eg: \{"nested.prop": "dmp"\}
155
- */
156
- diffMatchPatch(attrs: AttributeSet): this
157
- /**
158
- * Unsets the attribute paths provided.
159
- * The operation is added to the current patch, ready to be commited by `commit()`
160
- *
161
- * @param attrs - Attribute paths to unset.
162
- */
163
- unset(attrs: string[]): this
164
- /**
165
- * Increment a numeric value. Each entry in the argument is either an attribute or a JSON path. The value may be a positive or negative integer or floating-point value. The operation will fail if target value is not a numeric value, or doesn't exist.
166
- *
167
- * @param attrs - Object of attribute paths to increment, values representing the number to increment by.
168
- */
169
- inc(attrs: {[key: string]: number}): this
170
- /**
171
- * Decrement a numeric value. Each entry in the argument is either an attribute or a JSON path. The value may be a positive or negative integer or floating-point value. The operation will fail if target value is not a numeric value, or doesn't exist.
172
- *
173
- * @param attrs - Object of attribute paths to decrement, values representing the number to decrement by.
174
- */
175
- dec(attrs: {[key: string]: number}): this
176
- /**
177
- * Provides methods for modifying arrays, by inserting, appending and replacing elements via a JSONPath expression.
178
- *
179
- * @param at - Location to insert at, relative to the given selector, or 'replace' the matched path
180
- * @param selector - JSONPath expression, eg `comments[-1]` or `blocks[_key=="abc123"]`
181
- * @param items - Array of items to insert/replace
182
- */
183
- insert(at: 'before' | 'after' | 'replace', selector: string, items: Any[]): this
184
- /**
185
- * Append the given items to the array at the given JSONPath
186
- *
187
- * @param selector - Attribute/path to append to, eg `comments` or `person.hobbies`
188
- * @param items - Array of items to append to the array
189
- */
190
- append(selector: string, items: Any[]): this
191
- /**
192
- * Prepend the given items to the array at the given JSONPath
193
- *
194
- * @param selector - Attribute/path to prepend to, eg `comments` or `person.hobbies`
195
- * @param items - Array of items to prepend to the array
196
- */
197
- prepend(selector: string, items: Any[]): this
198
- /**
199
- * Change the contents of an array by removing existing elements and/or adding new elements.
200
- *
201
- * @param selector - Attribute or JSONPath expression for array
202
- * @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
203
- * @param deleteCount - An integer indicating the number of old array elements to remove.
204
- * @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.
205
- */
206
- splice(selector: string, start: number, deleteCount?: number, items?: Any[]): this
207
- /**
208
- * Adds a revision clause, preventing the document from being patched if the `_rev` property does not match the given value
209
- *
210
- * @param rev - Revision to lock the patch to
211
- */
212
- ifRevisionId(rev: string): this
213
- /**
214
- * Return a plain JSON representation of the patch
215
- */
216
- serialize(): PatchMutationOperation
217
- /**
218
- * Return a plain JSON representation of the patch
219
- */
220
- toJSON(): PatchMutationOperation
221
- /**
222
- * Clears the patch of all operations
223
- */
224
- reset(): this
225
- protected _assign(op: keyof PatchOperations, props: Any, merge?: boolean): this
226
- protected _set(op: keyof PatchOperations, props: Any): this
227
- }
228
-
229
- /** @internal */
230
- declare class BaseTransaction {
231
- protected operations: Mutation[]
232
- protected trxId?: string
233
- constructor(operations?: Mutation[], transactionId?: string)
234
- /**
235
- * Creates a new Sanity document. If `_id` is provided and already exists, the mutation will fail. If no `_id` is given, one will automatically be generated by the database.
236
- * The operation is added to the current transaction, ready to be commited by `commit()`
237
- *
238
- * @param doc - Document to create. Requires a `_type` property.
239
- */
240
- create<R extends Record<string, Any> = Record<string, Any>>(doc: SanityDocumentStub<R>): this
241
- /**
242
- * Creates a new Sanity document. If a document with the same `_id` already exists, the create operation will be ignored.
243
- * The operation is added to the current transaction, ready to be commited by `commit()`
244
- *
245
- * @param doc - Document to create if it does not already exist. Requires `_id` and `_type` properties.
246
- */
247
- createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(
248
- doc: IdentifiedSanityDocumentStub<R>,
249
- ): this
250
- /**
251
- * Creates a new Sanity document, or replaces an existing one if the same `_id` is already used.
252
- * The operation is added to the current transaction, ready to be commited by `commit()`
253
- *
254
- * @param doc - Document to create or replace. Requires `_id` and `_type` properties.
255
- */
256
- createOrReplace<R extends Record<string, Any> = Record<string, Any>>(
257
- doc: IdentifiedSanityDocumentStub<R>,
258
- ): this
259
- /**
260
- * Deletes the document with the given document ID
261
- * The operation is added to the current transaction, ready to be commited by `commit()`
262
- *
263
- * @param documentId - Document ID to delete
264
- */
265
- delete(documentId: string): this
266
- /**
267
- * Gets the current transaction ID, if any
268
- */
269
- transactionId(): string | undefined
270
- /**
271
- * Set the ID of this transaction.
272
- *
273
- * @param id - Transaction ID
274
- */
275
- transactionId(id: string): this
276
- /**
277
- * Return a plain JSON representation of the transaction
278
- */
279
- serialize(): Mutation[]
280
- /**
281
- * Return a plain JSON representation of the transaction
282
- */
283
- toJSON(): Mutation[]
284
- /**
285
- * Clears the transaction of all operations
286
- */
287
- reset(): this
288
- protected _add(mut: Mutation): this
289
- }
290
-
291
- /**
292
- * An error occurred. This is different from a network-level error (which will be emitted as 'error').
293
- * Possible causes are things such as malformed filters, non-existant datasets or similar.
294
- *
295
- * @public
296
- */
297
- declare type ChannelErrorEvent = {
298
- type: 'channelError'
299
- message: string
300
- }
301
-
302
- /** @public */
303
- declare interface ClientConfig {
304
- projectId?: string
305
- dataset?: string
306
- /** @defaultValue true */
307
- useCdn?: boolean
308
- token?: string
309
- /**
310
- * What perspective to use for the client. See {@link https://www.sanity.io/docs/perspectives|perspective documentation}
311
- * @remarks
312
- * As of API version `v2025-02-19`, the default perspective has changed from `raw` to `published`. {@link https://www.sanity.io/changelog/676aaa9d-2da6-44fb-abe5-580f28047c10|Changelog}
313
- * @defaultValue 'published'
314
- */
315
- perspective?: ClientPerspective
316
- apiHost?: string
317
- /**
318
- @remarks
319
- * As of API version `v2025-02-19`, the default perspective has changed from `raw` to `published`. {@link https://www.sanity.io/changelog/676aaa9d-2da6-44fb-abe5-580f28047c10|Changelog}
320
- */
321
- apiVersion?: string
322
- proxy?: string
323
- /**
324
- * Optional request tag prefix for all request tags
325
- */
326
- requestTagPrefix?: string
327
- ignoreBrowserTokenWarning?: boolean
328
- withCredentials?: boolean
329
- allowReconfigure?: boolean
330
- timeout?: number
331
- /** Number of retries for requests. Defaults to 5. */
332
- maxRetries?: number
333
- /**
334
- * The amount of time, in milliseconds, to wait before retrying, given an attemptNumber (starting at 0).
335
- *
336
- * Defaults to exponential back-off, starting at 100ms, doubling for each attempt, together with random
337
- * jitter between 0 and 100 milliseconds. More specifically the following algorithm is used:
338
- *
339
- * Delay = 100 * 2^attemptNumber + randomNumberBetween0and100
340
- */
341
- retryDelay?: (attemptNumber: number) => number
342
- /**
343
- * @deprecated Don't use
344
- */
345
- useProjectHostname?: boolean
346
- /**
347
- * @deprecated Don't use
348
- */
349
- requester?: Requester
350
- /**
351
- * Adds a `resultSourceMap` key to the API response, with the type `ContentSourceMap`
352
- */
353
- resultSourceMap?: boolean | 'withKeyArraySelector'
354
- /**
355
- *@deprecated set `cache` and `next` options on `client.fetch` instead
356
- */
357
- fetch?:
358
- | {
359
- cache?: ResponseQueryOptions['cache']
360
- next?: ResponseQueryOptions['next']
361
- }
362
- | boolean
363
- /**
364
- * Options for how, if enabled, Content Source Maps are encoded into query results using steganography
365
- */
366
- stega?: StegaConfig | boolean
367
- }
368
-
369
- /** @public */
370
- declare type ClientPerspective =
371
- | DeprecatedPreviewDrafts
372
- | 'published'
373
- | 'drafts'
374
- | 'raw'
375
- | StackablePerspective[]
376
-
377
- /** @public */
378
- declare type ClientReturn<
379
- GroqString extends string,
380
- Fallback = Any,
381
- > = GroqString extends keyof SanityQueries ? SanityQueries[GroqString] : Fallback
382
-
383
- /** @public */
384
- declare interface ContentSourceMap {
385
- mappings: ContentSourceMapMappings
386
- documents: ContentSourceMapDocuments_2
387
- paths: ContentSourceMapPaths
388
- }
389
-
390
- /** @public */
391
- declare interface ContentSourceMapDocument extends ContentSourceMapDocumentBase {
392
- _projectId?: undefined
393
- _dataset?: undefined
394
- }
395
-
396
- /** @public */
397
- declare interface ContentSourceMapDocument_2 extends ContentSourceMapDocumentBase_2 {
398
- _projectId?: undefined
399
- _dataset?: undefined
400
- }
401
-
402
- /** @public */
403
- declare interface ContentSourceMapDocumentBase {
404
- _id: string
405
- _type: string
406
- }
407
-
408
- /** @public */
409
- declare interface ContentSourceMapDocumentBase_2 {
410
- _id: string
411
- _type: string
412
- }
413
-
414
- /** @public */
415
- declare type ContentSourceMapDocuments = (
416
- | ContentSourceMapDocument
417
- | ContentSourceMapRemoteDocument
418
- )[]
419
-
420
- /** @public */
421
- declare type ContentSourceMapDocuments_2 = (
422
- | ContentSourceMapDocument_2
423
- | ContentSourceMapRemoteDocument_2
424
- )[]
425
-
426
- /**
427
- * DocumentValueSource is a path to a value within a document
428
- * @public
429
- */
430
- declare interface ContentSourceMapDocumentValueSource {
431
- type: 'documentValue'
432
- document: number
433
- path: number
434
- }
435
-
436
- /**
437
- * When a value is not from a source, its a literal
438
- * @public
439
- */
440
- declare interface ContentSourceMapLiteralSource {
441
- type: 'literal'
442
- }
443
-
444
- /** @public */
445
- declare type ContentSourceMapMapping = ContentSourceMapValueMapping
446
-
447
- /** @public */
448
- declare type ContentSourceMapMappings = Record<string, ContentSourceMapMapping>
449
-
450
- /** @alpha */
451
- declare type ContentSourceMapParsedPath = (
452
- | string
453
- | number
454
- | ContentSourceMapParsedPathKeyedSegment
455
- )[]
456
-
457
- /** @alpha */
458
- declare type ContentSourceMapParsedPathKeyedSegment = {
459
- _key: string
460
- _index: number
461
- }
462
-
463
- /** @public */
464
- declare type ContentSourceMapPaths = string[]
465
-
466
- /** @public */
467
- declare interface ContentSourceMapRemoteDocument extends ContentSourceMapDocumentBase {
468
- _projectId: string
469
- _dataset: string
470
- }
471
-
472
- /** @public */
473
- declare interface ContentSourceMapRemoteDocument_2 extends ContentSourceMapDocumentBase_2 {
474
- _projectId: string
475
- _dataset: string
476
- }
477
-
478
- /** @public */
479
- declare type ContentSourceMapSource =
480
- | ContentSourceMapDocumentValueSource
481
- | ContentSourceMapLiteralSource
482
- | ContentSourceMapUnknownSource
483
-
484
- /**
485
- * When a field source is unknown
486
- * @public
487
- */
488
- declare interface ContentSourceMapUnknownSource {
489
- type: 'unknown'
490
- }
491
-
492
- /**
493
- * ValueMapping is a mapping when for value that is from a single source value
494
- * It may refer to a field within a document or a literal value
495
- * @public
496
- */
497
- declare interface ContentSourceMapValueMapping {
498
- type: 'value'
499
- source: ContentSourceMapSource
500
- }
501
-
502
- /**
503
- * Creates a new draft document. The published version of the document must not already exist.
504
- * If the draft version of the document already exists the action will fail by default, but
505
- * this can be adjusted to instead leave the existing document in place.
506
- *
507
- * @public
508
- */
509
- declare type CreateAction = {
510
- actionType: 'sanity.action.document.create'
511
- /**
512
- * ID of the published document to create a draft for.
513
- */
514
- publishedId: string
515
- /**
516
- * Document to create. Requires a `_type` property.
517
- */
518
- attributes: IdentifiedSanityDocumentStub
519
- /**
520
- * ifExists controls what to do if the draft already exists
521
- */
522
- ifExists: 'fail' | 'ignore'
523
- }
524
-
525
- /** @public */
526
- declare interface CurrentSanityUser {
527
- id: string
528
- name: string
529
- email: string
530
- profileImage: string | null
531
- role: string
532
- }
533
-
534
- export {CurrentUser}
535
-
536
- /** @public */
537
- declare type DatasetAclMode = 'public' | 'private' | 'custom'
538
-
539
- /** @public */
540
- declare type DatasetResponse = {
541
- datasetName: string
542
- aclMode: DatasetAclMode
543
- }
544
-
545
- /** @internal */
546
- declare class DatasetsClient {
547
- #private
548
- constructor(client: SanityClient, httpRequest: HttpRequest)
549
- /**
550
- * Create a new dataset with the given name
551
- *
552
- * @param name - Name of the dataset to create
553
- * @param options - Options for the dataset
554
- */
555
- create(
556
- name: string,
557
- options?: {
558
- aclMode?: DatasetAclMode
559
- },
560
- ): Promise<DatasetResponse>
561
- /**
562
- * Edit a dataset with the given name
563
- *
564
- * @param name - Name of the dataset to edit
565
- * @param options - New options for the dataset
566
- */
567
- edit(
568
- name: string,
569
- options?: {
570
- aclMode?: DatasetAclMode
571
- },
572
- ): Promise<DatasetResponse>
573
- /**
574
- * Delete a dataset with the given name
575
- *
576
- * @param name - Name of the dataset to delete
577
- */
578
- delete(name: string): Promise<{
579
- deleted: true
580
- }>
581
- /**
582
- * Fetch a list of datasets for the configured project
583
- */
584
- list(): Promise<DatasetsResponse>
585
- }
586
-
587
- /** @public */
588
- export declare type DatasetsResponse = {
589
- name: string
590
- aclMode: DatasetAclMode
591
- createdAt: string
592
- createdByUserId: string
593
- addonFor: string | null
594
- datasetProfile: string
595
- features: string[]
596
- tags: string[]
597
- }[]
598
-
599
- /**
600
- * Deletes the published version of a document and optionally some (likely all known) draft versions.
601
- * If any draft version exists that is not specified for deletion this is an error.
602
- * If the purge flag is set then the document history is also deleted.
603
- *
604
- * @public
605
- */
606
- declare type DeleteAction = {
607
- actionType: 'sanity.action.document.delete'
608
- /**
609
- * Published document ID to delete
610
- */
611
- publishedId: string
612
- /**
613
- * Draft document ID to delete
614
- */
615
- includeDrafts: string[]
616
- /**
617
- * Delete document history
618
- */
619
- purge?: boolean
620
- }
621
-
622
- /**
623
- * @deprecated use 'drafts' instead
624
- */
625
- declare type DeprecatedPreviewDrafts = 'previewDrafts'
626
-
627
- /**
628
- * Delete the draft version of a document.
629
- * It is an error if it does not exist. If the purge flag is set, the document history is also deleted.
630
- *
631
- * @public
632
- */
633
- declare type DiscardAction = {
634
- actionType: 'sanity.action.document.discard'
635
- /**
636
- * Draft document ID to delete
637
- */
638
- draftId: string
639
- /**
640
- * Delete document history
641
- */
642
- purge?: boolean
643
- }
644
-
645
- /**
646
- * The listener has been told to explicitly disconnect and not reconnect.
647
- * This is a rare situation, but may occur if the API knows reconnect attempts will fail,
648
- * eg in the case of a deleted dataset, a blocked project or similar events.
649
- *
650
- * Note that this is not treated as an error on the observable, but will complete the observable.
651
- *
652
- * @public
653
- */
654
- declare type DisconnectEvent = {
655
- type: 'disconnect'
656
- reason: string
657
- }
658
-
659
- export {DocumentHandle}
660
-
661
- /**
662
- * Modifies an existing draft document.
663
- * It applies the given patch to the document referenced by draftId.
664
- * If there is no such document then one is created using the current state of the published version and then that is updated accordingly.
665
- *
666
- * @public
667
- */
668
- declare type EditAction = {
669
- actionType: 'sanity.action.document.edit'
670
- /**
671
- * Draft document ID to edit
672
- */
673
- draftId: string
674
- /**
675
- * Published document ID to create draft from, if draft does not exist
676
- */
677
- publishedId: string
678
- /**
679
- * Patch operations to apply
680
- */
681
- patch: PatchOperations
682
- }
683
-
684
- /** @public */
685
- declare type FilterDefault = (props: {
686
- /**
687
- * The path to the value in the source document, for example if you queried for a document like this:
688
- * `*[_type == "author"][0]{"slug": slug.current}`
689
- * Then the `sourcePath` for `result.slug` would be `['slug', 'current']`.
690
- *
691
- */
692
- sourcePath: ContentSourceMapParsedPath
693
- /**
694
- * If `sourcePath` alone isn't enough to tell you if it's safe to contain stega strings, then you can use `sourceDocument`
695
- * for additional metadata.
696
- * It'll always have a `_type` property, which can be used to trace it to the Studio Schema that were used initially.
697
- * It also has `_id` to help you debug and look at the whole document when troubleshooting.
698
- * Finally, if the document origins in a Cross Dataset Reference you'll also have `_projectId` and `_dataset` properties to help you trace it.
699
- */
700
- sourceDocument: ContentSourceMapDocuments[number]
701
- /**
702
- * If you don't colocate your Studio Schemas with your GROQ queries it might be hard to make sense of `sourcePath`,
703
- * as it operates on the original shape of a document.
704
- * In that case `resultPath` can be used, as it mirrors the path to the value in the result.
705
- * For example in a query like this:
706
- * `*[_type == "author"][0]{"slug": slug.current}`
707
- * The `resultPath` for `result.slug` would be `['slug']`, while `sourcePath` will be `['slug', 'current']`.
708
- */
709
- resultPath: ContentSourceMapParsedPath
710
- /**
711
- * You can also use your own string validation logic to determine if it's safe.
712
- */
713
- value: string
714
- /**
715
- * If you want to keep the default filtering behavior, but only override it for a specific path, you can use `filterDefault` to do that.
716
- * For example, here all "icon" documents in a Page Builder skips encoding:
717
- * ```ts
718
- {
719
- filter: (props) => {
720
- switch (props.sourceDocument._type) {
721
- case 'icon':
722
- return false
723
- default:
724
- return props.filterDefault(props)
725
- }
726
- }
727
- }
728
- * ```
729
- */
730
- filterDefault: FilterDefault
731
- }) => boolean
732
-
733
- /** @public */
734
- declare interface FilteredResponseQueryOptions extends ResponseQueryOptions {
735
- filterResponse?: true
736
- }
737
-
738
- /** @internal */
739
- declare type FirstDocumentIdMutationOptions = BaseMutationOptions & {
740
- returnFirst?: true
741
- returnDocuments: false
742
- }
743
-
744
- /** @internal */
745
- declare type FirstDocumentMutationOptions = BaseMutationOptions & {
746
- returnFirst?: true
747
- returnDocuments?: true
748
- }
749
-
750
- /**
751
- * @internal
752
- */
753
- export declare interface FrameConnection<TFrameMessage extends FrameMessage> {
754
- connect: (frameWindow: Window) => () => void
755
- sendMessage: <T extends TFrameMessage['type']>(
756
- ...params: Extract<
757
- TFrameMessage,
758
- {
759
- type: T
760
- }
761
- >['data'] extends undefined
762
- ? [type: T]
763
- : [
764
- type: T,
765
- data: Extract<
766
- TFrameMessage,
767
- {
768
- type: T
769
- }
770
- >['data'],
771
- ]
772
- ) => void
773
- status: Status
774
- }
775
-
776
- /** @public */
777
- declare type HttpRequest = {
778
- (options: RequestOptions, requester: Requester): ReturnType<Requester>
779
- }
780
-
781
- /** @public */
782
- declare type HttpRequestEvent<T = unknown> = ResponseEvent<T> | ProgressEvent_2
783
-
784
- /** @public */
785
- declare type IdentifiedSanityDocumentStub<T extends Record<string, Any> = Record<string, Any>> = {
786
- [P in keyof T]: T[P]
787
- } & {
788
- _id: string
789
- } & SanityDocumentStub
790
-
791
- /**
792
- * Return value from the useInfiniteList hook
793
- *
794
- * @beta
795
- * @category Types
796
- */
797
- export declare interface InfiniteList {
798
- /**
799
- * Array of document handles for the current batch
800
- */
801
- data: DocumentHandle[]
802
- /**
803
- * Whether there are more items available to load
804
- */
805
- hasMore: boolean
806
- /**
807
- * Total count of items matching the query
808
- */
809
- count: number
810
- /**
811
- * Whether a query is currently in progress
812
- */
813
- isPending: boolean
814
- /**
815
- * Function to load the next batch of results
816
- */
817
- loadMore: () => void
818
- }
819
-
820
- /**
821
- * Configuration options for the useInfiniteList hook
822
- *
823
- * @beta
824
- * @category Types
825
- */
826
- export declare interface InfiniteListOptions extends QueryOptions {
827
- /**
828
- * GROQ filter expression to apply to the query
829
- */
830
- filter?: string
831
- /**
832
- * Number of items to load per batch (defaults to 25)
833
- */
834
- batchSize?: number
835
- /**
836
- * Sorting configuration for the results
837
- */
838
- orderings?: SortOrderingItem[]
839
- /**
840
- * Text search query to filter results
841
- */
842
- search?: string
843
- }
844
-
845
- /** @public */
846
- declare interface InitializedClientConfig extends ClientConfig {
847
- apiHost: string
848
- apiVersion: string
849
- useProjectHostname: boolean
850
- useCdn: boolean
851
- /**
852
- * @deprecated Internal, don't use
853
- */
854
- isDefaultApi: boolean
855
- /**
856
- * @deprecated Internal, don't use
857
- */
858
- url: string
859
- /**
860
- * @deprecated Internal, don't use
861
- */
862
- cdnUrl: string
863
- /**
864
- * The fully initialized stega config, can be used to check if stega is enabled
865
- */
866
- stega: InitializedStegaConfig
867
- }
868
-
869
- /** @public */
870
- declare type InitializedStegaConfig = Omit<StegaConfig, StegaConfigRequiredKeys> &
871
- Required<Pick<StegaConfig, StegaConfigRequiredKeys>>
872
-
873
- /** @internal */
874
- declare type InsertPatch =
875
- | {
876
- before: string
877
- items: Any[]
878
- }
879
- | {
880
- after: string
881
- items: Any[]
882
- }
883
- | {
884
- replace: string
885
- items: Any[]
886
- }
887
-
888
- /**
889
- * Set up a listener that will be notified when mutations occur on documents matching the provided query/filter.
890
- *
891
- * @param query - GROQ-filter to listen to changes for
892
- * @param params - Optional query parameters
893
- * @param options - Optional listener options
894
- * @public
895
- */
896
- declare function _listen<R extends Record<string, Any> = Record<string, Any>>(
897
- this: SanityClient | ObservableSanityClient,
898
- query: string,
899
- params?: ListenParams,
900
- ): Observable<MutationEvent_2<R>>
901
-
902
- /**
903
- * Set up a listener that will be notified when mutations occur on documents matching the provided query/filter.
904
- *
905
- * @param query - GROQ-filter to listen to changes for
906
- * @param params - Optional query parameters
907
- * @param options - Optional listener options
908
- * @public
909
- */
910
- declare function _listen<R extends Record<string, Any> = Record<string, Any>>(
911
- this: SanityClient | ObservableSanityClient,
912
- query: string,
913
- params?: ListenParams,
914
- options?: ListenOptions,
915
- ): Observable<ListenEvent<R>>
916
-
917
- /** @public */
918
- declare type ListenEvent<R extends Record<string, Any>> =
919
- | MutationEvent_2<R>
920
- | ChannelErrorEvent
921
- | DisconnectEvent
922
- | ReconnectEvent
923
- | WelcomeEvent
924
- | OpenEvent
925
-
926
- /** @public */
927
- declare type ListenEventName =
928
- /** A mutation was performed */
929
- | 'mutation'
930
- /** The listener has been (re)established */
931
- | 'welcome'
932
- /** The listener has been disconnected, and a reconnect attempt is scheduled */
933
- | 'reconnect'
934
-
935
- /** @public */
936
- declare interface ListenOptions {
937
- /**
938
- * Whether or not to include the resulting document in addition to the mutations performed.
939
- * If you do not need the actual document, set this to `false` to reduce bandwidth usage.
940
- * The result will be available on the `.result` property of the events.
941
- * @defaultValue `true`
942
- */
943
- includeResult?: boolean
944
- /**
945
- * Whether or not to include the mutations that was performed.
946
- * If you do not need the mutations, set this to `false` to reduce bandwidth usage.
947
- * @defaultValue `true`
948
- */
949
- includeMutations?: boolean
950
- /**
951
- * Whether or not to include the document as it looked before the mutation event.
952
- * The previous revision will be available on the `.previous` property of the events,
953
- * and may be `null` in the case of a new document.
954
- * @defaultValue `false`
955
- */
956
- includePreviousRevision?: boolean
957
- /**
958
- * Whether to include events for drafts and versions. As of API Version >= v2025-02-19, only events
959
- * for published documents will be included by default (see {@link https://www.sanity.io/changelog/676aaa9d-2da6-44fb-abe5-580f28047c10|Changelog})
960
- * If you need events from drafts and versions, set this to `true`.
961
- * Note: Keep in mind that additional document variants may be introduced in the future, so it's
962
- * recommended to respond to events in a way that's tolerant of potential future variants, e.g. by
963
- * explicitly checking whether the event is for a draft or a version.
964
- * @defaultValue `false`
965
- */
966
- includeAllVersions?: boolean
967
- /**
968
- * Whether events should be sent as soon as a transaction has been committed (`transaction`, default),
969
- * or only after they are available for queries (query). Note that this is on a best-effort basis,
970
- * and listeners with `query` may in certain cases (notably with deferred transactions) receive events
971
- * that are not yet visible to queries.
972
- *
973
- * @defaultValue `'transaction'`
974
- */
975
- visibility?: 'transaction' | 'query'
976
- /**
977
- * Array of event names to include in the observable. By default, only mutation events are included.
978
- *
979
- * @defaultValue `['mutation']`
980
- */
981
- events?: ListenEventName[]
982
- /**
983
- * Format of "effects", eg the resulting changes of a mutation.
984
- * Currently only `mendoza` is supported, and (if set) will include `apply` and `revert` arrays
985
- * in the mutation events under the `effects` property.
986
- *
987
- * See {@link https://github.com/sanity-io/mendoza | The mendoza docs} for more info
988
- *
989
- * @defaultValue `undefined`
990
- */
991
- effectFormat?: 'mendoza'
992
- /**
993
- * Optional request tag for the listener. Use to identify the request in logs.
994
- *
995
- * @defaultValue `undefined`
996
- */
997
- tag?: string
998
- }
999
-
1000
- /** @public */
1001
- declare type ListenParams = {
1002
- [key: string]: Any
1003
- }
1004
-
1005
- /**
1006
- * @public
1007
- */
1008
- declare class LiveClient {
1009
- #private
1010
- constructor(client: SanityClient | ObservableSanityClient)
1011
- /**
1012
- * Requires `apiVersion` to be `2021-03-25` or later.
1013
- */
1014
- events({
1015
- includeDrafts,
1016
- tag: _tag,
1017
- }?: {
1018
- includeDrafts?: boolean
1019
- /**
1020
- * Optional request tag for the listener. Use to identify the request in logs.
1021
- *
1022
- * @defaultValue `undefined`
1023
- */
1024
- tag?: string
1025
- }): Observable<LiveEvent>
1026
- }
1027
-
1028
- /** @public */
1029
- declare type LiveEvent = LiveEventRestart | LiveEventReconnect | LiveEventMessage | LiveEventWelcome
1030
-
1031
- /** @public */
1032
- declare interface LiveEventMessage {
1033
- type: 'message'
1034
- id: string
1035
- tags: SyncTag[]
1036
- }
1037
-
1038
- /** @public */
1039
- declare interface LiveEventReconnect {
1040
- type: 'reconnect'
1041
- }
1042
-
1043
- /** @public */
1044
- declare interface LiveEventRestart {
1045
- type: 'restart'
1046
- id: string
1047
- }
1048
-
1049
- /** @public */
1050
- declare interface LiveEventWelcome {
1051
- type: 'welcome'
1052
- }
1053
-
1054
- /** @public */
1055
- declare type Logger =
1056
- | typeof console
1057
- | Partial<
1058
- Pick<typeof console, 'debug' | 'error' | 'groupCollapsed' | 'groupEnd' | 'log' | 'table'>
1059
- >
1060
-
1061
- /**
1062
- * @internal
1063
- */
1064
- export declare type MessageHandler<TWindowMessage extends WindowMessage> = (
1065
- event: TWindowMessage['data'],
1066
- ) => TWindowMessage['response'] | Promise<TWindowMessage['response']>
1067
-
1068
- /** @internal */
1069
- declare interface MultipleActionResult {
1070
- transactionId: string
1071
- }
1072
-
1073
- /** @internal */
1074
- declare interface MultipleMutationResult {
1075
- transactionId: string
1076
- documentIds: string[]
1077
- results: {
1078
- id: string
1079
- operation: MutationOperation
1080
- }[]
1081
- }
1082
-
1083
- /** @public */
1084
- declare type Mutation<R extends Record<string, Any> = Record<string, Any>> =
1085
- | {
1086
- create: SanityDocumentStub<R>
1087
- }
1088
- | {
1089
- createOrReplace: IdentifiedSanityDocumentStub<R>
1090
- }
1091
- | {
1092
- createIfNotExists: IdentifiedSanityDocumentStub<R>
1093
- }
1094
- | {
1095
- delete: MutationSelection
1096
- }
1097
- | {
1098
- patch: PatchMutationOperation
1099
- }
1100
-
1101
- /**
1102
- * A mutation was performed. Note that when updating multiple documents in a transaction,
1103
- * each document affected will get a separate mutation event.
1104
- *
1105
- * @public
1106
- */
1107
- declare type MutationEvent_2<R extends Record<string, Any> = Record<string, Any>> = {
1108
- type: 'mutation'
1109
- /**
1110
- * The ID of the document that was affected
1111
- */
1112
- documentId: string
1113
- /**
1114
- * A unique ID for this event
1115
- */
1116
- eventId: string
1117
- /**
1118
- * The user ID of the user that performed the mutation
1119
- */
1120
- identity: string
1121
- /**
1122
- * An array of mutations that were performed. Note that this can differ slightly from the
1123
- * mutations sent to the server, as the server may perform some mutations automatically.
1124
- */
1125
- mutations: Mutation[]
1126
- /**
1127
- * The revision ID of the document before the mutation was performed
1128
- */
1129
- previousRev?: string
1130
- /**
1131
- * The revision ID of the document after the mutation was performed
1132
- */
1133
- resultRev?: string
1134
- /**
1135
- * The document as it looked after the mutation was performed. This is only included if
1136
- * the listener was configured with `includeResult: true`.
1137
- */
1138
- result?: SanityDocument_2<R>
1139
- /**
1140
- * The document as it looked before the mutation was performed. This is only included if
1141
- * the listener was configured with `includePreviousRevision: true`.
1142
- */
1143
- previous?: SanityDocument_2<R> | null
1144
- /**
1145
- * The effects of the mutation, if the listener was configured with `effectFormat: 'mendoza'`.
1146
- * Object with `apply` and `revert` arrays, see {@link https://github.com/sanity-io/mendoza}.
1147
- */
1148
- effects?: {
1149
- apply: unknown[]
1150
- revert: unknown[]
1151
- }
1152
- /**
1153
- * A timestamp for when the mutation was performed
1154
- */
1155
- timestamp: string
1156
- /**
1157
- * The transaction ID for the mutation
1158
- */
1159
- transactionId: string
1160
- /**
1161
- * The type of transition the document went through.
1162
- *
1163
- * - `update` means the document was previously part of the subscribed set of documents,
1164
- * and still is.
1165
- * - `appear` means the document was not previously part of the subscribed set of documents,
1166
- * but is now. This can happen both on create or if updating to a state where it now matches
1167
- * the filter provided to the listener.
1168
- * - `disappear` means the document was previously part of the subscribed set of documents,
1169
- * but is no longer. This can happen both on delete or if updating to a state where it no
1170
- * longer matches the filter provided to the listener.
1171
- */
1172
- transition: 'update' | 'appear' | 'disappear'
1173
- /**
1174
- * Whether the change that triggered this event is visible to queries (query) or only to
1175
- * subsequent transactions (transaction). The listener client can specify a preferred visibility
1176
- * through the `visibility` parameter on the listener, but this is only on a best-effort basis,
1177
- * and may yet not be accurate.
1178
- */
1179
- visibility: 'query' | 'transaction'
1180
- /**
1181
- * The total number of events that will be sent for this transaction.
1182
- * Note that this may differ from the amount of _documents_ affected by the transaction, as this
1183
- * number only includes the documents that matches the given filter.
1184
- *
1185
- * This can be useful if you need to perform changes to all matched documents atomically,
1186
- * eg you would wait for `transactionTotalEvents` events with the same `transactionId` before
1187
- * applying the changes locally.
1188
- */
1189
- transactionTotalEvents: number
1190
- /**
1191
- * The index of this event within the transaction. Note that events may be delivered out of order,
1192
- * and that the index is zero-based.
1193
- */
1194
- transactionCurrentEvent: number
1195
- }
1196
-
1197
- /** @internal */
1198
- declare type MutationOperation = 'create' | 'delete' | 'update' | 'none'
1199
-
1200
- /** @internal */
1201
- declare type MutationSelection =
1202
- | {
1203
- query: string
1204
- params?: MutationSelectionQueryParams
1205
- }
1206
- | {
1207
- id: string | string[]
1208
- }
1209
-
1210
- /** @internal */
1211
- declare type MutationSelectionQueryParams = {
1212
- [key: string]: Any
1213
- }
1214
-
1215
- /** @internal */
1216
- declare class ObservableAssetsClient {
1217
- #private
1218
- constructor(client: ObservableSanityClient, httpRequest: HttpRequest)
1219
- /**
1220
- * Uploads a file asset to the configured dataset
1221
- *
1222
- * @param assetType - Asset type (file)
1223
- * @param body - Asset content - can be a browser File instance, a Blob, a Node.js Buffer instance or a Node.js ReadableStream.
1224
- * @param options - Options to use for the upload
1225
- */
1226
- upload(
1227
- assetType: 'file',
1228
- body: UploadBody,
1229
- options?: UploadClientConfig,
1230
- ): Observable<
1231
- HttpRequestEvent<{
1232
- document: SanityAssetDocument
1233
- }>
1234
- >
1235
- /**
1236
- * Uploads an image asset to the configured dataset
1237
- *
1238
- * @param assetType - Asset type (image)
1239
- * @param body - Asset content - can be a browser File instance, a Blob, a Node.js Buffer instance or a Node.js ReadableStream.
1240
- * @param options - Options to use for the upload
1241
- */
1242
- upload(
1243
- assetType: 'image',
1244
- body: UploadBody,
1245
- options?: UploadClientConfig,
1246
- ): Observable<
1247
- HttpRequestEvent<{
1248
- document: SanityImageAssetDocument
1249
- }>
1250
- >
1251
- /**
1252
- * Uploads a file or an image asset to the configured dataset
1253
- *
1254
- * @param assetType - Asset type (file/image)
1255
- * @param body - Asset content - can be a browser File instance, a Blob, a Node.js Buffer instance or a Node.js ReadableStream.
1256
- * @param options - Options to use for the upload
1257
- */
1258
- upload(
1259
- assetType: 'file' | 'image',
1260
- body: UploadBody,
1261
- options?: UploadClientConfig,
1262
- ): Observable<
1263
- HttpRequestEvent<{
1264
- document: SanityAssetDocument | SanityImageAssetDocument
1265
- }>
1266
- >
1267
- }
1268
-
1269
- /** @internal */
1270
- declare class ObservableDatasetsClient {
1271
- #private
1272
- constructor(client: ObservableSanityClient, httpRequest: HttpRequest)
1273
- /**
1274
- * Create a new dataset with the given name
1275
- *
1276
- * @param name - Name of the dataset to create
1277
- * @param options - Options for the dataset
1278
- */
1279
- create(
1280
- name: string,
1281
- options?: {
1282
- aclMode?: DatasetAclMode
1283
- },
1284
- ): Observable<DatasetResponse>
1285
- /**
1286
- * Edit a dataset with the given name
1287
- *
1288
- * @param name - Name of the dataset to edit
1289
- * @param options - New options for the dataset
1290
- */
1291
- edit(
1292
- name: string,
1293
- options?: {
1294
- aclMode?: DatasetAclMode
1295
- },
1296
- ): Observable<DatasetResponse>
1297
- /**
1298
- * Delete a dataset with the given name
1299
- *
1300
- * @param name - Name of the dataset to delete
1301
- */
1302
- delete(name: string): Observable<{
1303
- deleted: true
1304
- }>
1305
- /**
1306
- * Fetch a list of datasets for the configured project
1307
- */
1308
- list(): Observable<DatasetsResponse>
1309
- }
1310
-
1311
- /** @public */
1312
- declare class ObservablePatch extends BasePatch {
1313
- #private
1314
- constructor(
1315
- selection: PatchSelection,
1316
- operations?: PatchOperations,
1317
- client?: ObservableSanityClient,
1318
- )
1319
- /**
1320
- * Clones the patch
1321
- */
1322
- clone(): ObservablePatch
1323
- /**
1324
- * Commit the patch, returning an observable that produces the first patched document
1325
- *
1326
- * @param options - Options for the mutation operation
1327
- */
1328
- commit<R extends Record<string, Any> = Record<string, Any>>(
1329
- options: FirstDocumentMutationOptions,
1330
- ): Observable<SanityDocument_2<R>>
1331
- /**
1332
- * Commit the patch, returning an observable that produces an array of the mutated documents
1333
- *
1334
- * @param options - Options for the mutation operation
1335
- */
1336
- commit<R extends Record<string, Any> = Record<string, Any>>(
1337
- options: AllDocumentsMutationOptions,
1338
- ): Observable<SanityDocument_2<R>[]>
1339
- /**
1340
- * Commit the patch, returning an observable that produces a mutation result object
1341
- *
1342
- * @param options - Options for the mutation operation
1343
- */
1344
- commit(options: FirstDocumentIdMutationOptions): Observable<SingleMutationResult>
1345
- /**
1346
- * Commit the patch, returning an observable that produces a mutation result object
1347
- *
1348
- * @param options - Options for the mutation operation
1349
- */
1350
- commit(options: AllDocumentIdsMutationOptions): Observable<MultipleMutationResult>
1351
- /**
1352
- * Commit the patch, returning an observable that produces the first patched document
1353
- *
1354
- * @param options - Options for the mutation operation
1355
- */
1356
- commit<R extends Record<string, Any> = Record<string, Any>>(
1357
- options?: BaseMutationOptions,
1358
- ): Observable<SanityDocument_2<R>>
1359
- }
1360
-
1361
- /** @public */
1362
- declare type ObservablePatchBuilder = (patch: ObservablePatch) => ObservablePatch
1363
-
1364
- /** @internal */
1365
- declare class ObservableProjectsClient {
1366
- #private
1367
- constructor(client: ObservableSanityClient, httpRequest: HttpRequest)
1368
- /**
1369
- * Fetch a list of projects the authenticated user has access to.
1370
- *
1371
- * @param options - Options for the list request
1372
- * @param options.includeMembers - Whether to include members in the response (default: true)
1373
- */
1374
- list(options?: {includeMembers?: true}): Observable<SanityProject[]>
1375
- list(options?: {includeMembers?: false}): Observable<Omit<SanityProject, 'members'>[]>
1376
- /**
1377
- * Fetch a project by project ID
1378
- *
1379
- * @param projectId - ID of the project to fetch
1380
- */
1381
- getById(projectId: string): Observable<SanityProject>
1382
- }
1383
-
1384
- /** @public */
1385
- declare class ObservableSanityClient {
1386
- #private
1387
- assets: ObservableAssetsClient
1388
- datasets: ObservableDatasetsClient
1389
- live: LiveClient
1390
- projects: ObservableProjectsClient
1391
- users: ObservableUsersClient
1392
- /**
1393
- * Instance properties
1394
- */
1395
- listen: typeof _listen
1396
- constructor(httpRequest: HttpRequest, config?: ClientConfig)
1397
- /**
1398
- * Clone the client - returns a new instance
1399
- */
1400
- clone(): ObservableSanityClient
1401
- /**
1402
- * Returns the current client configuration
1403
- */
1404
- config(): InitializedClientConfig
1405
- /**
1406
- * Reconfigure the client. Note that this _mutates_ the current client.
1407
- */
1408
- config(newConfig?: Partial<ClientConfig>): this
1409
- /**
1410
- * Clone the client with a new (partial) configuration.
1411
- *
1412
- * @param newConfig - New client configuration properties, shallowly merged with existing configuration
1413
- */
1414
- withConfig(newConfig?: Partial<ClientConfig>): ObservableSanityClient
1415
- /**
1416
- * Perform a GROQ-query against the configured dataset.
1417
- *
1418
- * @param query - GROQ-query to perform
1419
- */
1420
- fetch<
1421
- R = Any,
1422
- Q extends QueryWithoutParams = QueryWithoutParams,
1423
- const G extends string = string,
1424
- >(query: G, params?: Q | QueryWithoutParams): Observable<ClientReturn<G, R>>
1425
- /**
1426
- * Perform a GROQ-query against the configured dataset.
1427
- *
1428
- * @param query - GROQ-query to perform
1429
- * @param params - Optional query parameters
1430
- * @param options - Optional request options
1431
- */
1432
- fetch<
1433
- R = Any,
1434
- Q extends QueryWithoutParams | QueryParams = QueryParams,
1435
- const G extends string = string,
1436
- >(
1437
- query: G,
1438
- params: Q extends QueryWithoutParams ? QueryWithoutParams : Q,
1439
- options?: FilteredResponseQueryOptions,
1440
- ): Observable<ClientReturn<G, R>>
1441
- /**
1442
- * Perform a GROQ-query against the configured dataset.
1443
- *
1444
- * @param query - GROQ-query to perform
1445
- * @param params - Optional query parameters
1446
- * @param options - Request options
1447
- */
1448
- fetch<
1449
- R = Any,
1450
- Q extends QueryWithoutParams | QueryParams = QueryParams,
1451
- const G extends string = string,
1452
- >(
1453
- query: string,
1454
- params: Q extends QueryWithoutParams ? QueryWithoutParams : Q,
1455
- options: UnfilteredResponseQueryOptions,
1456
- ): Observable<RawQueryResponse<ClientReturn<G, R>>>
1457
- /**
1458
- * Perform a GROQ-query against the configured dataset.
1459
- *
1460
- * @param query - GROQ-query to perform
1461
- * @param params - Optional query parameters
1462
- * @param options - Request options
1463
- */
1464
- fetch<
1465
- R = Any,
1466
- Q extends QueryWithoutParams | QueryParams = QueryParams,
1467
- const G extends string = string,
1468
- >(
1469
- query: G,
1470
- params: Q extends QueryWithoutParams ? QueryWithoutParams : Q,
1471
- options: UnfilteredResponseWithoutQuery,
1472
- ): Observable<RawQuerylessQueryResponse<ClientReturn<G, R>>>
1473
- /**
1474
- * Fetch a single document with the given ID.
1475
- *
1476
- * @param id - Document ID to fetch
1477
- * @param options - Request options
1478
- */
1479
- getDocument<R extends Record<string, Any> = Record<string, Any>>(
1480
- id: string,
1481
- options?: {
1482
- tag?: string
1483
- },
1484
- ): Observable<SanityDocument_2<R> | undefined>
1485
- /**
1486
- * Fetch multiple documents in one request.
1487
- * Should be used sparingly - performing a query is usually a better option.
1488
- * The order/position of documents is preserved based on the original array of IDs.
1489
- * If any of the documents are missing, they will be replaced by a `null` entry in the returned array
1490
- *
1491
- * @param ids - Document IDs to fetch
1492
- * @param options - Request options
1493
- */
1494
- getDocuments<R extends Record<string, Any> = Record<string, Any>>(
1495
- ids: string[],
1496
- options?: {
1497
- tag?: string
1498
- },
1499
- ): Observable<(SanityDocument_2<R> | null)[]>
1500
- /**
1501
- * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.
1502
- * Returns an observable that resolves to the created document.
1503
- *
1504
- * @param document - Document to create
1505
- * @param options - Mutation options
1506
- */
1507
- create<R extends Record<string, Any> = Record<string, Any>>(
1508
- document: SanityDocumentStub<R>,
1509
- options: FirstDocumentMutationOptions,
1510
- ): Observable<SanityDocument_2<R>>
1511
- /**
1512
- * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.
1513
- * Returns an observable that resolves to an array containing the created document.
1514
- *
1515
- * @param document - Document to create
1516
- * @param options - Mutation options
1517
- */
1518
- create<R extends Record<string, Any> = Record<string, Any>>(
1519
- document: SanityDocumentStub<R>,
1520
- options: AllDocumentsMutationOptions,
1521
- ): Observable<SanityDocument_2<R>[]>
1522
- /**
1523
- * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.
1524
- * Returns an observable that resolves to a mutation result object containing the ID of the created document.
1525
- *
1526
- * @param document - Document to create
1527
- * @param options - Mutation options
1528
- */
1529
- create<R extends Record<string, Any> = Record<string, Any>>(
1530
- document: SanityDocumentStub<R>,
1531
- options: FirstDocumentIdMutationOptions,
1532
- ): Observable<SingleMutationResult>
1533
- /**
1534
- * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.
1535
- * Returns an observable that resolves to a mutation result object containing the ID of the created document.
1536
- *
1537
- * @param document - Document to create
1538
- * @param options - Mutation options
1539
- */
1540
- create<R extends Record<string, Any> = Record<string, Any>>(
1541
- document: SanityDocumentStub<R>,
1542
- options: AllDocumentIdsMutationOptions,
1543
- ): Observable<MultipleMutationResult>
1544
- /**
1545
- * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.
1546
- * Returns an observable that resolves to the created document.
1547
- *
1548
- * @param document - Document to create
1549
- * @param options - Mutation options
1550
- */
1551
- create<R extends Record<string, Any> = Record<string, Any>>(
1552
- document: SanityDocumentStub<R>,
1553
- options?: BaseMutationOptions,
1554
- ): Observable<SanityDocument_2<R>>
1555
- /**
1556
- * Create a document if no document with the same ID already exists.
1557
- * Returns an observable that resolves to the created document.
1558
- *
1559
- * @param document - Document to create
1560
- * @param options - Mutation options
1561
- */
1562
- createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(
1563
- document: IdentifiedSanityDocumentStub<R>,
1564
- options: FirstDocumentMutationOptions,
1565
- ): Observable<SanityDocument_2<R>>
1566
- /**
1567
- * Create a document if no document with the same ID already exists.
1568
- * Returns an observable that resolves to an array containing the created document.
1569
- *
1570
- * @param document - Document to create
1571
- * @param options - Mutation options
1572
- */
1573
- createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(
1574
- document: IdentifiedSanityDocumentStub<R>,
1575
- options: AllDocumentsMutationOptions,
1576
- ): Observable<SanityDocument_2<R>[]>
1577
- /**
1578
- * Create a document if no document with the same ID already exists.
1579
- * Returns an observable that resolves to a mutation result object containing the ID of the created document.
1580
- *
1581
- * @param document - Document to create
1582
- * @param options - Mutation options
1583
- */
1584
- createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(
1585
- document: IdentifiedSanityDocumentStub<R>,
1586
- options: FirstDocumentIdMutationOptions,
1587
- ): Observable<SingleMutationResult>
1588
- /**
1589
- * Create a document if no document with the same ID already exists.
1590
- * Returns an observable that resolves to a mutation result object containing the ID of the created document.
1591
- *
1592
- * @param document - Document to create
1593
- * @param options - Mutation options
1594
- */
1595
- createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(
1596
- document: IdentifiedSanityDocumentStub<R>,
1597
- options: AllDocumentIdsMutationOptions,
1598
- ): Observable<MultipleMutationResult>
1599
- /**
1600
- * Create a document if no document with the same ID already exists.
1601
- * Returns an observable that resolves to the created document.
1602
- *
1603
- * @param document - Document to create
1604
- * @param options - Mutation options
1605
- */
1606
- createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(
1607
- document: IdentifiedSanityDocumentStub<R>,
1608
- options?: BaseMutationOptions,
1609
- ): Observable<SanityDocument_2<R>>
1610
- /**
1611
- * Create a document if it does not exist, or replace a document with the same document ID
1612
- * Returns an observable that resolves to the created document.
1613
- *
1614
- * @param document - Document to either create or replace
1615
- * @param options - Mutation options
1616
- */
1617
- createOrReplace<R extends Record<string, Any> = Record<string, Any>>(
1618
- document: IdentifiedSanityDocumentStub<R>,
1619
- options: FirstDocumentMutationOptions,
1620
- ): Observable<SanityDocument_2<R>>
1621
- /**
1622
- * Create a document if it does not exist, or replace a document with the same document ID
1623
- * Returns an observable that resolves to an array containing the created document.
1624
- *
1625
- * @param document - Document to either create or replace
1626
- * @param options - Mutation options
1627
- */
1628
- createOrReplace<R extends Record<string, Any> = Record<string, Any>>(
1629
- document: IdentifiedSanityDocumentStub<R>,
1630
- options: AllDocumentsMutationOptions,
1631
- ): Observable<SanityDocument_2<R>[]>
1632
- /**
1633
- * Create a document if it does not exist, or replace a document with the same document ID
1634
- * Returns an observable that resolves to a mutation result object containing the ID of the created document.
1635
- *
1636
- * @param document - Document to either create or replace
1637
- * @param options - Mutation options
1638
- */
1639
- createOrReplace<R extends Record<string, Any> = Record<string, Any>>(
1640
- document: IdentifiedSanityDocumentStub<R>,
1641
- options: FirstDocumentIdMutationOptions,
1642
- ): Observable<SingleMutationResult>
1643
- /**
1644
- * Create a document if it does not exist, or replace a document with the same document ID
1645
- * Returns an observable that resolves to a mutation result object containing the created document ID.
1646
- *
1647
- * @param document - Document to either create or replace
1648
- * @param options - Mutation options
1649
- */
1650
- createOrReplace<R extends Record<string, Any> = Record<string, Any>>(
1651
- document: IdentifiedSanityDocumentStub<R>,
1652
- options: AllDocumentIdsMutationOptions,
1653
- ): Observable<MultipleMutationResult>
1654
- /**
1655
- * Create a document if it does not exist, or replace a document with the same document ID
1656
- * Returns an observable that resolves to the created document.
1657
- *
1658
- * @param document - Document to either create or replace
1659
- * @param options - Mutation options
1660
- */
1661
- createOrReplace<R extends Record<string, Any> = Record<string, Any>>(
1662
- document: IdentifiedSanityDocumentStub<R>,
1663
- options?: BaseMutationOptions,
1664
- ): Observable<SanityDocument_2<R>>
1665
- /**
1666
- * Deletes a document with the given document ID.
1667
- * Returns an observable that resolves to the deleted document.
1668
- *
1669
- * @param id - Document ID to delete
1670
- * @param options - Options for the mutation
1671
- */
1672
- delete<R extends Record<string, Any> = Record<string, Any>>(
1673
- id: string,
1674
- options: FirstDocumentMutationOptions,
1675
- ): Observable<SanityDocument_2<R>>
1676
- /**
1677
- * Deletes a document with the given document ID.
1678
- * Returns an observable that resolves to an array containing the deleted document.
1679
- *
1680
- * @param id - Document ID to delete
1681
- * @param options - Options for the mutation
1682
- */
1683
- delete<R extends Record<string, Any> = Record<string, Any>>(
1684
- id: string,
1685
- options: AllDocumentsMutationOptions,
1686
- ): Observable<SanityDocument_2<R>[]>
1687
- /**
1688
- * Deletes a document with the given document ID.
1689
- * Returns an observable that resolves to a mutation result object containing the deleted document ID.
1690
- *
1691
- * @param id - Document ID to delete
1692
- * @param options - Options for the mutation
1693
- */
1694
- delete(id: string, options: FirstDocumentIdMutationOptions): Observable<SingleMutationResult>
1695
- /**
1696
- * Deletes a document with the given document ID.
1697
- * Returns an observable that resolves to a mutation result object containing the deleted document ID.
1698
- *
1699
- * @param id - Document ID to delete
1700
- * @param options - Options for the mutation
1701
- */
1702
- delete(id: string, options: AllDocumentIdsMutationOptions): Observable<MultipleMutationResult>
1703
- /**
1704
- * Deletes a document with the given document ID.
1705
- * Returns an observable that resolves to the deleted document.
1706
- *
1707
- * @param id - Document ID to delete
1708
- * @param options - Options for the mutation
1709
- */
1710
- delete<R extends Record<string, Any> = Record<string, Any>>(
1711
- id: string,
1712
- options?: BaseMutationOptions,
1713
- ): Observable<SanityDocument_2<R>>
1714
- /**
1715
- * Deletes one or more documents matching the given query or document ID.
1716
- * Returns an observable that resolves to first deleted document.
1717
- *
1718
- * @param selection - An object with either an `id` or `query` key defining what to delete
1719
- * @param options - Options for the mutation
1720
- */
1721
- delete<R extends Record<string, Any> = Record<string, Any>>(
1722
- selection: MutationSelection,
1723
- options: FirstDocumentMutationOptions,
1724
- ): Observable<SanityDocument_2<R>>
1725
- /**
1726
- * Deletes one or more documents matching the given query or document ID.
1727
- * Returns an observable that resolves to an array containing the deleted documents.
1728
- *
1729
- * @param selection - An object with either an `id` or `query` key defining what to delete
1730
- * @param options - Options for the mutation
1731
- */
1732
- delete<R extends Record<string, Any> = Record<string, Any>>(
1733
- selection: MutationSelection,
1734
- options: AllDocumentsMutationOptions,
1735
- ): Observable<SanityDocument_2<R>[]>
1736
- /**
1737
- * Deletes one or more documents matching the given query or document ID.
1738
- * Returns an observable that resolves to a mutation result object containing the ID of the first deleted document.
1739
- *
1740
- * @param selection - An object with either an `id` or `query` key defining what to delete
1741
- * @param options - Options for the mutation
1742
- */
1743
- delete(
1744
- selection: MutationSelection,
1745
- options: FirstDocumentIdMutationOptions,
1746
- ): Observable<SingleMutationResult>
1747
- /**
1748
- * Deletes one or more documents matching the given query or document ID.
1749
- * Returns an observable that resolves to a mutation result object containing the document IDs that were deleted.
1750
- *
1751
- * @param selection - An object with either an `id` or `query` key defining what to delete
1752
- * @param options - Options for the mutation
1753
- */
1754
- delete(
1755
- selection: MutationSelection,
1756
- options: AllDocumentIdsMutationOptions,
1757
- ): Observable<MultipleMutationResult>
1758
- /**
1759
- * Deletes one or more documents matching the given query or document ID.
1760
- * Returns an observable that resolves to first deleted document.
1761
- *
1762
- * @param selection - An object with either an `id` or `query` key defining what to delete
1763
- * @param options - Options for the mutation
1764
- */
1765
- delete<R extends Record<string, Any> = Record<string, Any>>(
1766
- selection: MutationSelection,
1767
- options?: BaseMutationOptions,
1768
- ): Observable<SanityDocument_2<R>>
1769
- /**
1770
- * Perform mutation operations against the configured dataset
1771
- * Returns an observable that resolves to the first mutated document.
1772
- *
1773
- * @param operations - Mutation operations to execute
1774
- * @param options - Mutation options
1775
- */
1776
- mutate<R extends Record<string, Any> = Record<string, Any>>(
1777
- operations: Mutation<R>[] | ObservablePatch | ObservableTransaction,
1778
- options: FirstDocumentMutationOptions,
1779
- ): Observable<SanityDocument_2<R>>
1780
- /**
1781
- * Perform mutation operations against the configured dataset.
1782
- * Returns an observable that resolves to an array of the mutated documents.
1783
- *
1784
- * @param operations - Mutation operations to execute
1785
- * @param options - Mutation options
1786
- */
1787
- mutate<R extends Record<string, Any> = Record<string, Any>>(
1788
- operations: Mutation<R>[] | ObservablePatch | ObservableTransaction,
1789
- options: AllDocumentsMutationOptions,
1790
- ): Observable<SanityDocument_2<R>[]>
1791
- /**
1792
- * Perform mutation operations against the configured dataset
1793
- * Returns an observable that resolves to a mutation result object containing the document ID of the first mutated document.
1794
- *
1795
- * @param operations - Mutation operations to execute
1796
- * @param options - Mutation options
1797
- */
1798
- mutate<R extends Record<string, Any> = Record<string, Any>>(
1799
- operations: Mutation<R>[] | ObservablePatch | ObservableTransaction,
1800
- options: FirstDocumentIdMutationOptions,
1801
- ): Observable<SingleMutationResult>
1802
- /**
1803
- * Perform mutation operations against the configured dataset
1804
- * Returns an observable that resolves to a mutation result object containing the mutated document IDs.
1805
- *
1806
- * @param operations - Mutation operations to execute
1807
- * @param options - Mutation options
1808
- */
1809
- mutate<R extends Record<string, Any> = Record<string, Any>>(
1810
- operations: Mutation<R>[] | ObservablePatch | ObservableTransaction,
1811
- options: AllDocumentIdsMutationOptions,
1812
- ): Observable<MultipleMutationResult>
1813
- /**
1814
- * Perform mutation operations against the configured dataset
1815
- * Returns an observable that resolves to the first mutated document.
1816
- *
1817
- * @param operations - Mutation operations to execute
1818
- * @param options - Mutation options
1819
- */
1820
- mutate<R extends Record<string, Any> = Record<string, Any>>(
1821
- operations: Mutation<R>[] | ObservablePatch | ObservableTransaction,
1822
- options?: BaseMutationOptions,
1823
- ): Observable<SanityDocument_2<R>>
1824
- /**
1825
- * Create a new buildable patch of operations to perform
1826
- *
1827
- * @param documentId - Document ID to patch
1828
- * @param operations - Optional object of patch operations to initialize the patch instance with
1829
- * @returns Patch instance - call `.commit()` to perform the operations defined
1830
- */
1831
- patch(documentId: string, operations?: PatchOperations): ObservablePatch
1832
- /**
1833
- * Create a new buildable patch of operations to perform
1834
- *
1835
- * @param documentIds - Array of document IDs to patch
1836
- * @param operations - Optional object of patch operations to initialize the patch instance with
1837
- * @returns Patch instance - call `.commit()` to perform the operations defined
1838
- */
1839
- patch(documentIds: string[], operations?: PatchOperations): ObservablePatch
1840
- /**
1841
- * Create a new buildable patch of operations to perform
1842
- *
1843
- * @param selection - An object with `query` and optional `params`, defining which document(s) to patch
1844
- * @param operations - Optional object of patch operations to initialize the patch instance with
1845
- * @returns Patch instance - call `.commit()` to perform the operations defined
1846
- */
1847
- patch(selection: MutationSelection, operations?: PatchOperations): ObservablePatch
1848
- /**
1849
- * Create a new transaction of mutations
1850
- *
1851
- * @param operations - Optional array of mutation operations to initialize the transaction instance with
1852
- */
1853
- transaction<R extends Record<string, Any> = Record<string, Any>>(
1854
- operations?: Mutation<R>[],
1855
- ): ObservableTransaction
1856
- /**
1857
- * Perform action operations against the configured dataset
1858
- *
1859
- * @param operations - Action operation(s) to execute
1860
- * @param options - Action options
1861
- */
1862
- action(
1863
- operations: Action | Action[],
1864
- options?: BaseActionOptions,
1865
- ): Observable<SingleActionResult | MultipleActionResult>
1866
- /**
1867
- * Perform an HTTP request against the Sanity API
1868
- *
1869
- * @param options - Request options
1870
- */
1871
- request<R = Any>(options: RawRequestOptions): Observable<R>
1872
- /**
1873
- * Get a Sanity API URL for the URI provided
1874
- *
1875
- * @param uri - URI/path to build URL for
1876
- * @param canUseCdn - Whether or not to allow using the API CDN for this route
1877
- */
1878
- getUrl(uri: string, canUseCdn?: boolean): string
1879
- /**
1880
- * Get a Sanity API URL for the data operation and path provided
1881
- *
1882
- * @param operation - Data operation (eg `query`, `mutate`, `listen` or similar)
1883
- * @param path - Path to append after the operation
1884
- */
1885
- getDataUrl(operation: string, path?: string): string
1886
- }
1887
-
1888
- /** @public */
1889
- declare class ObservableTransaction extends BaseTransaction {
1890
- #private
1891
- constructor(operations?: Mutation[], client?: ObservableSanityClient, transactionId?: string)
1892
- /**
1893
- * Clones the transaction
1894
- */
1895
- clone(): ObservableTransaction
1896
- /**
1897
- * Commit the transaction, returning an observable that produces the first mutated document
1898
- *
1899
- * @param options - Options for the mutation operation
1900
- */
1901
- commit<R extends Record<string, Any>>(
1902
- options: TransactionFirstDocumentMutationOptions,
1903
- ): Observable<SanityDocument_2<R>>
1904
- /**
1905
- * Commit the transaction, returning an observable that produces an array of the mutated documents
1906
- *
1907
- * @param options - Options for the mutation operation
1908
- */
1909
- commit<R extends Record<string, Any>>(
1910
- options: TransactionAllDocumentsMutationOptions,
1911
- ): Observable<SanityDocument_2<R>[]>
1912
- /**
1913
- * Commit the transaction, returning an observable that produces a mutation result object
1914
- *
1915
- * @param options - Options for the mutation operation
1916
- */
1917
- commit(options: TransactionFirstDocumentIdMutationOptions): Observable<SingleMutationResult>
1918
- /**
1919
- * Commit the transaction, returning an observable that produces a mutation result object
1920
- *
1921
- * @param options - Options for the mutation operation
1922
- */
1923
- commit(options: TransactionAllDocumentIdsMutationOptions): Observable<MultipleMutationResult>
1924
- /**
1925
- * Commit the transaction, returning an observable that produces a mutation result object
1926
- *
1927
- * @param options - Options for the mutation operation
1928
- */
1929
- commit(options?: BaseMutationOptions): Observable<MultipleMutationResult>
1930
- /**
1931
- * Performs a patch on the given document ID. Can either be a builder function or an object of patch operations.
1932
- * The operation is added to the current transaction, ready to be commited by `commit()`
1933
- *
1934
- * @param documentId - Document ID to perform the patch operation on
1935
- * @param patchOps - Operations to perform, or a builder function
1936
- */
1937
- patch(documentId: string, patchOps?: ObservablePatchBuilder | PatchOperations): this
1938
- /**
1939
- * Adds the given patch instance to the transaction.
1940
- * The operation is added to the current transaction, ready to be commited by `commit()`
1941
- *
1942
- * @param patch - ObservablePatch to execute
1943
- */
1944
- patch(patch: ObservablePatch): this
1945
- }
1946
-
1947
- /** @public */
1948
- declare class ObservableUsersClient {
1949
- #private
1950
- constructor(client: ObservableSanityClient, httpRequest: HttpRequest)
1951
- /**
1952
- * Fetch a user by user ID
1953
- *
1954
- * @param id - User ID of the user to fetch. If `me` is provided, a minimal response including the users role is returned.
1955
- */
1956
- getById<T extends 'me' | string>(
1957
- id: T,
1958
- ): Observable<T extends 'me' ? CurrentSanityUser : SanityUser>
1959
- }
1960
-
1961
- /**
1962
- * The listener connection has been established
1963
- * note: it's usually a better option to use the 'welcome' event
1964
- * @public
1965
- */
1966
- declare type OpenEvent = {
1967
- type: 'open'
1968
- }
1969
-
1970
- /**
1971
- * Return value from the usePaginatedList hook
1972
- *
1973
- * @beta
1974
- * @category Types
1975
- */
1976
- export declare interface PaginatedList {
1977
- /**
1978
- * Array of document handles for the current page
1979
- */
1980
- data: DocumentHandle[]
1981
- /**
1982
- * Whether a query is currently in progress
1983
- */
1984
- isPending: boolean
1985
- /**
1986
- * Number of items displayed per page
1987
- */
1988
- pageSize: number
1989
- /**
1990
- * Current page number (1-indexed)
1991
- */
1992
- currentPage: number
1993
- /**
1994
- * Total number of pages available
1995
- */
1996
- totalPages: number
1997
- /**
1998
- * Starting index of the current page (0-indexed)
1999
- */
2000
- startIndex: number
2001
- /**
2002
- * Ending index of the current page (exclusive, 0-indexed)
2003
- */
2004
- endIndex: number
2005
- /**
2006
- * Total count of items matching the query
2007
- */
2008
- count: number
2009
- /**
2010
- * Navigate to the first page
2011
- */
2012
- firstPage: () => void
2013
- /**
2014
- * Whether there is a first page available to navigate to
2015
- */
2016
- hasFirstPage: boolean
2017
- /**
2018
- * Navigate to the previous page
2019
- */
2020
- previousPage: () => void
2021
- /**
2022
- * Whether there is a previous page available to navigate to
2023
- */
2024
- hasPreviousPage: boolean
2025
- /**
2026
- * Navigate to the next page
2027
- */
2028
- nextPage: () => void
2029
- /**
2030
- * Whether there is a next page available to navigate to
2031
- */
2032
- hasNextPage: boolean
2033
- /**
2034
- * Navigate to the last page
2035
- */
2036
- lastPage: () => void
2037
- /**
2038
- * Whether there is a last page available to navigate to
2039
- */
2040
- hasLastPage: boolean
2041
- /**
2042
- * Navigate to a specific page number
2043
- * @param pageNumber - The page number to navigate to (1-indexed)
2044
- */
2045
- goToPage: (pageNumber: number) => void
2046
- }
2047
-
2048
- /**
2049
- * Configuration options for the usePaginatedList hook
2050
- *
2051
- * @beta
2052
- * @category Types
2053
- */
2054
- export declare interface PaginatedListOptions extends QueryOptions {
2055
- /**
2056
- * GROQ filter expression to apply to the query
2057
- */
2058
- filter?: string
2059
- /**
2060
- * Number of items to display per page (defaults to 25)
2061
- */
2062
- pageSize?: number
2063
- /**
2064
- * Sorting configuration for the results
2065
- */
2066
- orderings?: SortOrderingItem[]
2067
- /**
2068
- * Text search query to filter results
2069
- */
2070
- search?: string
2071
- }
2072
-
2073
- /** @public */
2074
- declare class Patch extends BasePatch {
2075
- #private
2076
- constructor(selection: PatchSelection, operations?: PatchOperations, client?: SanityClient)
2077
- /**
2078
- * Clones the patch
2079
- */
2080
- clone(): Patch
2081
- /**
2082
- * Commit the patch, returning a promise that resolves to the first patched document
2083
- *
2084
- * @param options - Options for the mutation operation
2085
- */
2086
- commit<R extends Record<string, Any> = Record<string, Any>>(
2087
- options: FirstDocumentMutationOptions,
2088
- ): Promise<SanityDocument_2<R>>
2089
- /**
2090
- * Commit the patch, returning a promise that resolves to an array of the mutated documents
2091
- *
2092
- * @param options - Options for the mutation operation
2093
- */
2094
- commit<R extends Record<string, Any> = Record<string, Any>>(
2095
- options: AllDocumentsMutationOptions,
2096
- ): Promise<SanityDocument_2<R>[]>
2097
- /**
2098
- * Commit the patch, returning a promise that resolves to a mutation result object
2099
- *
2100
- * @param options - Options for the mutation operation
2101
- */
2102
- commit(options: FirstDocumentIdMutationOptions): Promise<SingleMutationResult>
2103
- /**
2104
- * Commit the patch, returning a promise that resolves to a mutation result object
2105
- *
2106
- * @param options - Options for the mutation operation
2107
- */
2108
- commit(options: AllDocumentIdsMutationOptions): Promise<MultipleMutationResult>
2109
- /**
2110
- * Commit the patch, returning a promise that resolves to the first patched document
2111
- *
2112
- * @param options - Options for the mutation operation
2113
- */
2114
- commit<R extends Record<string, Any> = Record<string, Any>>(
2115
- options?: BaseMutationOptions,
2116
- ): Promise<SanityDocument_2<R>>
2117
- }
2118
-
2119
- /** @public */
2120
- declare type PatchBuilder = (patch: Patch) => Patch
2121
-
2122
- /** @internal */
2123
- declare type PatchMutationOperation = PatchOperations & MutationSelection
2124
-
2125
- /** @internal */
2126
- declare interface PatchOperations {
2127
- set?: {
2128
- [key: string]: Any
2129
- }
2130
- setIfMissing?: {
2131
- [key: string]: Any
2132
- }
2133
- diffMatchPatch?: {
2134
- [key: string]: Any
2135
- }
2136
- unset?: string[]
2137
- inc?: {
2138
- [key: string]: number
2139
- }
2140
- dec?: {
2141
- [key: string]: number
2142
- }
2143
- insert?: InsertPatch
2144
- ifRevisionID?: string
2145
- }
2146
-
2147
- /** @internal */
2148
- declare type PatchSelection = string | string[] | MutationSelection
2149
-
2150
- /** @public */
2151
- declare interface ProgressEvent_2 {
2152
- type: 'progress'
2153
- stage: 'upload' | 'download'
2154
- percent: number
2155
- total?: number
2156
- loaded?: number
2157
- lengthComputable: boolean
2158
- }
2159
-
2160
- /** @internal */
2161
- declare class ProjectsClient {
2162
- #private
2163
- constructor(client: SanityClient, httpRequest: HttpRequest)
2164
- /**
2165
- * Fetch a list of projects the authenticated user has access to.
2166
- *
2167
- * @param options - Options for the list request
2168
- * @param options.includeMembers - Whether to include members in the response (default: true)
2169
- */
2170
- list(options?: {includeMembers?: true}): Promise<SanityProject[]>
2171
- list(options?: {includeMembers?: false}): Promise<Omit<SanityProject, 'members'>[]>
2172
- /**
2173
- * Fetch a project by project ID
2174
- *
2175
- * @param projectId - ID of the project to fetch
2176
- */
2177
- getById(projectId: string): Promise<SanityProject>
2178
- }
2179
-
2180
- /**
2181
- * @public
2182
- * @category Types
2183
- */
2184
- export declare type ProjectWithoutMembers = Omit<SanityProject, 'members'>
2185
-
2186
- /**
2187
- * Publishes a draft document.
2188
- * If a published version of the document already exists this is replaced by the current draft document.
2189
- * In either case the draft document is deleted.
2190
- * The optional revision id parameters can be used for optimistic locking to ensure
2191
- * that the draft and/or published versions of the document have not been changed by another client.
2192
- *
2193
- * @public
2194
- */
2195
- declare type PublishAction = {
2196
- actionType: 'sanity.action.document.publish'
2197
- /**
2198
- * Draft document ID to publish
2199
- */
2200
- draftId: string
2201
- /**
2202
- * Draft revision ID to match
2203
- */
2204
- ifDraftRevisionId?: string
2205
- /**
2206
- * Published document ID to replace
2207
- */
2208
- publishedId: string
2209
- /**
2210
- * Published revision ID to match
2211
- */
2212
- ifPublishedRevisionId?: string
2213
- }
2214
-
2215
- /** @public */
2216
- declare interface QueryParams {
2217
- [key: string]: any
2218
- /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
2219
- body?: never
2220
- /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
2221
- cache?: 'next' extends keyof RequestInit ? never : any
2222
- /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
2223
- filterResponse?: never
2224
- /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
2225
- headers?: never
2226
- /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
2227
- method?: never
2228
- /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
2229
- next?: 'next' extends keyof RequestInit ? never : any
2230
- /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
2231
- perspective?: never
2232
- /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
2233
- query?: never
2234
- /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
2235
- resultSourceMap?: never
2236
- /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
2237
- returnQuery?: never
2238
- /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
2239
- signal?: never
2240
- /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
2241
- stega?: never
2242
- /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
2243
- tag?: never
2244
- /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
2245
- timeout?: never
2246
- /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
2247
- token?: never
2248
- /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
2249
- useCdn?: never
2250
- /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
2251
- lastLiveEventId?: never
2252
- /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
2253
- cacheMode?: never
2254
- }
2255
-
2256
- /**
2257
- * This type can be used with `client.fetch` to indicate that the query has no GROQ parameters.
2258
- * @public
2259
- */
2260
- declare type QueryWithoutParams = Record<string, never> | undefined
2261
-
2262
- /** @public */
2263
- declare type RawQuerylessQueryResponse<R> = Omit<RawQueryResponse<R>, 'query'>
2264
-
2265
- /** @public */
2266
- declare interface RawQueryResponse<R> {
2267
- query: string
2268
- ms: number
2269
- result: R
2270
- resultSourceMap?: ContentSourceMap
2271
- /** Requires `apiVersion` to be `2021-03-25` or later. */
2272
- syncTags?: SyncTag[]
2273
- }
2274
-
2275
- /** @internal */
2276
- declare interface RawRequestOptions {
2277
- url?: string
2278
- uri?: string
2279
- method?: string
2280
- token?: string
2281
- json?: boolean
2282
- tag?: string
2283
- useGlobalApi?: boolean
2284
- withCredentials?: boolean
2285
- query?: {
2286
- [key: string]: string | string[]
2287
- }
2288
- headers?: {
2289
- [key: string]: string
2290
- }
2291
- timeout?: number
2292
- proxy?: string
2293
- body?: Any
2294
- maxRedirects?: number
2295
- signal?: AbortSignal
2296
- }
2297
-
2298
- /**
2299
- * The listener has been disconnected, and a reconnect attempt is scheduled.
2300
- *
2301
- * @public
2302
- */
2303
- declare type ReconnectEvent = {
2304
- type: 'reconnect'
2305
- }
2306
-
2307
- /**
2308
- * Replaces an existing draft document.
2309
- * At least one of the draft or published versions of the document must exist.
2310
- *
2311
- * @public
2312
- */
2313
- declare type ReplaceDraftAction = {
2314
- actionType: 'sanity.action.document.replaceDraft'
2315
- /**
2316
- * Published document ID to create draft from, if draft does not exist
2317
- */
2318
- publishedId: string
2319
- /**
2320
- * Document to create if it does not already exist. Requires `_id` and `_type` properties.
2321
- */
2322
- attributes: IdentifiedSanityDocumentStub
2323
- }
2324
-
2325
- /** @public */
2326
- declare interface RequestOptions {
2327
- timeout?: number
2328
- token?: string
2329
- tag?: string
2330
- headers?: Record<string, string>
2331
- method?: string
2332
- query?: Any
2333
- body?: Any
2334
- signal?: AbortSignal
2335
- }
2336
-
2337
- /** @alpha */
2338
- declare type ResolveStudioUrl = (sourceDocument: ContentSourceMapDocuments[number]) => StudioUrl
2339
-
2340
- /** @public */
2341
- declare interface ResponseEvent<T = unknown> {
2342
- type: 'response'
2343
- body: T
2344
- url: string
2345
- method: string
2346
- statusCode: number
2347
- statusMessage?: string
2348
- headers: Record<string, string>
2349
- }
2350
-
2351
- /** @public */
2352
- declare interface ResponseQueryOptions extends RequestOptions {
2353
- perspective?: ClientPerspective
2354
- resultSourceMap?: boolean | 'withKeyArraySelector'
2355
- returnQuery?: boolean
2356
- useCdn?: boolean
2357
- stega?: boolean | StegaConfig
2358
- cache?: 'next' extends keyof RequestInit ? RequestInit['cache'] : never
2359
- next?: ('next' extends keyof RequestInit ? RequestInit : never)['next']
2360
- lastLiveEventId?: string | string[] | null
2361
- /**
2362
- * When set to `noStale`, APICDN will not return a cached response if the content is stale.
2363
- * Tradeoff between latency and freshness of content.
2364
- *
2365
- * Only to be used with live content queries and when useCdn is true.
2366
- */
2367
- cacheMode?: 'noStale'
2368
- }
2369
-
2370
- /** @internal */
2371
- declare interface SanityAssetDocument extends SanityDocument_2 {
2372
- url: string
2373
- path: string
2374
- size: number
2375
- assetId: string
2376
- mimeType: string
2377
- sha1hash: string
2378
- extension: string
2379
- uploadId?: string
2380
- originalFilename?: string
2381
- }
2382
-
2383
- /** @public */
2384
- declare class SanityClient {
2385
- #private
2386
- assets: AssetsClient
2387
- datasets: DatasetsClient
2388
- live: LiveClient
2389
- projects: ProjectsClient
2390
- users: UsersClient
2391
- /**
2392
- * Observable version of the Sanity client, with the same configuration as the promise-based one
2393
- */
2394
- observable: ObservableSanityClient
2395
- /**
2396
- * Instance properties
2397
- */
2398
- listen: typeof _listen
2399
- constructor(httpRequest: HttpRequest, config?: ClientConfig)
2400
- /**
2401
- * Clone the client - returns a new instance
2402
- */
2403
- clone(): SanityClient
2404
- /**
2405
- * Returns the current client configuration
2406
- */
2407
- config(): InitializedClientConfig
2408
- /**
2409
- * Reconfigure the client. Note that this _mutates_ the current client.
2410
- */
2411
- config(newConfig?: Partial<ClientConfig>): this
2412
- /**
2413
- * Clone the client with a new (partial) configuration.
2414
- *
2415
- * @param newConfig - New client configuration properties, shallowly merged with existing configuration
2416
- */
2417
- withConfig(newConfig?: Partial<ClientConfig>): SanityClient
2418
- /**
2419
- * Perform a GROQ-query against the configured dataset.
2420
- *
2421
- * @param query - GROQ-query to perform
2422
- */
2423
- fetch<
2424
- R = Any,
2425
- Q extends QueryWithoutParams = QueryWithoutParams,
2426
- const G extends string = string,
2427
- >(query: G, params?: Q | QueryWithoutParams): Promise<ClientReturn<G, R>>
2428
- /**
2429
- * Perform a GROQ-query against the configured dataset.
2430
- *
2431
- * @param query - GROQ-query to perform
2432
- * @param params - Optional query parameters
2433
- * @param options - Optional request options
2434
- */
2435
- fetch<
2436
- R = Any,
2437
- Q extends QueryWithoutParams | QueryParams = QueryParams,
2438
- const G extends string = string,
2439
- >(
2440
- query: G,
2441
- params: Q extends QueryWithoutParams ? QueryWithoutParams : Q,
2442
- options?: FilteredResponseQueryOptions,
2443
- ): Promise<ClientReturn<G, R>>
2444
- /**
2445
- * Perform a GROQ-query against the configured dataset.
2446
- *
2447
- * @param query - GROQ-query to perform
2448
- * @param params - Optional query parameters
2449
- * @param options - Request options
2450
- */
2451
- fetch<
2452
- R = Any,
2453
- Q extends QueryWithoutParams | QueryParams = QueryParams,
2454
- const G extends string = string,
2455
- >(
2456
- query: G,
2457
- params: Q extends QueryWithoutParams ? QueryWithoutParams : Q,
2458
- options: UnfilteredResponseQueryOptions,
2459
- ): Promise<RawQueryResponse<ClientReturn<G, R>>>
2460
- /**
2461
- * Perform a GROQ-query against the configured dataset.
2462
- *
2463
- * @param query - GROQ-query to perform
2464
- * @param params - Optional query parameters
2465
- * @param options - Request options
2466
- */
2467
- fetch<
2468
- R = Any,
2469
- Q extends QueryWithoutParams | QueryParams = QueryParams,
2470
- const G extends string = string,
2471
- >(
2472
- query: G,
2473
- params: Q extends QueryWithoutParams ? QueryWithoutParams : Q,
2474
- options: UnfilteredResponseWithoutQuery,
2475
- ): Promise<RawQuerylessQueryResponse<ClientReturn<G, R>>>
2476
- /**
2477
- * Fetch a single document with the given ID.
2478
- *
2479
- * @param id - Document ID to fetch
2480
- * @param options - Request options
2481
- */
2482
- getDocument<R extends Record<string, Any> = Record<string, Any>>(
2483
- id: string,
2484
- options?: {
2485
- signal?: AbortSignal
2486
- tag?: string
2487
- },
2488
- ): Promise<SanityDocument_2<R> | undefined>
2489
- /**
2490
- * Fetch multiple documents in one request.
2491
- * Should be used sparingly - performing a query is usually a better option.
2492
- * The order/position of documents is preserved based on the original array of IDs.
2493
- * If any of the documents are missing, they will be replaced by a `null` entry in the returned array
2494
- *
2495
- * @param ids - Document IDs to fetch
2496
- * @param options - Request options
2497
- */
2498
- getDocuments<R extends Record<string, Any> = Record<string, Any>>(
2499
- ids: string[],
2500
- options?: {
2501
- signal?: AbortSignal
2502
- tag?: string
2503
- },
2504
- ): Promise<(SanityDocument_2<R> | null)[]>
2505
- /**
2506
- * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.
2507
- * Returns a promise that resolves to the created document.
2508
- *
2509
- * @param document - Document to create
2510
- * @param options - Mutation options
2511
- */
2512
- create<R extends Record<string, Any> = Record<string, Any>>(
2513
- document: SanityDocumentStub<R>,
2514
- options: FirstDocumentMutationOptions,
2515
- ): Promise<SanityDocument_2<R>>
2516
- /**
2517
- * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.
2518
- * Returns a promise that resolves to an array containing the created document.
2519
- *
2520
- * @param document - Document to create
2521
- * @param options - Mutation options
2522
- */
2523
- create<R extends Record<string, Any> = Record<string, Any>>(
2524
- document: SanityDocumentStub<R>,
2525
- options: AllDocumentsMutationOptions,
2526
- ): Promise<SanityDocument_2<R>[]>
2527
- /**
2528
- * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.
2529
- * Returns a promise that resolves to a mutation result object containing the ID of the created document.
2530
- *
2531
- * @param document - Document to create
2532
- * @param options - Mutation options
2533
- */
2534
- create<R extends Record<string, Any> = Record<string, Any>>(
2535
- document: SanityDocumentStub<R>,
2536
- options: FirstDocumentIdMutationOptions,
2537
- ): Promise<SingleMutationResult>
2538
- /**
2539
- * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.
2540
- * Returns a promise that resolves to a mutation result object containing the ID of the created document.
2541
- *
2542
- * @param document - Document to create
2543
- * @param options - Mutation options
2544
- */
2545
- create<R extends Record<string, Any> = Record<string, Any>>(
2546
- document: SanityDocumentStub<R>,
2547
- options: AllDocumentIdsMutationOptions,
2548
- ): Promise<MultipleMutationResult>
2549
- /**
2550
- * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.
2551
- * Returns a promise that resolves to the created document.
2552
- *
2553
- * @param document - Document to create
2554
- * @param options - Mutation options
2555
- */
2556
- create<R extends Record<string, Any> = Record<string, Any>>(
2557
- document: SanityDocumentStub<R>,
2558
- options?: BaseMutationOptions,
2559
- ): Promise<SanityDocument_2<R>>
2560
- /**
2561
- * Create a document if no document with the same ID already exists.
2562
- * Returns a promise that resolves to the created document.
2563
- *
2564
- * @param document - Document to create
2565
- * @param options - Mutation options
2566
- */
2567
- createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(
2568
- document: IdentifiedSanityDocumentStub<R>,
2569
- options: FirstDocumentMutationOptions,
2570
- ): Promise<SanityDocument_2<R>>
2571
- /**
2572
- * Create a document if no document with the same ID already exists.
2573
- * Returns a promise that resolves to an array containing the created document.
2574
- *
2575
- * @param document - Document to create
2576
- * @param options - Mutation options
2577
- */
2578
- createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(
2579
- document: IdentifiedSanityDocumentStub<R>,
2580
- options: AllDocumentsMutationOptions,
2581
- ): Promise<SanityDocument_2<R>[]>
2582
- /**
2583
- * Create a document if no document with the same ID already exists.
2584
- * Returns a promise that resolves to a mutation result object containing the ID of the created document.
2585
- *
2586
- * @param document - Document to create
2587
- * @param options - Mutation options
2588
- */
2589
- createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(
2590
- document: IdentifiedSanityDocumentStub<R>,
2591
- options: FirstDocumentIdMutationOptions,
2592
- ): Promise<SingleMutationResult>
2593
- /**
2594
- * Create a document if no document with the same ID already exists.
2595
- * Returns a promise that resolves to a mutation result object containing the ID of the created document.
2596
- *
2597
- * @param document - Document to create
2598
- * @param options - Mutation options
2599
- */
2600
- createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(
2601
- document: IdentifiedSanityDocumentStub<R>,
2602
- options: AllDocumentIdsMutationOptions,
2603
- ): Promise<MultipleMutationResult>
2604
- /**
2605
- * Create a document if no document with the same ID already exists.
2606
- * Returns a promise that resolves to the created document.
2607
- *
2608
- * @param document - Document to create
2609
- * @param options - Mutation options
2610
- */
2611
- createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(
2612
- document: IdentifiedSanityDocumentStub<R>,
2613
- options?: BaseMutationOptions,
2614
- ): Promise<SanityDocument_2<R>>
2615
- /**
2616
- * Create a document if it does not exist, or replace a document with the same document ID
2617
- * Returns a promise that resolves to the created document.
2618
- *
2619
- * @param document - Document to either create or replace
2620
- * @param options - Mutation options
2621
- */
2622
- createOrReplace<R extends Record<string, Any> = Record<string, Any>>(
2623
- document: IdentifiedSanityDocumentStub<R>,
2624
- options: FirstDocumentMutationOptions,
2625
- ): Promise<SanityDocument_2<R>>
2626
- /**
2627
- * Create a document if it does not exist, or replace a document with the same document ID
2628
- * Returns a promise that resolves to an array containing the created document.
2629
- *
2630
- * @param document - Document to either create or replace
2631
- * @param options - Mutation options
2632
- */
2633
- createOrReplace<R extends Record<string, Any> = Record<string, Any>>(
2634
- document: IdentifiedSanityDocumentStub<R>,
2635
- options: AllDocumentsMutationOptions,
2636
- ): Promise<SanityDocument_2<R>[]>
2637
- /**
2638
- * Create a document if it does not exist, or replace a document with the same document ID
2639
- * Returns a promise that resolves to a mutation result object containing the ID of the created document.
2640
- *
2641
- * @param document - Document to either create or replace
2642
- * @param options - Mutation options
2643
- */
2644
- createOrReplace<R extends Record<string, Any> = Record<string, Any>>(
2645
- document: IdentifiedSanityDocumentStub<R>,
2646
- options: FirstDocumentIdMutationOptions,
2647
- ): Promise<SingleMutationResult>
2648
- /**
2649
- * Create a document if it does not exist, or replace a document with the same document ID
2650
- * Returns a promise that resolves to a mutation result object containing the created document ID.
2651
- *
2652
- * @param document - Document to either create or replace
2653
- * @param options - Mutation options
2654
- */
2655
- createOrReplace<R extends Record<string, Any> = Record<string, Any>>(
2656
- document: IdentifiedSanityDocumentStub<R>,
2657
- options: AllDocumentIdsMutationOptions,
2658
- ): Promise<MultipleMutationResult>
2659
- /**
2660
- * Create a document if it does not exist, or replace a document with the same document ID
2661
- * Returns a promise that resolves to the created document.
2662
- *
2663
- * @param document - Document to either create or replace
2664
- * @param options - Mutation options
2665
- */
2666
- createOrReplace<R extends Record<string, Any> = Record<string, Any>>(
2667
- document: IdentifiedSanityDocumentStub<R>,
2668
- options?: BaseMutationOptions,
2669
- ): Promise<SanityDocument_2<R>>
2670
- /**
2671
- * Deletes a document with the given document ID.
2672
- * Returns a promise that resolves to the deleted document.
2673
- *
2674
- * @param id - Document ID to delete
2675
- * @param options - Options for the mutation
2676
- */
2677
- delete<R extends Record<string, Any> = Record<string, Any>>(
2678
- id: string,
2679
- options: FirstDocumentMutationOptions,
2680
- ): Promise<SanityDocument_2<R>>
2681
- /**
2682
- * Deletes a document with the given document ID.
2683
- * Returns a promise that resolves to an array containing the deleted document.
2684
- *
2685
- * @param id - Document ID to delete
2686
- * @param options - Options for the mutation
2687
- */
2688
- delete<R extends Record<string, Any> = Record<string, Any>>(
2689
- id: string,
2690
- options: AllDocumentsMutationOptions,
2691
- ): Promise<SanityDocument_2<R>[]>
2692
- /**
2693
- * Deletes a document with the given document ID.
2694
- * Returns a promise that resolves to a mutation result object containing the deleted document ID.
2695
- *
2696
- * @param id - Document ID to delete
2697
- * @param options - Options for the mutation
2698
- */
2699
- delete(id: string, options: FirstDocumentIdMutationOptions): Promise<SingleMutationResult>
2700
- /**
2701
- * Deletes a document with the given document ID.
2702
- * Returns a promise that resolves to a mutation result object containing the deleted document ID.
2703
- *
2704
- * @param id - Document ID to delete
2705
- * @param options - Options for the mutation
2706
- */
2707
- delete(id: string, options: AllDocumentIdsMutationOptions): Promise<MultipleMutationResult>
2708
- /**
2709
- * Deletes a document with the given document ID.
2710
- * Returns a promise that resolves to the deleted document.
2711
- *
2712
- * @param id - Document ID to delete
2713
- * @param options - Options for the mutation
2714
- */
2715
- delete<R extends Record<string, Any> = Record<string, Any>>(
2716
- id: string,
2717
- options?: BaseMutationOptions,
2718
- ): Promise<SanityDocument_2<R>>
2719
- /**
2720
- * Deletes one or more documents matching the given query or document ID.
2721
- * Returns a promise that resolves to first deleted document.
2722
- *
2723
- * @param selection - An object with either an `id` or `query` key defining what to delete
2724
- * @param options - Options for the mutation
2725
- */
2726
- delete<R extends Record<string, Any> = Record<string, Any>>(
2727
- selection: MutationSelection,
2728
- options: FirstDocumentMutationOptions,
2729
- ): Promise<SanityDocument_2<R>>
2730
- /**
2731
- * Deletes one or more documents matching the given query or document ID.
2732
- * Returns a promise that resolves to an array containing the deleted documents.
2733
- *
2734
- * @param selection - An object with either an `id` or `query` key defining what to delete
2735
- * @param options - Options for the mutation
2736
- */
2737
- delete<R extends Record<string, Any> = Record<string, Any>>(
2738
- selection: MutationSelection,
2739
- options: AllDocumentsMutationOptions,
2740
- ): Promise<SanityDocument_2<R>[]>
2741
- /**
2742
- * Deletes one or more documents matching the given query or document ID.
2743
- * Returns a promise that resolves to a mutation result object containing the ID of the first deleted document.
2744
- *
2745
- * @param selection - An object with either an `id` or `query` key defining what to delete
2746
- * @param options - Options for the mutation
2747
- */
2748
- delete(
2749
- selection: MutationSelection,
2750
- options: FirstDocumentIdMutationOptions,
2751
- ): Promise<SingleMutationResult>
2752
- /**
2753
- * Deletes one or more documents matching the given query or document ID.
2754
- * Returns a promise that resolves to a mutation result object containing the document IDs that were deleted.
2755
- *
2756
- * @param selection - An object with either an `id` or `query` key defining what to delete
2757
- * @param options - Options for the mutation
2758
- */
2759
- delete(
2760
- selection: MutationSelection,
2761
- options: AllDocumentIdsMutationOptions,
2762
- ): Promise<MultipleMutationResult>
2763
- /**
2764
- * Deletes one or more documents matching the given query or document ID.
2765
- * Returns a promise that resolves to first deleted document.
2766
- *
2767
- * @param selection - An object with either an `id` or `query` key defining what to delete
2768
- * @param options - Options for the mutation
2769
- */
2770
- delete<R extends Record<string, Any> = Record<string, Any>>(
2771
- selection: MutationSelection,
2772
- options?: BaseMutationOptions,
2773
- ): Promise<SanityDocument_2<R>>
2774
- /**
2775
- * Perform mutation operations against the configured dataset
2776
- * Returns a promise that resolves to the first mutated document.
2777
- *
2778
- * @param operations - Mutation operations to execute
2779
- * @param options - Mutation options
2780
- */
2781
- mutate<R extends Record<string, Any> = Record<string, Any>>(
2782
- operations: Mutation<R>[] | Patch | Transaction,
2783
- options: FirstDocumentMutationOptions,
2784
- ): Promise<SanityDocument_2<R>>
2785
- /**
2786
- * Perform mutation operations against the configured dataset.
2787
- * Returns a promise that resolves to an array of the mutated documents.
2788
- *
2789
- * @param operations - Mutation operations to execute
2790
- * @param options - Mutation options
2791
- */
2792
- mutate<R extends Record<string, Any> = Record<string, Any>>(
2793
- operations: Mutation<R>[] | Patch | Transaction,
2794
- options: AllDocumentsMutationOptions,
2795
- ): Promise<SanityDocument_2<R>[]>
2796
- /**
2797
- * Perform mutation operations against the configured dataset
2798
- * Returns a promise that resolves to a mutation result object containing the document ID of the first mutated document.
2799
- *
2800
- * @param operations - Mutation operations to execute
2801
- * @param options - Mutation options
2802
- */
2803
- mutate<R extends Record<string, Any> = Record<string, Any>>(
2804
- operations: Mutation<R>[] | Patch | Transaction,
2805
- options: FirstDocumentIdMutationOptions,
2806
- ): Promise<SingleMutationResult>
2807
- /**
2808
- * Perform mutation operations against the configured dataset
2809
- * Returns a promise that resolves to a mutation result object containing the mutated document IDs.
2810
- *
2811
- * @param operations - Mutation operations to execute
2812
- * @param options - Mutation options
2813
- */
2814
- mutate<R extends Record<string, Any>>(
2815
- operations: Mutation<R>[] | Patch | Transaction,
2816
- options: AllDocumentIdsMutationOptions,
2817
- ): Promise<MultipleMutationResult>
2818
- /**
2819
- * Perform mutation operations against the configured dataset
2820
- * Returns a promise that resolves to the first mutated document.
2821
- *
2822
- * @param operations - Mutation operations to execute
2823
- * @param options - Mutation options
2824
- */
2825
- mutate<R extends Record<string, Any> = Record<string, Any>>(
2826
- operations: Mutation<R>[] | Patch | Transaction,
2827
- options?: BaseMutationOptions,
2828
- ): Promise<SanityDocument_2<R>>
2829
- /**
2830
- * Create a new buildable patch of operations to perform
2831
- *
2832
- * @param documentId - Document ID to patch
2833
- * @param operations - Optional object of patch operations to initialize the patch instance with
2834
- * @returns Patch instance - call `.commit()` to perform the operations defined
2835
- */
2836
- patch(documentId: string, operations?: PatchOperations): Patch
2837
- /**
2838
- * Create a new buildable patch of operations to perform
2839
- *
2840
- * @param documentIds - Array of document IDs to patch
2841
- * @param operations - Optional object of patch operations to initialize the patch instance with
2842
- * @returns Patch instance - call `.commit()` to perform the operations defined
2843
- */
2844
- patch(documentIds: string[], operations?: PatchOperations): Patch
2845
- /**
2846
- * Create a new buildable patch of operations to perform
2847
- *
2848
- * @param selection - An object with `query` and optional `params`, defining which document(s) to patch
2849
- * @param operations - Optional object of patch operations to initialize the patch instance with
2850
- * @returns Patch instance - call `.commit()` to perform the operations defined
2851
- */
2852
- patch(selection: MutationSelection, operations?: PatchOperations): Patch
2853
- /**
2854
- * Create a new transaction of mutations
2855
- *
2856
- * @param operations - Optional array of mutation operations to initialize the transaction instance with
2857
- */
2858
- transaction<R extends Record<string, Any> = Record<string, Any>>(
2859
- operations?: Mutation<R>[],
2860
- ): Transaction
2861
- /**
2862
- * Perform action operations against the configured dataset
2863
- * Returns a promise that resolves to the transaction result
2864
- *
2865
- * @param operations - Action operation(s) to execute
2866
- * @param options - Action options
2867
- */
2868
- action(
2869
- operations: Action | Action[],
2870
- options?: BaseActionOptions,
2871
- ): Promise<SingleActionResult | MultipleActionResult>
2872
- /**
2873
- * Perform a request against the Sanity API
2874
- * NOTE: Only use this for Sanity API endpoints, not for your own APIs!
2875
- *
2876
- * @param options - Request options
2877
- * @returns Promise resolving to the response body
2878
- */
2879
- request<R = Any>(options: RawRequestOptions): Promise<R>
2880
- /**
2881
- * Perform an HTTP request a `/data` sub-endpoint
2882
- * NOTE: Considered internal, thus marked as deprecated. Use `request` instead.
2883
- *
2884
- * @deprecated - Use `request()` or your own HTTP library instead
2885
- * @param endpoint - Endpoint to hit (mutate, query etc)
2886
- * @param body - Request body
2887
- * @param options - Request options
2888
- * @internal
2889
- */
2890
- dataRequest(endpoint: string, body: unknown, options?: BaseMutationOptions): Promise<Any>
2891
- /**
2892
- * Get a Sanity API URL for the URI provided
2893
- *
2894
- * @param uri - URI/path to build URL for
2895
- * @param canUseCdn - Whether or not to allow using the API CDN for this route
2896
- */
2897
- getUrl(uri: string, canUseCdn?: boolean): string
2898
- /**
2899
- * Get a Sanity API URL for the data operation and path provided
2900
- *
2901
- * @param operation - Data operation (eg `query`, `mutate`, `listen` or similar)
2902
- * @param path - Path to append after the operation
2903
- */
2904
- getDataUrl(operation: string, path?: string): string
2905
- }
2906
-
2907
- export {SanityDocument}
2908
-
2909
- /** @internal */
2910
- declare type SanityDocument_2<T extends Record<string, Any> = Record<string, Any>> = {
2911
- [P in keyof T]: T[P]
2912
- } & {
2913
- _id: string
2914
- _rev: string
2915
- _type: string
2916
- _createdAt: string
2917
- _updatedAt: string
2918
- /**
2919
- * Present when `perspective` is set to `previewDrafts`
2920
- */
2921
- _originalId?: string
2922
- }
2923
-
2924
- /** @public */
2925
- declare type SanityDocumentStub<T extends Record<string, Any> = Record<string, Any>> = {
2926
- [P in keyof T]: T[P]
2927
- } & {
2928
- _type: string
2929
- }
2930
-
2931
- /** @internal */
2932
- declare interface SanityImageAssetDocument extends SanityAssetDocument {
2933
- metadata: {
2934
- _type: 'sanity.imageMetadata'
2935
- hasAlpha: boolean
2936
- isOpaque: boolean
2937
- lqip?: string
2938
- blurHash?: string
2939
- dimensions: {
2940
- _type: 'sanity.imageDimensions'
2941
- aspectRatio: number
2942
- height: number
2943
- width: number
2944
- }
2945
- palette?: {
2946
- _type: 'sanity.imagePalette'
2947
- darkMuted?: SanityImagePalette
2948
- darkVibrant?: SanityImagePalette
2949
- dominant?: SanityImagePalette
2950
- lightMuted?: SanityImagePalette
2951
- lightVibrant?: SanityImagePalette
2952
- muted?: SanityImagePalette
2953
- vibrant?: SanityImagePalette
2954
- }
2955
- image?: {
2956
- _type: 'sanity.imageExifTags'
2957
- [key: string]: Any
2958
- }
2959
- exif?: {
2960
- _type: 'sanity.imageExifMetadata'
2961
- [key: string]: Any
2962
- }
2963
- }
2964
- }
2965
-
2966
- /** @internal */
2967
- declare interface SanityImagePalette {
2968
- background: string
2969
- foreground: string
2970
- population: number
2971
- title: string
2972
- }
2973
-
2974
- /** @public */
2975
- export declare interface SanityProject {
2976
- id: string
2977
- displayName: string
2978
- /**
2979
- * @deprecated Use the `/user-applications` endpoint instead, which lists all deployed studios/applications
2980
- * @see https://www.sanity.io/help/studio-host-user-applications
2981
- */
2982
- studioHost: string | null
2983
- organizationId: string | null
2984
- isBlocked: boolean
2985
- isDisabled: boolean
2986
- isDisabledByUser: boolean
2987
- createdAt: string
2988
- pendingInvites?: number
2989
- maxRetentionDays?: number
2990
- members: SanityProjectMember[]
2991
- metadata: {
2992
- cliInitializedAt?: string
2993
- color?: string
2994
- /**
2995
- * @deprecated Use the `/user-applications` endpoint instead, which lists all deployed studios/applications
2996
- * @see https://www.sanity.io/help/studio-host-user-applications
2997
- */
2998
- externalStudioHost?: string
2999
- }
3000
- }
3001
-
3002
- /** @public */
3003
- export declare interface SanityProjectMember {
3004
- id: string
3005
- role: string
3006
- isRobot: boolean
3007
- isCurrentUser: boolean
3008
- }
3009
-
3010
- /** @public */
3011
- declare interface SanityQueries {}
3012
-
3013
- /** @public */
3014
- declare interface SanityUser {
3015
- id: string
3016
- projectId: string
3017
- displayName: string
3018
- familyName: string | null
3019
- givenName: string | null
3020
- middleName: string | null
3021
- imageUrl: string | null
3022
- createdAt: string
3023
- updatedAt: string
3024
- isCurrentUser: boolean
3025
- }
3026
-
3027
- /** @internal */
3028
- declare interface SingleActionResult {
3029
- transactionId: string
3030
- }
3031
-
3032
- /** @internal */
3033
- declare interface SingleMutationResult {
3034
- transactionId: string
3035
- documentId: string
3036
- results: {
3037
- id: string
3038
- operation: MutationOperation
3039
- }[]
3040
- }
3041
-
3042
- export {SortOrderingItem}
3043
-
3044
- /** @public */
3045
- declare type StackablePerspective = ('published' | 'drafts' | string) & {}
3046
-
3047
- /**
3048
- * @public
3049
- */
3050
- declare type Status = 'idle' | 'handshaking' | 'connected' | 'disconnected'
3051
-
3052
- /** @public */
3053
- declare interface StegaConfig {
3054
- /**
3055
- * Enable or disable stega encoded strings in query results
3056
- * ```ts
3057
- {
3058
- enabled: process.env.VERCEL_ENV !== 'production'
3059
- }
3060
- * ```
3061
- * @defaultValue `false`
3062
- */
3063
- enabled?: boolean
3064
- /**
3065
- * Where the Studio is hosted.
3066
- * If it's embedded in the app, use the base path for example `/studio`.
3067
- * Otherwise provide the full URL to where the Studio is hosted, for example: `https://blog.sanity.studio`.
3068
- *
3069
- */
3070
- studioUrl?: StudioUrl | ResolveStudioUrl
3071
- filter?: FilterDefault
3072
- /**
3073
- * Specify a `console.log` compatible logger to see debug logs, which keys are encoded and which are not.
3074
- */
3075
- logger?: Logger
3076
- /**
3077
- * Set to `true` to omit cross dataset reference specific data from encoded strings
3078
- */
3079
- omitCrossDatasetReferenceData?: boolean
3080
- }
3081
-
3082
- /** @public */
3083
- declare type StegaConfigRequiredKeys = Extract<keyof StegaConfig, 'enabled'>
3084
-
3085
- /** @alpha */
3086
- declare type StudioBaseRoute = {
3087
- baseUrl: StudioBaseUrl
3088
- workspace?: string
3089
- tool?: string
3090
- }
3091
-
3092
- /** @alpha */
3093
- declare type StudioBaseUrl = `/${string}` | `${string}.sanity.studio` | `https://${string}` | string
3094
-
3095
- /** @alpha */
3096
- declare type StudioUrl = StudioBaseUrl | StudioBaseRoute
3097
-
3098
- /** @public */
3099
- declare type SyncTag = `s1:${string}`
3100
-
3101
- /** @public */
3102
- declare class Transaction extends BaseTransaction {
3103
- #private
3104
- constructor(operations?: Mutation[], client?: SanityClient, transactionId?: string)
3105
- /**
3106
- * Clones the transaction
3107
- */
3108
- clone(): Transaction
3109
- /**
3110
- * Commit the transaction, returning a promise that resolves to the first mutated document
3111
- *
3112
- * @param options - Options for the mutation operation
3113
- */
3114
- commit<R extends Record<string, Any>>(
3115
- options: TransactionFirstDocumentMutationOptions,
3116
- ): Promise<SanityDocument_2<R>>
3117
- /**
3118
- * Commit the transaction, returning a promise that resolves to an array of the mutated documents
3119
- *
3120
- * @param options - Options for the mutation operation
3121
- */
3122
- commit<R extends Record<string, Any>>(
3123
- options: TransactionAllDocumentsMutationOptions,
3124
- ): Promise<SanityDocument_2<R>[]>
3125
- /**
3126
- * Commit the transaction, returning a promise that resolves to a mutation result object
3127
- *
3128
- * @param options - Options for the mutation operation
3129
- */
3130
- commit(options: TransactionFirstDocumentIdMutationOptions): Promise<SingleMutationResult>
3131
- /**
3132
- * Commit the transaction, returning a promise that resolves to a mutation result object
3133
- *
3134
- * @param options - Options for the mutation operation
3135
- */
3136
- commit(options: TransactionAllDocumentIdsMutationOptions): Promise<MultipleMutationResult>
3137
- /**
3138
- * Commit the transaction, returning a promise that resolves to a mutation result object
3139
- *
3140
- * @param options - Options for the mutation operation
3141
- */
3142
- commit(options?: BaseMutationOptions): Promise<MultipleMutationResult>
3143
- /**
3144
- * Performs a patch on the given document ID. Can either be a builder function or an object of patch operations.
3145
- * The operation is added to the current transaction, ready to be commited by `commit()`
3146
- *
3147
- * @param documentId - Document ID to perform the patch operation on
3148
- * @param patchOps - Operations to perform, or a builder function
3149
- */
3150
- patch(documentId: string, patchOps?: PatchBuilder | PatchOperations): this
3151
- /**
3152
- * Performs a patch on the given selection. Can either be a builder function or an object of patch operations.
3153
- *
3154
- * @param selection - An object with `query` and optional `params`, defining which document(s) to patch
3155
- * @param patchOps - Operations to perform, or a builder function
3156
- */
3157
- patch(patch: MutationSelection, patchOps?: PatchBuilder | PatchOperations): this
3158
- /**
3159
- * Adds the given patch instance to the transaction.
3160
- * The operation is added to the current transaction, ready to be commited by `commit()`
3161
- *
3162
- * @param patch - Patch to execute
3163
- */
3164
- patch(patch: Patch): this
3165
- }
3166
-
3167
- /** @internal */
3168
- declare type TransactionAllDocumentIdsMutationOptions = BaseMutationOptions & {
3169
- returnFirst?: false
3170
- returnDocuments?: false
3171
- }
3172
-
3173
- /** @internal */
3174
- declare type TransactionAllDocumentsMutationOptions = BaseMutationOptions & {
3175
- returnFirst?: false
3176
- returnDocuments: true
3177
- }
3178
-
3179
- /** @internal */
3180
- declare type TransactionFirstDocumentIdMutationOptions = BaseMutationOptions & {
3181
- returnFirst: true
3182
- returnDocuments?: false
3183
- }
3184
-
3185
- /** @internal */
3186
- declare type TransactionFirstDocumentMutationOptions = BaseMutationOptions & {
3187
- returnFirst: true
3188
- returnDocuments: true
3189
- }
3190
-
3191
- /** @public */
3192
- declare interface UnfilteredResponseQueryOptions extends ResponseQueryOptions {
3193
- filterResponse: false
3194
- /**
3195
- * When `filterResponse` is `false`, `returnQuery` also defaults to `true` for
3196
- * backwards compatibility (on the client side, not from the content lake API).
3197
- * Can also explicitly be set to `true`.
3198
- */
3199
- returnQuery?: true
3200
- }
3201
-
3202
- /**
3203
- * When using `filterResponse: false`, but you do not wish to receive back the query from
3204
- * the content lake API.
3205
- *
3206
- * @public
3207
- */
3208
- declare interface UnfilteredResponseWithoutQuery extends ResponseQueryOptions {
3209
- filterResponse: false
3210
- returnQuery: false
3211
- }
3212
-
3213
- /**
3214
- * Retract a published document.
3215
- * If there is no draft version then this is created from the published version.
3216
- * In either case the published version is deleted.
3217
- *
3218
- * @public
3219
- */
3220
- declare type UnpublishAction = {
3221
- actionType: 'sanity.action.document.unpublish'
3222
- /**
3223
- * Draft document ID to replace the published document with
3224
- */
3225
- draftId: string
3226
- /**
3227
- * Published document ID to delete
3228
- */
3229
- publishedId: string
3230
- }
3231
-
3232
- declare type Updater<TValue> = TValue | ((nextValue: TValue) => TValue)
3233
-
3234
- /** @public */
3235
- declare type UploadBody = File | Blob | Buffer | NodeJS.ReadableStream
3236
-
3237
- /** @public */
3238
- declare interface UploadClientConfig {
3239
- /**
3240
- * Optional request tag for the upload
3241
- */
3242
- tag?: string
3243
- /**
3244
- * Whether or not to preserve the original filename (default: true)
3245
- */
3246
- preserveFilename?: boolean
3247
- /**
3248
- * Filename for this file (optional)
3249
- */
3250
- filename?: string
3251
- /**
3252
- * Milliseconds to wait before timing the request out
3253
- */
3254
- timeout?: number
3255
- /**
3256
- * Mime type of the file
3257
- */
3258
- contentType?: string
3259
- /**
3260
- * Array of metadata parts to extract from asset
3261
- */
3262
- extract?: AssetMetadataType[]
3263
- /**
3264
- * Optional freeform label for the asset. Generally not used.
3265
- */
3266
- label?: string
3267
- /**
3268
- * Optional title for the asset
3269
- */
3270
- title?: string
3271
- /**
3272
- * Optional description for the asset
3273
- */
3274
- description?: string
3275
- /**
3276
- * The credit to person(s) and/or organization(s) required by the supplier of the asset to be used when published
3277
- */
3278
- creditLine?: string
3279
- /**
3280
- * Source data (when the asset is from an external service)
3281
- */
3282
- source?: {
3283
- /**
3284
- * The (u)id of the asset within the source, i.e. 'i-f323r1E'
3285
- */
3286
- id: string
3287
- /**
3288
- * The name of the source, i.e. 'unsplash'
3289
- */
3290
- name: string
3291
- /**
3292
- * A url to where to find the asset, or get more info about it in the source
3293
- */
3294
- url?: string
3295
- }
3296
- }
3297
-
3298
- /**
3299
- *
3300
- * @beta
3301
- *
3302
- * Provides a callback for applying one or more actions to a document.
3303
- *
3304
- * @category Documents
3305
- * @param resourceId - The resource ID of the document to apply actions to. If not provided, the document will use the default resource.
3306
- * @returns A function that takes one more more {@link DocumentAction}s and returns a promise that resolves to an {@link ActionsResult}.
3307
- * @example Publish or unpublish a document
3308
- * ```
3309
- * import { publishDocument, unpublishDocument } from '@sanity/sdk'
3310
- * import { useApplyActions } from '@sanity/sdk-react'
3311
- *
3312
- * const apply = useApplyActions()
3313
- * const myDocument = { _id: 'my-document-id', _type: 'my-document-type' }
3314
- *
3315
- * return (
3316
- * <button onClick={() => apply(publishDocument(myDocument))}>Publish</button>
3317
- * <button onClick={() => apply(unpublishDocument(myDocument))}>Unpublish</button>
3318
- * )
3319
- * ```
3320
- *
3321
- * @example Create and publish a new document
3322
- * ```
3323
- * import { createDocument, publishDocument } from '@sanity/sdk'
3324
- * import { useApplyActions } from '@sanity/sdk-react'
3325
- *
3326
- * const apply = useApplyActions()
3327
- *
3328
- * const handleCreateAndPublish = () => {
3329
- * const handle = { _id: window.crypto.randomUUID(), _type: 'my-document-type' }
3330
- * apply([
3331
- * createDocument(handle),
3332
- * publishDocument(handle),
3333
- * ])
3334
- * }
3335
- *
3336
- * return (
3337
- * <button onClick={handleCreateAndPublish}>
3338
- * I’m feeling lucky
3339
- * </button>
3340
- * )
3341
- * ```
3342
- */
3343
- export declare function useApplyActions(
3344
- resourceId?: ResourceId,
3345
- ): <TDocument extends SanityDocument>(
3346
- action: DocumentAction<TDocument> | DocumentAction<TDocument>[],
3347
- options?: ApplyActionsOptions,
3348
- ) => Promise<ActionsResult<TDocument>>
3349
-
3350
- /**
3351
- * @internal
3352
- * A React hook that subscribes to authentication state changes.
3353
- *
3354
- * This hook provides access to the current authentication state type from the Sanity auth store.
3355
- * It automatically re-renders when the authentication state changes.
3356
- *
3357
- * @remarks
3358
- * The hook uses `useSyncExternalStore` to safely subscribe to auth state changes
3359
- * and ensure consistency between server and client rendering.
3360
- *
3361
- * @returns The current authentication state type
3362
- *
3363
- * @example
3364
- * ```tsx
3365
- * function AuthStatus() {
3366
- * const authState = useAuthState()
3367
- * return <div>Current auth state: {authState}</div>
3368
- * }
3369
- * ```
3370
- */
3371
- export declare const useAuthState: () => AuthState
3372
-
3373
- /**
3374
- * Hook to get the currently logged in user
3375
- * @internal
3376
- * @returns The current user or null if not authenticated
3377
- */
3378
- export declare const useAuthToken: () => string | null
3379
-
3380
- /**
3381
- * A React hook that provides a client that subscribes to changes in your application,
3382
- * such as user authentication changes.
3383
- *
3384
- * @remarks
3385
- * The hook uses `useSyncExternalStore` to safely subscribe to changes
3386
- * and ensure consistency between server and client rendering.
3387
- *
3388
- * @category Platform
3389
- * @returns A Sanity client
3390
- *
3391
- * @example
3392
- * ```tsx
3393
- * function MyComponent() {
3394
- * const client = useClient({apiVersion: '2024-11-12'})
3395
- * const [document, setDocument] = useState(null)
3396
- * useEffect(async () => {
3397
- * const doc = client.fetch('*[_id == "myDocumentId"]')
3398
- * setDocument(doc)
3399
- * }, [])
3400
- * return <div>{JSON.stringify(document) ?? 'Loading...'}</div>
3401
- * }
3402
- * ```
3403
- *
3404
- * @public
3405
- */
3406
- export declare const useClient: (e: ClientOptions) => SanityClient
3407
-
3408
- declare type UseCurrentUser = {
3409
- /**
3410
- * @public
3411
- *
3412
- * Provides the currently authenticated user’s profile information.
3413
- *
3414
- * @category Users
3415
- * @returns The current user data
3416
- *
3417
- * @example Rendering a basic user profile
3418
- * ```
3419
- * const user = useCurrentUser()
3420
- *
3421
- * return (
3422
- * <figure>
3423
- * <img src={user?.profileImage} alt=`Profile image for ${user?.name}` />
3424
- * <h2>{user?.name}</h2>
3425
- * </figure>
3426
- * )
3427
- * ```
3428
- */
3429
- (): CurrentUser | null
3430
- }
3431
-
3432
- /**
3433
- * @public
3434
- * @TODO This should not return null — users of a custom app will always be authenticated via Core
3435
- */
3436
- export declare const useCurrentUser: UseCurrentUser
3437
-
3438
- declare type UseDatasets = {
3439
- /**
3440
- *
3441
- * Returns metadata for each dataset in your organization.
3442
- *
3443
- * @category Datasets
3444
- * @returns The metadata for your organization's datasets
3445
- *
3446
- * @example
3447
- * ```tsx
3448
- * const datasets = useDatasets()
3449
- *
3450
- * return (
3451
- * <select>
3452
- * {datasets.map((dataset) => (
3453
- * <option key={dataset.name}>{dataset.name}</option>
3454
- * ))}
3455
- * </select>
3456
- * )
3457
- * ```
3458
- *
3459
- */
3460
- (): DatasetsResponse
3461
- }
3462
-
3463
- /** @public */
3464
- export declare const useDatasets: UseDatasets
3465
-
3466
- /**
3467
- * @beta
3468
- *
3469
- * ## useDocument(doc, path)
3470
- * Read and subscribe to nested values in a document
3471
- * @category Documents
3472
- * @param doc - The document to read state from. If you pass a `DocumentHandle` with a `resourceId` in the DocumentResourceId format (`document:projectId.dataset:documentId`)
3473
- * the document will be read from the specified Sanity project and dataset that is included in the handle. If no `resourceId` is provided, the default project and dataset from your `SanityApp` configuration will be used.
3474
- * @param path - The path to the nested value to read from
3475
- * @returns The value at the specified path
3476
- * @example
3477
- * ```tsx
3478
- * import {type DocumentHandle, useDocument} from '@sanity/sdk-react'
3479
- *
3480
- * function OrderLink({documentHandle}: {documentHandle: DocumentHandle}) {
3481
- * const title = useDocument(documentHandle, 'title')
3482
- * const id = useDocument(documentHandle, '_id')
3483
- *
3484
- * return (
3485
- * <a href=`/order/${id}`>Order {title} today!</a>
3486
- * )
3487
- * }
3488
- * ```
3489
- *
3490
- */
3491
- export declare function useDocument<
3492
- TDocument extends SanityDocument,
3493
- TPath extends JsonMatchPath<TDocument>,
3494
- >(doc: DocumentHandle<TDocument>, path: TPath): JsonMatch<TDocument, TPath> | undefined
3495
-
3496
- /**
3497
- * @beta
3498
- * ## useDocument(doc)
3499
- * Read and subscribe to an entire document
3500
- * @param doc - The document to read state from
3501
- * @returns The document state as an object
3502
- * @example
3503
- * ```tsx
3504
- * import {type SanityDocument, type DocumentHandle, useDocument} from '@sanity/sdk-react'
3505
- *
3506
- * interface Book extends SanityDocument {
3507
- * title: string
3508
- * author: string
3509
- * summary: string
3510
- * }
3511
- *
3512
- * function DocumentView({documentHandle}: {documentHandle: DocumentHandle}) {
3513
- * const book = useDocument<Book>(documentHandle)
3514
- *
3515
- * return (
3516
- * <article>
3517
- * <h1>{book?.title}</h1>
3518
- * <address>By {book?.author}</address>
3519
- *
3520
- * <h2>Summary</h2>
3521
- * {book?.summary}
3522
- *
3523
- * <h2>Order</h2>
3524
- * <a href=`/order/${book._id}`>Order {book?.title} today!</a>
3525
- * </article>
3526
- * )
3527
- * }
3528
- * ```
3529
- *
3530
- */
3531
- export declare function useDocument<TDocument extends SanityDocument>(
3532
- doc: DocumentHandle<TDocument>,
3533
- ): TDocument | null
3534
-
3535
- /**
3536
- *
3537
- * @beta
3538
- *
3539
- * Subscribes an event handler to events in your application’s document store, such as document
3540
- * creation, deletion, and updates.
3541
- *
3542
- * @category Documents
3543
- * @param handler - The event handler to register.
3544
- * @param doc - The document to subscribe to events for. If you pass a `DocumentHandle` with a `resourceId` (in the format of `document:projectId.dataset:documentId`)
3545
- * the document will be read from the specified Sanity project and dataset that is included in the handle. If no `resourceId` is provided, the default project and dataset from your `SanityApp` configuration will be used.
3546
- * @example
3547
- * ```
3548
- * import {useDocumentEvent} from '@sanity/sdk-react'
3549
- * import {type DocumentEvent} from '@sanity/sdk'
3550
- *
3551
- * useDocumentEvent((event) => {
3552
- * if (event.type === DocumentEvent.DocumentDeletedEvent) {
3553
- * alert(`Document with ID ${event.documentId} deleted!`)
3554
- * } else {
3555
- * console.log(event)
3556
- * }
3557
- * })
3558
- * ```
3559
- */
3560
- export declare function useDocumentEvent(
3561
- handler: (documentEvent: DocumentEvent) => void,
3562
- doc: DocumentHandle,
3563
- ): void
3564
-
3565
- declare type UseDocumentSyncStatus = {
3566
- /**
3567
- * Exposes the document’s sync status between local and remote document states.
3568
- *
3569
- * @category Documents
3570
- * @param doc - The document handle to get sync status for. If you pass a `DocumentHandle` with a `resourceId` (in the format of `document:projectId.dataset:documentId`)
3571
- * the document will be read from the specified Sanity project and dataset that is included in the handle. If no `resourceId` is provided, the default project and dataset from your `SanityApp` configuration will be used.
3572
- * @returns `true` if local changes are synced with remote, `false` if the changes are not synced, and `undefined` if the document is not found
3573
- * @example Disable a Save button when there are no changes to sync
3574
- * ```
3575
- * const myDocumentHandle = { _id: 'documentId', _type: 'documentType', resourceId: 'document:projectId:dataset:documentId' }
3576
- * const documentSynced = useDocumentSyncStatus(myDocumentHandle)
3577
- *
3578
- * return (
3579
- * <button disabled={documentSynced}>
3580
- * Save Changes
3581
- * </button>
3582
- * )
3583
- * ```
3584
- */
3585
- (doc: DocumentHandle): boolean | undefined
3586
- }
3587
-
3588
- /** @beta */
3589
- export declare const useDocumentSyncStatus: UseDocumentSyncStatus
3590
-
3591
- /**
3592
- *
3593
- * @beta
3594
- *
3595
- * ## useEditDocument(doc, path)
3596
- * Edit a nested value within a document
3597
- *
3598
- * @category Documents
3599
- * @param doc - The document to be edited; either as a document handle or the document’s ID a string
3600
- * @param path - The path to the nested value to be edited
3601
- * @returns A function to update the nested value. Accepts either a new value, or an updater function that exposes the previous value and returns a new value.
3602
- * @example Update a document’s name by providing the new value directly
3603
- * ```
3604
- * const handle = { _id: 'documentId', _type: 'documentType' }
3605
- * const name = useDocument(handle, 'name')
3606
- * const editName = useEditDocument(handle, 'name')
3607
- *
3608
- * function handleNameChange(event: React.ChangeEvent<HTMLInputElement>) {
3609
- * editName(event.target.value)
3610
- * }
3611
- *
3612
- * return (
3613
- * <input type='text' value={name} onChange={handleNameChange} />
3614
- * )
3615
- * ```
3616
- *
3617
- * @example Update a count on a document by providing an updater function
3618
- * ```
3619
- * const handle = { _id: 'documentId', _type: 'documentType' }
3620
- * const count = useDocument(handle, 'count')
3621
- * const editCount = useEditDocument(handle, 'count')
3622
- *
3623
- * function incrementCount() {
3624
- * editCount(previousCount => previousCount + 1)
3625
- * }
3626
- *
3627
- * return (
3628
- * <>
3629
- * <button onClick={incrementCount}>
3630
- * Increment
3631
- * </button>
3632
- * Current count: {count}
3633
- * </>
3634
- * )
3635
- * ```
3636
- */
3637
- export declare function useEditDocument<
3638
- TDocument extends SanityDocument,
3639
- TPath extends JsonMatchPath<TDocument>,
3640
- >(
3641
- doc: DocumentHandle<TDocument>,
3642
- path: TPath,
3643
- ): (nextValue: Updater<JsonMatch<TDocument, TPath>>) => Promise<ActionsResult<TDocument>>
3644
-
3645
- /**
3646
- *
3647
- * @beta
3648
- *
3649
- * ## useEditDocument(doc)
3650
- * Edit an entire document
3651
- * @param doc - The document to be edited; either as a document handle or the document’s ID a string. If you pass a `DocumentHandle` with a `resourceId` (in the format of `document:projectId.dataset:documentId`)
3652
- * the document will be read from the specified Sanity project and dataset that is included in the handle. If no `resourceId` is provided, the default project and dataset from your `SanityApp` configuration will be used.
3653
- * @returns A function to update the document state. Accepts either a new document state, or an updater function that exposes the previous document state and returns the new document state.
3654
- * @example
3655
- * ```
3656
- * const myDocumentHandle = { _id: 'documentId', _type: 'documentType' }
3657
- *
3658
- * const myDocument = useDocument(myDocumentHandle)
3659
- * const { title, price } = myDocument
3660
- *
3661
- * const editMyDocument = useEditDocument(myDocumentHandle)
3662
- *
3663
- * function handleFieldChange(e: React.ChangeEvent<HTMLInputElement>) {
3664
- * const {name, value} = e.currentTarget
3665
- * // Use an updater function to update the document state based on the previous state
3666
- * editMyDocument(previousDocument => ({
3667
- * ...previousDocument,
3668
- * [name]: value
3669
- * }))
3670
- * }
3671
- *
3672
- * function handleSaleChange(e: React.ChangeEvent<HTMLInputElement>) {
3673
- * const { checked } = e.currentTarget
3674
- * if (checked) {
3675
- * // Use an updater function to add a new salePrice field;
3676
- * // set it at a 20% discount off the normal price
3677
- * editMyDocument(previousDocument => ({
3678
- * ...previousDocument,
3679
- * salePrice: previousDocument.price * 0.8,
3680
- * }))
3681
- * } else {
3682
- * // Get the document state without the salePrice field
3683
- * const { salePrice, ...rest } = myDocument
3684
- * // Update the document state to remove the salePrice field
3685
- * editMyDocument(rest)
3686
- * }
3687
- * }
3688
- *
3689
- * return (
3690
- * <>
3691
- * <form onSubmit={e => e.preventDefault()}>
3692
- * <input name='title' type='text' value={title} onChange={handleFieldChange} />
3693
- * <input name='price' type='number' value={price} onChange={handleFieldChange} />
3694
- * <input
3695
- * name='salePrice'
3696
- * type='checkbox'
3697
- * checked={Object(myDocument).hasOwnProperty('salePrice')}
3698
- * onChange={handleSaleChange}
3699
- * />
3700
- * </form>
3701
- * <pre><code>
3702
- * {JSON.stringify(myDocument, null, 2)}
3703
- * </code></pre>
3704
- * </>
3705
- * )
3706
- * ```
3707
- */
3708
- export declare function useEditDocument<TDocument extends SanityDocument>(
3709
- doc: DocumentHandle<TDocument>,
3710
- ): (nextValue: Updater<TDocument>) => Promise<ActionsResult<TDocument>>
3711
-
3712
- /**
3713
- * @internal
3714
- */
3715
- export declare function useFrameConnection<
3716
- TFrameMessage extends FrameMessage,
3717
- TWindowMessage extends WindowMessage,
3718
- >(options: UseFrameConnectionOptions<TWindowMessage>): FrameConnection<TFrameMessage>
3719
-
3720
- /**
3721
- * @internal
3722
- */
3723
- export declare interface UseFrameConnectionOptions<TWindowMessage extends WindowMessage> {
3724
- name: string
3725
- connectTo: string
3726
- targetOrigin: string
3727
- onMessage?: {
3728
- [K in TWindowMessage['type']]: (
3729
- data: Extract<
3730
- TWindowMessage,
3731
- {
3732
- type: K
3733
- }
3734
- >['data'],
3735
- ) => void
3736
- }
3737
- heartbeat?: boolean
3738
- }
3739
-
3740
- /**
3741
- * @internal
3742
- * A React hook that returns a function for handling authentication callbacks.
3743
- *
3744
- * @remarks
3745
- * This hook provides access to the authentication store's callback handler,
3746
- * which processes auth redirects by extracting the session ID and fetching the
3747
- * authentication token. If fetching the long-lived token is successful,
3748
- * `handleCallback` will return a Promise that resolves a new location that
3749
- * removes the short-lived token from the URL. Use this in combination with
3750
- * `history.replaceState` or your own router's `replace` function to update the
3751
- * current location without triggering a reload.
3752
- *
3753
- * @example
3754
- * ```tsx
3755
- * function AuthCallback() {
3756
- * const handleCallback = useHandleCallback()
3757
- * const router = useRouter() // Example router
3758
- *
3759
- * useEffect(() => {
3760
- * async function processCallback() {
3761
- * // Handle the callback and get the cleaned URL
3762
- * const newUrl = await handleCallback(window.location.href)
3763
- *
3764
- * if (newUrl) {
3765
- * // Replace URL without triggering navigation
3766
- * router.replace(newUrl, {shallow: true})
3767
- * }
3768
- * }
3769
- *
3770
- * processCallback().catch(console.error)
3771
- * }, [handleCallback, router])
3772
- *
3773
- * return <div>Completing login...</div>
3774
- * }
3775
- * ```
3776
- *
3777
- * @returns A callback handler function that processes OAuth redirects
3778
- * @public
3779
- */
3780
- export declare const useHandleCallback: () => (
3781
- locationHref?: string | undefined,
3782
- ) => Promise<string | false>
3783
-
3784
- /**
3785
- * Retrieves batches of {@link DocumentHandle}s, narrowed by optional filters, text searches, and custom ordering,
3786
- * with infinite scrolling support. The number of document handles returned per batch is customizable,
3787
- * and additional batches can be loaded using the supplied `loadMore` function.
3788
- *
3789
- * @beta
3790
- * @category Documents
3791
- * @param options - Configuration options for the infinite list
3792
- * @returns An object containing the list of document handles, the loading state, the total count of retrived document handles, and a function to load more
3793
- * @example
3794
- * ```tsx
3795
- * const {data, hasMore, isPending, loadMore} = useInfiniteList({
3796
- * filter: '_type == "post"',
3797
- * search: searchTerm,
3798
- * batchSize: 10,
3799
- * orderings: [{field: '_createdAt', direction: 'desc'}]
3800
- * })
3801
- *
3802
- * return (
3803
- * <div>
3804
- * Total documents: {count}
3805
- * <ol>
3806
- * {data.map((doc) => (
3807
- * <li key={doc._id}>
3808
- * <MyDocumentComponent doc={doc} />
3809
- * </li>
3810
- * ))}
3811
- * </ol>
3812
- * {hasMore && <button onClick={loadMore}>Load More</button>}
3813
- * </div>
3814
- * )
3815
- * ```
3816
- *
3817
- */
3818
- export declare function useInfiniteList({
3819
- batchSize,
3820
- params,
3821
- search,
3822
- filter,
3823
- orderings,
3824
- ...options
3825
- }: InfiniteListOptions): InfiniteList
3826
-
3827
- /**
3828
- * @internal
3829
- * A React hook that retrieves the available authentication provider URLs for login.
3830
- *
3831
- * @remarks
3832
- * This hook fetches the login URLs from the Sanity auth store when the component mounts.
3833
- * Each provider object contains information about an authentication method, including its URL.
3834
- * The hook will suspend if the login URLs have not yet loaded.
3835
- *
3836
- * @example
3837
- * ```tsx
3838
- * // LoginProviders component that uses the hook
3839
- * function LoginProviders() {
3840
- * const providers = useLoginUrls()
3841
- *
3842
- * return (
3843
- * <div>
3844
- * {providers.map((provider) => (
3845
- * <a key={provider.name} href={provider.url}>
3846
- * Login with {provider.title}
3847
- * </a>
3848
- * ))}
3849
- * </div>
3850
- * )
3851
- * }
3852
- *
3853
- * // Parent component with Suspense boundary
3854
- * function LoginPage() {
3855
- * return (
3856
- * <Suspense fallback={<div>Loading authentication providers...</div>}>
3857
- * <LoginProviders />
3858
- * </Suspense>
3859
- * )
3860
- * }
3861
- * ```
3862
- *
3863
- * @returns An array of {@link AuthProvider} objects containing login URLs and provider information
3864
- * @public
3865
- */
3866
- export declare function useLoginUrls(): AuthProvider[]
3867
-
3868
- /**
3869
- * Hook to log out of the current session
3870
- * @internal
3871
- * @returns A function to log out of the current session
3872
- */
3873
- export declare const useLogOut: () => () => Promise<void>
3874
-
3875
- /**
3876
- * Retrieves pages of {@link DocumentHandle}s, narrowed by optional filters, text searches, and custom ordering,
3877
- * with support for traditional paginated interfaces. The number of document handles returned per page is customizable,
3878
- * while page navigation is handled via the included navigation functions.
3879
- *
3880
- * @beta
3881
- * @category Documents
3882
- * @param options - Configuration options for the paginated list
3883
- * @returns An object containing the current page of document handles, the loading and pagination state, and navigation functions
3884
- * @example
3885
- * ```tsx
3886
- * const {
3887
- * data,
3888
- * isPending,
3889
- * currentPage,
3890
- * totalPages,
3891
- * nextPage,
3892
- * previousPage,
3893
- * hasNextPage,
3894
- * hasPreviousPage
3895
- * } = usePaginatedList({
3896
- * filter: '_type == "post"',
3897
- * search: searchTerm,
3898
- * pageSize: 10,
3899
- * orderings: [{field: '_createdAt', direction: 'desc'}]
3900
- * })
3901
- *
3902
- * return (
3903
- * <>
3904
- * <table>
3905
- * {data.map(doc => (
3906
- * <MyTableRowComponent key={doc._id} doc={doc} />
3907
- * ))}
3908
- * </table>
3909
- * <>
3910
- * {hasPreviousPage && <button onClick={previousPage}>Previous</button>}
3911
- * {currentPage} / {totalPages}
3912
- * {hasNextPage && <button onClick={nextPage}>Next</button>}
3913
- * </>
3914
- * </>
3915
- * )
3916
- * ```
3917
- *
3918
- */
3919
- export declare function usePaginatedList({
3920
- filter,
3921
- pageSize,
3922
- params,
3923
- orderings,
3924
- search,
3925
- ...options
3926
- }?: PaginatedListOptions): PaginatedList
3927
-
3928
- /**
3929
- *
3930
- * @beta
3931
- *
3932
- * Check if the current user has the specified permissions for the given document actions.
3933
- *
3934
- * @category Permissions
3935
- * @param actions - One more more calls to a particular document action function for a given document
3936
- * @returns An object that specifies whether the action is allowed; if the action is not allowed, an explanatory message and list of reasons is also provided.
3937
- *
3938
- * @example Checking for permission to publish a document
3939
- * ```ts
3940
- * import {usePermissions, useApplyActions} from '@sanity/sdk-react'
3941
- * import {publishDocument} from '@sanity/sdk'
3942
- *
3943
- * export function PublishButton({doc}: {doc: DocumentHandle}) {
3944
- * const canPublish = usePermissions(publishDocument(doc))
3945
- * const applyAction = useApplyActions()
3946
- *
3947
- * return (
3948
- * <>
3949
- * <button
3950
- * disabled={!canPublish.allowed}
3951
- * onClick={() => applyAction(publishDocument(doc))}
3952
- * popoverTarget={`${canPublish.allowed ? undefined : 'publishButtonPopover'}`}
3953
- * >
3954
- * Publish
3955
- * </button>
3956
- * {!canPublish.allowed && (
3957
- * <div popover id="publishButtonPopover">
3958
- * {canPublish.message}
3959
- * </div>
3960
- * )}
3961
- * </>
3962
- * )
3963
- * }
3964
- * ```
3965
- */
3966
- export declare function usePermissions(
3967
- actions: DocumentAction | DocumentAction[],
3968
- ): PermissionsResult
3969
-
3970
- /**
3971
- * @beta
3972
- *
3973
- * Returns the preview values of a document (specified via a `DocumentHandle`),
3974
- * including the document’s `title`, `subtitle`, `media`, and `status`. These values are live and will update in realtime.
3975
- * To reduce unnecessary network requests for resolving the preview values, an optional `ref` can be passed to the hook so that preview
3976
- * resolution will only occur if the `ref` is intersecting the current viewport.
3977
- *
3978
- * @category Documents
3979
- * @param options - The document handle for the document you want to resolve preview values for, and an optional ref
3980
- * @returns The preview values for the given document and a boolean to indicate whether the resolution is pending
3981
- *
3982
- * @example Combining with useDocuments to render a collection of document previews
3983
- * ```
3984
- * // PreviewComponent.jsx
3985
- * export default function PreviewComponent({ document }) {
3986
- * const { results: { title, subtitle, media }, isPending } = usePreview({ document })
3987
- * return (
3988
- * <article style={{ opacity: isPending ? 0.5 : 1}}>
3989
- * {media?.type === 'image-asset' ? <img src={media.url} alt='' /> : ''}
3990
- * <h2>{title}</h2>
3991
- * <p>{subtitle}</p>
3992
- * </article>
3993
- * )
3994
- * }
3995
- *
3996
- * // DocumentList.jsx
3997
- * const { results, isPending } = useDocuments({ filter: '_type == "movie"' })
3998
- * return (
3999
- * <div>
4000
- * <h1>Movies</h1>
4001
- * <ul>
4002
- * {isPending ? 'Loading…' : results.map(movie => (
4003
- * <li key={movie._id}>
4004
- * <Suspense fallback='Loading…'>
4005
- * <PreviewComponent document={movie} />
4006
- * </Suspense>
4007
- * </li>
4008
- * ))}
4009
- * </ul>
4010
- * </div>
4011
- * )
4012
- * ```
4013
- */
4014
- export declare function usePreview({
4015
- document: {_id, _type},
4016
- ref,
4017
- }: UsePreviewOptions): UsePreviewResults
4018
-
4019
- /**
4020
- * @beta
4021
- * @category Types
4022
- */
4023
- export declare interface UsePreviewOptions {
4024
- document: DocumentHandle
4025
- ref?: React.RefObject<unknown>
4026
- }
4027
-
4028
- /**
4029
- * @beta
4030
- * @category Types
4031
- */
4032
- export declare interface UsePreviewResults {
4033
- /** The results of resolving the document’s preview values */
4034
- results: PreviewValue
4035
- /** True when preview values are being refreshed */
4036
- isPending: boolean
4037
- }
4038
-
4039
- declare type UseProject = {
4040
- /**
4041
- *
4042
- * Returns metadata for a given project
4043
- *
4044
- * @category Projects
4045
- * @param projectId - The ID of the project to retrieve metadata for
4046
- * @returns The metadata for the project
4047
- * @example
4048
- * ```tsx
4049
- * function ProjectMetadata({ projectId }: { projectId: string }) {
4050
- * const project = useProject(projectId)
4051
- *
4052
- * return (
4053
- * <figure style={{ backgroundColor: project.metadata.color || 'lavender'}}>
4054
- * <h1>{project.displayName}</h1>
4055
- * </figure>
4056
- * )
4057
- * }
4058
- * ```
4059
- */
4060
- (projectId: string): SanityProject_2
4061
- }
4062
-
4063
- /** @public */
4064
- export declare const useProject: UseProject
4065
-
4066
- /**
4067
- * @beta
4068
- *
4069
- * Returns the projection values of a document (specified via a `DocumentHandle`),
4070
- * based on the provided projection string. These values are live and will update in realtime.
4071
- * To reduce unnecessary network requests for resolving the projection values, an optional `ref` can be passed to the hook so that projection
4072
- * resolution will only occur if the `ref` is intersecting the current viewport.
4073
- *
4074
- * @category Documents
4075
- * @param options - The document handle for the document you want to project values from, the projection string, and an optional ref
4076
- * @returns The projection values for the given document and a boolean to indicate whether the resolution is pending
4077
- *
4078
- * @example Using a projection to display specific document fields
4079
- * ```
4080
- * // ProjectionComponent.jsx
4081
- * export default function ProjectionComponent({ document }) {
4082
- * const ref = useRef(null)
4083
- * const { results: { title, description, authors }, isPending } = useProjection({
4084
- * document,
4085
- * projection: '{title, "description": pt::text("description"), "authors": array::join(authors[]->name, ", ")}',
4086
- * ref
4087
- * })
4088
- *
4089
- * return (
4090
- * <article ref={ref} style={{ opacity: isPending ? 0.5 : 1}}>
4091
- * <h2>{title}</h2>
4092
- * <p>{description}</p>
4093
- * <p>{authors}</p>
4094
- * </article>
4095
- * )
4096
- * }
4097
- * ```
4098
- *
4099
- * @example Combining with useInfiniteList to render a collection with specific fields
4100
- * ```
4101
- * // DocumentList.jsx
4102
- * const { data } = useInfiniteList({ filter: '_type == "article"' })
4103
- * return (
4104
- * <div>
4105
- * <h1>Articles</h1>
4106
- * <ul>
4107
- * {data.map(article => (
4108
- * <li key={article._id}>
4109
- * <Suspense fallback='Loading…'>
4110
- * <ProjectionComponent
4111
- * document={article}
4112
- * />
4113
- * </Suspense>
4114
- * </li>
4115
- * ))}
4116
- * </ul>
4117
- * </div>
4118
- * )
4119
- * ```
4120
- */
4121
- export declare function useProjection<TResult extends object>({
4122
- document: {_id, _type},
4123
- projection,
4124
- ref,
4125
- }: UseProjectionOptions): UseProjectionResults<TResult>
4126
-
4127
- declare interface UseProjectionOptions {
4128
- document: DocumentHandle
4129
- projection: ValidProjection
4130
- ref?: React.RefObject<unknown>
4131
- }
4132
-
4133
- declare interface UseProjectionResults<TResult extends object> {
4134
- results: TResult
4135
- isPending: boolean
4136
- }
4137
-
4138
- declare type UseProjects = {
4139
- /**
4140
- *
4141
- * Returns metadata for each project in your organization.
4142
- *
4143
- * @category Projects
4144
- * @returns An array of metadata (minus the projects’ members) for each project in your organization
4145
- * @example
4146
- * ```tsx
4147
- * const projects = useProjects()
4148
- *
4149
- * return (
4150
- * <select>
4151
- * {projects.map((project) => (
4152
- * <option key={project.id}>{project.displayName}</option>
4153
- * ))}
4154
- * </select>
4155
- * )
4156
- * ```
4157
- */
4158
- (): ProjectWithoutMembers[]
4159
- }
4160
-
4161
- /** @public */
4162
- export declare const useProjects: UseProjects
4163
-
4164
- /**
4165
- * Executes GROQ queries against a Sanity dataset.
4166
- *
4167
- * This hook provides a convenient way to fetch and subscribe to real-time updates
4168
- * for your Sanity content. Changes made to the dataset’s content will trigger
4169
- * automatic updates.
4170
- *
4171
- * @remarks
4172
- * The returned `isPending` flag indicates when a React transition is in progress,
4173
- * which can be used to show loading states for query changes.
4174
- *
4175
- * @beta
4176
- * @category GROQ
4177
- * @param query - GROQ query string to execute
4178
- * @param options - Optional configuration for the query
4179
- * @returns Object containing the query result and a pending state flag
4180
- *
4181
- * @example Basic usage
4182
- * ```tsx
4183
- * const {data, isPending} = useQuery<Movie[]>('*[_type == "movie"]')
4184
- * ```
4185
- *
4186
- * @example Using parameters
4187
- * ```tsx
4188
- * // With parameters
4189
- * const {data} = useQuery<Movie>('*[_type == "movie" && _id == $id][0]', {
4190
- * params: { id: 'movie-123' }
4191
- * })
4192
- * ```
4193
- *
4194
- * @example With a loading state for transitions
4195
- * ```tsx
4196
- * const {data, isPending} = useQuery<Movie[]>('*[_type == "movie"]')
4197
- * return (
4198
- * <div>
4199
- * {isPending && <div>Updating...</div>}
4200
- * <ul>
4201
- * {data.map(movie => <li key={movie._id}>{movie.title}</li>)}
4202
- * </ul>
4203
- * </div>
4204
- * )
4205
- * ```
4206
- *
4207
- */
4208
- export declare function useQuery<T>(
4209
- query: string,
4210
- options?: QueryOptions,
4211
- ): {
4212
- data: T
4213
- isPending: boolean
4214
- }
4215
-
4216
- /** @public */
4217
- declare class UsersClient {
4218
- #private
4219
- constructor(client: SanityClient, httpRequest: HttpRequest)
4220
- /**
4221
- * Fetch a user by user ID
4222
- *
4223
- * @param id - User ID of the user to fetch. If `me` is provided, a minimal response including the users role is returned.
4224
- */
4225
- getById<T extends 'me' | string>(id: T): Promise<T extends 'me' ? CurrentSanityUser : SanityUser>
4226
- }
4227
-
4228
- /**
4229
- * `useSanityInstance` returns the current Sanity instance from the application context.
4230
- * This must be called from within a `SanityProvider` component.
4231
- * @internal
4232
- *
4233
- * @param resourceId - The resourceId of the Sanity instance to return (optional)
4234
- * @returns The current Sanity instance
4235
- * @example
4236
- * ```tsx
4237
- * const instance = useSanityInstance('abc123.production')
4238
- * ```
4239
- */
4240
- export declare const useSanityInstance: (resourceId?: string) => SanityInstance
4241
-
4242
- /**
4243
- *
4244
- * @public
4245
- *
4246
- * Retrieves the users for a given resource (either a project or an organization).
4247
- *
4248
- * @category Users
4249
- * @param params - The resource type and its ID, and the limit of users to fetch
4250
- * @returns A list of users, a boolean indicating whether there are more users to fetch, and a function to load more users
4251
- *
4252
- * @example
4253
- * ```
4254
- * const { users, hasMore, loadMore } = useUsers({
4255
- * resourceType: 'organization',
4256
- * resourceId: 'my-org-id',
4257
- * limit: 10,
4258
- * })
4259
- *
4260
- * return (
4261
- * <div>
4262
- * {users.map(user => (
4263
- * <figure key={user.sanityUserId}>
4264
- * <img src={user.profile.imageUrl} alt='' />
4265
- * <figcaption>{user.profile.displayName}</figcaption>
4266
- * <address>{user.profile.email}</address>
4267
- * </figure>
4268
- * ))}
4269
- * {hasMore && <button onClick={loadMore}>Load More</button>}
4270
- * </div>
4271
- * )
4272
- * ```
4273
- */
4274
- export declare function useUsers(params: UseUsersParams): UseUsersResult
4275
-
4276
- /**
4277
- * @public
4278
- * @category Types
4279
- */
4280
- export declare interface UseUsersParams {
4281
- /**
4282
- * The type of resource to fetch users for.
4283
- */
4284
- resourceType: ResourceType
4285
- /**
4286
- * The ID of the resource to fetch users for.
4287
- */
4288
- resourceId: string
4289
- /**
4290
- * The limit of users to fetch.
4291
- */
4292
- limit?: number
4293
- }
4294
-
4295
- /**
4296
- * @public
4297
- * @category Types
4298
- */
4299
- export declare interface UseUsersResult {
4300
- /**
4301
- * The users fetched.
4302
- */
4303
- users: SanityUser_2[]
4304
- /**
4305
- * Whether there are more users to fetch.
4306
- */
4307
- hasMore: boolean
4308
- /**
4309
- * Load more users.
4310
- */
4311
- loadMore: () => void
4312
- }
4313
-
4314
- /**
4315
- * @internal
4316
- */
4317
- export declare function useWindowConnection<
4318
- TWindowMessage extends WindowMessage,
4319
- TFrameMessage extends FrameMessage,
4320
- >(options: UseWindowConnectionOptions<TFrameMessage>): WindowConnection<TWindowMessage>
4321
-
4322
- /**
4323
- * @internal
4324
- */
4325
- export declare interface UseWindowConnectionOptions<TMessage extends FrameMessage> {
4326
- name: string
4327
- connectTo: string
4328
- onMessage?: Record<TMessage['type'], WindowMessageHandler<TMessage>>
4329
- }
4330
-
4331
- /**
4332
- * The listener has been established, and will start receiving events.
4333
- * Note that this is also emitted upon _reconnection_.
4334
- *
4335
- * @public
4336
- */
4337
- declare type WelcomeEvent = {
4338
- type: 'welcome'
4339
- listenerName: string
4340
- }
4341
-
4342
- /**
4343
- * @internal
4344
- */
4345
- export declare interface WindowConnection<TMessage extends WindowMessage> {
4346
- sendMessage: <TType extends TMessage['type']>(
4347
- type: TType,
4348
- data?: Extract<
4349
- TMessage,
4350
- {
4351
- type: TType
4352
- }
4353
- >['data'],
4354
- ) => void
4355
- status: Status
4356
- }
4357
-
4358
- /**
4359
- * @internal
4360
- */
4361
- export declare type WindowMessageHandler<TFrameMessage extends FrameMessage> = (
4362
- event: TFrameMessage['data'],
4363
- ) => TFrameMessage['response']
4364
-
4365
- export {}