@sanity/sdk 2.3.1 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import * as _sanity_client12 from "@sanity/client";
2
- import { ClientConfig, ClientPerspective, ListenEvent, ResponseQueryOptions, SanityClient, SanityDocument as SanityDocument$1, SanityProject as SanityProject$1, StackablePerspective } from "@sanity/client";
2
+ import { ClientConfig, ClientError, ClientPerspective, ListenEvent, ResponseQueryOptions, SanityClient, SanityDocument as SanityDocument$1, SanityProject as SanityProject$1, StackablePerspective } from "@sanity/client";
3
3
  import { Observable, Subject } from "rxjs";
4
4
  import { CurrentUser, CurrentUser as CurrentUser$1, Mutation, PatchOperations, Role, SanityDocument, SanityDocument as SanityDocument$2, SanityDocumentLike } from "@sanity/types";
5
5
  import * as _sanity_comlink3 from "@sanity/comlink";
@@ -9,17 +9,6 @@ import { SanityDocument as SanityDocument$3, SanityProjectionResult, SanityQuery
9
9
  import { ExprNode } from "groq-js";
10
10
  import { CanvasResource, MediaResource, StudioResource } from "@sanity/message-protocol";
11
11
  import { getIndexForKey, getPathDepth, joinPaths, jsonMatch, slicePath, stringifyPath } from "@sanity/json-match";
12
- /**
13
- * Represents the various states the authentication type can be in.
14
- *
15
- * @public
16
- */
17
- declare enum AuthStateType {
18
- LOGGED_IN = "logged-in",
19
- LOGGING_IN = "logging-in",
20
- ERROR = "error",
21
- LOGGED_OUT = "logged-out",
22
- }
23
12
  /**
24
13
  * Configuration for an authentication provider
25
14
  * @public
@@ -150,6 +139,39 @@ interface SanityConfig extends DatasetHandle, PerspectiveHandle {
150
139
  enabled: boolean;
151
140
  };
152
141
  }
142
+ declare const SOURCE_ID = "__sanity_internal_sourceId";
143
+ /**
144
+ * A document source can be used for querying.
145
+ *
146
+ * @beta
147
+ * @see datasetSource Construct a document source for a given projectId and dataset.
148
+ * @see mediaLibrarySource Construct a document source for a mediaLibraryId.
149
+ * @see canvasSource Construct a document source for a canvasId.
150
+ */
151
+ type DocumentSource = {
152
+ [SOURCE_ID]: ['media-library', string] | ['canvas', string] | {
153
+ projectId: string;
154
+ dataset: string;
155
+ };
156
+ };
157
+ /**
158
+ * Returns a document source for a projectId and dataset.
159
+ *
160
+ * @beta
161
+ */
162
+ declare function datasetSource(projectId: string, dataset: string): DocumentSource;
163
+ /**
164
+ * Returns a document source for a Media Library.
165
+ *
166
+ * @beta
167
+ */
168
+ declare function mediaLibrarySource(id: string): DocumentSource;
169
+ /**
170
+ * Returns a document source for a Canvas.
171
+ *
172
+ * @beta
173
+ */
174
+ declare function canvasSource(id: string): DocumentSource;
153
175
  /**
154
176
  * Represents a Sanity.io resource instance with its own configuration and lifecycle
155
177
  * @remarks Instances form a hierarchy through parent/child relationships
@@ -211,6 +233,77 @@ interface SanityInstance {
211
233
  * @public
212
234
  */
213
235
  declare function createSanityInstance(config?: SanityConfig): SanityInstance;
236
+ /** @alpha */
237
+ type AgentGenerateOptions = Parameters<SanityClient['observable']['agent']['action']['generate']>[0];
238
+ /** @alpha */
239
+ type AgentTransformOptions = Parameters<SanityClient['observable']['agent']['action']['transform']>[0];
240
+ /** @alpha */
241
+ type AgentTranslateOptions = Parameters<SanityClient['observable']['agent']['action']['translate']>[0];
242
+ /** @alpha */
243
+ type AgentPromptOptions = Parameters<SanityClient['agent']['action']['prompt']>[0];
244
+ /** @alpha */
245
+ type AgentPatchOptions = Parameters<SanityClient['agent']['action']['patch']>[0];
246
+ /** @alpha */
247
+ type AgentGenerateResult = Awaited<ReturnType<SanityClient['observable']['agent']['action']['generate']>>;
248
+ /** @alpha */
249
+ type AgentTransformResult = Awaited<ReturnType<SanityClient['observable']['agent']['action']['transform']>>;
250
+ /** @alpha */
251
+ type AgentTranslateResult = Awaited<ReturnType<SanityClient['observable']['agent']['action']['translate']>>;
252
+ /** @alpha */
253
+ type AgentPromptResult = Awaited<ReturnType<SanityClient['agent']['action']['prompt']>>;
254
+ /** @alpha */
255
+ type AgentPatchResult = Awaited<ReturnType<SanityClient['agent']['action']['patch']>>;
256
+ /**
257
+ * Generates a new document using the agent.
258
+ * @param instance - The Sanity instance.
259
+ * @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.
260
+ * @returns An Observable emitting the result of the agent generate action.
261
+ * @alpha
262
+ */
263
+ declare function agentGenerate(instance: SanityInstance, options: AgentGenerateOptions): AgentGenerateResult;
264
+ /**
265
+ * Transforms a document using the agent.
266
+ * @param instance - The Sanity instance.
267
+ * @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.
268
+ * @returns An Observable emitting the result of the agent transform action.
269
+ * @alpha
270
+ */
271
+ declare function agentTransform(instance: SanityInstance, options: AgentTransformOptions): AgentTransformResult;
272
+ /**
273
+ * Translates a document using the agent.
274
+ * @param instance - The Sanity instance.
275
+ * @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.
276
+ * @returns An Observable emitting the result of the agent translate action.
277
+ * @alpha
278
+ */
279
+ declare function agentTranslate(instance: SanityInstance, options: AgentTranslateOptions): AgentTranslateResult;
280
+ /**
281
+ * Prompts the agent using the same instruction template format as the other actions, but returns text or json instead of acting on a document.
282
+ * @param instance - The Sanity instance.
283
+ * @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.
284
+ * @returns An Observable emitting the result of the agent prompt action.
285
+ * @alpha
286
+ */
287
+ declare function agentPrompt(instance: SanityInstance, options: AgentPromptOptions): Observable<AgentPromptResult>;
288
+ /**
289
+ * Patches a document using the agent.
290
+ * @param instance - The Sanity instance.
291
+ * @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.
292
+ * @returns An Observable emitting the result of the agent patch action.
293
+ * @alpha
294
+ */
295
+ declare function agentPatch(instance: SanityInstance, options: AgentPatchOptions): Observable<AgentPatchResult>;
296
+ /**
297
+ * Represents the various states the authentication type can be in.
298
+ *
299
+ * @public
300
+ */
301
+ declare enum AuthStateType {
302
+ LOGGED_IN = "logged-in",
303
+ LOGGING_IN = "logging-in",
304
+ ERROR = "error",
305
+ LOGGED_OUT = "logged-out",
306
+ }
214
307
  /**
215
308
  * Represents a store action that has been bound to a specific store instance
216
309
  */
@@ -374,6 +467,24 @@ declare const handleAuthCallback: BoundStoreAction<AuthStoreState, [locationHref
374
467
  * @public
375
468
  */
376
469
  declare const logout: BoundStoreAction<AuthStoreState, [], Promise<void>>;
470
+ /** @internal */
471
+ type ApiErrorBody = {
472
+ error?: {
473
+ type?: string;
474
+ description?: string;
475
+ };
476
+ type?: string;
477
+ description?: string;
478
+ message?: string;
479
+ };
480
+ /** @internal Extracts the structured API error body from a ClientError, if present. */
481
+ declare function getClientErrorApiBody(error: ClientError): ApiErrorBody | undefined;
482
+ /** @internal Returns the error type string from an API error body, if available. */
483
+ declare function getClientErrorApiType(error: ClientError): string | undefined;
484
+ /** @internal Returns the error description string from an API error body, if available. */
485
+ declare function getClientErrorApiDescription(error: ClientError): string | undefined;
486
+ /** @internal True if the error represents a projectUserNotFoundError. */
487
+ declare function isProjectUserNotFoundClientError(error: ClientError): boolean;
377
488
  type AllowedClientConfigKey = 'useCdn' | 'token' | 'perspective' | 'apiHost' | 'proxy' | 'withCredentials' | 'timeout' | 'maxRetries' | 'dataset' | 'projectId' | 'requestTagPrefix' | 'useProjectHostname';
378
489
  /**
379
490
  * States tracked by the client store
@@ -415,6 +526,10 @@ interface ClientOptions extends Pick<ClientConfig, AllowedClientConfigKey> {
415
526
  * @internal
416
527
  */
417
528
  '~experimental_resource'?: ClientConfig['~experimental_resource'];
529
+ /**
530
+ * @internal
531
+ */
532
+ 'source'?: DocumentSource;
418
533
  }
419
534
  /**
420
535
  * Retrieves a Sanity client instance configured with the provided options.
@@ -596,6 +711,12 @@ declare const resolveDatasets: BoundStoreAction<FetcherStoreState<[options?: Pro
596
711
  */
597
712
  interface CreateDocumentAction<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string> extends DocumentTypeHandle<TDocumentType, TDataset, TProjectId> {
598
713
  type: 'document.create';
714
+ /**
715
+ * Optional initial field values for the document.
716
+ * These values will be set when the document is created.
717
+ * System fields (_id, _type, _rev, _createdAt, _updatedAt) are omitted as they are set automatically.
718
+ */
719
+ initialValue?: Partial<Omit<SanityDocument$3<TDocumentType, `${TProjectId}.${TDataset}`>, '_id' | '_type' | '_rev' | '_createdAt' | '_updatedAt'>>;
599
720
  }
600
721
  /**
601
722
  * Represents an action to delete an existing document.
@@ -646,10 +767,11 @@ type DocumentAction<TDocumentType extends string = string, TDataset extends stri
646
767
  /**
647
768
  * Creates a `CreateDocumentAction` object.
648
769
  * @param doc - A handle identifying the document type, dataset, and project. An optional `documentId` can be provided.
770
+ * @param initialValue - Optional initial field values for the document. (System fields are omitted as they are set automatically.)
649
771
  * @returns A `CreateDocumentAction` object ready for dispatch.
650
772
  * @beta
651
773
  */
652
- declare function createDocument<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string>(doc: DocumentTypeHandle<TDocumentType, TDataset, TProjectId>): CreateDocumentAction<TDocumentType, TDataset, TProjectId>;
774
+ 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>;
653
775
  /**
654
776
  * Creates a `DeleteDocumentAction` object.
655
777
  * @param doc - A handle uniquely identifying the document to be deleted.
@@ -1494,6 +1616,7 @@ declare const resolveProjects: BoundStoreAction<FetcherStoreState<[options?: {
1494
1616
  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> {
1495
1617
  query: TQuery;
1496
1618
  params?: Record<string, unknown>;
1619
+ source?: DocumentSource;
1497
1620
  }
1498
1621
  /**
1499
1622
  * @beta
@@ -1579,7 +1702,7 @@ declare const getActiveReleasesState: BoundStoreAction<ReleasesStoreState, [], S
1579
1702
  *
1580
1703
  * @public
1581
1704
  */
1582
- declare const getPerspectiveState: BoundStoreAction<ReleasesStoreState, [options?: PerspectiveHandle | undefined], StateSource<string[] | "previewDrafts" | "published" | "drafts" | "raw" | undefined>>;
1705
+ declare const getPerspectiveState: BoundStoreAction<ReleasesStoreState, [options?: PerspectiveHandle | undefined], StateSource<string[] | "raw" | "previewDrafts" | "published" | "drafts" | undefined>>;
1583
1706
  /** @internal */
1584
1707
  declare const getUsersKey: (instance: SanityInstance, {
1585
1708
  resourceType,
@@ -1609,7 +1732,7 @@ declare const parseUsersKey: (key: string) => {
1609
1732
  *
1610
1733
  * @beta
1611
1734
  */
1612
- declare const getUsersState: BoundStoreAction<UsersStoreState, [options?: GetUsersOptions], StateSource<{
1735
+ declare const getUsersState: BoundStoreAction<UsersStoreState, [options?: GetUsersOptions | undefined], StateSource<{
1613
1736
  data: SanityUser[];
1614
1737
  totalCount: number;
1615
1738
  hasMore: boolean;
@@ -1658,7 +1781,7 @@ declare const getUserState: BoundStoreAction<UsersStoreState, [GetUserOptions],
1658
1781
  /**
1659
1782
  * @beta
1660
1783
  */
1661
- declare const resolveUser: BoundStoreAction<UsersStoreState, [ResolveUserOptions], Promise<SanityUser | undefined>>;
1784
+ declare const resolveUser: BoundStoreAction<UsersStoreState, [ResolveUserOptions], Promise<SanityUser>>;
1662
1785
  interface StoreEntry<TParams extends unknown[], TData> {
1663
1786
  params: TParams;
1664
1787
  instance: SanityInstance;
@@ -1870,4 +1993,4 @@ declare const CORE_SDK_VERSION: {};
1870
1993
  * @public
1871
1994
  */
1872
1995
  type SanityProject = SanityProject$1;
1873
- export { type ActionErrorEvent, type ActionsResult, type ApplyDocumentActionsOptions, type AuthConfig, type AuthProvider, type AuthState, AuthStateType, type AuthStoreState, CORE_SDK_VERSION, type ClientOptions, type ClientStoreState as ClientState, type ComlinkControllerState, type ComlinkNodeState, type CreateDocumentAction, type CurrentUser, type DatasetHandle, 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 DocumentTypeHandle, type DocumentUnpublishedEvent, type EditDocumentAction, type ErrorAuthState, type FavoriteStatusResponse, type FetcherStore, type FetcherStoreState, type FrameMessage, type GetPreviewStateOptions, type GetUserOptions, type GetUsersOptions, type Intent, type IntentFilter, type JsonMatch, type LoggedInAuthState, type LoggedOutAuthState, type LoggingInAuthState, 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 TransactionAcceptedEvent, type TransactionRevertedEvent, type TransportEvent, type UnpublishDocumentAction, type UserPresence, type UserProfile, type UsersGroupState, type UsersStoreState, type ValidProjection, type ValuePending, type WindowMessage, applyDocumentActions, createDatasetHandle, createDocument, createDocumentHandle, createDocumentTypeHandle, createGroqSearchFilter, createProjectHandle, createSanityInstance, defineIntent, deleteDocument, destroyController, discardDocument, editDocument, getActiveReleasesState, getAuthState, getClient, 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, 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 };
1996
+ 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 ClientOptions, type ClientStoreState as ClientState, type ComlinkControllerState, type ComlinkNodeState, type CreateDocumentAction, type CurrentUser, type DatasetHandle, 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 Intent, type IntentFilter, type JsonMatch, type LoggedInAuthState, type LoggedOutAuthState, type LoggingInAuthState, 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 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, canvasSource, createDatasetHandle, createDocument, createDocumentHandle, createDocumentTypeHandle, createGroqSearchFilter, createProjectHandle, createSanityInstance, datasetSource, 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, isProjectUserNotFoundClientError, joinPaths, jsonMatch, loadMoreUsers, logout, mediaLibrarySource, observeOrganizationVerificationState, parseQueryKey, parseUsersKey, publishDocument, releaseChannel, releaseNode, resolveDatasets, resolveDocument, resolveFavoritesState, resolvePermissions, resolvePreview, resolveProject, resolveProjection, resolveProjects, resolveQuery, resolveUser, resolveUsers, setAuthToken, slicePath, stringifyPath, subscribeDocumentEvents, unpublishDocument };
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
- import { createClient, CorsOriginError } from "@sanity/client";
2
1
  import { Observable, share, map, distinctUntilChanged, skip, filter, exhaustMap, from, timer, switchMap, takeWhile, firstValueFrom, fromEvent, EMPTY, defer, asapScheduler, combineLatest, of, concatMap, withLatestFrom, concat, throwError, first as first$1, Subject, takeUntil, partition, merge, shareReplay, tap as tap$1, catchError as catchError$1, startWith as startWith$1, pairwise as pairwise$1, groupBy as groupBy$1, mergeMap as mergeMap$1, throttle, race, NEVER, Subscription, retry, debounceTime as debounceTime$1 } from "rxjs";
2
+ import { createClient, CorsOriginError } from "@sanity/client";
3
+ import { pick, omit, isEqual, isObject } from "lodash-es";
3
4
  import { devtools } from "zustand/middleware";
4
5
  import { createStore } from "zustand/vanilla";
5
- import { pick, omit, isEqual, isObject } from "lodash-es";
6
6
  import { first, switchMap as switchMap$1, groupBy, mergeMap, startWith, pairwise, filter as filter$1, map as map$1, delay, tap, catchError, scan, share as share$1, take, debounceTime } from "rxjs/operators";
7
7
  import { createController, createNode } from "@sanity/comlink";
8
8
  import { createSelector } from "reselect";
@@ -17,7 +17,16 @@ import { isKeySegment, isKeyedObject } from "@sanity/types";
17
17
  import { createDocumentLoaderFromClient } from "@sanity/mutate/_unstable_store";
18
18
  import { SDK_CHANNEL_NAME, SDK_NODE_NAME } from "@sanity/message-protocol";
19
19
  import { fromUrl } from "@sanity/bifur-client";
20
- var AuthStateType = /* @__PURE__ */ ((AuthStateType2) => (AuthStateType2.LOGGED_IN = "logged-in", AuthStateType2.LOGGING_IN = "logging-in", AuthStateType2.ERROR = "error", AuthStateType2.LOGGED_OUT = "logged-out", AuthStateType2))(AuthStateType || {});
20
+ const SOURCE_ID = "__sanity_internal_sourceId";
21
+ function datasetSource(projectId, dataset) {
22
+ return { [SOURCE_ID]: { projectId, dataset } };
23
+ }
24
+ function mediaLibrarySource(id) {
25
+ return { [SOURCE_ID]: ["media-library", id] };
26
+ }
27
+ function canvasSource(id) {
28
+ return { [SOURCE_ID]: ["canvas", id] };
29
+ }
21
30
  function getPublishedId(id) {
22
31
  const draftsPrefix = "drafts.";
23
32
  return id.startsWith(draftsPrefix) ? id.slice(draftsPrefix.length) : id;
@@ -105,7 +114,7 @@ function createActionBinder(keyFn) {
105
114
  const instanceRegistry = /* @__PURE__ */ new Map(), storeRegistry = /* @__PURE__ */ new Map();
106
115
  return function(storeDefinition, action) {
107
116
  return function(instance, ...params) {
108
- const keySuffix = keyFn(instance.config), compositeKey = storeDefinition.name + (keySuffix ? `:${keySuffix}` : "");
117
+ const keySuffix = keyFn(instance.config, ...params), compositeKey = storeDefinition.name + (keySuffix ? `:${keySuffix}` : "");
109
118
  let instances = instanceRegistry.get(compositeKey);
110
119
  instances || (instances = /* @__PURE__ */ new Set(), instanceRegistry.set(compositeKey, instances)), instances.has(instance.instanceId) || (instances.add(instance.instanceId), instance.onDispose(() => {
111
120
  instances.delete(instance.instanceId), instances.size === 0 && (storeRegistry.get(compositeKey)?.dispose(), storeRegistry.delete(compositeKey), instanceRegistry.delete(compositeKey));
@@ -119,7 +128,18 @@ const bindActionByDataset = createActionBinder(({ projectId, dataset }) => {
119
128
  if (!projectId || !dataset)
120
129
  throw new Error("This API requires a project ID and dataset configured.");
121
130
  return `${projectId}.${dataset}`;
122
- }), bindActionGlobally = createActionBinder(() => "global");
131
+ }), bindActionBySource = createActionBinder(
132
+ ({ projectId, dataset }, { source }) => {
133
+ if (source) {
134
+ const id = source[SOURCE_ID];
135
+ if (!id) throw new Error("Invalid source (missing ID information)");
136
+ return Array.isArray(id) ? id.join(":") : `${id.projectId}.${id.dataset}`;
137
+ }
138
+ if (!projectId || !dataset)
139
+ throw new Error("This API requires a project ID and dataset configured.");
140
+ return `${projectId}.${dataset}`;
141
+ }
142
+ ), bindActionGlobally = createActionBinder(() => "global");
123
143
  function createStateSourceAction(options) {
124
144
  const selector = typeof options == "function" ? options : options.selector, subscribeHandler = options && "onSubscribe" in options ? options.onSubscribe : void 0, isEqual2 = options && "isEqual" in options ? options.isEqual ?? Object.is : Object.is, selectorContextCache = /* @__PURE__ */ new WeakMap();
125
145
  function stateSourceAction(context, ...params) {
@@ -167,6 +187,7 @@ function createStateSourceAction(options) {
167
187
  }
168
188
  return stateSourceAction;
169
189
  }
190
+ var AuthStateType = /* @__PURE__ */ ((AuthStateType2) => (AuthStateType2.LOGGED_IN = "logged-in", AuthStateType2.LOGGING_IN = "logging-in", AuthStateType2.ERROR = "error", AuthStateType2.LOGGED_OUT = "logged-out", AuthStateType2))(AuthStateType || {});
170
191
  const DEFAULT_BASE = "http://localhost", AUTH_CODE_PARAM = "sid", DEFAULT_API_VERSION$1 = "2021-06-07", REQUEST_TAG_PREFIX = "sanity.sdk.auth", REFRESH_INTERVAL = 12 * 60 * 60 * 1e3, LOCK_NAME = "sanity-token-refresh-lock";
171
192
  function getLastRefreshTime(storageArea, storageKey) {
172
193
  try {
@@ -389,6 +410,21 @@ function getCleanedUrl(locationUrl) {
389
410
  }
390
411
  return loc.searchParams.delete("sid"), loc.searchParams.delete("url"), loc.toString();
391
412
  }
413
+ function getClientErrorApiBody(error) {
414
+ const body = error.response?.body;
415
+ return body && typeof body == "object" ? body : void 0;
416
+ }
417
+ function getClientErrorApiType(error) {
418
+ const body = getClientErrorApiBody(error);
419
+ return body?.error?.type ?? body?.type;
420
+ }
421
+ function getClientErrorApiDescription(error) {
422
+ const body = getClientErrorApiBody(error);
423
+ return body?.error?.description ?? body?.description;
424
+ }
425
+ function isProjectUserNotFoundClientError(error) {
426
+ return getClientErrorApiType(error) === "projectUserNotFoundError";
427
+ }
392
428
  async function checkForCookieAuth(projectId, clientFactory) {
393
429
  if (!projectId) return !1;
394
430
  try {
@@ -584,13 +620,7 @@ const authStore = {
584
620
  }) : currentAuthState.type !== AuthStateType.LOGGED_OUT && state.set("setToken", {
585
621
  authState: { type: AuthStateType.LOGGED_OUT, isDestroyingSession: !1 }
586
622
  });
587
- });
588
- function compareProjectOrganization(projectId, projectOrganizationId, currentDashboardOrgId) {
589
- return projectOrganizationId !== currentDashboardOrgId ? {
590
- error: `Project ${projectId} belongs to Organization ${projectOrganizationId ?? "unknown"}, but the Dashboard has Organization ${currentDashboardOrgId} selected`
591
- } : { error: null };
592
- }
593
- const DEFAULT_API_VERSION = "2024-11-12", DEFAULT_REQUEST_TAG_PREFIX = "sanity.sdk", allowedKeys = Object.keys({
623
+ }), DEFAULT_API_VERSION = "2024-11-12", DEFAULT_REQUEST_TAG_PREFIX = "sanity.sdk", allowedKeys = Object.keys({
594
624
  apiHost: null,
595
625
  useCdn: null,
596
626
  token: null,
@@ -605,7 +635,8 @@ const DEFAULT_API_VERSION = "2024-11-12", DEFAULT_REQUEST_TAG_PREFIX = "sanity.s
605
635
  apiVersion: null,
606
636
  requestTagPrefix: null,
607
637
  useProjectHostname: null,
608
- "~experimental_resource": null
638
+ "~experimental_resource": null,
639
+ source: null
609
640
  }), DEFAULT_CLIENT_CONFIG = {
610
641
  apiVersion: DEFAULT_API_VERSION,
611
642
  useCdn: !1,
@@ -631,6 +662,10 @@ const DEFAULT_API_VERSION = "2024-11-12", DEFAULT_REQUEST_TAG_PREFIX = "sanity.s
631
662
  }), getClientConfigKey = (options) => JSON.stringify(pick(options, ...allowedKeys)), getClient = bindActionGlobally(
632
663
  clientStore,
633
664
  ({ state, instance }, options) => {
665
+ if (!options || typeof options != "object")
666
+ throw new Error(
667
+ 'getClient() requires a configuration object with at least an "apiVersion" property. Example: getClient(instance, { apiVersion: "2024-11-12" })'
668
+ );
634
669
  const disallowedKeys = Object.keys(options).filter((key2) => !allowedKeys.includes(key2));
635
670
  if (disallowedKeys.length > 0) {
636
671
  const listFormatter = new Intl.ListFormat("en", { style: "long", type: "conjunction" });
@@ -638,16 +673,22 @@ const DEFAULT_API_VERSION = "2024-11-12", DEFAULT_REQUEST_TAG_PREFIX = "sanity.s
638
673
  `The client options provided contains unsupported properties: ${listFormatter.format(disallowedKeys)}. Allowed keys are: ${listFormatter.format(allowedKeys)}.`
639
674
  );
640
675
  }
641
- const tokenFromState = state.get().token, { clients, authMethod } = state.get(), projectId = options.projectId ?? instance.config.projectId, dataset = options.dataset ?? instance.config.dataset, apiHost = options.apiHost ?? instance.config.auth?.apiHost, effectiveOptions = {
676
+ const tokenFromState = state.get().token, { clients, authMethod } = state.get(), hasSource = !!options.source;
677
+ let sourceId = options.source?.[SOURCE_ID], resource;
678
+ Array.isArray(sourceId) && (resource = { type: sourceId[0], id: sourceId[1] }, sourceId = void 0);
679
+ const projectId = options.projectId ?? instance.config.projectId, dataset = options.dataset ?? instance.config.dataset, apiHost = options.apiHost ?? instance.config.auth?.apiHost, effectiveOptions = {
642
680
  ...DEFAULT_CLIENT_CONFIG,
643
- ...(options.scope === "global" || !projectId) && { useProjectHostname: !1 },
681
+ ...(options.scope === "global" || !projectId || hasSource) && { useProjectHostname: !1 },
644
682
  token: authMethod === "cookie" ? void 0 : tokenFromState ?? void 0,
645
683
  ...options,
646
684
  ...projectId && { projectId },
647
685
  ...dataset && { dataset },
648
- ...apiHost && { apiHost }
686
+ ...apiHost && { apiHost },
687
+ ...resource && { "~experimental_resource": resource }
649
688
  };
650
- effectiveOptions.token === null || typeof effectiveOptions.token > "u" ? (delete effectiveOptions.token, authMethod === "cookie" && (effectiveOptions.withCredentials = !0)) : delete effectiveOptions.withCredentials;
689
+ hasSource && ((options.projectId || options.dataset) && console.warn(
690
+ "Both source and explicit projectId/dataset are provided. The source will be used and projectId/dataset will be ignored."
691
+ ), delete effectiveOptions.projectId, delete effectiveOptions.dataset), effectiveOptions.token === null || typeof effectiveOptions.token > "u" ? (delete effectiveOptions.token, authMethod === "cookie" && (effectiveOptions.withCredentials = !0)) : delete effectiveOptions.withCredentials;
651
692
  const key = getClientConfigKey(effectiveOptions);
652
693
  if (clients[key]) return clients[key];
653
694
  const client = createClient(effectiveOptions);
@@ -656,7 +697,47 @@ const DEFAULT_API_VERSION = "2024-11-12", DEFAULT_REQUEST_TAG_PREFIX = "sanity.s
656
697
  ), getClientState = bindActionGlobally(
657
698
  clientStore,
658
699
  createStateSourceAction(({ instance }, options) => getClient(instance, options))
659
- );
700
+ ), API_VERSION$6 = "vX";
701
+ function agentGenerate(instance, options) {
702
+ return getClientState(instance, {
703
+ apiVersion: API_VERSION$6,
704
+ projectId: instance.config.projectId,
705
+ dataset: instance.config.dataset
706
+ }).observable.pipe(switchMap((client) => client.observable.agent.action.generate(options)));
707
+ }
708
+ function agentTransform(instance, options) {
709
+ return getClientState(instance, {
710
+ apiVersion: API_VERSION$6,
711
+ projectId: instance.config.projectId,
712
+ dataset: instance.config.dataset
713
+ }).observable.pipe(switchMap((client) => client.observable.agent.action.transform(options)));
714
+ }
715
+ function agentTranslate(instance, options) {
716
+ return getClientState(instance, {
717
+ apiVersion: API_VERSION$6,
718
+ projectId: instance.config.projectId,
719
+ dataset: instance.config.dataset
720
+ }).observable.pipe(switchMap((client) => client.observable.agent.action.translate(options)));
721
+ }
722
+ function agentPrompt(instance, options) {
723
+ return getClientState(instance, {
724
+ apiVersion: API_VERSION$6,
725
+ projectId: instance.config.projectId,
726
+ dataset: instance.config.dataset
727
+ }).observable.pipe(switchMap((client) => from(client.agent.action.prompt(options))));
728
+ }
729
+ function agentPatch(instance, options) {
730
+ return getClientState(instance, {
731
+ apiVersion: API_VERSION$6,
732
+ projectId: instance.config.projectId,
733
+ dataset: instance.config.dataset
734
+ }).observable.pipe(switchMap((client) => from(client.agent.action.patch(options))));
735
+ }
736
+ function compareProjectOrganization(projectId, projectOrganizationId, currentDashboardOrgId) {
737
+ return projectOrganizationId !== currentDashboardOrgId ? {
738
+ error: `Project ${projectId} belongs to Organization ${projectOrganizationId ?? "unknown"}, but the Dashboard has Organization ${currentDashboardOrgId} selected`
739
+ } : { error: null };
740
+ }
660
741
  function createFetcherStore({
661
742
  name,
662
743
  fetcher: getObservable,
@@ -1078,11 +1159,12 @@ const API_VERSION$4 = "v2025-02-19", datasets = createFetcherStore({
1078
1159
  useProjectHostname: !0
1079
1160
  }).observable.pipe(switchMap((client) => client.observable.datasets.list()))
1080
1161
  }), getDatasetsState = datasets.getState, resolveDatasets = datasets.resolveState, isSanityMutatePatch = (value) => !(typeof value != "object" || !value || !("type" in value) || typeof value.type != "string" || value.type !== "patch" || !("id" in value) || typeof value.id != "string" || !("patches" in value) || !Array.isArray(value.patches));
1081
- function createDocument(doc) {
1162
+ function createDocument(doc, initialValue) {
1082
1163
  return {
1083
1164
  type: "document.create",
1084
1165
  ...doc,
1085
- ...doc.documentId && { documentId: getPublishedId(doc.documentId) }
1166
+ ...doc.documentId && { documentId: getPublishedId(doc.documentId) },
1167
+ ...initialValue && { initialValue }
1086
1168
  };
1087
1169
  }
1088
1170
  function deleteDocument(doc) {
@@ -1791,7 +1873,17 @@ function processActions({
1791
1873
  transactionId,
1792
1874
  message: "A draft version of this document already exists. Please use or discard the existing draft before creating a new one."
1793
1875
  });
1794
- const newDocBase = { ...base[publishedId], _type: action.documentType, _id: draftId }, newDocWorking = { ...working[publishedId], _type: action.documentType, _id: draftId }, mutations = [{ create: newDocWorking }];
1876
+ const newDocBase = {
1877
+ ...base[publishedId],
1878
+ _type: action.documentType,
1879
+ _id: draftId,
1880
+ ...action.initialValue
1881
+ }, newDocWorking = {
1882
+ ...working[publishedId],
1883
+ _type: action.documentType,
1884
+ _id: draftId,
1885
+ ...action.initialValue
1886
+ }, mutations = [{ create: newDocWorking }];
1795
1887
  if (base = processMutations({
1796
1888
  documents: base,
1797
1889
  transactionId,
@@ -3252,6 +3344,7 @@ const queryStore = {
3252
3344
  projectId,
3253
3345
  dataset,
3254
3346
  tag,
3347
+ source,
3255
3348
  perspective: perspectiveFromOptions,
3256
3349
  ...restOptions
3257
3350
  } = parseQueryKey(group$.key), perspective$ = getPerspectiveState(instance, {
@@ -3259,7 +3352,8 @@ const queryStore = {
3259
3352
  }).observable.pipe(filter(Boolean)), client$ = getClientState(instance, {
3260
3353
  apiVersion: QUERY_STORE_API_VERSION,
3261
3354
  projectId,
3262
- dataset
3355
+ dataset,
3356
+ source
3263
3357
  }).observable;
3264
3358
  return combineLatest([lastLiveEventId$, client$, perspective$]).pipe(
3265
3359
  switchMap(
@@ -3322,7 +3416,7 @@ const queryStore = {
3322
3416
  function getQueryState(...args) {
3323
3417
  return _getQueryState(...args);
3324
3418
  }
3325
- const _getQueryState = bindActionByDataset(
3419
+ const _getQueryState = bindActionBySource(
3326
3420
  queryStore,
3327
3421
  createStateSourceAction({
3328
3422
  selector: ({ state, instance }, options) => {
@@ -3345,7 +3439,7 @@ const _getQueryState = bindActionByDataset(
3345
3439
  function resolveQuery(...args) {
3346
3440
  return _resolveQuery(...args);
3347
3441
  }
3348
- const _resolveQuery = bindActionByDataset(
3442
+ const _resolveQuery = bindActionBySource(
3349
3443
  queryStore,
3350
3444
  ({ state, instance }, { signal, ...options }) => {
3351
3445
  const normalized = normalizeOptionsWithPerspective(instance, options), { getCurrent } = getQueryState(instance, normalized), key = getQueryKey(normalized), aborted$ = signal ? new Observable((observer) => {
@@ -3902,12 +3996,18 @@ function getCorsErrorProjectId(error) {
3902
3996
  const projMatch = (error.message || "").match(/manage\/project\/([^/?#]+)/);
3903
3997
  return projMatch ? projMatch[1] : null;
3904
3998
  }
3905
- var version = "2.3.1";
3999
+ var version = "2.4.0";
3906
4000
  const CORE_SDK_VERSION = getEnv("PKG_VERSION") || `${version}-development`;
3907
4001
  export {
3908
4002
  AuthStateType,
3909
4003
  CORE_SDK_VERSION,
4004
+ agentGenerate,
4005
+ agentPatch,
4006
+ agentPrompt,
4007
+ agentTransform,
4008
+ agentTranslate,
3910
4009
  applyDocumentActions,
4010
+ canvasSource,
3911
4011
  createDatasetHandle,
3912
4012
  createDocument,
3913
4013
  createDocumentHandle,
@@ -3915,6 +4015,7 @@ export {
3915
4015
  createGroqSearchFilter,
3916
4016
  createProjectHandle,
3917
4017
  createSanityInstance,
4018
+ datasetSource,
3918
4019
  defineIntent,
3919
4020
  deleteDocument,
3920
4021
  destroyController,
@@ -3923,6 +4024,9 @@ export {
3923
4024
  getActiveReleasesState,
3924
4025
  getAuthState,
3925
4026
  getClient,
4027
+ getClientErrorApiBody,
4028
+ getClientErrorApiDescription,
4029
+ getClientErrorApiType,
3926
4030
  getClientState,
3927
4031
  getCorsErrorProjectId,
3928
4032
  getCurrentUserState,
@@ -3953,10 +4057,12 @@ export {
3953
4057
  getUsersKey,
3954
4058
  getUsersState,
3955
4059
  handleAuthCallback,
4060
+ isProjectUserNotFoundClientError,
3956
4061
  joinPaths,
3957
4062
  jsonMatch2 as jsonMatch,
3958
4063
  loadMoreUsers,
3959
4064
  logout,
4065
+ mediaLibrarySource,
3960
4066
  observeOrganizationVerificationState,
3961
4067
  parseQueryKey,
3962
4068
  parseUsersKey,