UNPKG

@sanity/sdk

Version:
1,831 lines (1,657 loc) 71.4 kB
import {AuthStoreState as AuthStoreState_2} from './authStore' import {BoundStoreAction} from '../store/createActionBinder' import {BoundStoreAction as BoundStoreAction_2} from '../../store/createActionBinder' import {CanvasResource} from '@sanity/message-protocol' import {ChannelInput} from '@sanity/comlink' import {ChannelInstance} from '@sanity/comlink' import {ClientConfig} from '@sanity/client' import {ClientPerspective} from '@sanity/client' import {Controller} from '@sanity/comlink' import {CurrentUser} from '@sanity/types' import {DatasetsResponse} from '@sanity/client' import {DocumentPermissionsResult as DocumentPermissionsResult_2} from './permissions' import {FetcherStoreState as FetcherStoreState_2} from '../_exports' import {getIndexForKey} from '@sanity/json-match' import {getPathDepth} from '@sanity/json-match' import {joinPaths} from '@sanity/json-match' import {jsonMatch} from '@sanity/json-match' import {ListenEvent} from '@sanity/client' import {MediaResource} from '@sanity/message-protocol' import {Message} from '@sanity/comlink' import {Mutation} from '@sanity/types' import {Node as Node_2} from '@sanity/comlink' import {NodeInput} from '@sanity/comlink' import {Observable} from 'rxjs' import {PatchMutation} from '@sanity/mutate/_unstable_store' import {PatchOperations} from '@sanity/types' import {PreviewStoreState as PreviewStoreState_2} from './previewStore' import {ResponseQueryOptions} from '@sanity/client' import {Role} from '@sanity/types' import {SanityClient} from '@sanity/client' import {SanityDocument} from '@sanity/types' import {SanityDocument as SanityDocument_2} from 'groq' import {SanityDocument as SanityDocument_3} from '@sanity/client' import {SanityDocumentLike} from '@sanity/types' import {SanityProject as SanityProject_2} from '@sanity/client' import {SanityProjectionResult} from 'groq' import {SanityQueryResult} from 'groq' import {SanityUser as SanityUser_2} from './types' import {slicePath} from '@sanity/json-match' import {StackablePerspective} from '@sanity/client' import {StateSource as StateSource_2} from '../_exports' import {StateSource as StateSource_3} from '../../_exports' import {Status} from '@sanity/comlink' import {stringifyPath} from '@sanity/json-match' import {StudioResource} from '@sanity/message-protocol' import {Subject} from 'rxjs' import {ValuePending as ValuePending_2} from './previewStore' declare interface AccessAttributeNode extends BaseNode { type: 'AccessAttribute' base?: ExprNode name: string } declare interface AccessElementNode extends BaseNode { type: 'AccessElement' base: ExprNode index: number } /** * @beta * Event emitted when a precondition to applying an action fails. * (For example: when trying to edit a document that no longer exists.) */ export declare interface ActionErrorEvent { type: 'error' documentId: string transactionId: string message: string error: unknown } declare type ActionMap = { create: 'sanity.action.document.version.create' discard: 'sanity.action.document.version.discard' unpublish: 'sanity.action.document.unpublish' delete: 'sanity.action.document.delete' edit: 'sanity.action.document.edit' publish: 'sanity.action.document.publish' } /** @beta */ export declare interface ActionsResult<TDocument extends SanityDocument_2 = SanityDocument_2> { transactionId: string documents: DocumentSet<TDocument> previous: DocumentSet<TDocument> previousRevs: { [documentId: string]: string | undefined } appeared: string[] updated: string[] disappeared: string[] submitted: () => ReturnType<SanityClient['action']> } declare type AllowedClientConfigKey = | 'useCdn' | 'token' | 'perspective' | 'apiHost' | 'proxy' | 'withCredentials' | 'timeout' | 'maxRetries' | 'dataset' | 'projectId' | 'requestTagPrefix' | 'useProjectHostname' declare interface AndNode extends BaseNode { type: 'And' left: ExprNode right: ExprNode } declare type AnyStaticValue = | StringValue | NumberValue | NullValue | BooleanValue | DateTimeValue | ObjectValue | ArrayValue | PathValue /** * Represents a transaction that has been applied locally but has not been * committed/transitioned-to-outgoing. These transactions are visible to the * user but may be rebased upon a new working document set. Applied transactions * also contain the resulting `outgoingActions` that will be submitted to * Content Lake. These `outgoingActions` depend on the state of the working * documents so they are recomputed on rebase and are only relevant to applied * actions (we cannot compute `outgoingActions` for queued transactions because * we haven't resolved the set of documents the actions are dependent on yet). * * In order to support better conflict resolution, the original `previous` set * is saved as the `base` set. */ declare interface AppliedTransaction extends QueuedTransaction { /** * the resulting set of documents after the actions have been applied */ working: DocumentSet /** * the previous set of documents before the action was applied */ previous: DocumentSet /** * the original `previous` document set captured when this action was * originally applied. this is used as a reference point to do a 3-way merge * if this applied transaction ever needs to be reapplied on a different * set of documents. */ base: DocumentSet /** * the `_rev`s from `previous` document set */ previousRevs: { [TDocumentId in string]?: string } /** * a timestamp for when this transaction was applied locally */ timestamp: string /** * the resulting HTTP actions derived from the state of the `working` document * set. these are sent to Content Lake as-is when this transaction is batched * and transitioned into an outgoing transaction. */ outgoingActions: HttpAction[] /** * similar to `outgoingActions` but comprised of mutations instead of action. * this left here for debugging purposes but could be used to send mutations * to Content Lake instead of actions. */ outgoingMutations: Mutation[] } /** @beta */ export declare function applyDocumentActions< TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string, >( instance: SanityInstance, action: | DocumentAction<TDocumentType, TDataset, TProjectId> | DocumentAction<TDocumentType, TDataset, TProjectId>[], options?: ApplyDocumentActionsOptions, ): Promise<ActionsResult<SanityDocument_2<TDocumentType, `${TProjectId}.${TDataset}`>>> /** @beta */ export declare function applyDocumentActions( instance: SanityInstance, action: DocumentAction | DocumentAction[], options?: ApplyDocumentActionsOptions, ): Promise<ActionsResult> /** @beta */ export declare interface ApplyDocumentActionsOptions { /** * Optionally provide an ID to be used as this transaction ID */ transactionId?: string /** * Set this to true to prevent this action from being batched with others. */ disableBatching?: boolean } declare interface ArrayCoerceNode extends BaseNode { type: 'ArrayCoerce' base: ExprNode } declare interface ArrayElementNode extends BaseNode { type: 'ArrayElement' value: ExprNode isSplat: boolean } declare interface ArrayNode extends BaseNode { type: 'Array' elements: ArrayElementNode[] } declare type ArrayValue = StaticValue<unknown[], 'array'> declare interface AscNode extends BaseNode { type: 'Asc' base: ExprNode } /** * Configuration options for creating an auth store. * * @public */ export declare interface AuthConfig { /** * The initial location href to use when handling auth callbacks. * Defaults to the current window location if available. */ initialLocationHref?: string /** * Factory function to create a SanityClient instance. * Defaults to the standard Sanity client factory if not provided. */ clientFactory?: (config: ClientConfig) => SanityClient /** * Custom authentication providers to use instead of or in addition to the default ones. * Can be an array of providers or a function that takes the default providers and returns * a modified array or a Promise resolving to one. */ providers?: AuthProvider[] | ((prev: AuthProvider[]) => AuthProvider[] | Promise<AuthProvider[]>) /** * The API hostname for requests. Usually leave this undefined, but it can be set * if using a custom domain or CNAME for the API endpoint. */ apiHost?: string /** * Storage implementation to persist authentication state. * Defaults to `localStorage` if available. */ storageArea?: Storage /** * A callback URL for your application. * If none is provided, the auth API will redirect back to the current location (`location.href`). * When handling callbacks, this URL's pathname is checked to ensure it matches the callback. */ callbackUrl?: string /** * A static authentication token to use instead of handling the OAuth flow. * When provided, the auth store will remain in a logged-in state with this token, * ignoring any storage or callback handling. */ token?: string } declare type AuthMethodOptions = 'localstorage' | 'cookie' | undefined /** * Configuration for an authentication provider * @public */ export declare interface AuthProvider { /** * Unique identifier for the auth provider (e.g., 'google', 'github') */ name: string /** * Display name for the auth provider in the UI */ title: string /** * Complete authentication URL including callback and token parameters */ url: string /** * Optional URL for direct sign-up flow */ signUpUrl?: string } /** * Represents the various states the authentication can be in. * * @public */ export declare type AuthState = | LoggedInAuthState | LoggedOutAuthState | LoggingInAuthState | ErrorAuthState /** * Represents the various states the authentication type can be in. * * @public */ export declare enum AuthStateType { LOGGED_IN = 'logged-in', LOGGING_IN = 'logging-in', ERROR = 'error', LOGGED_OUT = 'logged-out', } /** * @public */ export declare interface AuthStoreState { authState: AuthState providers?: AuthProvider[] options: { initialLocationHref: string clientFactory: (config: ClientConfig) => SanityClient customProviders: AuthConfig['providers'] storageKey: string storageArea: Storage | undefined apiHost: string | undefined loginUrl: string callbackUrl: string | undefined providedToken: string | undefined authMethod: AuthMethodOptions } dashboardContext?: DashboardContext } /** The base interface for SyntaxNode. */ declare interface BaseNode { type: string } declare type BooleanValue = StaticValue<boolean, 'boolean'> /** * Represents a store action that has been bound to a specific store instance */ declare type BoundStoreAction_3<_TState, TParams extends unknown[], TReturn> = ( instance: SanityInstance, ...params: TParams ) => TReturn /** * Individual channel with its relevant options * @public */ declare interface ChannelEntry { channel: ChannelInstance<FrameMessage, WindowMessage> options: ChannelInput refCount: number } /** * Options used when retrieving a client instance from the client store. * * This interface extends the base {@link ClientConfig} and adds: * * - **apiVersion:** A required string indicating the API version for the client. * - **scope:** An optional flag to choose between the project-specific client * ('project') and the global client ('global'). When set to `'global'`, the * global client is used. * * These options are utilized by `getClient` and `getClientState` to configure and * return appropriate client instances that automatically handle authentication * updates and configuration changes. * * @public */ export declare interface ClientOptions extends Pick<ClientConfig, AllowedClientConfigKey> { /** * An optional flag to choose between the default client (typically project-level) * and the global client ('global'). When set to `'global'`, the global client * is used. */ 'scope'?: 'default' | 'global' /** * A required string indicating the API version for the client. */ 'apiVersion': string /** * @internal */ '~experimental_resource'?: ClientConfig['~experimental_resource'] } /** * States tracked by the client store * @public */ export declare interface ClientState { token: string | null clients: { [TKey in string]?: SanityClient } authMethod?: 'localstorage' | 'cookie' } /** * Internal state tracking comlink connections * @public */ export declare interface ComlinkControllerState { controller: Controller | null controllerOrigin: string | null channels: Map<string, ChannelEntry> } /** * Internal state tracking comlink connections * @public */ export declare interface ComlinkNodeState { nodes: Map<string, NodeEntry> subscriptions: Map<string, Set<symbol>> } declare interface Context { timestamp: Date identity: string before: Value | null after: Value | null sanity?: { projectId: string dataset: string } dereference?: DereferenceFunction } declare interface ContextNode extends BaseNode { type: 'Context' key: string } /** * This version is provided by pkg-utils at build time * @internal */ export declare const CORE_SDK_VERSION: {} /** * Creates or validates a `DatasetHandle` object. * Ensures the provided object conforms to the `DatasetHandle` interface. * @param handle - The object containing dataset identification properties. * @returns The validated `DatasetHandle` object. * @public */ export declare function createDatasetHandle< TDataset extends string = string, TProjectId extends string = string, >(handle: DatasetHandle<TDataset, TProjectId>): DatasetHandle<TDataset, TProjectId> /** * Creates a `CreateDocumentAction` object. * @param doc - A handle identifying the document type, dataset, and project. An optional `documentId` can be provided. * @returns A `CreateDocumentAction` object ready for dispatch. * @beta */ export declare function createDocument< TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string, >( doc: DocumentTypeHandle<TDocumentType, TDataset, TProjectId>, ): CreateDocumentAction<TDocumentType, TDataset, TProjectId> /** * Represents an action to create a new document. * Specifies the document type and optionally a document ID (which will be treated as the published ID). * @beta */ export declare interface CreateDocumentAction< TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string, > extends DocumentTypeHandle<TDocumentType, TDataset, TProjectId> { type: 'document.create' } /** * Creates or validates a `DocumentHandle` object. * Ensures the provided object conforms to the `DocumentHandle` interface. * @param handle - The object containing document identification properties. * @returns The validated `DocumentHandle` object. * @public */ export declare function createDocumentHandle< TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string, >( handle: DocumentHandle<TDocumentType, TDataset, TProjectId>, ): DocumentHandle<TDocumentType, TDataset, TProjectId> /** * Creates or validates a `DocumentTypeHandle` object. * Ensures the provided object conforms to the `DocumentTypeHandle` interface. * @param handle - The object containing document type identification properties. * @returns The validated `DocumentTypeHandle` object. * @public */ export declare function createDocumentTypeHandle< TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string, >( handle: DocumentTypeHandle<TDocumentType, TDataset, TProjectId>, ): DocumentTypeHandle<TDocumentType, TDataset, TProjectId> /** * Creates a GROQ search filter string (`[@] match text::query("...")`) * from a raw search query string. * * It applies wildcard ('*') logic to the last eligible token and escapes * double quotes within the search term. * * If the input query is empty or only whitespace, it returns an empty string. * * @param query - The raw input search string. * @returns The GROQ search filter string, or an empty string. * @internal */ export declare function createGroqSearchFilter(query: string): string /** * Creates or validates a `ProjectHandle` object. * Ensures the provided object conforms to the `ProjectHandle` interface. * @param handle - The object containing project identification properties. * @returns The validated `ProjectHandle` object. * @public */ export declare function createProjectHandle<TProjectId extends string = string>( handle: ProjectHandle<TProjectId>, ): ProjectHandle<TProjectId> /** * Creates a new Sanity resource instance * @param config - Configuration for the instance (optional) * @returns A configured SanityInstance * @remarks When creating child instances, configurations are merged with parent values * * @public */ export declare function createSanityInstance(config?: SanityConfig): SanityInstance export {CurrentUser} /** * Represents the various states the authentication can be in. * * @public */ declare interface DashboardContext { mode?: string env?: string orgId?: string } /** * @public */ export declare interface DatasetHandle< TDataset extends string = string, TProjectId extends string = string, > extends ProjectHandle<TProjectId>, PerspectiveHandle { dataset?: TDataset } declare class DateTime { date: Date constructor(date: Date) static parseToValue(str: string): Value equals(other: DateTime): boolean add(secs: number): DateTime difference(other: DateTime): number compareTo(other: DateTime): number toString(): string toJSON(): string } declare type DateTimeValue = StaticValue<DateTime, 'datetime'> /** * Given a type T and an array of "access keys" Parts, recursively index into T. * * If a part is a key, it looks up that property. * If T is an array and the part is a number, it "indexes" into the element type. */ declare 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, // Key/index doesn't exist TTail extends readonly (string | number)[] ? TTail : [] > : never /** * Creates a `DeleteDocumentAction` object. * @param doc - A handle uniquely identifying the document to be deleted. * @returns A `DeleteDocumentAction` object ready for dispatch. * @beta */ export declare function deleteDocument< TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string, >( doc: DocumentHandle<TDocumentType, TDataset, TProjectId>, ): DeleteDocumentAction<TDocumentType, TDataset, TProjectId> /** * Represents an action to delete an existing document. * Requires the full document handle including the document ID. * @beta */ export declare interface DeleteDocumentAction< TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string, > extends DocumentHandle<TDocumentType, TDataset, TProjectId> { type: 'document.delete' } declare type DereferenceFunction = (obj: { _ref: string }) => PromiseLike<Document_2 | null | undefined> declare interface DerefNode extends BaseNode { type: 'Deref' base: ExprNode } declare interface DescNode extends BaseNode { type: 'Desc' base: ExprNode } /** * Calls the destroy method on the controller and resets the controller state. * @public */ export declare const destroyController: BoundStoreAction_2<ComlinkControllerState, [], void> /** * Creates a `DiscardDocumentAction` object. * @param doc - A handle uniquely identifying the document whose draft changes are to be discarded. * @returns A `DiscardDocumentAction` object ready for dispatch. * @beta */ export declare function discardDocument< TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string, >( doc: DocumentHandle<TDocumentType, TDataset, TProjectId>, ): DiscardDocumentAction<TDocumentType, TDataset, TProjectId> /** * Represents an action to discard the draft changes of a document. * Requires the full document handle. * @beta */ export declare interface DiscardDocumentAction< TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string, > extends DocumentHandle<TDocumentType, TDataset, TProjectId> { type: 'document.discard' } declare type Document_2 = { _id?: string _type?: string [T: string]: unknown } /** * Union type representing all possible document actions within the SDK. * @beta */ export declare 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> /** * @beta * Event emitted when a document is created. */ export declare interface DocumentCreatedEvent { type: 'created' documentId: string outgoing: OutgoingTransaction } /** * @beta * Event emitted when a document is deleted. */ export declare interface DocumentDeletedEvent { type: 'deleted' documentId: string outgoing: OutgoingTransaction } /** * @beta * Event emitted when a document version is discarded. */ export declare interface DocumentDiscardedEvent { type: 'discarded' documentId: string outgoing: OutgoingTransaction } /** * @beta * Event emitted when a document is edited. */ export declare interface DocumentEditedEvent { type: 'edited' documentId: string outgoing: OutgoingTransaction } /** @beta */ export declare type DocumentEvent = | ActionErrorEvent | TransactionRevertedEvent | TransactionAcceptedEvent | DocumentRebaseErrorEvent | DocumentEditedEvent | DocumentCreatedEvent | DocumentDeletedEvent | DocumentPublishedEvent | DocumentUnpublishedEvent | DocumentDiscardedEvent /** * Uniquely identifies a specific document within a Sanity dataset and project. * Includes `projectId`, `dataset`, `documentType`, and the required `documentId`. * Commonly used by document-related hooks and components to reference a document without fetching its full content initially. * @public */ export declare interface DocumentHandle< TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string, > extends DocumentTypeHandle<TDocumentType, TDataset, TProjectId> { documentId: string } /** * @beta * Options for specifying a document and optionally a path within it. */ export declare interface DocumentOptions< TPath extends string | undefined = undefined, TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string, > extends DocumentHandle<TDocumentType, TDataset, TProjectId> { path?: TPath } /** @beta */ export declare type DocumentPermissionsResult = | { allowed: false message: string reasons: PermissionDeniedReason[] } | { allowed: true message?: undefined reasons?: undefined } /** * @beta * Event emitted when a document is published. */ export declare interface DocumentPublishedEvent { type: 'published' documentId: string outgoing: OutgoingTransaction } /** * @beta * Event emitted when an attempt to apply local changes to a modified remote document fails. */ declare interface DocumentRebaseErrorEvent { type: 'rebase-error' documentId: string transactionId: string message: string error: unknown } /** * Represents a set of document that will go into `applyMutations`. Before * applying a mutation, it's expected that all relevant documents that the * mutations affect are included, including those that do not exist yet. * Documents that don't exist have a `null` value. */ declare type DocumentSet<TDocument extends SanityDocument = SanityDocument> = { [TDocumentId in string]?: TDocument | null } declare interface DocumentState { id: string /** * the "remote" local copy that matches the server. represents the last known * server state. this gets updated every time we confirm remote patches */ remote?: SanityDocument_2 | null /** * the current ephemeral working copy that includes local optimistic changes * that have not yet been confirmed by the server */ local?: SanityDocument_2 | null /** * the revision that our remote document is at */ remoteRev?: string | null /** * Array of subscription IDs. This document state will be deleted if there are * no subscribers. */ subscriptions: string[] /** * An object keyed by transaction ID of revisions sent out but that have not * yet been verified yet. When an applied transaction is transitioned to an * outgoing transaction, it also adds unverified revisions for each document * that is part of that outgoing transaction. Transactions are submitted to * the server with a locally generated transaction ID. This way we can observe * when our transaction comes back through the shared listener. Each listener * event that comes back contains a `previousRev`. If we see our own * transaction with a different `previousRev` than expected, we can rebase our * local transactions on top of this new remote. */ unverifiedRevisions?: { [TTransactionId in string]?: UnverifiedDocumentRevision } } declare interface DocumentStoreState { documentStates: { [TDocumentId in string]?: DocumentState } queued: QueuedTransaction[] applied: AppliedTransaction[] outgoing?: OutgoingTransaction grants?: Record<Grant, ExprNode> error?: unknown sharedListener: SharedListener fetchDocument: (documentId: string) => Observable<SanityDocument_2 | null> events: Subject<DocumentEvent> } /** * Identifies a specific document type within a Sanity dataset and project. * Includes `projectId`, `dataset`, and `documentType`. * Optionally includes a `documentId`, useful for referencing a specific document type context, potentially without a specific document ID. * @public */ export declare interface DocumentTypeHandle< TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string, > extends DatasetHandle<TDataset, TProjectId> { documentId?: string documentType: TDocumentType } /** * @beta * Event emitted when a document is unpublished. */ export declare interface DocumentUnpublishedEvent { type: 'unpublished' documentId: string outgoing: OutgoingTransaction } /** * Creates an `EditDocumentAction` object with patches for modifying a document. * Accepts patches in either the standard `PatchOperations` format or as a `SanityMutatePatchMutation` from `@sanity/mutate`. * * @param doc - A handle uniquely identifying the document to be edited. * @param sanityMutatePatch - A patch mutation object from `@sanity/mutate`. * @returns An `EditDocumentAction` object ready for dispatch. * @beta */ export 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> /** * Creates an `EditDocumentAction` object with patches for modifying a document. * * @param doc - A handle uniquely identifying the document to be edited. * @param patches - A single patch operation or an array of patch operations. * @returns An `EditDocumentAction` object ready for dispatch. * @beta */ export 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> /** * Represents an action to edit an existing document using patches. * Requires the full document handle and an array of patch operations. * @beta */ export declare interface EditDocumentAction< TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string, > extends DocumentHandle<TDocumentType, TDataset, TProjectId> { type: 'document.edit' patches?: PatchOperations[] } /** * Error state from the auth state. * @public */ export declare type ErrorAuthState = { type: AuthStateType.ERROR error: unknown } declare interface EverythingNode extends BaseNode { type: 'Everything' } declare type Executor<N = ExprNode> = (node: N, scope: Scope) => Value | PromiseLike<Value> /** * A node which can be evaluated into a value. * @public */ declare type ExprNode = | AccessAttributeNode | AccessElementNode | AndNode | ArrayNode | ArrayCoerceNode | AscNode | ContextNode | DerefNode | DescNode | EverythingNode | FilterNode | FlatMapNode | FuncCallNode | GroupNode | InRangeNode | MapNode | NegNode | NotNode | ObjectNode | OpCallNode | OrNode | ParameterNode | ParentNode_2 | PipeFuncCallNode | PosNode | ProjectionNode | SelectNode | SelectorNode | SliceNode | ThisNode | TupleNode | ValueNode /** * @public */ declare interface FavoriteDocumentContext extends DocumentHandle { resourceId: string resourceType: StudioResource['type'] | MediaResource['type'] | CanvasResource['type'] schemaName?: string } /** * @public */ export declare interface FavoriteStatusResponse { isFavorited: boolean } /** * Internal helper type * @public */ export declare interface FetcherStore<TParams extends unknown[], TData> { getState: BoundStoreAction_3< FetcherStoreState<TParams, TData>, TParams, StateSource<TData | undefined> > resolveState: BoundStoreAction_3<FetcherStoreState<TParams, TData>, TParams, Promise<TData>> } /** * Internal helper type * @public */ export declare interface FetcherStoreState<TParams extends unknown[], TData> { stateByParams: { [TSerializedKey in string]?: StoreEntry<TParams, TData> } error?: unknown } declare interface FilterNode extends BaseNode { type: 'Filter' base: ExprNode expr: ExprNode } declare interface FlatMapNode extends BaseNode { type: 'FlatMap' base: ExprNode expr: ExprNode } /** * Message sent from a containing app to an iframe * @public */ export declare type FrameMessage = Message declare interface FuncCallNode extends BaseNode { type: 'FuncCall' func: GroqFunction namespace: string name: string args: ExprNode[] } /** * Get the active releases from the store. * @internal */ export declare const getActiveReleasesState: BoundStoreAction< ReleasesStoreState, [], StateSource_2<ReleaseDocument[] | undefined> > /** * @public */ export declare const getAuthState: BoundStoreAction<AuthStoreState, [], StateSource_2<AuthState>> /** * Retrieves a Sanity client instance configured with the provided options. * * This function returns a client instance configured for the project or as a * global client based on the options provided. It ensures efficient reuse of * client instances by returning the same instance for the same options. * For automatic handling of authentication token updates, consider using * `getClientState`. * * @public */ export declare const getClient: BoundStoreAction< ClientState, [options: ClientOptions], SanityClient > /** * Returns a state source for the Sanity client instance. * * This function provides a subscribable state source that emits updated client * instances whenever relevant configurations change (such as authentication tokens). * Use this when you need to react to client configuration changes in your application. * * @public */ export declare const getClientState: BoundStoreAction< ClientState, [options: ClientOptions], StateSource_2<SanityClient> > /** * @public */ export declare const getCurrentUserState: BoundStoreAction< AuthStoreState, [], StateSource_2<CurrentUser | null> > /** * @public */ export declare const getDashboardOrganizationId: BoundStoreAction< AuthStoreState, [], StateSource_2<string | undefined> > /** @public */ export declare const getDatasetsState: BoundStoreAction< FetcherStoreState_2<[options?: ProjectHandle<string> | undefined], DatasetsResponse>, [options?: ProjectHandle<string> | undefined], StateSource_2<DatasetsResponse | undefined> > /** @beta */ export 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_2<TDocumentType, `${TProjectId}.${TDataset}`> | undefined | null> /** @beta */ export 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_2<TDocumentType, `${TProjectId}.${TDataset}`>, TPath> | undefined > /** @beta */ export declare function getDocumentState<TData>( instance: SanityInstance, options: DocumentOptions<string | undefined>, ): StateSource<TData | undefined | null> /** @beta */ export declare const getDocumentSyncStatus: BoundStoreAction< DocumentStoreState, [doc: DocumentHandle<string, string, string>], StateSource<boolean | undefined> > /** * Gets a StateSource for the favorite status of a document. * @param instance - The Sanity instance. * @param context - The document context including ID, type, and resource information. * @returns A StateSource emitting `{ isFavorited: boolean }`. * @public */ export declare const getFavoritesState: BoundStoreAction< FetcherStoreState_2<[FavoriteDocumentContext], FavoriteStatusResponse>, [FavoriteDocumentContext], StateSource_2<FavoriteStatusResponse | undefined> > export {getIndexForKey} /** * Returns a state source indicating if the SDK is running within a dashboard context. * @public */ export declare const getIsInDashboardState: BoundStoreAction< AuthStoreState, [], StateSource_2<boolean> > /** * @public */ export declare const getLoginUrlState: BoundStoreAction<AuthStoreState, [], StateSource_2<string>> /** * Provides a subscribable state source for a node by name * @param instance - The Sanity instance to get the node state for * @param nodeInput - The configuration for the node to get the state for * @returns A subscribable state source for the node * @public */ export declare const getNodeState: BoundStoreAction_2< ComlinkNodeState, [NodeInput], StateSource_3<NodeState | undefined> > /** * Retrieve or create a channel to be used for communication between * an application and the controller. * @public */ export declare const getOrCreateChannel: BoundStoreAction_2< ComlinkControllerState, [options: ChannelInput], ChannelInstance<Message, Message> > /** * Initializes or fetches a controller to handle communication * between an application and iframes. * @public */ export declare const getOrCreateController: BoundStoreAction_2< ComlinkControllerState, [targetOrigin: string], Controller > /** * Retrieve or create a node to be used for communication between * an application and the controller -- specifically, a node should * be created within a frame / window to communicate with the controller. * @public */ export declare const getOrCreateNode: BoundStoreAction_2< ComlinkNodeState, [options: NodeInput], Node_2<Message, Message> > export {getPathDepth} /** @beta */ export declare const getPermissionsState: BoundStoreAction< DocumentStoreState, [DocumentAction | DocumentAction[]], StateSource<DocumentPermissionsResult_2 | undefined> > /** * Provides a subscribable state source for a "perspective" for the Sanity client, * which is used to fetch documents as though certain Content Releases are active. * * @param instance - The Sanity instance to get the perspective for * @param options - The options for the perspective -- usually a release name * * @returns A subscribable perspective value, usually a list of applicable release names, * or a single release name / default perspective (such as 'drafts'). * * @public */ export declare const getPerspectiveState: BoundStoreAction< ReleasesStoreState, [options?: PerspectiveHandle | undefined], StateSource_2<string[] | 'published' | 'drafts' | 'previewDrafts' | 'raw' | undefined> > /** * @beta */ export declare function getPreviewState<TResult extends object>( instance: SanityInstance, options: GetPreviewStateOptions, ): StateSource<ValuePending<TResult>> /** * @beta */ export declare function getPreviewState( instance: SanityInstance, options: GetPreviewStateOptions, ): StateSource<ValuePending<PreviewValue>> /** * @beta */ export declare type GetPreviewStateOptions = DocumentHandle /** * @beta */ export declare function getProjectionState< TProjection extends ValidProjection = ValidProjection, 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 > /** * @beta */ export declare function getProjectionState<TData extends object>( instance: SanityInstance, options: ProjectionOptions, ): StateSource<ProjectionValuePending<TData> | undefined> /** * @beta */ export declare function getProjectionState( instance: SanityInstance, options: ProjectionOptions, ): StateSource<ProjectionValuePending<Record<string, unknown>> | undefined> /** @public */ export declare const getProjectsState: BoundStoreAction< FetcherStoreState_2<[], Omit<SanityProject_2, 'members'>[]>, [], StateSource_2<Omit<SanityProject_2, 'members'>[] | undefined> > /** @public */ export declare const getProjectState: BoundStoreAction< FetcherStoreState_2<[options?: ProjectHandle<string> | undefined], SanityProject_2>, [options?: ProjectHandle<string> | undefined], StateSource_2<SanityProject_2 | undefined> > /** @beta */ export declare const getQueryKey: (options: QueryOptions) => string /** * Returns the state source for a query. * * This function returns a state source that represents the current result of a GROQ query. * Subscribing to the state source will instruct the SDK to fetch the query (if not already fetched) * and will keep the query live using the Live content API (considering sync tags) to provide up-to-date results. * When the last subscriber is removed, the query state is automatically cleaned up from the store. * * Note: This functionality is for advanced users who want to build their own framework integrations. * Our SDK also provides a React integration (useQuery hook) for convenient usage. * * Note: Automatic cleanup can interfere with React Suspense because if a component suspends while being the only subscriber, * cleanup might occur unexpectedly. In such cases, consider using `resolveQuery` instead. * * @beta */ export 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> /** @beta */ export declare function getQueryState<TData>( instance: SanityInstance, queryOptions: QueryOptions, ): StateSource<TData | undefined> /** @beta */ export declare function getQueryState( instance: SanityInstance, queryOptions: QueryOptions, ): StateSource<unknown> /** * @public */ export declare const getTokenState: BoundStoreAction< AuthStoreState, [], StateSource_2<string | null> > /** @internal */ export declare const getUsersKey: ( instance: SanityInstance, {resourceType, organizationId, batchSize, projectId}?: GetUsersOptions, ) => string /** * @public */ export declare interface GetUsersOptions extends ProjectHandle { resourceType?: 'organization' | 'project' batchSize?: number organizationId?: string } /** * Returns the state source for users associated with a specific resource. * * This function returns a state source that represents the current list of users for a given * resource. Subscribing to the state source will instruct the SDK to fetch the users (if not * already fetched) and will load more from this state source as well. When the last subscriber is * removed, the users state is automatically cleaned up from the store after a delay. * * Note: This functionality is for advanced users who want to build their own framework * integrations. Our SDK also provides a React integration for convenient usage. * * @beta */ export declare const getUsersState: BoundStoreAction< UsersStoreState, [options?: GetUsersOptions | undefined], StateSource_2< | { data: SanityUser_2[] totalCount: number hasMore: boolean } | undefined > > declare type Grant = 'read' | 'update' | 'create' | 'history' /** @public */ declare type GroqFunction = ( args: GroqFunctionArg[], scope: Scope, execute: Executor, ) => PromiseLike<Value> /** @public */ declare type GroqFunctionArg = ExprNode declare type GroqPipeFunction = ( base: Value, args: ExprNode[], scope: Scope, execute: Executor, ) => PromiseLike<Value> /** * A type of a value in GROQ. */ declare type GroqType = | 'null' | 'boolean' | 'number' | 'string' | 'array' | 'object' | 'path' | 'datetime' declare interface GroupNode extends BaseNode { type: 'Group' base: ExprNode } /** * @public */ export declare const handleAuthCallback: BoundStoreAction< AuthStoreState, [locationHref?: string | undefined], Promise<string | false> > declare type HttpAction = | { actionType: ActionMap['create'] publishedId: string attributes: SanityDocumentLike } | { actionType: ActionMap['discard'] versionId: string purge?: boolean } | { actionType: ActionMap['unpublish'] draftId: string publishedId: string } | { actionType: ActionMap['delete'] publishedId: string includeDrafts?: string[] } | { actionType: ActionMap['edit'] draftId: string publishedId: string patch: PatchOperations } | ({ actionType: ActionMap['publish'] draftId: string publishedId: string } & OptimisticLock) declare interface InRangeNode extends BaseNode { type: 'InRange' base: ExprNode left: ExprNode right: ExprNode isInclusive: boolean } export {joinPaths} /** * Given a document type TDocument and a JSON Match path string TPath, * compute the type found at that path. * @beta */ export declare type JsonMatch<TDocument, TPath extends string> = DeepGet< TDocument, PathParts<TPath> > export {jsonMatch} /** * Loads more users for a specific resource. * * This function triggers a request to fetch the next page of users for a given resource. It * requires that users have already been loaded for the resource (via `resolveUsers` or * `getUsersState`), and that there are more users available to load (as indicated by the `hasMore` * property). * * The function returns a promise that resolves when the next page of users has been loaded. * * @beta */ export declare const loadMoreUsers: BoundStoreAction< UsersStoreState, [options?: GetUsersOptions | undefined], Promise<{ data: SanityUser_2[] totalCount: number hasMore: boolean }> > /** * Logged-in state from the auth state. * @public */ export declare type LoggedInAuthState = { type: AuthStateType.LOGGED_IN token: string currentUser: CurrentUser | null } /** * Logged-out state from the auth state. * @public */ export declare type LoggedOutAuthState = { type: AuthStateType.LOGGED_OUT isDestroyingSession: boolean } /** * Logging-in state from the auth state. * @public */ export declare type LoggingInAuthState = { type: AuthStateType.LOGGING_IN isExchangingToken: boolean } /** * @public */ export declare const logout: BoundStoreAction<AuthStoreState_2, [], Promise<void>> declare interface MapNode extends BaseNode { type: 'Map' base: ExprNode expr: ExprNode } /** * @public */ export declare interface Membership { addedAt?: string resourceType: string resourceId: string roleNames: Array<string> lastSeenAt?: string | null } declare interface NegNode extends BaseNode { type: 'Neg' base: ExprNode } /** * Message from Parent (dashboard) to SDK (iframe) with the new token * @internal */ export declare type NewTokenResponseMessage = { type: 'dashboard/v1/auth/tokens/create' payload: { token: string | null error?: string } } /** * Individual node with its relevant options * @public */ declare interface NodeEntry { node: Node_2<WindowMessage, FrameMessage> options: NodeInput status: Status statusUnsub?: () => void } /** * @public */ export declare interface NodeState { node: Node_2<WindowMessage, FrameMessage> status: Status | undefined } declare interface NotNode extends BaseNode { type: 'Not' base: ExprNode } declare type NullValue = StaticValue<null, 'null'> declare type NumberValue = StaticValue<number, 'number'> declare type ObjectAttributeNode = | ObjectAttributeValueNode | ObjectConditionalSplatNode | ObjectSplatNode declare interface ObjectAttributeValueNode extends BaseNode { type: 'ObjectAttributeValue' name: string value: ExprNode } declare interface ObjectConditionalSplatNode extends BaseNode { type: 'ObjectConditionalSplat' condition: ExprNode value: ExprNode } declare interface ObjectNode extends BaseNode { type: 'Object' attributes: ObjectAttributeNode[] } declare interface ObjectSplatNode extends BaseNode { type: 'ObjectSplat' value: ExprNode } declare type ObjectValue = StaticValue<Record<string, unknown>, 'object'> /** * Creates an observable that emits the organization verification state for a given instance. * It combines the dashboard organization ID (from auth context) with the * project's actual organization ID (fetched via getProjectState) and compares them. * @public */ export declare function observeOrganizationVerificationState( instance: SanityInstance, projectIds: string[], ): Observable<OrgVerificationResult> declare type OpCall = | '==' | '!=' | '>' | '>=' | '<' | '<=' | '+' | '-' | '*' | '/' | '%' | '**' | 'in' | 'match' declare interface OpCallNode extends BaseNode { type: 'OpCall' op: OpCall left: ExprNode right: ExprNode } declare type OptimisticLock = { ifDraftRevisionId?: string ifPublishedRevisionId?: string } /** * Error message returned by the organization verification * @public */ export declare interface OrgVerificationResult { error: string | null } declare interface OrNode extends BaseNode { type: 'Or' left: ExprNode right: ExprNode } /** * Represents a set of applied transactions batched into a single outgoing * transaction. An outgoing transaction is the result of batching many applied * actions. An outgoing transaction may be reverted locally if the server * does not accept it. */ declare interface OutgoingTransaction extends AppliedTransaction { disableBatching: boolean batchedTransactionIds: string[] } declare interface ParameterNode extends BaseNode { type: 'Parameter' name: string } declare interface ParentNode_2 extends BaseNode { type: 'Parent' n: number } /** @beta */ export declare const parseQueryKey: (key: string) => QueryOptions /** @internal */ export declare const parseUsersKey: (key: string) => { batchSize: number resourceType?: 'organization' | 'project' projectId?: string organizationId?: string } declare class Path { private pattern private patternRe constructor(pattern: string) matches(str: string): boolean toJSON(): string } /** * Split the entire path string on dots "outside" of any brackets. * * For example: * ``` * "friends[0].name" * ``` * * becomes: * * ``` * [...ParseSegment<"friends[0]">, ...ParseSegment<"name">] * ``` * * (We use a simple recursion that splits on the first dot.) */ declare type PathParts<TPath extends string> = TPath extends `${infer Head}.${infer Tail}` ? [Head, ...PathParts<Tail>] : TPath extends '' ? [] : [TPath] declare type PathValue = StaticValue<Path, 'path'> /** @beta */ export declare interface PermissionDeniedReason { type: 'precondit