@sanity/sdk 2.8.0 → 2.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/dist/_chunks-dts/utils.d.ts +2396 -0
  2. package/dist/_chunks-es/_internal.js +129 -0
  3. package/dist/_chunks-es/_internal.js.map +1 -0
  4. package/dist/_chunks-es/createGroqSearchFilter.js +1460 -0
  5. package/dist/_chunks-es/createGroqSearchFilter.js.map +1 -0
  6. package/dist/_chunks-es/telemetryManager.js +87 -0
  7. package/dist/_chunks-es/telemetryManager.js.map +1 -0
  8. package/dist/_chunks-es/version.js +7 -0
  9. package/dist/_chunks-es/version.js.map +1 -0
  10. package/dist/_exports/_internal.d.ts +64 -0
  11. package/dist/_exports/_internal.js +20 -0
  12. package/dist/_exports/_internal.js.map +1 -0
  13. package/dist/index.d.ts +2 -2343
  14. package/dist/index.js +383 -1777
  15. package/dist/index.js.map +1 -1
  16. package/package.json +11 -4
  17. package/src/_exports/_internal.ts +14 -0
  18. package/src/_exports/index.ts +10 -1
  19. package/src/auth/authStore.test.ts +150 -1
  20. package/src/auth/authStore.ts +11 -11
  21. package/src/auth/dashboardAuth.ts +2 -2
  22. package/src/auth/handleAuthCallback.ts +9 -3
  23. package/src/auth/logout.test.ts +1 -1
  24. package/src/auth/logout.ts +1 -1
  25. package/src/auth/refreshStampedToken.test.ts +118 -1
  26. package/src/auth/refreshStampedToken.ts +3 -2
  27. package/src/auth/standaloneAuth.ts +9 -3
  28. package/src/auth/studioAuth.ts +34 -7
  29. package/src/auth/studioModeAuth.ts +2 -1
  30. package/src/auth/subscribeToStateAndFetchCurrentUser.test.ts +10 -2
  31. package/src/auth/subscribeToStateAndFetchCurrentUser.ts +5 -1
  32. package/src/auth/subscribeToStorageEventsAndSetToken.ts +2 -2
  33. package/src/auth/utils.ts +33 -0
  34. package/src/client/clientStore.test.ts +14 -0
  35. package/src/client/clientStore.ts +2 -1
  36. package/src/comlink/node/getNodeState.ts +2 -1
  37. package/src/config/sanityConfig.ts +6 -0
  38. package/src/document/actions.ts +18 -11
  39. package/src/document/applyDocumentActions.test.ts +7 -6
  40. package/src/document/applyDocumentActions.ts +10 -4
  41. package/src/document/documentStore.test.ts +536 -188
  42. package/src/document/documentStore.ts +142 -76
  43. package/src/document/events.ts +7 -2
  44. package/src/document/permissions.test.ts +18 -16
  45. package/src/document/permissions.ts +35 -11
  46. package/src/document/processActions.test.ts +359 -32
  47. package/src/document/processActions.ts +104 -76
  48. package/src/document/reducers.test.ts +117 -29
  49. package/src/document/reducers.ts +43 -36
  50. package/src/document/sharedListener.ts +16 -6
  51. package/src/document/util.ts +14 -0
  52. package/src/favorites/favorites.test.ts +9 -2
  53. package/src/presence/bifurTransport.ts +6 -1
  54. package/src/preview/getPreviewState.test.ts +115 -98
  55. package/src/preview/getPreviewState.ts +38 -60
  56. package/src/preview/previewProjectionUtils.test.ts +179 -0
  57. package/src/preview/previewProjectionUtils.ts +93 -0
  58. package/src/preview/resolvePreview.test.ts +42 -25
  59. package/src/preview/resolvePreview.ts +29 -10
  60. package/src/preview/{previewStore.ts → types.ts} +8 -17
  61. package/src/projection/getProjectionState.test.ts +16 -16
  62. package/src/projection/getProjectionState.ts +2 -1
  63. package/src/projection/projectionQuery.ts +2 -3
  64. package/src/projection/types.ts +1 -1
  65. package/src/query/queryStore.ts +2 -1
  66. package/src/releases/getPerspectiveState.ts +7 -6
  67. package/src/releases/releasesStore.test.ts +20 -5
  68. package/src/releases/releasesStore.ts +20 -8
  69. package/src/store/createStateSourceAction.test.ts +62 -0
  70. package/src/store/createStateSourceAction.ts +34 -39
  71. package/src/telemetry/__telemetry__/sdk.telemetry.ts +42 -0
  72. package/src/telemetry/devMode.test.ts +52 -0
  73. package/src/telemetry/devMode.ts +40 -0
  74. package/src/telemetry/initTelemetry.test.ts +225 -0
  75. package/src/telemetry/initTelemetry.ts +205 -0
  76. package/src/telemetry/telemetryManager.test.ts +263 -0
  77. package/src/telemetry/telemetryManager.ts +187 -0
  78. package/src/users/usersStore.test.ts +1 -0
  79. package/src/users/usersStore.ts +5 -1
  80. package/src/utils/createFetcherStore.test.ts +6 -4
  81. package/src/utils/createFetcherStore.ts +2 -1
  82. package/src/utils/getStagingApiHost.test.ts +21 -0
  83. package/src/utils/getStagingApiHost.ts +14 -0
  84. package/src/utils/ids.test.ts +1 -29
  85. package/src/utils/ids.ts +0 -10
  86. package/src/utils/setCleanupTimeout.ts +24 -0
  87. package/src/preview/previewQuery.test.ts +0 -236
  88. package/src/preview/previewQuery.ts +0 -153
  89. package/src/preview/previewStore.test.ts +0 -36
  90. package/src/preview/subscribeToStateAndFetchBatches.test.ts +0 -221
  91. package/src/preview/subscribeToStateAndFetchBatches.ts +0 -112
  92. package/src/preview/util.ts +0 -13
package/dist/index.d.ts CHANGED
@@ -1,2343 +1,2 @@
1
- import * as _sanity_client12 from "@sanity/client";
2
- import { ClientConfig, ClientError, ClientPerspective, ListenEvent, ResponseQueryOptions, SanityClient, SanityDocument as SanityDocument$1, SanityProject as SanityProject$1, StackablePerspective } from "@sanity/client";
3
- import { Observable, Subject } from "rxjs";
4
- import { CurrentUser, CurrentUser as CurrentUser$1, Mutation, PatchOperations, Role, SanityDocument, SanityDocument as SanityDocument$2, SanityDocumentLike } from "@sanity/types";
5
- import * as _sanity_comlink3 from "@sanity/comlink";
6
- import { ChannelInput, ChannelInstance, Controller, Message, Node, NodeInput, Status } from "@sanity/comlink";
7
- import { PatchMutation } from "@sanity/mutate/_unstable_store";
8
- import { SanityDocument as SanityDocument$3, SanityProjectionResult, SanityQueryResult } from "groq";
9
- import { ExprNode } from "groq-js";
10
- import { CanvasResource, MediaResource, StudioResource } from "@sanity/message-protocol";
11
- import { getIndexForKey, getPathDepth, joinPaths, jsonMatch, slicePath, stringifyPath } from "@sanity/json-match";
12
- /**
13
- * Configuration for an authentication provider
14
- * @public
15
- */
16
- interface AuthProvider {
17
- /**
18
- * Unique identifier for the auth provider (e.g., 'google', 'github')
19
- */
20
- name: string;
21
- /**
22
- * Display name for the auth provider in the UI
23
- */
24
- title: string;
25
- /**
26
- * Complete authentication URL including callback and token parameters
27
- */
28
- url: string;
29
- /**
30
- * Optional URL for direct sign-up flow
31
- */
32
- signUpUrl?: string;
33
- }
34
- /**
35
- * Configuration options for creating an auth store.
36
- *
37
- * @public
38
- */
39
- interface AuthConfig {
40
- /**
41
- * The initial location href to use when handling auth callbacks.
42
- * Defaults to the current window location if available.
43
- */
44
- initialLocationHref?: string;
45
- /**
46
- * Factory function to create a SanityClient instance.
47
- * Defaults to the standard Sanity client factory if not provided.
48
- */
49
- clientFactory?: (config: ClientConfig) => SanityClient;
50
- /**
51
- * Custom authentication providers to use instead of or in addition to the default ones.
52
- * Can be an array of providers or a function that takes the default providers and returns
53
- * a modified array or a Promise resolving to one.
54
- */
55
- providers?: AuthProvider[] | ((prev: AuthProvider[]) => AuthProvider[] | Promise<AuthProvider[]>);
56
- /**
57
- * The API hostname for requests. Usually leave this undefined, but it can be set
58
- * if using a custom domain or CNAME for the API endpoint.
59
- */
60
- apiHost?: string;
61
- /**
62
- * Storage implementation to persist authentication state.
63
- * Defaults to `localStorage` if available.
64
- */
65
- storageArea?: Storage;
66
- /**
67
- * A callback URL for your application.
68
- * If none is provided, the auth API will redirect back to the current location (`location.href`).
69
- * When handling callbacks, this URL's pathname is checked to ensure it matches the callback.
70
- */
71
- callbackUrl?: string;
72
- /**
73
- * A static authentication token to use instead of handling the OAuth flow.
74
- * When provided, the auth store will remain in a logged-in state with this token,
75
- * ignoring any storage or callback handling.
76
- */
77
- token?: string;
78
- }
79
- /**
80
- * A minimal Observable-compatible interface for subscribing to token changes.
81
- * Any object with a `subscribe` method that follows this contract will work,
82
- * including RxJS Observables. This avoids coupling the SDK to a specific
83
- * reactive library.
84
- *
85
- * @public
86
- */
87
- interface TokenSource {
88
- /** Subscribe to token emissions. Emits `null` when logged out. */
89
- subscribe(observer: {
90
- next: (token: string | null) => void;
91
- }): {
92
- unsubscribe(): void;
93
- };
94
- }
95
- /**
96
- * Studio-specific configuration for the SDK.
97
- * When present, the SDK operates in studio mode and derives auth from the
98
- * provided token source instead of discovering tokens independently.
99
- *
100
- * @public
101
- */
102
- interface StudioConfig {
103
- /** Reactive auth token source from the Studio's auth store. */
104
- auth?: {
105
- /**
106
- * A reactive token source. The SDK subscribes and stays in sync — the
107
- * Studio is the single authority for auth and handles token refresh.
108
- *
109
- * Optional because older Studios may not expose it. When absent, the
110
- * SDK falls back to localStorage/cookie discovery.
111
- */
112
- token?: TokenSource;
113
- };
114
- }
115
- /**
116
- * Represents the minimal configuration required to identify a Sanity project.
117
- * @public
118
- */
119
- interface ProjectHandle<TProjectId extends string = string> {
120
- projectId?: TProjectId;
121
- }
122
- /**
123
- * @public
124
- */
125
- type ReleasePerspective = {
126
- releaseName: string;
127
- excludedPerspectives?: StackablePerspective[];
128
- };
129
- /**
130
- * @public
131
- */
132
- interface PerspectiveHandle {
133
- perspective?: ClientPerspective | ReleasePerspective;
134
- }
135
- /**
136
- * @public
137
- */
138
- interface DatasetHandle<TDataset extends string = string, TProjectId extends string = string> extends ProjectHandle<TProjectId>, PerspectiveHandle {
139
- dataset?: TDataset;
140
- /**
141
- * @beta
142
- * Explicit source object to use for this operation.
143
- */
144
- source?: DocumentSource;
145
- }
146
- /**
147
- * Identifies a specific document type within a Sanity dataset and project.
148
- * Includes `projectId`, `dataset`, and `documentType`.
149
- * Optionally includes a `documentId` and `liveEdit` flag.
150
- * @public
151
- */
152
- interface DocumentTypeHandle<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string> extends DatasetHandle<TDataset, TProjectId> {
153
- documentId?: string;
154
- documentType: TDocumentType;
155
- /**
156
- * Indicates whether this document uses liveEdit mode.
157
- * When `true`, the document does not use the draft/published model and edits are applied directly to the document.
158
- * @see https://www.sanity.io/docs/content-lake/drafts#ca0663a8f002
159
- */
160
- liveEdit?: boolean;
161
- }
162
- /**
163
- * Uniquely identifies a specific document within a Sanity dataset and project.
164
- * Includes `projectId`, `dataset`, `documentType`, and the required `documentId`.
165
- * Commonly used by document-related hooks and components to reference a document without fetching its full content initially.
166
- * @public
167
- */
168
- interface DocumentHandle<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string> extends DocumentTypeHandle<TDocumentType, TDataset, TProjectId> {
169
- documentId: string;
170
- }
171
- /**
172
- * Represents the complete configuration for a Sanity SDK instance
173
- * @public
174
- */
175
- interface SanityConfig extends DatasetHandle, PerspectiveHandle {
176
- /**
177
- * Authentication configuration for the instance
178
- * @remarks Merged with parent configurations when using createChild
179
- */
180
- auth?: AuthConfig;
181
- /**
182
- * Studio configuration provided by a Sanity Studio workspace.
183
- * When present, the SDK operates in studio mode and derives auth from the
184
- * workspace's reactive token source — no manual configuration needed.
185
- *
186
- * @remarks Typically set automatically by `SanityApp` when it detects an
187
- * `SDKStudioContext` provider. Can also be set explicitly for programmatic use.
188
- */
189
- studio?: StudioConfig;
190
- /**
191
- * Studio mode configuration for use of the SDK in a Sanity Studio.
192
- * @remarks Controls whether studio mode features are enabled.
193
- * @deprecated Use `studio` instead, which provides richer integration
194
- * with the Studio's workspace (auth token sync, etc.).
195
- */
196
- studioMode?: {
197
- enabled: boolean;
198
- };
199
- /**
200
- * @beta
201
- * A list of named sources to use for this instance.
202
- */
203
- sources?: Record<string, DocumentSource>;
204
- }
205
- /**
206
- * A document source can be used for querying.
207
- * This will soon be the default way to identify where you are querying from.
208
- *
209
- * @beta
210
- */
211
- type DocumentSource = DatasetSource | MediaLibrarySource | CanvasSource;
212
- /**
213
- * @beta
214
- */
215
- type DatasetSource = {
216
- projectId: string;
217
- dataset: string;
218
- };
219
- /**
220
- * @beta
221
- */
222
- type MediaLibrarySource = {
223
- mediaLibraryId: string;
224
- };
225
- /**
226
- * @beta
227
- */
228
- type CanvasSource = {
229
- canvasId: string;
230
- };
231
- /**
232
- * @beta
233
- */
234
- declare function isDatasetSource(source: DocumentSource): source is DatasetSource;
235
- /**
236
- * @beta
237
- */
238
- declare function isMediaLibrarySource(source: DocumentSource): source is MediaLibrarySource;
239
- /**
240
- * @beta
241
- */
242
- declare function isCanvasSource(source: DocumentSource): source is CanvasSource;
243
- /**
244
- * Represents a Sanity.io resource instance with its own configuration and lifecycle
245
- * @remarks Instances form a hierarchy through parent/child relationships
246
- *
247
- * @public
248
- */
249
- interface SanityInstance {
250
- /**
251
- * Unique identifier for this instance
252
- * @remarks Generated using crypto.randomUUID()
253
- */
254
- readonly instanceId: string;
255
- /**
256
- * Resolved configuration for this instance
257
- * @remarks Merges values from parent instances where appropriate
258
- */
259
- readonly config: SanityConfig;
260
- /**
261
- * Checks if the instance has been disposed
262
- * @returns true if dispose() has been called
263
- */
264
- isDisposed(): boolean;
265
- /**
266
- * Disposes the instance and cleans up associated resources
267
- * @remarks Triggers all registered onDispose callbacks
268
- */
269
- dispose(): void;
270
- /**
271
- * Registers a callback to be invoked when the instance is disposed
272
- * @param cb - Callback to execute on disposal
273
- * @returns Function to unsubscribe the callback
274
- */
275
- onDispose(cb: () => void): () => void;
276
- /**
277
- * Gets the parent instance in the hierarchy
278
- * @returns Parent instance or undefined if this is the root
279
- */
280
- getParent(): SanityInstance | undefined;
281
- /**
282
- * Creates a child instance with merged configuration
283
- * @param config - Configuration to merge with parent values
284
- * @remarks Child instances inherit parent configuration but can override values
285
- */
286
- createChild(config: SanityConfig): SanityInstance;
287
- /**
288
- * Traverses the instance hierarchy to find the first instance whose configuration
289
- * matches the given target config using a shallow comparison.
290
- * @param targetConfig - A partial configuration object containing key-value pairs to match.
291
- * @returns The first matching instance or undefined if no match is found.
292
- */
293
- match(targetConfig: Partial<SanityConfig>): SanityInstance | undefined;
294
- }
295
- /**
296
- * Creates a new Sanity resource instance
297
- * @param config - Configuration for the instance (optional)
298
- * @returns A configured SanityInstance
299
- * @remarks When creating child instances, configurations are merged with parent values
300
- *
301
- * @public
302
- */
303
- declare function createSanityInstance(config?: SanityConfig): SanityInstance;
304
- /** @alpha */
305
- type AgentGenerateOptions = Parameters<SanityClient['observable']['agent']['action']['generate']>[0];
306
- /** @alpha */
307
- type AgentTransformOptions = Parameters<SanityClient['observable']['agent']['action']['transform']>[0];
308
- /** @alpha */
309
- type AgentTranslateOptions = Parameters<SanityClient['observable']['agent']['action']['translate']>[0];
310
- /** @alpha */
311
- type AgentPromptOptions = Parameters<SanityClient['agent']['action']['prompt']>[0];
312
- /** @alpha */
313
- type AgentPatchOptions = Parameters<SanityClient['agent']['action']['patch']>[0];
314
- /** @alpha */
315
- type AgentGenerateResult = Awaited<ReturnType<SanityClient['observable']['agent']['action']['generate']>>;
316
- /** @alpha */
317
- type AgentTransformResult = Awaited<ReturnType<SanityClient['observable']['agent']['action']['transform']>>;
318
- /** @alpha */
319
- type AgentTranslateResult = Awaited<ReturnType<SanityClient['observable']['agent']['action']['translate']>>;
320
- /** @alpha */
321
- type AgentPromptResult = Awaited<ReturnType<SanityClient['agent']['action']['prompt']>>;
322
- /** @alpha */
323
- type AgentPatchResult = Awaited<ReturnType<SanityClient['agent']['action']['patch']>>;
324
- /**
325
- * Generates a new document using the agent.
326
- * @param instance - The Sanity instance.
327
- * @param options - The options for the agent generate action. See the [Agent Actions API](https://www.sanity.io/docs/agent-actions/introduction) for more details.
328
- * @returns An Observable emitting the result of the agent generate action.
329
- * @alpha
330
- */
331
- declare function agentGenerate(instance: SanityInstance, options: AgentGenerateOptions): AgentGenerateResult;
332
- /**
333
- * Transforms a document using the agent.
334
- * @param instance - The Sanity instance.
335
- * @param options - The options for the agent transform action. See the [Agent Actions API](https://www.sanity.io/docs/agent-actions/introduction) for more details.
336
- * @returns An Observable emitting the result of the agent transform action.
337
- * @alpha
338
- */
339
- declare function agentTransform(instance: SanityInstance, options: AgentTransformOptions): AgentTransformResult;
340
- /**
341
- * Translates a document using the agent.
342
- * @param instance - The Sanity instance.
343
- * @param options - The options for the agent translate action. See the [Agent Actions API](https://www.sanity.io/docs/agent-actions/introduction) for more details.
344
- * @returns An Observable emitting the result of the agent translate action.
345
- * @alpha
346
- */
347
- declare function agentTranslate(instance: SanityInstance, options: AgentTranslateOptions): AgentTranslateResult;
348
- /**
349
- * Prompts the agent using the same instruction template format as the other actions, but returns text or json instead of acting on a document.
350
- * @param instance - The Sanity instance.
351
- * @param options - The options for the agent prompt action. See the [Agent Actions API](https://www.sanity.io/docs/agent-actions/introduction) for more details.
352
- * @returns An Observable emitting the result of the agent prompt action.
353
- * @alpha
354
- */
355
- declare function agentPrompt(instance: SanityInstance, options: AgentPromptOptions): Observable<AgentPromptResult>;
356
- /**
357
- * Patches a document using the agent.
358
- * @param instance - The Sanity instance.
359
- * @param options - The options for the agent patch action. See the [Agent Actions API](https://www.sanity.io/docs/agent-actions/introduction) for more details.
360
- * @returns An Observable emitting the result of the agent patch action.
361
- * @alpha
362
- */
363
- declare function agentPatch(instance: SanityInstance, options: AgentPatchOptions): Observable<AgentPatchResult>;
364
- /**
365
- * Returns `true` when the config indicates the SDK is running inside a Studio.
366
- * Checks the new `studio` field first, then falls back to the deprecated
367
- * `studioMode.enabled` for backwards compatibility.
368
- *
369
- * @internal
370
- */
371
- declare function isStudioConfig(config: SanityConfig): boolean;
372
- /**
373
- * Represents the various states the authentication type can be in.
374
- *
375
- * @public
376
- */
377
- declare enum AuthStateType {
378
- LOGGED_IN = "logged-in",
379
- LOGGING_IN = "logging-in",
380
- ERROR = "error",
381
- LOGGED_OUT = "logged-out",
382
- }
383
- /**
384
- * Represents a reactive store state container with multiple access patterns
385
- */
386
- interface StoreState<TState> {
387
- /**
388
- * Gets the current state value
389
- *
390
- * @remarks
391
- * This is a direct synchronous accessor that doesn't trigger subscriptions
392
- */
393
- get: () => TState;
394
- /**
395
- * Updates the store state
396
- * @param name - Action name for devtools tracking
397
- * @param updatedState - New state value or updater function
398
- *
399
- * @remarks
400
- * When providing a partial object, previous top-level keys not included in
401
- * the update will be preserved.
402
- */
403
- set: (name: string, updatedState: Partial<TState> | ((s: TState) => Partial<TState>)) => void;
404
- /**
405
- * Observable stream of state changes
406
- * @remarks
407
- * - Emits immediately with current state on subscription
408
- * - Shares underlying subscription between observers
409
- * - Only emits when state reference changes
410
- * - Completes when store is disposed
411
- */
412
- observable: Observable<TState>;
413
- }
414
- /**
415
- * Context object provided to store initialization functions
416
- */
417
- interface StoreContext<TState, TKey = unknown> {
418
- /**
419
- * Sanity instance associated with this store
420
- *
421
- * @remarks
422
- * Provides access to the Sanity configuration and instance lifecycle methods
423
- */
424
- instance: SanityInstance;
425
- /**
426
- * Reactive store state management utilities
427
- *
428
- * @remarks
429
- * Contains methods for getting/setting state and observing changes
430
- */
431
- state: StoreState<TState>;
432
- /**
433
- * The key used to instantiate the store.
434
- */
435
- key: TKey;
436
- }
437
- /**
438
- * Defines a store action that operates on a specific state type
439
- */
440
- type StoreAction<TState, TParams extends unknown[], TReturn, TKey = unknown> = (context: StoreContext<TState, TKey>, ...params: TParams) => TReturn;
441
- /**
442
- * Represents a store action that has been bound to a specific store instance
443
- */
444
- type BoundStoreAction<_TState, TParams extends unknown[], TReturn> = (instance: SanityInstance, ...params: TParams) => TReturn;
445
- /**
446
- * Represents the various states the authentication can be in.
447
- *
448
- * @public
449
- */
450
- type AuthState = LoggedInAuthState | LoggedOutAuthState | LoggingInAuthState | ErrorAuthState;
451
- /**
452
- * Logged-in state from the auth state.
453
- * @public
454
- */
455
- type LoggedInAuthState = {
456
- type: AuthStateType.LOGGED_IN;
457
- token: string;
458
- currentUser: CurrentUser$1 | null;
459
- lastTokenRefresh?: number;
460
- };
461
- /**
462
- * Logged-out state from the auth state.
463
- * @public
464
- */
465
- type LoggedOutAuthState = {
466
- type: AuthStateType.LOGGED_OUT;
467
- isDestroyingSession: boolean;
468
- };
469
- /**
470
- * Logging-in state from the auth state.
471
- * @public
472
- */
473
- type LoggingInAuthState = {
474
- type: AuthStateType.LOGGING_IN;
475
- isExchangingToken: boolean;
476
- };
477
- /**
478
- * Error state from the auth state.
479
- * @public
480
- */
481
- type ErrorAuthState = {
482
- type: AuthStateType.ERROR;
483
- error: unknown;
484
- };
485
- /**
486
- * Represents the various states the authentication can be in.
487
- *
488
- * @public
489
- */
490
- interface DashboardContext {
491
- mode?: string;
492
- env?: string;
493
- orgId?: string;
494
- }
495
- /**
496
- * The method of authentication used.
497
- * @internal
498
- */
499
- type AuthMethodOptions = 'localstorage' | 'cookie' | undefined;
500
- /**
501
- * @public
502
- */
503
- interface AuthStoreState {
504
- authState: AuthState;
505
- providers?: AuthProvider[];
506
- options: {
507
- initialLocationHref: string;
508
- clientFactory: (config: ClientConfig) => SanityClient;
509
- customProviders: AuthConfig['providers'];
510
- storageKey: string;
511
- storageArea: Storage | undefined;
512
- apiHost: string | undefined;
513
- loginUrl: string;
514
- callbackUrl: string | undefined;
515
- providedToken: string | undefined;
516
- authMethod: AuthMethodOptions;
517
- };
518
- dashboardContext?: DashboardContext;
519
- }
520
- /**
521
- * @public
522
- */
523
- declare const getCurrentUserState: BoundStoreAction<AuthStoreState, [], StateSource<CurrentUser$1 | null>>;
524
- /**
525
- * @public
526
- */
527
- declare const getTokenState: BoundStoreAction<AuthStoreState, [], StateSource<string | null>>;
528
- /**
529
- * @public
530
- */
531
- declare const getLoginUrlState: BoundStoreAction<AuthStoreState, [], StateSource<string>>;
532
- /**
533
- * @public
534
- */
535
- declare const getAuthState: BoundStoreAction<AuthStoreState, [], StateSource<AuthState>>;
536
- /**
537
- * @public
538
- */
539
- declare const getDashboardOrganizationId: BoundStoreAction<AuthStoreState, [], StateSource<string | undefined>>;
540
- /**
541
- * Returns a state source indicating if the SDK is running within a dashboard context.
542
- * @public
543
- */
544
- declare const getIsInDashboardState: BoundStoreAction<AuthStoreState, [], StateSource<boolean>>;
545
- /**
546
- * Action to explicitly set the authentication token.
547
- * Used internally by the Comlink token refresh.
548
- * @internal
549
- */
550
- declare const setAuthToken: BoundStoreAction<AuthStoreState, [token: string | null], void>;
551
- /**
552
- * Error message returned by the organization verification
553
- * @public
554
- */
555
- interface OrgVerificationResult {
556
- error: string | null;
557
- }
558
- /**
559
- * Creates an observable that emits the organization verification state for a given instance.
560
- * It combines the dashboard organization ID (from auth context) with the
561
- * project's actual organization ID (fetched via getProjectState) and compares them.
562
- * @public
563
- */
564
- declare function observeOrganizationVerificationState(instance: SanityInstance, projectIds: string[]): Observable<OrgVerificationResult>;
565
- /**
566
- * @public
567
- */
568
- declare const handleAuthCallback: BoundStoreAction<AuthStoreState, [locationHref?: string | undefined], Promise<string | false>>;
569
- /**
570
- * @public
571
- */
572
- declare const logout: BoundStoreAction<AuthStoreState, [], Promise<void>>;
573
- /** @internal */
574
- type ApiErrorBody = {
575
- error?: {
576
- type?: string;
577
- description?: string;
578
- };
579
- type?: string;
580
- description?: string;
581
- message?: string;
582
- };
583
- /** @internal Extracts the structured API error body from a ClientError, if present. */
584
- declare function getClientErrorApiBody(error: ClientError): ApiErrorBody | undefined;
585
- /** @internal Returns the error type string from an API error body, if available. */
586
- declare function getClientErrorApiType(error: ClientError): string | undefined;
587
- /** @internal Returns the error description string from an API error body, if available. */
588
- declare function getClientErrorApiDescription(error: ClientError): string | undefined;
589
- /** @internal True if the error represents a projectUserNotFoundError. */
590
- declare function isProjectUserNotFoundClientError(error: ClientError): boolean;
591
- type AllowedClientConfigKey = 'useCdn' | 'token' | 'perspective' | 'apiHost' | 'proxy' | 'withCredentials' | 'timeout' | 'maxRetries' | 'dataset' | 'projectId' | 'requestTagPrefix' | 'useProjectHostname';
592
- /**
593
- * States tracked by the client store
594
- * @public
595
- */
596
- interface ClientStoreState {
597
- token: string | null;
598
- clients: { [TKey in string]?: SanityClient };
599
- authMethod?: 'localstorage' | 'cookie';
600
- }
601
- /**
602
- * Options used when retrieving a client instance from the client store.
603
- *
604
- * This interface extends the base {@link ClientConfig} and adds:
605
- *
606
- * - **apiVersion:** A required string indicating the API version for the client.
607
- * - **scope:** An optional flag to choose between the project-specific client
608
- * ('project') and the global client ('global'). When set to `'global'`, the
609
- * global client is used.
610
- *
611
- * These options are utilized by `getClient` and `getClientState` to configure and
612
- * return appropriate client instances that automatically handle authentication
613
- * updates and configuration changes.
614
- *
615
- * @public
616
- */
617
- interface ClientOptions extends Pick<ClientConfig, AllowedClientConfigKey> {
618
- /**
619
- * An optional flag to choose between the default client (typically project-level)
620
- * and the global client ('global'). When set to `'global'`, the global client
621
- * is used.
622
- */
623
- 'scope'?: 'default' | 'global';
624
- /**
625
- * A required string indicating the API version for the client.
626
- */
627
- 'apiVersion': string;
628
- /**
629
- * @internal
630
- */
631
- '~experimental_resource'?: ClientConfig['~experimental_resource'];
632
- /**
633
- * @internal
634
- */
635
- 'source'?: DocumentSource;
636
- }
637
- /**
638
- * Retrieves a Sanity client instance configured with the provided options.
639
- *
640
- * This function returns a client instance configured for the project or as a
641
- * global client based on the options provided. It ensures efficient reuse of
642
- * client instances by returning the same instance for the same options.
643
- * For automatic handling of authentication token updates, consider using
644
- * `getClientState`.
645
- *
646
- * @public
647
- */
648
- declare const getClient: BoundStoreAction<ClientStoreState, [options: ClientOptions], SanityClient>;
649
- /**
650
- * Returns a state source for the Sanity client instance.
651
- *
652
- * This function provides a subscribable state source that emits updated client
653
- * instances whenever relevant configurations change (such as authentication tokens).
654
- * Use this when you need to react to client configuration changes in your application.
655
- *
656
- * @public
657
- */
658
- declare const getClientState: BoundStoreAction<ClientStoreState, [options: ClientOptions], StateSource<SanityClient>>;
659
- /**
660
- * Message sent from a containing app to an iframe
661
- * @public
662
- */
663
- type FrameMessage = Message;
664
- /**
665
- * Message sent from an iframe to a containing app
666
- * @public
667
- */
668
- type WindowMessage = Message;
669
- /**
670
- * Message from SDK (iframe) to Parent (dashboard) to request a new token
671
- * @internal
672
- */
673
- type RequestNewTokenMessage = {
674
- type: 'dashboard/v1/auth/tokens/create';
675
- payload?: undefined;
676
- };
677
- /**
678
- * Message from Parent (dashboard) to SDK (iframe) with the new token
679
- * @internal
680
- */
681
- type NewTokenResponseMessage = {
682
- type: 'dashboard/v1/auth/tokens/create';
683
- payload: {
684
- token: string | null;
685
- error?: string;
686
- };
687
- };
688
- /**
689
- * Individual channel with its relevant options
690
- * @public
691
- */
692
- interface ChannelEntry {
693
- channel: ChannelInstance<FrameMessage, WindowMessage>;
694
- options: ChannelInput;
695
- refCount: number;
696
- }
697
- /**
698
- * Internal state tracking comlink connections
699
- * @public
700
- */
701
- interface ComlinkControllerState {
702
- controller: Controller | null;
703
- controllerOrigin: string | null;
704
- channels: Map<string, ChannelEntry>;
705
- }
706
- /**
707
- * Calls the destroy method on the controller and resets the controller state.
708
- * @public
709
- */
710
- declare const destroyController: BoundStoreAction<ComlinkControllerState, [], void>;
711
- /**
712
- * Retrieve or create a channel to be used for communication between
713
- * an application and the controller.
714
- * @public
715
- */
716
- declare const getOrCreateChannel: BoundStoreAction<ComlinkControllerState, [options: ChannelInput], ChannelInstance<_sanity_comlink3.Message, _sanity_comlink3.Message>>;
717
- /**
718
- * Initializes or fetches a controller to handle communication
719
- * between an application and iframes.
720
- * @public
721
- */
722
- declare const getOrCreateController: BoundStoreAction<ComlinkControllerState, [targetOrigin: string], Controller>;
723
- /**
724
- * Signals to the store that the consumer has stopped using the channel
725
- * @public
726
- */
727
- declare const releaseChannel: BoundStoreAction<ComlinkControllerState, [name: string], void>;
728
- /**
729
- * Individual node with its relevant options
730
- * @public
731
- */
732
- interface NodeEntry {
733
- node: Node<WindowMessage, FrameMessage>;
734
- options: NodeInput;
735
- status: Status;
736
- statusUnsub?: () => void;
737
- }
738
- /**
739
- * Internal state tracking comlink connections
740
- * @public
741
- */
742
- interface ComlinkNodeState {
743
- nodes: Map<string, NodeEntry>;
744
- subscriptions: Map<string, Set<symbol>>;
745
- }
746
- /**
747
- * Signals to the store that the consumer has stopped using the node
748
- * @public
749
- */
750
- declare const releaseNode: BoundStoreAction<ComlinkNodeState, [name: string], void>;
751
- /**
752
- * Retrieve or create a node to be used for communication between
753
- * an application and the controller -- specifically, a node should
754
- * be created within a frame / window to communicate with the controller.
755
- * @public
756
- */
757
- declare const getOrCreateNode: BoundStoreAction<ComlinkNodeState, [options: NodeInput], Node<_sanity_comlink3.Message, _sanity_comlink3.Message>>;
758
- /**
759
- * @public
760
- */
761
- interface NodeState {
762
- node: Node<WindowMessage, FrameMessage>;
763
- status: Status | undefined;
764
- }
765
- /**
766
- * Provides a subscribable state source for a node by name
767
- * @param instance - The Sanity instance to get the node state for
768
- * @param nodeInput - The configuration for the node to get the state for
769
-
770
- * @returns A subscribable state source for the node
771
- * @public
772
- */
773
- declare const getNodeState: BoundStoreAction<ComlinkNodeState, [NodeInput], StateSource<NodeState | undefined>>;
774
- /**
775
- * Creates or validates a `DocumentHandle` object.
776
- * Ensures the provided object conforms to the `DocumentHandle` interface.
777
- * @param handle - The object containing document identification properties.
778
- * @returns The validated `DocumentHandle` object.
779
- * @public
780
- */
781
- declare function createDocumentHandle<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string>(handle: DocumentHandle<TDocumentType, TDataset, TProjectId>): DocumentHandle<TDocumentType, TDataset, TProjectId>;
782
- /**
783
- * Creates or validates a `DocumentTypeHandle` object.
784
- * Ensures the provided object conforms to the `DocumentTypeHandle` interface.
785
- * @param handle - The object containing document type identification properties.
786
- * @returns The validated `DocumentTypeHandle` object.
787
- * @public
788
- */
789
- declare function createDocumentTypeHandle<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string>(handle: DocumentTypeHandle<TDocumentType, TDataset, TProjectId>): DocumentTypeHandle<TDocumentType, TDataset, TProjectId>;
790
- /**
791
- * Creates or validates a `ProjectHandle` object.
792
- * Ensures the provided object conforms to the `ProjectHandle` interface.
793
- * @param handle - The object containing project identification properties.
794
- * @returns The validated `ProjectHandle` object.
795
- * @public
796
- */
797
- declare function createProjectHandle<TProjectId extends string = string>(handle: ProjectHandle<TProjectId>): ProjectHandle<TProjectId>;
798
- /**
799
- * Creates or validates a `DatasetHandle` object.
800
- * Ensures the provided object conforms to the `DatasetHandle` interface.
801
- * @param handle - The object containing dataset identification properties.
802
- * @returns The validated `DatasetHandle` object.
803
- * @public
804
- */
805
- declare function createDatasetHandle<TDataset extends string = string, TProjectId extends string = string>(handle: DatasetHandle<TDataset, TProjectId>): DatasetHandle<TDataset, TProjectId>;
806
- /**
807
- * Logging infrastructure for the Sanity SDK
808
- *
809
- * Provides multi-level, namespace-based logging for both SDK users and maintainers.
810
- * In production builds, all logging can be stripped via tree-shaking.
811
- *
812
- * @example SDK User
813
- * ```ts
814
- * import {configureLogging} from '@sanity/sdk'
815
- *
816
- * configureLogging({
817
- * level: 'info',
818
- * namespaces: ['auth', 'document']
819
- * })
820
- * ```
821
- *
822
- * @example SDK Maintainer
823
- * ```ts
824
- * configureLogging({
825
- * level: 'trace',
826
- * namespaces: ['*'],
827
- * internal: true
828
- * })
829
- * ```
830
- */
831
- /**
832
- * Log levels in order of verbosity (least to most)
833
- * - error: Critical failures that prevent operation
834
- * - warn: Issues that may cause problems but don't stop execution
835
- * - info: High-level informational messages (SDK user level)
836
- * - debug: Detailed debugging information (maintainer level)
837
- * - trace: Very detailed tracing (maintainer level, includes RxJS streams)
838
- * @public
839
- */
840
- type LogLevel = 'error' | 'warn' | 'info' | 'debug' | 'trace';
841
- /**
842
- * Log namespaces organize logs by functional domain
843
- *
844
- * @remarks
845
- * This is an extensible string type. As logging is added to more modules,
846
- * additional namespaces will be recognized. Currently implemented namespaces
847
- * will be documented as they are added.
848
- * @internal
849
- */
850
- type LogNamespace = string;
851
- /**
852
- * Configuration for the logging system
853
- * @public
854
- */
855
- interface LoggerConfig {
856
- /**
857
- * Minimum log level to output
858
- * @defaultValue 'warn'
859
- */
860
- level?: LogLevel;
861
- /**
862
- * Namespaces to enable. Use ['*'] for all namespaces
863
- * @defaultValue []
864
- * @remarks
865
- * Available namespaces depend on which modules have logging integrated.
866
- * Check the SDK documentation for the current list of instrumented modules.
867
- * @example ['auth', 'document']
868
- */
869
- namespaces?: string[];
870
- /**
871
- * Enable internal/maintainer-level logging
872
- * Shows RxJS streams, store internals, etc.
873
- * @defaultValue false
874
- */
875
- internal?: boolean;
876
- /**
877
- * Custom log handler (for testing or custom output)
878
- * @defaultValue console methods
879
- */
880
- handler?: LogHandler;
881
- /**
882
- * Enable timestamps in log output
883
- * @defaultValue true
884
- */
885
- timestamps?: boolean;
886
- /**
887
- * Enable in production builds
888
- * @defaultValue false
889
- */
890
- enableInProduction?: boolean;
891
- }
892
- /**
893
- * Custom log handler interface
894
- *
895
- * @internal
896
- */
897
- interface LogHandler {
898
- error: (message: string, context?: LogContext) => void;
899
- warn: (message: string, context?: LogContext) => void;
900
- info: (message: string, context?: LogContext) => void;
901
- debug: (message: string, context?: LogContext) => void;
902
- trace: (message: string, context?: LogContext) => void;
903
- }
904
- /**
905
- * Context object attached to log messages
906
- *
907
- * This interface allows you to attach arbitrary contextual data to log messages.
908
- * The index signature `[key: string]: unknown` enables you to add any custom
909
- * properties relevant to your log entry (e.g., `userId`, `documentId`, `action`, etc.).
910
- *
911
- * **Sensitive data sanitization:**
912
- * Top-level keys containing sensitive names (`token`, `password`, `secret`, `apiKey`,
913
- * `authorization`) are automatically redacted to `[REDACTED]` in log output.
914
- *
915
- * @example
916
- * ```ts
917
- * logger.info('User logged in', {
918
- * userId: '123', // Custom context
919
- * action: 'login', // Custom context
920
- * token: 'secret' // Will be redacted to [REDACTED]
921
- * })
922
- * ```
923
- *
924
- * @internal
925
- */
926
- interface LogContext {
927
- /**
928
- * Custom context properties that provide additional information about the log entry.
929
- * Any key-value pairs can be added here (e.g., userId, documentId, requestId, etc.).
930
- * Keys with sensitive names (token, password, secret, apiKey, authorization) are
931
- * automatically sanitized.
932
- */
933
- [key: string]: unknown;
934
- /** Error object if logging an error */
935
- error?: Error | unknown;
936
- /** Duration in milliseconds for timed operations */
937
- duration?: number;
938
- /** Stack trace for debugging */
939
- stack?: string;
940
- /** Instance context (automatically added when available) */
941
- instanceContext?: InstanceContext;
942
- }
943
- /**
944
- * Instance context information automatically added to logs
945
- * @internal
946
- */
947
- interface InstanceContext {
948
- /** Unique instance ID */
949
- instanceId?: string;
950
- /** Project ID */
951
- projectId?: string;
952
- /** Dataset name */
953
- dataset?: string;
954
- }
955
- /**
956
- * Logger instance for a specific namespace
957
- * @internal
958
- */
959
- interface Logger {
960
- readonly namespace: string;
961
- error: (message: string, context?: LogContext) => void;
962
- warn: (message: string, context?: LogContext) => void;
963
- info: (message: string, context?: LogContext) => void;
964
- debug: (message: string, context?: LogContext) => void;
965
- trace: (message: string, context?: LogContext) => void;
966
- /** Check if a log level is enabled (for performance-sensitive code) */
967
- isLevelEnabled: (level: LogLevel) => boolean;
968
- /** Create a child logger with extended context */
969
- child: (context: LogContext) => Logger;
970
- /** Get the instance context if available */
971
- getInstanceContext: () => InstanceContext | undefined;
972
- }
973
- /**
974
- * Configure logging for the Sanity SDK
975
- *
976
- * This function allows you to control what logs are output by the SDK,
977
- * making it easier to debug issues in development or production.
978
- *
979
- * @remarks
980
- * **Zero-Config via Environment Variable (Recommended):**
981
- *
982
- * The SDK automatically reads the `DEBUG` environment variable, making it
983
- * easy to enable logging without code changes:
984
- *
985
- * ```bash
986
- * # Enable all SDK logging at debug level
987
- * DEBUG=sanity:* npm start
988
- *
989
- * # Enable specific namespaces
990
- * DEBUG=sanity:auth,sanity:document npm start
991
- *
992
- * # Enable trace level for all namespaces
993
- * DEBUG=sanity:trace:* npm start
994
- *
995
- * # Enable internal/maintainer logs
996
- * DEBUG=sanity:*:internal npm start
997
- * ```
998
- *
999
- * This matches the pattern used by Sanity CLI and Studio, making it familiar
1000
- * and easy for support teams to help troubleshoot issues.
1001
- *
1002
- * **Programmatic Configuration (Advanced):**
1003
- *
1004
- * For more control (custom handlers, dynamic configuration), call this function
1005
- * explicitly. Programmatic configuration overrides environment variables.
1006
- *
1007
- * **For Application Developers:**
1008
- * Use `info`, `warn`, or `error` levels to see high-level SDK activity
1009
- * without being overwhelmed by internal details.
1010
- *
1011
- * **For SDK Maintainers:**
1012
- * Use `debug` or `trace` levels with `internal: true` to see detailed
1013
- * information about store operations, RxJS streams, and state transitions.
1014
- *
1015
- * **Instance Context:**
1016
- * Logs automatically include instance information (projectId, dataset, instanceId)
1017
- * when available, making it easier to debug multi-instance scenarios:
1018
- * ```
1019
- * [INFO] [auth] [project:abc] [dataset:production] User logged in
1020
- * ```
1021
- *
1022
- * **Available Namespaces:**
1023
- * - `sdk` - SDK initialization, configuration, and lifecycle
1024
- * - `auth` - Authentication and authorization (when instrumented in the future)
1025
- * - And more as logging is added to modules
1026
- *
1027
- * @example Zero-config via environment variable (recommended for debugging)
1028
- * ```bash
1029
- * # Just set DEBUG and run your app - no code changes needed!
1030
- * DEBUG=sanity:* npm start
1031
- * ```
1032
- *
1033
- * @example Programmatic configuration (application developer)
1034
- * ```ts
1035
- * import {configureLogging} from '@sanity/sdk'
1036
- *
1037
- * // Log warnings and errors for auth and document operations
1038
- * configureLogging({
1039
- * level: 'warn',
1040
- * namespaces: ['auth', 'document']
1041
- * })
1042
- * ```
1043
- *
1044
- * @example Programmatic configuration (SDK maintainer)
1045
- * ```ts
1046
- * import {configureLogging} from '@sanity/sdk'
1047
- *
1048
- * // Enable all logs including internal traces
1049
- * configureLogging({
1050
- * level: 'trace',
1051
- * namespaces: ['*'],
1052
- * internal: true
1053
- * })
1054
- * ```
1055
- *
1056
- * @example Custom handler (for testing)
1057
- * ```ts
1058
- * import {configureLogging} from '@sanity/sdk'
1059
- *
1060
- * const logs: string[] = []
1061
- * configureLogging({
1062
- * level: 'info',
1063
- * namespaces: ['*'],
1064
- * handler: {
1065
- * error: (msg) => logs.push(msg),
1066
- * warn: (msg) => logs.push(msg),
1067
- * info: (msg) => logs.push(msg),
1068
- * debug: (msg) => logs.push(msg),
1069
- * trace: (msg) => logs.push(msg),
1070
- * }
1071
- * })
1072
- * ```
1073
- *
1074
- * @public
1075
- */
1076
- declare function configureLogging(config: LoggerConfig): void;
1077
- /** @public */
1078
- declare const getDatasetsState: BoundStoreAction<FetcherStoreState<[options?: ProjectHandle<string> | undefined], _sanity_client12.DatasetsResponse>, [options?: ProjectHandle<string> | undefined], StateSource<_sanity_client12.DatasetsResponse | undefined>>;
1079
- /** @public */
1080
- declare const resolveDatasets: BoundStoreAction<FetcherStoreState<[options?: ProjectHandle<string> | undefined], _sanity_client12.DatasetsResponse>, [options?: ProjectHandle<string> | undefined], Promise<_sanity_client12.DatasetsResponse>>;
1081
- /**
1082
- * Represents an action to create a new document.
1083
- * Specifies the document type and optionally a document ID (which will be treated as the published ID).
1084
- * @beta
1085
- */
1086
- interface CreateDocumentAction<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string> extends DocumentTypeHandle<TDocumentType, TDataset, TProjectId> {
1087
- type: 'document.create';
1088
- /**
1089
- * Optional initial field values for the document.
1090
- * These values will be set when the document is created.
1091
- * System fields (_id, _type, _rev, _createdAt, _updatedAt) are omitted as they are set automatically.
1092
- */
1093
- initialValue?: Partial<Omit<SanityDocument$3<TDocumentType, `${TProjectId}.${TDataset}`>, '_id' | '_type' | '_rev' | '_createdAt' | '_updatedAt'>>;
1094
- }
1095
- /**
1096
- * Represents an action to delete an existing document.
1097
- * Requires the full document handle including the document ID.
1098
- * @beta
1099
- */
1100
- interface DeleteDocumentAction<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string> extends DocumentHandle<TDocumentType, TDataset, TProjectId> {
1101
- type: 'document.delete';
1102
- }
1103
- /**
1104
- * Represents an action to edit an existing document using patches.
1105
- * Requires the full document handle and an array of patch operations.
1106
- * @beta
1107
- */
1108
- interface EditDocumentAction<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string> extends DocumentHandle<TDocumentType, TDataset, TProjectId> {
1109
- type: 'document.edit';
1110
- patches?: PatchOperations[];
1111
- }
1112
- /**
1113
- * Represents an action to publish the draft version of a document.
1114
- * Requires the full document handle.
1115
- * @beta
1116
- */
1117
- interface PublishDocumentAction<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string> extends DocumentHandle<TDocumentType, TDataset, TProjectId> {
1118
- type: 'document.publish';
1119
- }
1120
- /**
1121
- * Represents an action to unpublish a document, moving its published content to a draft.
1122
- * Requires the full document handle.
1123
- * @beta
1124
- */
1125
- interface UnpublishDocumentAction<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string> extends DocumentHandle<TDocumentType, TDataset, TProjectId> {
1126
- type: 'document.unpublish';
1127
- }
1128
- /**
1129
- * Represents an action to discard the draft changes of a document.
1130
- * Requires the full document handle.
1131
- * @beta
1132
- */
1133
- interface DiscardDocumentAction<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string> extends DocumentHandle<TDocumentType, TDataset, TProjectId> {
1134
- type: 'document.discard';
1135
- }
1136
- /**
1137
- * Union type representing all possible document actions within the SDK.
1138
- * @beta
1139
- */
1140
- type DocumentAction<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string> = CreateDocumentAction<TDocumentType, TDataset, TProjectId> | DeleteDocumentAction<TDocumentType, TDataset, TProjectId> | EditDocumentAction<TDocumentType, TDataset, TProjectId> | PublishDocumentAction<TDocumentType, TDataset, TProjectId> | UnpublishDocumentAction<TDocumentType, TDataset, TProjectId> | DiscardDocumentAction<TDocumentType, TDataset, TProjectId>;
1141
- /**
1142
- * Creates a `CreateDocumentAction` object.
1143
- * @param doc - A handle identifying the document type, dataset, and project. An optional `documentId` can be provided.
1144
- * @param initialValue - Optional initial field values for the document. (System fields are omitted as they are set automatically.)
1145
- * @returns A `CreateDocumentAction` object ready for dispatch.
1146
- * @beta
1147
- */
1148
- declare function createDocument<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string>(doc: DocumentTypeHandle<TDocumentType, TDataset, TProjectId>, initialValue?: Partial<Omit<SanityDocument$3<TDocumentType, `${TProjectId}.${TDataset}`>, '_id' | '_type' | '_rev' | '_createdAt' | '_updatedAt'>>): CreateDocumentAction<TDocumentType, TDataset, TProjectId>;
1149
- /**
1150
- * Creates a `DeleteDocumentAction` object.
1151
- * @param doc - A handle uniquely identifying the document to be deleted.
1152
- * @returns A `DeleteDocumentAction` object ready for dispatch.
1153
- * @beta
1154
- */
1155
- declare function deleteDocument<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string>(doc: DocumentHandle<TDocumentType, TDataset, TProjectId>): DeleteDocumentAction<TDocumentType, TDataset, TProjectId>;
1156
- /**
1157
- * Creates an `EditDocumentAction` object with patches for modifying a document.
1158
- * Accepts patches in either the standard `PatchOperations` format or as a `SanityMutatePatchMutation` from `@sanity/mutate`.
1159
- *
1160
- * @param doc - A handle uniquely identifying the document to be edited.
1161
- * @param sanityMutatePatch - A patch mutation object from `@sanity/mutate`.
1162
- * @returns An `EditDocumentAction` object ready for dispatch.
1163
- * @beta
1164
- */
1165
- declare function editDocument<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string>(doc: DocumentHandle<TDocumentType, TDataset, TProjectId>, sanityMutatePatch: PatchMutation): EditDocumentAction<TDocumentType, TDataset, TProjectId>;
1166
- /**
1167
- * Creates an `EditDocumentAction` object with patches for modifying a document.
1168
- *
1169
- * @param doc - A handle uniquely identifying the document to be edited.
1170
- * @param patches - A single patch operation or an array of patch operations.
1171
- * @returns An `EditDocumentAction` object ready for dispatch.
1172
- * @beta
1173
- */
1174
- declare function editDocument<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string>(doc: DocumentHandle<TDocumentType, TDataset, TProjectId>, patches?: PatchOperations | PatchOperations[]): EditDocumentAction<TDocumentType, TDataset, TProjectId>;
1175
- /**
1176
- * Creates a `PublishDocumentAction` object.
1177
- * @param doc - A handle uniquely identifying the document to be published.
1178
- * @returns A `PublishDocumentAction` object ready for dispatch.
1179
- * @beta
1180
- */
1181
- declare function publishDocument<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string>(doc: DocumentHandle<TDocumentType, TDataset, TProjectId>): PublishDocumentAction<TDocumentType, TDataset, TProjectId>;
1182
- /**
1183
- * Creates an `UnpublishDocumentAction` object.
1184
- * @param doc - A handle uniquely identifying the document to be unpublished.
1185
- * @returns An `UnpublishDocumentAction` object ready for dispatch.
1186
- * @beta
1187
- */
1188
- declare function unpublishDocument<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string>(doc: DocumentHandle<TDocumentType, TDataset, TProjectId>): UnpublishDocumentAction<TDocumentType, TDataset, TProjectId>;
1189
- /**
1190
- * Creates a `DiscardDocumentAction` object.
1191
- * @param doc - A handle uniquely identifying the document whose draft changes are to be discarded.
1192
- * @returns A `DiscardDocumentAction` object ready for dispatch.
1193
- * @beta
1194
- */
1195
- declare function discardDocument<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string>(doc: DocumentHandle<TDocumentType, TDataset, TProjectId>): DiscardDocumentAction<TDocumentType, TDataset, TProjectId>;
1196
- /**
1197
- * Represents a set of document that will go into `applyMutations`. Before
1198
- * applying a mutation, it's expected that all relevant documents that the
1199
- * mutations affect are included, including those that do not exist yet.
1200
- * Documents that don't exist have a `null` value.
1201
- */
1202
- type DocumentSet<TDocument extends SanityDocument$2 = SanityDocument$2> = { [TDocumentId in string]?: TDocument | null };
1203
- /** @beta */
1204
- interface ActionsResult<TDocument extends SanityDocument$3 = SanityDocument$3> {
1205
- transactionId: string;
1206
- documents: DocumentSet<TDocument>;
1207
- previous: DocumentSet<TDocument>;
1208
- previousRevs: {
1209
- [documentId: string]: string | undefined;
1210
- };
1211
- appeared: string[];
1212
- updated: string[];
1213
- disappeared: string[];
1214
- submitted: () => ReturnType<SanityClient['action']>;
1215
- }
1216
- /** @beta */
1217
- interface ApplyDocumentActionsOptions {
1218
- /**
1219
- * List of actions to apply.
1220
- */
1221
- actions: DocumentAction[];
1222
- /**
1223
- * Optionally provide an ID to be used as this transaction ID
1224
- */
1225
- transactionId?: string;
1226
- /**
1227
- * Set this to true to prevent this action from being batched with others.
1228
- */
1229
- disableBatching?: boolean;
1230
- }
1231
- /** @beta */
1232
- declare function applyDocumentActions<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string>(instance: SanityInstance, options: ApplyDocumentActionsOptions): Promise<ActionsResult<SanityDocument$3<TDocumentType, `${TProjectId}.${TDataset}`>>>;
1233
- /** @beta */
1234
- declare function applyDocumentActions(instance: SanityInstance, options: ApplyDocumentActionsOptions): Promise<ActionsResult>;
1235
- /**
1236
- * Represents a reactive state source that provides synchronized access to store data
1237
- *
1238
- * @remarks
1239
- * Designed to work with React's useSyncExternalStore hook. Provides three ways to access data:
1240
- * 1. `getCurrent()` for synchronous current value access
1241
- * 2. `subscribe()` for imperative change notifications
1242
- * 3. `observable` for reactive stream access
1243
- *
1244
- * @public
1245
- */
1246
- interface StateSource<T> {
1247
- /**
1248
- * Subscribes to state changes with optional callback
1249
- * @param onStoreChanged - Called whenever relevant state changes occur
1250
- * @returns Unsubscribe function to clean up the subscription
1251
- */
1252
- subscribe: (onStoreChanged?: () => void) => () => void;
1253
- /**
1254
- * Gets the current derived state value
1255
- *
1256
- * @remarks
1257
- * Safe to call without subscription. Will always return the latest value
1258
- * based on the current store state and selector parameters.
1259
- */
1260
- getCurrent: () => T;
1261
- /**
1262
- * Observable stream of state values
1263
- *
1264
- * @remarks
1265
- * Shares a single underlying subscription between all observers. Emits:
1266
- * - Immediately with current value on subscription
1267
- * - On every relevant state change
1268
- * - Errors if selector throws
1269
- */
1270
- observable: Observable<T>;
1271
- }
1272
- /**
1273
- * Context passed to selectors when deriving state
1274
- *
1275
- * @remarks
1276
- * Provides access to both the current state value and the Sanity instance,
1277
- * allowing selectors to use configuration values when computing derived state.
1278
- * The context is memoized for each state object and instance combination
1279
- * to optimize performance and prevent unnecessary recalculations.
1280
- *
1281
- * @example
1282
- * ```ts
1283
- * // Using both state and instance in a selector (psuedo example)
1284
- * const getUserByProjectId = createStateSourceAction(
1285
- * ({ state, instance }: SelectorContext<UsersState>, options?: ProjectHandle) => {
1286
- * const allUsers = state.users
1287
- * const projectId = options?.projectId ?? instance.config.projectId
1288
- * return allUsers.filter(user => user.projectId === projectId)
1289
- * }
1290
- * )
1291
- * ```
1292
- */
1293
- interface SelectorContext<TState> {
1294
- /**
1295
- * The current state object from the store
1296
- */
1297
- state: TState;
1298
- /**
1299
- * The Sanity instance associated with this state
1300
- */
1301
- instance: SanityInstance;
1302
- }
1303
- /**
1304
- * Function type for selecting derived state from store state and parameters
1305
- * @public
1306
- */
1307
- type Selector<TState, TParams extends unknown[], TReturn> = (context: SelectorContext<TState>, ...params: TParams) => TReturn;
1308
- type ActionMap = {
1309
- create: 'sanity.action.document.version.create';
1310
- createLiveEdit: 'sanity.action.document.create';
1311
- discard: 'sanity.action.document.version.discard';
1312
- unpublish: 'sanity.action.document.unpublish';
1313
- delete: 'sanity.action.document.delete';
1314
- edit: 'sanity.action.document.edit';
1315
- publish: 'sanity.action.document.publish';
1316
- };
1317
- type OptimisticLock = {
1318
- ifDraftRevisionId?: string;
1319
- ifPublishedRevisionId?: string;
1320
- };
1321
- type HttpAction = {
1322
- actionType: ActionMap['create'];
1323
- publishedId: string;
1324
- attributes: SanityDocumentLike;
1325
- } | {
1326
- actionType: ActionMap['createLiveEdit'];
1327
- publishedId: string;
1328
- attributes: SanityDocumentLike;
1329
- } | {
1330
- actionType: ActionMap['discard'];
1331
- versionId: string;
1332
- purge?: boolean;
1333
- } | {
1334
- actionType: ActionMap['unpublish'];
1335
- draftId: string;
1336
- publishedId: string;
1337
- } | {
1338
- actionType: ActionMap['delete'];
1339
- publishedId: string;
1340
- includeDrafts?: string[];
1341
- } | {
1342
- actionType: ActionMap['edit'];
1343
- draftId: string;
1344
- publishedId: string;
1345
- patch: PatchOperations;
1346
- } | ({
1347
- actionType: ActionMap['publish'];
1348
- draftId: string;
1349
- publishedId: string;
1350
- } & OptimisticLock);
1351
- /**
1352
- * Represents a transaction that is queued to be applied but has not yet been
1353
- * applied. A transaction will remain in a queued state until all required
1354
- * documents for the transactions are available locally.
1355
- */
1356
- interface QueuedTransaction {
1357
- /**
1358
- * the ID of this transaction. this is generated client-side.
1359
- */
1360
- transactionId: string;
1361
- /**
1362
- * the high-level actions associated with this transaction. note that these
1363
- * actions don't mention draft IDs and is meant to abstract away the draft
1364
- * model from users.
1365
- */
1366
- actions: DocumentAction[];
1367
- /**
1368
- * An optional flag set to disable this transaction from being batched with
1369
- * other transactions.
1370
- */
1371
- disableBatching?: boolean;
1372
- }
1373
- /**
1374
- * Represents a transaction that has been applied locally but has not been
1375
- * committed/transitioned-to-outgoing. These transactions are visible to the
1376
- * user but may be rebased upon a new working document set. Applied transactions
1377
- * also contain the resulting `outgoingActions` that will be submitted to
1378
- * Content Lake. These `outgoingActions` depend on the state of the working
1379
- * documents so they are recomputed on rebase and are only relevant to applied
1380
- * actions (we cannot compute `outgoingActions` for queued transactions because
1381
- * we haven't resolved the set of documents the actions are dependent on yet).
1382
- *
1383
- * In order to support better conflict resolution, the original `previous` set
1384
- * is saved as the `base` set.
1385
- */
1386
- interface AppliedTransaction extends QueuedTransaction {
1387
- /**
1388
- * the resulting set of documents after the actions have been applied
1389
- */
1390
- working: DocumentSet;
1391
- /**
1392
- * the previous set of documents before the action was applied
1393
- */
1394
- previous: DocumentSet;
1395
- /**
1396
- * the original `previous` document set captured when this action was
1397
- * originally applied. this is used as a reference point to do a 3-way merge
1398
- * if this applied transaction ever needs to be reapplied on a different
1399
- * set of documents.
1400
- */
1401
- base: DocumentSet;
1402
- /**
1403
- * the `_rev`s from `previous` document set
1404
- */
1405
- previousRevs: { [TDocumentId in string]?: string };
1406
- /**
1407
- * a timestamp for when this transaction was applied locally
1408
- */
1409
- timestamp: string;
1410
- /**
1411
- * the resulting HTTP actions derived from the state of the `working` document
1412
- * set. these are sent to Content Lake as-is when this transaction is batched
1413
- * and transitioned into an outgoing transaction.
1414
- */
1415
- outgoingActions: HttpAction[];
1416
- /**
1417
- * similar to `outgoingActions` but comprised of mutations instead of action.
1418
- * this left here for debugging purposes but could be used to send mutations
1419
- * to Content Lake instead of actions.
1420
- */
1421
- outgoingMutations: Mutation[];
1422
- }
1423
- /**
1424
- * Represents a set of applied transactions batched into a single outgoing
1425
- * transaction. An outgoing transaction is the result of batching many applied
1426
- * actions. An outgoing transaction may be reverted locally if the server
1427
- * does not accept it.
1428
- */
1429
- interface OutgoingTransaction extends AppliedTransaction {
1430
- disableBatching: boolean;
1431
- batchedTransactionIds: string[];
1432
- }
1433
- interface UnverifiedDocumentRevision {
1434
- transactionId: string;
1435
- documentId: string;
1436
- previousRev: string | undefined;
1437
- timestamp: string;
1438
- }
1439
- type Grant = 'read' | 'update' | 'create' | 'history';
1440
- /** @beta */
1441
- interface PermissionDeniedReason {
1442
- type: 'precondition' | 'access';
1443
- message: string;
1444
- documentId?: string;
1445
- }
1446
- /** @beta */
1447
- type DocumentPermissionsResult = {
1448
- allowed: false;
1449
- message: string;
1450
- reasons: PermissionDeniedReason[];
1451
- } | {
1452
- allowed: true;
1453
- message?: undefined;
1454
- reasons?: undefined;
1455
- };
1456
- /** @beta */
1457
- type DocumentEvent = ActionErrorEvent | TransactionRevertedEvent | TransactionAcceptedEvent | DocumentRebaseErrorEvent | DocumentEditedEvent | DocumentCreatedEvent | DocumentDeletedEvent | DocumentPublishedEvent | DocumentUnpublishedEvent | DocumentDiscardedEvent;
1458
- /**
1459
- * @beta
1460
- * Event emitted when a precondition to applying an action fails.
1461
- * (For example: when trying to edit a document that no longer exists.)
1462
- */
1463
- interface ActionErrorEvent {
1464
- type: 'error';
1465
- documentId: string;
1466
- transactionId: string;
1467
- message: string;
1468
- error: unknown;
1469
- }
1470
- /**
1471
- * @beta
1472
- * Event emitted when a transaction is accepted.
1473
- */
1474
- interface TransactionAcceptedEvent {
1475
- type: 'accepted';
1476
- outgoing: OutgoingTransaction;
1477
- result: Awaited<ReturnType<SanityClient['action']>>;
1478
- }
1479
- /**
1480
- * @beta
1481
- * Event emitted when a transaction is reverted.
1482
- */
1483
- interface TransactionRevertedEvent {
1484
- type: 'reverted';
1485
- message: string;
1486
- error: unknown;
1487
- outgoing: OutgoingTransaction;
1488
- }
1489
- /**
1490
- * @beta
1491
- * Event emitted when an attempt to apply local changes to a modified remote document fails.
1492
- */
1493
- interface DocumentRebaseErrorEvent {
1494
- type: 'rebase-error';
1495
- documentId: string;
1496
- transactionId: string;
1497
- message: string;
1498
- error: unknown;
1499
- }
1500
- /**
1501
- * @beta
1502
- * Event emitted when a document is edited.
1503
- */
1504
- interface DocumentEditedEvent {
1505
- type: 'edited';
1506
- documentId: string;
1507
- outgoing: OutgoingTransaction;
1508
- }
1509
- /**
1510
- * @beta
1511
- * Event emitted when a document is created.
1512
- */
1513
- interface DocumentCreatedEvent {
1514
- type: 'created';
1515
- documentId: string;
1516
- outgoing: OutgoingTransaction;
1517
- }
1518
- /**
1519
- * @beta
1520
- * Event emitted when a document is deleted.
1521
- */
1522
- interface DocumentDeletedEvent {
1523
- type: 'deleted';
1524
- documentId: string;
1525
- outgoing: OutgoingTransaction;
1526
- }
1527
- /**
1528
- * @beta
1529
- * Event emitted when a document is published.
1530
- */
1531
- interface DocumentPublishedEvent {
1532
- type: 'published';
1533
- documentId: string;
1534
- outgoing: OutgoingTransaction;
1535
- }
1536
- /**
1537
- * @beta
1538
- * Event emitted when a document is unpublished.
1539
- */
1540
- interface DocumentUnpublishedEvent {
1541
- type: 'unpublished';
1542
- documentId: string;
1543
- outgoing: OutgoingTransaction;
1544
- }
1545
- /**
1546
- * @beta
1547
- * Event emitted when a document version is discarded.
1548
- */
1549
- interface DocumentDiscardedEvent {
1550
- type: 'discarded';
1551
- documentId: string;
1552
- outgoing: OutgoingTransaction;
1553
- }
1554
- /**
1555
- * Split the entire path string on dots "outside" of any brackets.
1556
- *
1557
- * For example:
1558
- * ```
1559
- * "friends[0].name"
1560
- * ```
1561
- *
1562
- * becomes:
1563
- *
1564
- * ```
1565
- * [...ParseSegment<"friends[0]">, ...ParseSegment<"name">]
1566
- * ```
1567
- *
1568
- * (We use a simple recursion that splits on the first dot.)
1569
- */
1570
- type PathParts<TPath extends string> = TPath extends `${infer Head}.${infer Tail}` ? [Head, ...PathParts<Tail>] : TPath extends '' ? [] : [TPath];
1571
- /**
1572
- * Given a type T and an array of "access keys" Parts, recursively index into T.
1573
- *
1574
- * If a part is a key, it looks up that property.
1575
- * If T is an array and the part is a number, it "indexes" into the element type.
1576
- */
1577
- type DeepGet<TValue, TPath extends readonly (string | number)[]> = TPath extends [] ? TValue : TPath extends readonly [infer THead, ...infer TTail] ? DeepGet<TValue extends undefined | null ? undefined : THead extends keyof TValue ? TValue[THead] : THead extends number ? TValue extends readonly (infer TElement)[] ? TElement | undefined : undefined : undefined,
1578
- // Key/index doesn't exist
1579
- TTail extends readonly (string | number)[] ? TTail : []> : never;
1580
- /**
1581
- * Given a document type TDocument and a JSON Match path string TPath,
1582
- * compute the type found at that path.
1583
- * @beta
1584
- */
1585
- type JsonMatch<TDocument, TPath extends string> = DeepGet<TDocument, PathParts<TPath>>;
1586
- interface SharedListener {
1587
- events: Observable<ListenEvent<SanityDocument$1>>;
1588
- dispose: () => void;
1589
- }
1590
- interface DocumentStoreState {
1591
- documentStates: { [TDocumentId in string]?: DocumentState };
1592
- queued: QueuedTransaction[];
1593
- applied: AppliedTransaction[];
1594
- outgoing?: OutgoingTransaction;
1595
- grants?: Record<Grant, ExprNode>;
1596
- error?: unknown;
1597
- sharedListener: SharedListener;
1598
- fetchDocument: (documentId: string) => Observable<SanityDocument$3 | null>;
1599
- events: Subject<DocumentEvent>;
1600
- }
1601
- interface DocumentState {
1602
- id: string;
1603
- /**
1604
- * the "remote" local copy that matches the server. represents the last known
1605
- * server state. this gets updated every time we confirm remote patches
1606
- */
1607
- remote?: SanityDocument$3 | null;
1608
- /**
1609
- * the current ephemeral working copy that includes local optimistic changes
1610
- * that have not yet been confirmed by the server
1611
- */
1612
- local?: SanityDocument$3 | null;
1613
- /**
1614
- * the revision that our remote document is at
1615
- */
1616
- remoteRev?: string | null;
1617
- /**
1618
- * Array of subscription IDs. This document state will be deleted if there are
1619
- * no subscribers.
1620
- */
1621
- subscriptions: string[];
1622
- /**
1623
- * An object keyed by transaction ID of revisions sent out but that have not
1624
- * yet been verified yet. When an applied transaction is transitioned to an
1625
- * outgoing transaction, it also adds unverified revisions for each document
1626
- * that is part of that outgoing transaction. Transactions are submitted to
1627
- * the server with a locally generated transaction ID. This way we can observe
1628
- * when our transaction comes back through the shared listener. Each listener
1629
- * event that comes back contains a `previousRev`. If we see our own
1630
- * transaction with a different `previousRev` than expected, we can rebase our
1631
- * local transactions on top of this new remote.
1632
- */
1633
- unverifiedRevisions?: { [TTransactionId in string]?: UnverifiedDocumentRevision };
1634
- }
1635
- /**
1636
- * @beta
1637
- * Options for specifying a document and optionally a path within it.
1638
- */
1639
- interface DocumentOptions<TPath extends string | undefined = undefined, TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string> extends DocumentHandle<TDocumentType, TDataset, TProjectId> {
1640
- path?: TPath;
1641
- }
1642
- /** @beta */
1643
- declare function getDocumentState<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string>(instance: SanityInstance, options: DocumentOptions<undefined, TDocumentType, TDataset, TProjectId>): StateSource<SanityDocument$3<TDocumentType, `${TProjectId}.${TDataset}`> | undefined | null>;
1644
- /** @beta */
1645
- declare function getDocumentState<TPath extends string = string, TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string>(instance: SanityInstance, options: DocumentOptions<TPath, TDocumentType, TDataset, TProjectId>): StateSource<JsonMatch<SanityDocument$3<TDocumentType, `${TProjectId}.${TDataset}`>, TPath> | undefined>;
1646
- /** @beta */
1647
- declare function getDocumentState<TData>(instance: SanityInstance, options: DocumentOptions<string | undefined>): StateSource<TData | undefined | null>;
1648
- /** @beta */
1649
- declare function resolveDocument<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string>(instance: SanityInstance, docHandle: DocumentHandle<TDocumentType, TDataset, TProjectId>): Promise<SanityDocument$3<TDocumentType, `${TProjectId}.${TDataset}`> | null>;
1650
- /** @beta */
1651
- declare function resolveDocument<TData extends SanityDocument$3>(instance: SanityInstance, docHandle: DocumentHandle<string, string, string>): Promise<TData | null>;
1652
- /** @beta */
1653
- declare const getDocumentSyncStatus: BoundStoreAction<DocumentStoreState, [doc: DocumentHandle<string, string, string>], StateSource<boolean | undefined>>;
1654
- type PermissionsStateOptions = {
1655
- actions: DocumentAction[];
1656
- };
1657
- /** @beta */
1658
- declare const getPermissionsState: BoundStoreAction<DocumentStoreState, [PermissionsStateOptions], StateSource<DocumentPermissionsResult | undefined>>;
1659
- /** @beta */
1660
- declare const resolvePermissions: BoundStoreAction<DocumentStoreState, [options: PermissionsStateOptions], Promise<DocumentPermissionsResult>>;
1661
- /** @beta */
1662
- declare const subscribeDocumentEvents: BoundStoreAction<DocumentStoreState, [eventHandler: (e: DocumentEvent) => void], () => void>;
1663
- /**
1664
- * @public
1665
- */
1666
- interface FavoriteStatusResponse {
1667
- isFavorited: boolean;
1668
- }
1669
- /**
1670
- * @public
1671
- */
1672
- interface FavoriteDocumentContext extends DocumentHandle {
1673
- resourceId: string;
1674
- resourceType: StudioResource['type'] | MediaResource['type'] | CanvasResource['type'];
1675
- schemaName?: string;
1676
- }
1677
- /**
1678
- * Gets a StateSource for the favorite status of a document.
1679
- * @param instance - The Sanity instance.
1680
- * @param context - The document context including ID, type, and resource information.
1681
- * @returns A StateSource emitting `{ isFavorited: boolean }`.
1682
- * @public
1683
- */
1684
- declare const getFavoritesState: BoundStoreAction<FetcherStoreState<[FavoriteDocumentContext], FavoriteStatusResponse>, [FavoriteDocumentContext], StateSource<FavoriteStatusResponse | undefined>>;
1685
- /**
1686
- * Resolves the favorite status for a document.
1687
- * @param instance - The Sanity instance.
1688
- * @param context - The document context including ID, type, and resource information.
1689
- * @returns A Promise resolving to `{ isFavorited: boolean }`.
1690
- * @public
1691
- */
1692
- declare const resolveFavoritesState: BoundStoreAction<FetcherStoreState<[FavoriteDocumentContext], FavoriteStatusResponse>, [FavoriteDocumentContext], Promise<FavoriteStatusResponse>>;
1693
- /**
1694
- * @public
1695
- */
1696
- interface SanityUser {
1697
- sanityUserId: string;
1698
- profile: UserProfile;
1699
- memberships: Membership[];
1700
- }
1701
- /**
1702
- * @public
1703
- */
1704
- interface Membership {
1705
- addedAt?: string;
1706
- resourceType: string;
1707
- resourceId: string;
1708
- roleNames: Array<string>;
1709
- lastSeenAt?: string | null;
1710
- }
1711
- /**
1712
- * @public
1713
- */
1714
- interface UserProfile {
1715
- id: string;
1716
- displayName: string;
1717
- email: string;
1718
- familyName?: string;
1719
- givenName?: string;
1720
- middleName?: string | null;
1721
- imageUrl?: string;
1722
- provider: string;
1723
- tosAcceptedAt?: string;
1724
- createdAt: string;
1725
- updatedAt?: string;
1726
- isCurrentUser?: boolean;
1727
- providerId?: string;
1728
- }
1729
- /**
1730
- * @public
1731
- */
1732
- interface GetUsersOptions extends ProjectHandle {
1733
- resourceType?: 'organization' | 'project';
1734
- batchSize?: number;
1735
- organizationId?: string;
1736
- userId?: string;
1737
- }
1738
- /**
1739
- * @public
1740
- */
1741
- interface UsersGroupState {
1742
- subscriptions: string[];
1743
- totalCount?: number;
1744
- nextCursor?: string | null;
1745
- lastLoadMoreRequest?: string;
1746
- users?: SanityUser[];
1747
- error?: unknown;
1748
- }
1749
- /**
1750
- * @public
1751
- */
1752
- interface SanityUserResponse {
1753
- data: SanityUser[];
1754
- totalCount: number;
1755
- nextCursor: string | null;
1756
- }
1757
- /**
1758
- * @public
1759
- */
1760
- interface UsersStoreState {
1761
- users: { [TUsersKey in string]?: UsersGroupState };
1762
- error?: unknown;
1763
- }
1764
- /**
1765
- * @public
1766
- */
1767
- interface ResolveUsersOptions extends GetUsersOptions {
1768
- signal?: AbortSignal;
1769
- }
1770
- /**
1771
- * @public
1772
- */
1773
- interface GetUserOptions extends ProjectHandle {
1774
- userId: string;
1775
- resourceType?: 'organization' | 'project';
1776
- organizationId?: string;
1777
- }
1778
- /**
1779
- * @public
1780
- */
1781
- interface ResolveUserOptions extends GetUserOptions {
1782
- signal?: AbortSignal;
1783
- }
1784
- /** @public */
1785
- interface PresenceLocation {
1786
- type: 'document';
1787
- documentId: string;
1788
- path: string[];
1789
- lastActiveAt: string;
1790
- }
1791
- /** @public */
1792
- interface UserPresence {
1793
- user: SanityUser;
1794
- locations: PresenceLocation[];
1795
- sessionId: string;
1796
- }
1797
- /** @public */
1798
- type TransportEvent = RollCallEvent | StateEvent | DisconnectEvent;
1799
- /** @public */
1800
- interface RollCallEvent {
1801
- type: 'rollCall';
1802
- userId: string;
1803
- sessionId: string;
1804
- }
1805
- /** @public */
1806
- interface StateEvent {
1807
- type: 'state';
1808
- userId: string;
1809
- sessionId: string;
1810
- timestamp: string;
1811
- locations: PresenceLocation[];
1812
- }
1813
- /** @public */
1814
- interface DisconnectEvent {
1815
- type: 'disconnect';
1816
- userId: string;
1817
- sessionId: string;
1818
- timestamp: string;
1819
- }
1820
- type PresenceStoreState = {
1821
- locations: Map<string, {
1822
- userId: string;
1823
- locations: PresenceLocation[];
1824
- }>;
1825
- users: Record<string, SanityUser | undefined>;
1826
- };
1827
- /** @public */
1828
-
1829
- /** @public */
1830
- declare const getPresence: BoundStoreAction<PresenceStoreState, [((object & {
1831
- projectId?: string;
1832
- dataset?: string;
1833
- }) | undefined)?, ...unknown[]], StateSource<UserPresence[]>>;
1834
- /**
1835
- * Represents a media asset in a preview.
1836
- *
1837
- * @public
1838
- */
1839
- interface PreviewMedia {
1840
- type: 'image-asset';
1841
- _ref: string;
1842
- url: string;
1843
- }
1844
- /**
1845
- * Represents the set of values displayed as a preview for a given Sanity document.
1846
- * This includes a primary title, a secondary subtitle, an optional piece of media associated
1847
- * with the document, and the document's status.
1848
- *
1849
- * @public
1850
- */
1851
- interface PreviewValue {
1852
- /**
1853
- * The primary text displayed for the document preview.
1854
- */
1855
- title: string;
1856
- /**
1857
- * A secondary line of text providing additional context about the document.
1858
- */
1859
- subtitle?: string;
1860
- /**
1861
- * An optional piece of media representing the document within its preview.
1862
- * Currently, only image assets are available.
1863
- */
1864
- media?: PreviewMedia | null;
1865
- /**
1866
- * The status of the document.
1867
- */
1868
- _status?: {
1869
- /** The date of the last published edit */
1870
- lastEditedPublishedAt?: string;
1871
- /** The date of the last draft edit */
1872
- lastEditedDraftAt?: string;
1873
- };
1874
- }
1875
- /**
1876
- * Represents the current state of a preview value along with a flag indicating whether
1877
- * the preview data is still being fetched or is fully resolved.
1878
- *
1879
- * The tuple contains a preview value or null, and a boolean indicating if the data is
1880
- * pending. A `true` value means a fetch is ongoing; `false` indicates that the
1881
- * currently provided preview value is up-to-date.
1882
- *
1883
- * @public
1884
- */
1885
- type ValuePending<T> = {
1886
- data: T | null;
1887
- isPending: boolean;
1888
- };
1889
- /**
1890
- * @public
1891
- */
1892
- interface PreviewStoreState {
1893
- values: { [TDocumentId in string]?: ValuePending<PreviewValue> };
1894
- subscriptions: { [TDocumentId in string]?: { [TSubscriptionId in string]?: true } };
1895
- }
1896
- /**
1897
- * @beta
1898
- */
1899
- type GetPreviewStateOptions = DocumentHandle;
1900
- /**
1901
- * @beta
1902
- */
1903
- declare function getPreviewState<TResult extends object>(instance: SanityInstance, options: GetPreviewStateOptions): StateSource<ValuePending<TResult>>;
1904
- /**
1905
- * @beta
1906
- */
1907
- declare function getPreviewState(instance: SanityInstance, options: GetPreviewStateOptions): StateSource<ValuePending<PreviewValue>>;
1908
- /**
1909
- * @beta
1910
- */
1911
- type ResolvePreviewOptions = DocumentHandle;
1912
- /**
1913
- * @beta
1914
- */
1915
- declare const resolvePreview: BoundStoreAction<PreviewStoreState, [docHandle: ResolvePreviewOptions], Promise<ValuePending<object>>>;
1916
- /** @public */
1917
- declare const getProjectState: BoundStoreAction<FetcherStoreState<[options?: ProjectHandle<string> | undefined], _sanity_client12.SanityProject>, [options?: ProjectHandle<string> | undefined], StateSource<_sanity_client12.SanityProject | undefined>>;
1918
- /** @public */
1919
- declare const resolveProject: BoundStoreAction<FetcherStoreState<[options?: ProjectHandle<string> | undefined], _sanity_client12.SanityProject>, [options?: ProjectHandle<string> | undefined], Promise<_sanity_client12.SanityProject>>;
1920
- /**
1921
- * @public
1922
- * The result of a projection query
1923
- */
1924
- interface ProjectionValuePending<TValue extends object> {
1925
- data: TValue | null;
1926
- isPending: boolean;
1927
- }
1928
- /**
1929
- * @public
1930
- * @deprecated
1931
- * Template literals are a bit too limited, so this type is deprecated.
1932
- * Use `string` instead. Projection strings are validated at runtime.
1933
- */
1934
- type ValidProjection = string;
1935
- interface ProjectionOptions<TProjection extends string = string, TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string> extends DocumentHandle<TDocumentType, TDataset, TProjectId> {
1936
- projection: TProjection;
1937
- }
1938
- /**
1939
- * @beta
1940
- */
1941
- declare function getProjectionState<TProjection extends string = string, TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string>(instance: SanityInstance, options: ProjectionOptions<TProjection, TDocumentType, TDataset, TProjectId>): StateSource<ProjectionValuePending<SanityProjectionResult<TProjection, TDocumentType, `${TProjectId}.${TDataset}`>> | undefined>;
1942
- /**
1943
- * @beta
1944
- */
1945
- declare function getProjectionState<TData extends object>(instance: SanityInstance, options: ProjectionOptions): StateSource<ProjectionValuePending<TData> | undefined>;
1946
- /**
1947
- * @beta
1948
- */
1949
- declare function getProjectionState(instance: SanityInstance, options: ProjectionOptions): StateSource<ProjectionValuePending<Record<string, unknown>> | undefined>;
1950
- /** @beta */
1951
- declare function resolveProjection<TProjection extends string = string, TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string>(instance: SanityInstance, options: ProjectionOptions<TProjection, TDocumentType, TDataset, TProjectId>): Promise<ProjectionValuePending<SanityProjectionResult<TProjection, TDocumentType, `${TProjectId}.${TDataset}`>>>;
1952
- /** @beta */
1953
- declare function resolveProjection<TData extends object>(instance: SanityInstance, options: ProjectionOptions): Promise<ProjectionValuePending<TData>>;
1954
- /** @public */
1955
- declare const getProjectsState: BoundStoreAction<FetcherStoreState<[options?: {
1956
- organizationId?: string;
1957
- includeMembers?: boolean;
1958
- } | undefined], Omit<_sanity_client12.SanityProject, "members">[]>, [options?: {
1959
- organizationId?: string;
1960
- includeMembers?: boolean;
1961
- } | undefined], StateSource<Omit<_sanity_client12.SanityProject, "members">[] | undefined>>;
1962
- /** @public */
1963
- declare const resolveProjects: BoundStoreAction<FetcherStoreState<[options?: {
1964
- organizationId?: string;
1965
- includeMembers?: boolean;
1966
- } | undefined], Omit<_sanity_client12.SanityProject, "members">[]>, [options?: {
1967
- organizationId?: string;
1968
- includeMembers?: boolean;
1969
- } | undefined], Promise<Omit<_sanity_client12.SanityProject, "members">[]>>;
1970
- /**
1971
- * @beta
1972
- */
1973
- interface QueryOptions<TQuery extends string = string, TDataset extends string = string, TProjectId extends string = string> extends Pick<ResponseQueryOptions, 'useCdn' | 'cache' | 'next' | 'cacheMode' | 'tag'>, DatasetHandle<TDataset, TProjectId> {
1974
- query: TQuery;
1975
- params?: Record<string, unknown>;
1976
- }
1977
- /**
1978
- * @beta
1979
- */
1980
- interface ResolveQueryOptions<TQuery extends string = string, TDataset extends string = string, TProjectId extends string = string> extends QueryOptions<TQuery, TDataset, TProjectId> {
1981
- signal?: AbortSignal;
1982
- }
1983
- /** @beta */
1984
- declare const getQueryKey: (options: QueryOptions) => string;
1985
- /** @beta */
1986
- declare const parseQueryKey: (key: string) => QueryOptions;
1987
- /**
1988
- * Returns the state source for a query.
1989
- *
1990
- * This function returns a state source that represents the current result of a GROQ query.
1991
- * Subscribing to the state source will instruct the SDK to fetch the query (if not already fetched)
1992
- * and will keep the query live using the Live content API (considering sync tags) to provide up-to-date results.
1993
- * When the last subscriber is removed, the query state is automatically cleaned up from the store.
1994
- *
1995
- * Note: This functionality is for advanced users who want to build their own framework integrations.
1996
- * Our SDK also provides a React integration (useQuery hook) for convenient usage.
1997
- *
1998
- * Note: Automatic cleanup can interfere with React Suspense because if a component suspends while being the only subscriber,
1999
- * cleanup might occur unexpectedly. In such cases, consider using `resolveQuery` instead.
2000
- *
2001
- * @beta
2002
- */
2003
- declare function getQueryState<TQuery extends string = string, TDataset extends string = string, TProjectId extends string = string>(instance: SanityInstance, queryOptions: QueryOptions<TQuery, TDataset, TProjectId>): StateSource<SanityQueryResult<TQuery, `${TProjectId}.${TDataset}`> | undefined>;
2004
- /** @beta */
2005
- declare function getQueryState<TData>(instance: SanityInstance, queryOptions: QueryOptions): StateSource<TData | undefined>;
2006
- /** @beta */
2007
- declare function getQueryState(instance: SanityInstance, queryOptions: QueryOptions): StateSource<unknown>;
2008
- /**
2009
- * Resolves the result of a query without registering a lasting subscriber.
2010
- *
2011
- * This function fetches the result of a GROQ query and returns a promise that resolves with the query result.
2012
- * Unlike `getQueryState`, which registers subscribers to keep the query live and performs automatic cleanup,
2013
- * `resolveQuery` does not track subscribers. This makes it ideal for use with React Suspense, where the returned
2014
- * promise is thrown to delay rendering until the query result becomes available.
2015
- * Once the promise resolves, it is expected that a real subscriber will be added via `getQueryState` to manage ongoing updates.
2016
- *
2017
- * Additionally, an optional AbortSignal can be provided to cancel the query and immediately clear the associated state
2018
- * if there are no active subscribers.
2019
- *
2020
- * @beta
2021
- */
2022
- declare function resolveQuery<TQuery extends string = string, TDataset extends string = string, TProjectId extends string = string>(instance: SanityInstance, queryOptions: ResolveQueryOptions<TQuery, TDataset, TProjectId>): Promise<SanityQueryResult<TQuery, `${TProjectId}.${TDataset}`>>;
2023
- /** @beta */
2024
- declare function resolveQuery<TData>(instance: SanityInstance, queryOptions: ResolveQueryOptions): Promise<TData>;
2025
- /**
2026
- * Represents a document in a Sanity dataset that represents release options.
2027
- * @internal
2028
- */
2029
- type ReleaseDocument = SanityDocument$2 & {
2030
- name: string;
2031
- publishAt?: string;
2032
- state: 'active' | 'scheduled';
2033
- metadata: {
2034
- title: string;
2035
- releaseType: 'asap' | 'scheduled' | 'undecided';
2036
- intendedPublishAt?: string;
2037
- description?: string;
2038
- };
2039
- };
2040
- interface ReleasesStoreState {
2041
- activeReleases?: ReleaseDocument[];
2042
- error?: unknown;
2043
- }
2044
- /**
2045
- * Get the active releases from the store.
2046
- * @internal
2047
- */
2048
- declare const getActiveReleasesState: BoundStoreAction<ReleasesStoreState, [((object & {
2049
- projectId?: string;
2050
- dataset?: string;
2051
- }) | undefined)?, ...unknown[]], StateSource<ReleaseDocument[] | undefined>>;
2052
- declare const _getPerspectiveStateSelector: StoreAction<ReleasesStoreState, [_?: (PerspectiveHandle & {
2053
- projectId?: string;
2054
- dataset?: string;
2055
- }) | undefined], StateSource<string[] | "previewDrafts" | "published" | "drafts" | "raw" | undefined>, unknown>;
2056
- type OmitFirst<T extends unknown[]> = T extends [unknown, ...infer R] ? R : never;
2057
- type SelectorParams = OmitFirst<Parameters<typeof _getPerspectiveStateSelector>>;
2058
- type BoundGetPerspectiveState = BoundStoreAction<ReleasesStoreState, SelectorParams, ReturnType<typeof _getPerspectiveStateSelector>>;
2059
- /**
2060
- * Provides a subscribable state source for a "perspective" for the Sanity client,
2061
- * which is used to fetch documents as though certain Content Releases are active.
2062
- *
2063
- * @param instance - The Sanity instance to get the perspective for
2064
- * @param options - The options for the perspective -- usually a release name
2065
- *
2066
- * @returns A subscribable perspective value, usually a list of applicable release names,
2067
- * or a single release name / default perspective (such as 'drafts').
2068
- *
2069
- * @public
2070
- */
2071
- declare const getPerspectiveState: BoundGetPerspectiveState;
2072
- /** @internal */
2073
- declare const getUsersKey: (instance: SanityInstance, {
2074
- resourceType,
2075
- organizationId,
2076
- batchSize,
2077
- projectId,
2078
- userId
2079
- }?: GetUsersOptions) => string;
2080
- /** @internal */
2081
- declare const parseUsersKey: (key: string) => {
2082
- batchSize: number;
2083
- resourceType?: "organization" | "project";
2084
- projectId?: string;
2085
- organizationId?: string;
2086
- userId?: string;
2087
- };
2088
- /**
2089
- * Returns the state source for users associated with a specific resource.
2090
- *
2091
- * This function returns a state source that represents the current list of users for a given
2092
- * resource. Subscribing to the state source will instruct the SDK to fetch the users (if not
2093
- * already fetched) and will load more from this state source as well. When the last subscriber is
2094
- * removed, the users state is automatically cleaned up from the store after a delay.
2095
- *
2096
- * Note: This functionality is for advanced users who want to build their own framework
2097
- * integrations. Our SDK also provides a React integration for convenient usage.
2098
- *
2099
- * @beta
2100
- */
2101
- declare const getUsersState: BoundStoreAction<UsersStoreState, [options?: GetUsersOptions | undefined], StateSource<{
2102
- data: SanityUser[];
2103
- totalCount: number;
2104
- hasMore: boolean;
2105
- } | undefined>>;
2106
- /**
2107
- * Resolves the users for a specific resource without registering a lasting subscriber.
2108
- *
2109
- * This function fetches the users for a given resource and returns a promise that resolves with
2110
- * the users result. Unlike `getUsersState`, which registers subscribers to keep the data live and
2111
- * performs automatic cleanup, `resolveUsers` does not track subscribers. This makes it ideal for
2112
- * use with React Suspense, where the returned promise is thrown to delay rendering until the users
2113
- * result becomes available. Once the promise resolves, it is expected that a real subscriber will
2114
- * be added via `getUsersState` to manage ongoing updates.
2115
- *
2116
- * Additionally, an optional AbortSignal can be provided to cancel the request and immediately
2117
- * clear the associated state if there are no active subscribers.
2118
- *
2119
- * @beta
2120
- */
2121
- declare const resolveUsers: BoundStoreAction<UsersStoreState, [ResolveUsersOptions], Promise<{
2122
- data: SanityUser[];
2123
- totalCount: number;
2124
- hasMore: boolean;
2125
- }>>;
2126
- /**
2127
- * Loads more users for a specific resource.
2128
- *
2129
- * This function triggers a request to fetch the next page of users for a given resource. It
2130
- * requires that users have already been loaded for the resource (via `resolveUsers` or
2131
- * `getUsersState`), and that there are more users available to load (as indicated by the `hasMore`
2132
- * property).
2133
- *
2134
- * The function returns a promise that resolves when the next page of users has been loaded.
2135
- *
2136
- * @beta
2137
- */
2138
- declare const loadMoreUsers: BoundStoreAction<UsersStoreState, [options?: GetUsersOptions | undefined], Promise<{
2139
- data: SanityUser[];
2140
- totalCount: number;
2141
- hasMore: boolean;
2142
- }>>;
2143
- /**
2144
- * @beta
2145
- */
2146
- declare const getUserState: BoundStoreAction<UsersStoreState, [GetUserOptions], Observable<SanityUser | undefined>>;
2147
- /**
2148
- * @beta
2149
- */
2150
- declare const resolveUser: BoundStoreAction<UsersStoreState, [ResolveUserOptions], Promise<SanityUser>>;
2151
- interface StoreEntry<TParams extends unknown[], TData> {
2152
- params: TParams;
2153
- instance: SanityInstance;
2154
- key: string;
2155
- data?: TData;
2156
- error?: unknown;
2157
- subscriptions: string[];
2158
- lastFetchInitiatedAt?: string;
2159
- }
2160
- /**
2161
- * Internal helper type
2162
- * @public
2163
- */
2164
- interface FetcherStoreState<TParams extends unknown[], TData> {
2165
- stateByParams: { [TSerializedKey in string]?: StoreEntry<TParams, TData> };
2166
- error?: unknown;
2167
- }
2168
- /**
2169
- * Internal helper type
2170
- * @public
2171
- */
2172
- interface FetcherStore<TParams extends unknown[], TData> {
2173
- getState: BoundStoreAction<FetcherStoreState<TParams, TData>, TParams, StateSource<TData | undefined>>;
2174
- resolveState: BoundStoreAction<FetcherStoreState<TParams, TData>, TParams, Promise<TData>>;
2175
- }
2176
- /**
2177
- * Creates a GROQ search filter string (`[@] match text::query("...")`)
2178
- * from a raw search query string.
2179
- *
2180
- * It applies wildcard ('*') logic to the last eligible token and escapes
2181
- * double quotes within the search term.
2182
- *
2183
- * If the input query is empty or only whitespace, it returns an empty string.
2184
- *
2185
- * @param query - The raw input search string.
2186
- * @returns The GROQ search filter string, or an empty string.
2187
- * @internal
2188
- */
2189
- declare function createGroqSearchFilter(query: string): string;
2190
- /**
2191
- * Filter criteria for intent matching. Can be combined to create more specific intents.
2192
- *
2193
- * @example
2194
- * ```typescript
2195
- * // matches only geopoints in the travel-project project, production dataset
2196
- * const filter: IntentFilter = {
2197
- * projectId: 'travel-project',
2198
- * dataset: 'production',
2199
- * types: ['geopoint']
2200
- * }
2201
- *
2202
- * // matches all documents in the travel-project project
2203
- * const filter: IntentFilter = {
2204
- * projectId: 'travel-project',
2205
- * types: ['*']
2206
- * }
2207
- *
2208
- * // matches geopoints in the travel-project production dataset and map pins in all projects in the org
2209
- * const filters: IntentFilter[] = [
2210
- * {
2211
- * projectId: 'travel-project',
2212
- * dataset: 'production',
2213
- * types: ['geopoint']
2214
- * },
2215
- * {
2216
- * types: ['map-pin']
2217
- * }
2218
- * ]
2219
- * ```
2220
- * @public
2221
- */
2222
- interface IntentFilter {
2223
- /**
2224
- * Project ID to match against
2225
- * @remarks When specified, the intent will only match for the specified project.
2226
- */
2227
- projectId?: string;
2228
- /**
2229
- * Dataset to match against
2230
- * @remarks When specified, the intent will only match for the specified dataset. Requires projectId to be specified.
2231
- */
2232
- dataset?: string;
2233
- /**
2234
- * Document types that this intent can handle
2235
- * @remarks This is required for all filters. Use ['*'] to match all document types.
2236
- */
2237
- types: string[];
2238
- }
2239
- /**
2240
- * Intent definition structure for registering user intents
2241
- * @public
2242
- */
2243
- interface Intent {
2244
- /**
2245
- * Unique identifier for this intent
2246
- * @remarks Should be unique across all registered intents in an org for proper matching
2247
- */
2248
- id: string;
2249
- /**
2250
- * The action that this intent performs
2251
- * @remarks Examples: "view", "edit", "create", "delete"
2252
- */
2253
- action: 'view' | 'edit' | 'create' | 'delete';
2254
- /**
2255
- * Human-readable title for this intent
2256
- * @remarks Used for display purposes in UI or logs
2257
- */
2258
- title: string;
2259
- /**
2260
- * Detailed description of what this intent does
2261
- * @remarks Helps users understand the purpose and behavior of the intent
2262
- */
2263
- description?: string;
2264
- /**
2265
- * Array of filter criteria for intent matching
2266
- * @remarks At least one filter is required. Use `{types: ['*']}` to match everything
2267
- */
2268
- filters: IntentFilter[];
2269
- }
2270
- /**
2271
- * Creates a properly typed intent definition for registration with the backend.
2272
- *
2273
- * This utility function provides TypeScript support and validation for intent declarations.
2274
- * It is also used in the CLI if intents are declared as bare objects in an intents file.
2275
- *
2276
- * @param intent - The intent definition object
2277
- * @returns The same intent object with proper typing
2278
- *
2279
- * @example
2280
- * ```typescript
2281
- * // Specific filter for a document type
2282
- * const viewGeopointInMapApp = defineIntent({
2283
- * id: 'viewGeopointInMapApp',
2284
- * action: 'view',
2285
- * title: 'View a geopoint in the map app',
2286
- * description: 'This lets you view a geopoint in the map app',
2287
- * filters: [
2288
- * {
2289
- * projectId: 'travel-project',
2290
- * dataset: 'production',
2291
- * types: ['geopoint']
2292
- * }
2293
- * ]
2294
- * })
2295
- *
2296
- * export default viewGeopointInMapApp
2297
- * ```
2298
- *
2299
- * If your intent is asynchronous, resolve the promise before defining / returning the intent
2300
- * ```typescript
2301
- * async function createAsyncIntent() {
2302
- * const currentProject = await asyncProjectFunction()
2303
- * const currentDataset = await asyncDatasetFunction()
2304
- *
2305
- * return defineIntent({
2306
- * id: 'dynamicIntent',
2307
- * action: 'view',
2308
- * title: 'Dynamic Intent',
2309
- * description: 'Intent with dynamically resolved values',
2310
- * filters: [
2311
- * {
2312
- * projectId: currentProject, // Resolved value
2313
- * dataset: currentDataset, // Resolved value
2314
- * types: ['document']
2315
- * }
2316
- * ]
2317
- * })
2318
- * }
2319
- *
2320
- * const intent = await createAsyncIntent()
2321
- * export default intent
2322
- * ```
2323
- *
2324
- * @public
2325
- */
2326
- declare function defineIntent(intent: Intent): Intent;
2327
- /**
2328
- * @public
2329
- * Extracts the project ID from a CorsOriginError message.
2330
- * @param error - The error to extract the project ID from.
2331
- * @returns The project ID or null if the error is not a CorsOriginError.
2332
- */
2333
- declare function getCorsErrorProjectId(error: Error): string | null;
2334
- /**
2335
- * This version is provided by pkg-utils at build time
2336
- * @internal
2337
- */
2338
- declare const CORE_SDK_VERSION: {};
2339
- /**
2340
- * @public
2341
- */
2342
- type SanityProject = SanityProject$1;
2343
- export { type ActionErrorEvent, type ActionsResult, type AgentGenerateOptions, type AgentGenerateResult, type AgentPatchOptions, type AgentPatchResult, type AgentPromptOptions, type AgentPromptResult, type AgentTransformOptions, type AgentTransformResult, type AgentTranslateOptions, type AgentTranslateResult, type ApiErrorBody, type ApplyDocumentActionsOptions, type AuthConfig, type AuthProvider, type AuthState, AuthStateType, type AuthStoreState, CORE_SDK_VERSION, type CanvasSource, type ClientOptions, type ClientStoreState as ClientState, type ComlinkControllerState, type ComlinkNodeState, type CreateDocumentAction, type CurrentUser, type DatasetHandle, type DatasetSource, type DeleteDocumentAction, type DiscardDocumentAction, type DisconnectEvent, type DocumentAction, type DocumentCreatedEvent, type DocumentDeletedEvent, type DocumentDiscardedEvent, type DocumentEditedEvent, type DocumentEvent, type DocumentHandle, type DocumentOptions, type DocumentPermissionsResult, type DocumentPublishedEvent, type DocumentSource, type DocumentTypeHandle, type DocumentUnpublishedEvent, type EditDocumentAction, type ErrorAuthState, type FavoriteStatusResponse, type FetcherStore, type FetcherStoreState, type FrameMessage, type GetPreviewStateOptions, type GetUserOptions, type GetUsersOptions, type InstanceContext, type Intent, type IntentFilter, type JsonMatch, type LogContext, type LogLevel, type LogNamespace, type LoggedInAuthState, type LoggedOutAuthState, type Logger, type LoggerConfig, type LoggingInAuthState, type MediaLibrarySource, type Membership, type NewTokenResponseMessage, type NodeState, type OrgVerificationResult, type PermissionDeniedReason, type PerspectiveHandle, type PresenceLocation, type PreviewStoreState, type PreviewValue, type ProjectHandle, type ProjectionValuePending, type PublishDocumentAction, type QueryOptions, type ReleaseDocument, type ReleasePerspective, type RequestNewTokenMessage, type ResolvePreviewOptions, type ResolveUserOptions, type ResolveUsersOptions, type Role, type RollCallEvent, type SanityConfig, type SanityDocument, type SanityInstance, SanityProject, type SanityUser, type SanityUserResponse, type Selector, type StateEvent, type StateSource, type StudioConfig, type TokenSource, type TransactionAcceptedEvent, type TransactionRevertedEvent, type TransportEvent, type UnpublishDocumentAction, type UserPresence, type UserProfile, type UsersGroupState, type UsersStoreState, type ValidProjection, type ValuePending, type WindowMessage, agentGenerate, agentPatch, agentPrompt, agentTransform, agentTranslate, applyDocumentActions, configureLogging, createDatasetHandle, createDocument, createDocumentHandle, createDocumentTypeHandle, createGroqSearchFilter, createProjectHandle, createSanityInstance, defineIntent, deleteDocument, destroyController, discardDocument, editDocument, getActiveReleasesState, getAuthState, getClient, getClientErrorApiBody, getClientErrorApiDescription, getClientErrorApiType, getClientState, getCorsErrorProjectId, getCurrentUserState, getDashboardOrganizationId, getDatasetsState, getDocumentState, getDocumentSyncStatus, getFavoritesState, getIndexForKey, getIsInDashboardState, getLoginUrlState, getNodeState, getOrCreateChannel, getOrCreateController, getOrCreateNode, getPathDepth, getPermissionsState, getPerspectiveState, getPresence, getPreviewState, getProjectState, getProjectionState, getProjectsState, getQueryKey, getQueryState, getTokenState, getUserState, getUsersKey, getUsersState, handleAuthCallback, isCanvasSource, isDatasetSource, isMediaLibrarySource, isProjectUserNotFoundClientError, isStudioConfig, joinPaths, jsonMatch, loadMoreUsers, logout, observeOrganizationVerificationState, parseQueryKey, parseUsersKey, publishDocument, releaseChannel, releaseNode, resolveDatasets, resolveDocument, resolveFavoritesState, resolvePermissions, resolvePreview, resolveProject, resolveProjection, resolveProjects, resolveQuery, resolveUser, resolveUsers, setAuthToken, slicePath, stringifyPath, subscribeDocumentEvents, unpublishDocument };
1
+ import { $ as resolveProjects, $n as logout, $t as getDocumentSyncStatus, A as getCorsErrorProjectId, An as LoggerConfig, Ar as ProjectHandle, At as SanityUserResponse, B as resolveUser, Bn as ComlinkControllerState, Bt as ActionErrorEvent, C as getIndexForKey, Cn as resolveDatasets, Cr as DatasetHandle, Ct as UserPresence, D as slicePath, Dn as LogLevel, Dr as DocumentTypeHandle, Dt as ResolveUserOptions, E as jsonMatch, En as LogContext, Er as DocumentSource, Et as Membership, F as FetcherStore, Fn as NodeState, Fr as isCanvasSource, Ft as getFavoritesState, G as ReleaseDocument, Gn as FrameMessage, Gt as DocumentEvent, H as getUsersKey, Hn as getOrCreateChannel, Ht as DocumentDeletedEvent, I as FetcherStoreState, In as getNodeState, Ir as isDatasetSource, It as resolveFavoritesState, J as getQueryKey, Jn as WindowMessage, Jt as DocumentUnpublishedEvent, K as getActiveReleasesState, Kn as NewTokenResponseMessage, Kt as DocumentPublishedEvent, L as getUserState, Ln as ComlinkNodeState, Lr as isMediaLibrarySource, Lt as ActionsResult, M as IntentFilter, Mn as createDocumentHandle, Mr as SanityConfig, Mt as UsersGroupState, N as defineIntent, Nn as createDocumentTypeHandle, Nr as StudioConfig, Nt as UsersStoreState, O as stringifyPath, On as LogNamespace, Or as MediaLibrarySource, Ot as ResolveUsersOptions, P as createGroqSearchFilter, Pn as createProjectHandle, Pr as TokenSource, Pt as FavoriteStatusResponse, Q as getProjectsState, Qn as getClientState, Qt as getDocumentState, R as getUsersState, Rn as getOrCreateNode, Rr as AuthConfig, Rt as ApplyDocumentActionsOptions, S as SanityProject, Sn as getDatasetsState, Sr as CanvasSource, St as TransportEvent, T as joinPaths, Tn as InstanceContext, Tr as DocumentHandle, Tt as GetUsersOptions, U as parseUsersKey, Un as getOrCreateController, Ut as DocumentDiscardedEvent, V as resolveUsers, Vn as destroyController, Vt as DocumentCreatedEvent, W as getPerspectiveState, Wn as releaseChannel, Wt as DocumentEditedEvent, X as parseQueryKey, Xn as ClientStoreState, Xt as TransactionRevertedEvent, Y as getQueryState, Yn as ClientOptions, Yt as TransactionAcceptedEvent, Z as resolveQuery, Zn as getClient, Zt as DocumentOptions, _ as getTokenState, _n as deleteDocument, _r as agentTransform, _t as getPresence, a as isProjectUserNotFoundClientError, an as PermissionDeniedReason, ar as AgentGenerateResult, at as resolvePreview, b as Role, bn as publishDocument, br as createSanityInstance, bt as RollCallEvent, c as ErrorAuthState, cn as StateSource, cr as AgentPromptOptions, ct as GetPreviewStateOptions, d as LoggingInAuthState, dn as DiscardDocumentAction, dr as AgentTransformResult, dt as PreviewQueryResult, en as getPermissionsState, er as handleAuthCallback, et as resolveProjection, f as getAuthState, fn as DocumentAction, fr as AgentTranslateOptions, ft as PreviewStoreState, g as getLoginUrlState, gn as createDocument, gr as agentPrompt, gt as ValidProjection, h as getIsInDashboardState, hn as UnpublishDocumentAction, hr as agentPatch, ht as ProjectionValuePending, i as getClientErrorApiType, in as DocumentPermissionsResult, ir as AgentGenerateOptions, it as ResolvePreviewOptions, j as Intent, jn as createDatasetHandle, jr as ReleasePerspective, jt as UserProfile, k as CORE_SDK_VERSION, kn as Logger, kr as PerspectiveHandle, kt as SanityUser, l as LoggedInAuthState, ln as CreateDocumentAction, lr as AgentPromptResult, lt as getPreviewState, m as getDashboardOrganizationId, mn as PublishDocumentAction, mr as agentGenerate, mt as ValuePending, n as getClientErrorApiBody, nn as resolvePermissions, nr as OrgVerificationResult, nt as getProjectState, o as AuthState, on as JsonMatch, or as AgentPatchOptions, ot as transformProjectionToPreview, p as getCurrentUserState, pn as EditDocumentAction, pr as AgentTranslateResult, pt as PreviewValue, q as QueryOptions, qn as RequestNewTokenMessage, qt as DocumentTransactionSubmissionResult, r as getClientErrorApiDescription, rn as subscribeDocumentEvents, rr as AuthStateType, rt as resolveProject, s as AuthStoreState, sn as Selector, sr as AgentPatchResult, st as PREVIEW_PROJECTION, t as ApiErrorBody, tn as resolveDocument, tr as observeOrganizationVerificationState, tt as getProjectionState, u as LoggedOutAuthState, un as DeleteDocumentAction, ur as AgentTransformOptions, ut as PreviewMedia, v as setAuthToken, vn as discardDocument, vr as agentTranslate, vt as DisconnectEvent, w as getPathDepth, wn as configureLogging, wr as DatasetSource, wt as GetUserOptions, x as SanityDocument, xn as unpublishDocument, xr as isStudioConfig, xt as StateEvent, y as CurrentUser, yn as editDocument, yr as SanityInstance, yt as PresenceLocation, z as loadMoreUsers, zn as releaseNode, zr as AuthProvider, zt as applyDocumentActions } from "./_chunks-dts/utils.js";
2
+ export { ActionErrorEvent, ActionsResult, AgentGenerateOptions, AgentGenerateResult, AgentPatchOptions, AgentPatchResult, AgentPromptOptions, AgentPromptResult, AgentTransformOptions, AgentTransformResult, AgentTranslateOptions, AgentTranslateResult, ApiErrorBody, ApplyDocumentActionsOptions, AuthConfig, AuthProvider, AuthState, AuthStateType, AuthStoreState, CORE_SDK_VERSION, CanvasSource, ClientOptions, ClientStoreState as ClientState, ComlinkControllerState, ComlinkNodeState, CreateDocumentAction, CurrentUser, DatasetHandle, DatasetSource, DeleteDocumentAction, DiscardDocumentAction, DisconnectEvent, DocumentAction, DocumentCreatedEvent, DocumentDeletedEvent, DocumentDiscardedEvent, DocumentEditedEvent, DocumentEvent, DocumentHandle, DocumentOptions, DocumentPermissionsResult, DocumentPublishedEvent, DocumentSource, DocumentTransactionSubmissionResult, DocumentTypeHandle, DocumentUnpublishedEvent, EditDocumentAction, ErrorAuthState, FavoriteStatusResponse, FetcherStore, FetcherStoreState, FrameMessage, GetPreviewStateOptions, GetUserOptions, GetUsersOptions, InstanceContext, Intent, IntentFilter, JsonMatch, LogContext, LogLevel, LogNamespace, LoggedInAuthState, LoggedOutAuthState, Logger, LoggerConfig, LoggingInAuthState, MediaLibrarySource, Membership, NewTokenResponseMessage, NodeState, OrgVerificationResult, PREVIEW_PROJECTION, PermissionDeniedReason, PerspectiveHandle, PresenceLocation, PreviewMedia, PreviewQueryResult, PreviewStoreState, PreviewValue, ProjectHandle, ProjectionValuePending, PublishDocumentAction, QueryOptions, ReleaseDocument, ReleasePerspective, RequestNewTokenMessage, ResolvePreviewOptions, ResolveUserOptions, ResolveUsersOptions, Role, RollCallEvent, SanityConfig, SanityDocument, SanityInstance, SanityProject, SanityUser, SanityUserResponse, Selector, StateEvent, StateSource, StudioConfig, TokenSource, TransactionAcceptedEvent, TransactionRevertedEvent, TransportEvent, UnpublishDocumentAction, UserPresence, UserProfile, UsersGroupState, UsersStoreState, ValidProjection, ValuePending, WindowMessage, agentGenerate, agentPatch, agentPrompt, agentTransform, agentTranslate, applyDocumentActions, configureLogging, createDatasetHandle, createDocument, createDocumentHandle, createDocumentTypeHandle, createGroqSearchFilter, createProjectHandle, createSanityInstance, defineIntent, deleteDocument, destroyController, discardDocument, editDocument, getActiveReleasesState, getAuthState, getClient, getClientErrorApiBody, getClientErrorApiDescription, getClientErrorApiType, getClientState, getCorsErrorProjectId, getCurrentUserState, getDashboardOrganizationId, getDatasetsState, getDocumentState, getDocumentSyncStatus, getFavoritesState, getIndexForKey, getIsInDashboardState, getLoginUrlState, getNodeState, getOrCreateChannel, getOrCreateController, getOrCreateNode, getPathDepth, getPermissionsState, getPerspectiveState, getPresence, getPreviewState, getProjectState, getProjectionState, getProjectsState, getQueryKey, getQueryState, getTokenState, getUserState, getUsersKey, getUsersState, handleAuthCallback, isCanvasSource, isDatasetSource, isMediaLibrarySource, isProjectUserNotFoundClientError, isStudioConfig, joinPaths, jsonMatch, loadMoreUsers, logout, observeOrganizationVerificationState, parseQueryKey, parseUsersKey, publishDocument, releaseChannel, releaseNode, resolveDatasets, resolveDocument, resolveFavoritesState, resolvePermissions, resolvePreview, resolveProject, resolveProjection, resolveProjects, resolveQuery, resolveUser, resolveUsers, setAuthToken, slicePath, stringifyPath, subscribeDocumentEvents, transformProjectionToPreview, unpublishDocument };