@sanity/sdk-react 2.2.0 → 2.3.1
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 +2 -3
- package/dist/index.js +101 -26
- package/dist/index.js.map +1 -1
- package/package.json +7 -6
- package/src/components/auth/AuthBoundary.test.tsx +33 -20
- package/src/components/auth/AuthBoundary.tsx +20 -5
- package/src/components/auth/LoginError.tsx +9 -12
- package/src/components/errors/CorsErrorComponent.test.tsx +48 -0
- package/src/components/errors/CorsErrorComponent.tsx +37 -0
- package/src/components/errors/Error.styles.ts +35 -0
- package/src/components/errors/Error.tsx +40 -0
- package/src/context/ComlinkTokenRefresh.test.tsx +87 -38
- package/src/context/ComlinkTokenRefresh.tsx +2 -1
- package/src/hooks/auth/useDashboardOrganizationId.test.tsx +16 -7
- package/src/hooks/auth/useVerifyOrgProjects.test.tsx +56 -14
- package/src/hooks/dashboard/{useManageFavorite.test.ts → useManageFavorite.test.tsx} +99 -44
- package/src/hooks/document/{useDocument.test.ts → useDocument.test.tsx} +25 -22
- package/src/hooks/document/{useDocumentEvent.test.ts → useDocumentEvent.test.tsx} +17 -16
- package/src/hooks/document/{useDocumentPermissions.test.ts → useDocumentPermissions.test.tsx} +101 -40
- package/src/hooks/document/{useEditDocument.test.ts → useEditDocument.test.tsx} +52 -22
- package/src/hooks/documents/useDocuments.test.tsx +63 -25
- package/src/hooks/helpers/createCallbackHook.test.tsx +41 -37
- package/src/hooks/paginatedDocuments/usePaginatedDocuments.test.tsx +2 -2
- package/src/hooks/presence/usePresence.test.tsx +9 -6
- package/src/hooks/preview/useDocumentPreview.test.tsx +15 -16
- package/src/hooks/projection/useDocumentProjection.test.tsx +23 -38
- package/src/hooks/projection/useDocumentProjection.ts +3 -8
- package/src/hooks/query/useQuery.test.tsx +18 -10
- package/src/hooks/releases/useActiveReleases.test.tsx +25 -21
- package/src/hooks/releases/usePerspective.test.tsx +16 -22
- package/src/hooks/users/useUser.test.tsx +32 -15
- package/src/hooks/users/useUsers.test.tsx +19 -11
- package/src/hooks/_synchronous-groq-js.mjs +0 -4
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../src/context/SanityInstanceContext.ts","../src/hooks/context/useSanityInstance.ts","../src/hooks/helpers/createStateSourceHook.tsx","../src/hooks/auth/useAuthState.tsx","../src/hooks/comlink/useWindowConnection.ts","../src/context/ComlinkTokenRefresh.tsx","../src/hooks/auth/useLoginUrl.tsx","../src/hooks/auth/useVerifyOrgProjects.tsx","../src/components/utils.ts","../src/components/auth/AuthError.ts","../src/components/auth/ConfigurationError.ts","../src/hooks/helpers/createCallbackHook.tsx","../src/hooks/auth/useHandleAuthCallback.tsx","../src/components/auth/LoginCallback.tsx","../src/hooks/auth/useLogOut.tsx","../src/components/auth/LoginError.tsx","../src/components/auth/AuthBoundary.tsx","../src/context/ResourceProvider.tsx","../src/components/SDKProvider.tsx","../src/components/SanityApp.tsx","../src/hooks/auth/useAuthToken.tsx","../src/hooks/auth/useCurrentUser.tsx","../src/hooks/auth/useDashboardOrganizationId.tsx","../src/hooks/client/useClient.ts","../src/hooks/comlink/useFrameConnection.ts","../src/hooks/dashboard/useDashboardNavigate.ts","../src/hooks/dashboard/useManageFavorite.ts","../src/hooks/dashboard/useStudioWorkspacesByProjectIdDataset.ts","../src/hooks/dashboard/useNavigateToStudioDocument.ts","../src/hooks/dashboard/useRecordDocumentHistoryEvent.ts","../src/hooks/datasets/useDatasets.ts","../src/hooks/document/useApplyDocumentActions.ts","../src/hooks/document/useDocument.ts","../src/hooks/document/useDocumentEvent.ts","../src/hooks/document/useDocumentPermissions.ts","../src/hooks/document/useDocumentSyncStatus.ts","../src/hooks/document/useEditDocument.ts","../src/hooks/query/useQuery.ts","../src/hooks/documents/useDocuments.ts","../src/hooks/paginatedDocuments/usePaginatedDocuments.ts","../src/hooks/presence/usePresence.ts","../src/hooks/preview/useDocumentPreview.tsx","../src/hooks/projection/useDocumentProjection.ts","../src/hooks/projects/useProject.ts","../src/hooks/projects/useProjects.ts","../src/hooks/releases/useActiveReleases.ts","../src/hooks/releases/usePerspective.ts","../src/hooks/users/useUser.ts","../src/hooks/users/useUsers.ts","../src/utils/getEnv.ts","../src/version.ts"],"sourcesContent":["import {type SanityInstance} from '@sanity/sdk'\nimport {createContext} from 'react'\n\nexport const SanityInstanceContext = createContext<SanityInstance | null>(null)\n","import {type SanityConfig, type SanityInstance} from '@sanity/sdk'\nimport {useContext} from 'react'\n\nimport {SanityInstanceContext} from '../../context/SanityInstanceContext'\n\n/**\n * Retrieves the current Sanity instance or finds a matching instance from the hierarchy\n *\n * @public\n *\n * @category Platform\n * @param config - Optional configuration to match against when finding an instance\n * @returns The current or matching Sanity instance\n *\n * @remarks\n * This hook accesses the nearest Sanity instance from the React context. When provided with\n * a configuration object, it traverses up the instance hierarchy to find the closest instance\n * that matches the specified configuration using shallow comparison of properties.\n *\n * The hook must be used within a component wrapped by a `ResourceProvider` or `SanityApp`.\n *\n * Use this hook when you need to:\n * - Access the current SanityInstance from context\n * - Find a specific instance with matching project/dataset configuration\n * - Access a parent instance with specific configuration values\n *\n * @example Get the current instance\n * ```tsx\n * // Get the current instance from context\n * const instance = useSanityInstance()\n * console.log(instance.config.projectId)\n * ```\n *\n * @example Find an instance with specific configuration\n * ```tsx\n * // Find an instance matching the given project and dataset\n * const instance = useSanityInstance({\n * projectId: 'abc123',\n * dataset: 'production'\n * })\n *\n * // Use instance for API calls\n * const fetchDocument = (docId) => {\n * // Instance is guaranteed to have the matching config\n * return client.fetch(`*[_id == $id][0]`, { id: docId })\n * }\n * ```\n *\n * @example Match partial configuration\n * ```tsx\n * // Find an instance with specific auth configuration\n * const instance = useSanityInstance({\n * auth: { requireLogin: true }\n * })\n * ```\n *\n * @throws Error if no SanityInstance is found in context\n * @throws Error if no matching instance is found for the provided config\n */\nexport const useSanityInstance = (config?: SanityConfig): SanityInstance => {\n const instance = useContext(SanityInstanceContext)\n\n if (!instance) {\n throw new Error(\n `SanityInstance context not found. ${config ? `Requested config: ${JSON.stringify(config, null, 2)}. ` : ''}Please ensure that your component is wrapped in a ResourceProvider or a SanityApp component.`,\n )\n }\n\n if (!config) return instance\n\n const match = instance.match(config)\n if (!match) {\n throw new Error(\n `Could not find a matching Sanity instance for the requested configuration: ${JSON.stringify(config, null, 2)}.\nPlease ensure there is a ResourceProvider component with a matching configuration in the component hierarchy.`,\n )\n }\n\n return match\n}\n","import {type SanityConfig, type SanityInstance, type StateSource} from '@sanity/sdk'\nimport {useSyncExternalStore} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\ntype StateSourceFactory<TParams extends unknown[], TState> = (\n instance: SanityInstance,\n ...params: TParams\n) => StateSource<TState>\n\ninterface CreateStateSourceHookOptions<TParams extends unknown[], TState> {\n getState: StateSourceFactory<TParams, TState>\n shouldSuspend?: (instance: SanityInstance, ...params: TParams) => boolean\n suspender?: (instance: SanityInstance, ...params: TParams) => Promise<unknown>\n getConfig?: (...params: TParams) => SanityConfig | undefined\n}\n\nexport function createStateSourceHook<TParams extends unknown[], TState>(\n options: StateSourceFactory<TParams, TState> | CreateStateSourceHookOptions<TParams, TState>,\n): (...params: TParams) => TState {\n const getState = typeof options === 'function' ? options : options.getState\n const getConfig = 'getConfig' in options ? options.getConfig : undefined\n const suspense = 'shouldSuspend' in options && 'suspender' in options ? options : undefined\n\n function useHook(...params: TParams) {\n const instance = useSanityInstance(getConfig?.(...params))\n\n if (suspense?.suspender && suspense?.shouldSuspend?.(instance, ...params)) {\n throw suspense.suspender(instance, ...params)\n }\n\n const state = getState(instance, ...params)\n return useSyncExternalStore(state.subscribe, state.getCurrent)\n }\n\n return useHook\n}\n","import {type AuthState, getAuthState} from '@sanity/sdk'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\n/**\n * @internal\n * A React hook that subscribes to authentication state changes.\n *\n * This hook provides access to the current authentication state type from the Sanity auth store.\n * It automatically re-renders when the authentication state changes.\n *\n * @remarks\n * The hook uses `useSyncExternalStore` to safely subscribe to auth state changes\n * and ensure consistency between server and client rendering.\n *\n * @returns The current authentication state type\n *\n * @example\n * ```tsx\n * function AuthStatus() {\n * const authState = useAuthState()\n * return <div>Current auth state: {authState}</div>\n * }\n * ```\n */\nexport const useAuthState: () => AuthState = createStateSourceHook(getAuthState)\n","import {type MessageData, type NodeInput} from '@sanity/comlink'\nimport {\n type FrameMessage,\n getNodeState,\n type NodeState,\n type SanityInstance,\n type StateSource,\n type WindowMessage,\n} from '@sanity/sdk'\nimport {useCallback, useEffect, useRef} from 'react'\nimport {filter, firstValueFrom} from 'rxjs'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\n/**\n * @internal\n */\nexport type WindowMessageHandler<TFrameMessage extends FrameMessage> = (\n event: TFrameMessage['data'],\n) => TFrameMessage['response']\n\n/**\n * @internal\n */\nexport interface UseWindowConnectionOptions<TMessage extends FrameMessage> {\n name: string\n connectTo: string\n onMessage?: Record<TMessage['type'], WindowMessageHandler<TMessage>>\n}\n\n/**\n * @internal\n */\nexport interface WindowConnection<TMessage extends WindowMessage> {\n sendMessage: <TType extends TMessage['type']>(\n type: TType,\n data?: Extract<TMessage, {type: TType}>['data'],\n ) => void\n fetch: <TResponse>(\n type: string,\n data?: MessageData,\n options?: {\n signal?: AbortSignal\n suppressWarnings?: boolean\n responseTimeout?: number\n },\n ) => Promise<TResponse>\n}\n\nconst useNodeState = createStateSourceHook({\n getState: getNodeState as (\n instance: SanityInstance,\n nodeInput: NodeInput,\n ) => StateSource<NodeState>,\n shouldSuspend: (instance: SanityInstance, nodeInput: NodeInput) =>\n getNodeState(instance, nodeInput).getCurrent() === undefined,\n suspender: (instance: SanityInstance, nodeInput: NodeInput) => {\n return firstValueFrom(getNodeState(instance, nodeInput).observable.pipe(filter(Boolean)))\n },\n})\n\n/**\n * @internal\n * Hook to wrap a Comlink node in a React hook.\n * Our store functionality takes care of the lifecycle of the node,\n * as well as sharing a single node between invocations if they share the same name.\n *\n * Generally not to be used directly, but to be used as a dependency of\n * Comlink-powered hooks like `useManageFavorite`.\n */\nexport function useWindowConnection<\n TWindowMessage extends WindowMessage,\n TFrameMessage extends FrameMessage,\n>({\n name,\n connectTo,\n onMessage,\n}: UseWindowConnectionOptions<TFrameMessage>): WindowConnection<TWindowMessage> {\n const {node} = useNodeState({name, connectTo})\n const messageUnsubscribers = useRef<(() => void)[]>([])\n const instance = useSanityInstance()\n\n useEffect(() => {\n if (onMessage) {\n Object.entries(onMessage).forEach(([type, handler]) => {\n const messageUnsubscribe = node.on(type, handler as WindowMessageHandler<TFrameMessage>)\n if (messageUnsubscribe) {\n messageUnsubscribers.current.push(messageUnsubscribe)\n }\n })\n }\n\n return () => {\n messageUnsubscribers.current.forEach((unsubscribe) => unsubscribe())\n messageUnsubscribers.current = []\n }\n }, [instance, name, onMessage, node])\n\n const sendMessage = useCallback(\n (type: TWindowMessage['type'], data?: Extract<TWindowMessage, {type: typeof type}>['data']) => {\n node.post(type, data)\n },\n [node],\n )\n\n const fetch = useCallback(\n <TResponse>(\n type: string,\n data?: MessageData,\n fetchOptions?: {\n responseTimeout?: number\n signal?: AbortSignal\n suppressWarnings?: boolean\n },\n ): Promise<TResponse> => {\n return node.fetch(type, data, fetchOptions ?? {}) as Promise<TResponse>\n },\n [node],\n )\n return {\n sendMessage,\n fetch,\n }\n}\n","import {type ClientError} from '@sanity/client'\nimport {SDK_CHANNEL_NAME, SDK_NODE_NAME} from '@sanity/message-protocol'\nimport {\n AuthStateType,\n type FrameMessage,\n getIsInDashboardState,\n type NewTokenResponseMessage,\n type RequestNewTokenMessage,\n setAuthToken,\n type WindowMessage,\n} from '@sanity/sdk'\nimport React, {type PropsWithChildren, useCallback, useEffect, useMemo, useRef} from 'react'\n\nimport {useAuthState} from '../hooks/auth/useAuthState'\nimport {useWindowConnection} from '../hooks/comlink/useWindowConnection'\nimport {useSanityInstance} from '../hooks/context/useSanityInstance'\n\n// Define specific message types extending the base types for clarity\ntype SdkParentComlinkMessage = NewTokenResponseMessage | WindowMessage // Messages received by SDK\ntype SdkChildComlinkMessage = RequestNewTokenMessage | FrameMessage // Messages sent by SDK\n\nconst DEFAULT_RESPONSE_TIMEOUT = 10000 // 10 seconds\n\n/**\n * Component that handles token refresh in dashboard mode\n */\nfunction DashboardTokenRefresh({children}: PropsWithChildren) {\n const instance = useSanityInstance()\n const isTokenRefreshInProgress = useRef(false)\n const timeoutRef = useRef<NodeJS.Timeout | null>(null)\n const processed401ErrorRef = useRef<unknown | null>(null)\n const authState = useAuthState()\n\n const clearRefreshTimeout = useCallback(() => {\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current)\n timeoutRef.current = null\n }\n }, [])\n\n const windowConnection = useWindowConnection<SdkParentComlinkMessage, SdkChildComlinkMessage>({\n name: SDK_NODE_NAME,\n connectTo: SDK_CHANNEL_NAME,\n })\n\n const requestNewToken = useCallback(async () => {\n if (isTokenRefreshInProgress.current) {\n return\n }\n\n isTokenRefreshInProgress.current = true\n clearRefreshTimeout()\n\n timeoutRef.current = setTimeout(() => {\n if (isTokenRefreshInProgress.current) {\n isTokenRefreshInProgress.current = false\n }\n timeoutRef.current = null\n }, DEFAULT_RESPONSE_TIMEOUT)\n\n try {\n const res = await windowConnection.fetch<{token: string | null; error?: string}>(\n 'dashboard/v1/auth/tokens/create',\n )\n clearRefreshTimeout()\n\n if (res.token) {\n setAuthToken(instance, res.token)\n\n // Remove the unauthorized error from the error container\n const errorContainer = document.getElementById('__sanityError')\n if (errorContainer) {\n const hasUnauthorizedError = Array.from(errorContainer.getElementsByTagName('div')).some(\n (div) =>\n div.textContent?.includes(\n 'Uncaught error: Unauthorized - A valid session is required for this endpoint',\n ),\n )\n\n if (hasUnauthorizedError) {\n errorContainer.remove()\n }\n }\n }\n isTokenRefreshInProgress.current = false\n } catch {\n isTokenRefreshInProgress.current = false\n clearRefreshTimeout()\n }\n }, [windowConnection, clearRefreshTimeout, instance])\n\n useEffect(() => {\n return () => {\n clearRefreshTimeout()\n }\n }, [clearRefreshTimeout])\n\n useEffect(() => {\n const has401Error =\n authState.type === AuthStateType.ERROR &&\n authState.error &&\n (authState.error as ClientError)?.statusCode === 401 &&\n !isTokenRefreshInProgress.current &&\n processed401ErrorRef.current !== authState.error\n\n const isLoggedOut =\n authState.type === AuthStateType.LOGGED_OUT && !isTokenRefreshInProgress.current\n\n if (has401Error || isLoggedOut) {\n processed401ErrorRef.current =\n authState.type === AuthStateType.ERROR ? authState.error : undefined\n requestNewToken()\n } else if (\n authState.type !== AuthStateType.ERROR ||\n processed401ErrorRef.current !==\n (authState.type === AuthStateType.ERROR ? authState.error : undefined)\n ) {\n processed401ErrorRef.current = null\n }\n }, [authState, requestNewToken])\n\n return children\n}\n\n/**\n * This provider is used to provide the Comlink token refresh feature.\n * It is used to automatically request a new token on 401 error if enabled.\n * @public\n */\nexport const ComlinkTokenRefreshProvider: React.FC<PropsWithChildren> = ({children}) => {\n const instance = useSanityInstance()\n const isInDashboard = useMemo(() => getIsInDashboardState(instance).getCurrent(), [instance])\n\n if (isInDashboard) {\n return <DashboardTokenRefresh>{children}</DashboardTokenRefresh>\n }\n\n // If we're not in the dashboard, we don't need to do anything\n return children\n}\n","import {getLoginUrlState} from '@sanity/sdk'\nimport {useMemo, useSyncExternalStore} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * @internal\n */\nexport function useLoginUrl(): string {\n const instance = useSanityInstance()\n const {subscribe, getCurrent} = useMemo(() => getLoginUrlState(instance), [instance])\n\n return useSyncExternalStore(subscribe, getCurrent as () => string)\n}\n","import {observeOrganizationVerificationState, type OrgVerificationResult} from '@sanity/sdk'\nimport {useEffect, useState} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * Hook that verifies the current projects belongs to the organization ID specified in the dashboard context.\n *\n * @public\n * @param disabled - When true, disables verification and skips project verification API calls\n * @returns Error message if the project doesn't match the organization ID, or null if all match or verification isn't needed\n * @category Projects\n * @example\n * ```tsx\n * function OrgVerifier() {\n * const error = useVerifyOrgProjects()\n *\n * if (error) {\n * return <div className=\"error\">{error}</div>\n * }\n *\n * return <div>Organization projects verified!</div>\n * }\n * ```\n */\nexport function useVerifyOrgProjects(disabled = false, projectIds?: string[]): string | null {\n const instance = useSanityInstance()\n const [error, setError] = useState<string | null>(null)\n\n useEffect(() => {\n if (disabled || !projectIds || projectIds.length === 0) {\n if (error !== null) setError(null)\n return\n }\n\n const verificationObservable$ = observeOrganizationVerificationState(instance, projectIds)\n\n const subscription = verificationObservable$.subscribe((result: OrgVerificationResult) => {\n setError(result.error)\n })\n\n return () => {\n subscription.unsubscribe()\n }\n }, [instance, disabled, error, projectIds])\n\n return error\n}\n","export function isInIframe(): boolean {\n return typeof window !== 'undefined' && window.self !== window.top\n}\n\n/**\n * @internal\n *\n * Checks if the current URL is a local URL.\n *\n * @param window - The window object\n * @returns True if the current URL is a local URL, false otherwise\n */\nexport function isLocalUrl(window: Window): boolean {\n const url = typeof window !== 'undefined' ? window.location.href : ''\n\n return (\n url.startsWith('http://localhost') ||\n url.startsWith('https://localhost') ||\n url.startsWith('http://127.0.0.1') ||\n url.startsWith('https://127.0.0.1')\n )\n}\n","/**\n * Error class for authentication-related errors. Wraps errors thrown during the\n * authentication flow.\n *\n * @remarks\n * This class provides a consistent error type for authentication failures while\n * preserving the original error as the cause. If the original error has a\n * message property, it will be used as the error message.\n *\n * @alpha\n */\nexport class AuthError extends Error {\n constructor(error: unknown) {\n if (\n typeof error === 'object' &&\n !!error &&\n 'message' in error &&\n typeof error.message === 'string'\n ) {\n super(error.message)\n } else {\n super()\n }\n\n this.cause = error\n }\n}\n","/**\n * Error class for configuration-related errors. Wraps errors thrown during the\n * configuration flow.\n *\n * @alpha\n */\nexport class ConfigurationError extends Error {\n constructor(error: unknown) {\n if (\n typeof error === 'object' &&\n !!error &&\n 'message' in error &&\n typeof error.message === 'string'\n ) {\n super(error.message)\n } else {\n super()\n }\n\n this.cause = error\n }\n}\n","import {type SanityInstance} from '@sanity/sdk'\nimport {useCallback} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\nexport function createCallbackHook<TParams extends unknown[], TReturn>(\n callback: (instance: SanityInstance, ...params: TParams) => TReturn,\n): () => (...params: TParams) => TReturn {\n function useHook() {\n const instance = useSanityInstance()\n return useCallback((...params: TParams) => callback(instance, ...params), [instance])\n }\n\n return useHook\n}\n","import {handleAuthCallback} from '@sanity/sdk'\n\nimport {createCallbackHook} from '../helpers/createCallbackHook'\n\n/**\n * @internal\n * A React hook that returns a function for handling authentication callbacks.\n *\n * @remarks\n * This hook provides access to the authentication store's callback handler,\n * which processes auth redirects by extracting the session ID and fetching the\n * authentication token. If fetching the long-lived token is successful,\n * `handleAuthCallback` will return a Promise that resolves a new location that\n * removes the short-lived token from the URL. Use this in combination with\n * `history.replaceState` or your own router's `replace` function to update the\n * current location without triggering a reload.\n *\n * @example\n * ```tsx\n * function AuthCallback() {\n * const handleAuthCallback = useHandleAuthCallback()\n * const router = useRouter() // Example router\n *\n * useEffect(() => {\n * async function processCallback() {\n * // Handle the callback and get the cleaned URL\n * const newUrl = await handleAuthCallback(window.location.href)\n *\n * if (newUrl) {\n * // Replace URL without triggering navigation\n * router.replace(newUrl, {shallow: true})\n * }\n * }\n *\n * processCallback().catch(console.error)\n * }, [handleAuthCallback, router])\n *\n * return <div>Completing login...</div>\n * }\n * ```\n *\n * @returns A callback handler function that processes OAuth redirects\n * @public\n */\nexport const useHandleAuthCallback = createCallbackHook(handleAuthCallback)\n","import {useEffect} from 'react'\n\nimport {useHandleAuthCallback} from '../../hooks/auth/useHandleAuthCallback'\n\n/**\n * Component shown during auth callback processing that handles login completion.\n * Automatically processes the auth callback when mounted and updates the URL\n * to remove callback parameters without triggering a page reload.\n *\n * @alpha\n */\nexport function LoginCallback(): React.ReactNode {\n const handleAuthCallback = useHandleAuthCallback()\n\n useEffect(() => {\n const url = new URL(location.href)\n handleAuthCallback(url.toString()).then((replacementLocation) => {\n if (replacementLocation) {\n // history API with `replaceState` is used to prevent a reload but still\n // remove the short-lived token from the URL\n history.replaceState(null, '', replacementLocation)\n }\n })\n }, [handleAuthCallback])\n\n return null\n}\n","import {logout} from '@sanity/sdk'\n\nimport {createCallbackHook} from '../helpers/createCallbackHook'\n\n/**\n * Hook to log out of the current session\n * @internal\n * @returns A function to log out of the current session\n */\nexport const useLogOut = createCallbackHook(logout)\n","import {ClientError} from '@sanity/client'\nimport {AuthStateType} from '@sanity/sdk'\nimport {useCallback, useEffect, useState} from 'react'\nimport {type FallbackProps} from 'react-error-boundary'\n\nimport {useAuthState} from '../../hooks/auth/useAuthState'\nimport {useLogOut} from '../../hooks/auth/useLogOut'\nimport {AuthError} from './AuthError'\nimport {ConfigurationError} from './ConfigurationError'\n/**\n * @alpha\n */\nexport type LoginErrorProps = FallbackProps\n\n/**\n * Displays authentication error details and provides retry functionality.\n * Only handles {@link AuthError} instances - rethrows other error types.\n *\n * @alpha\n */\nexport function LoginError({error, resetErrorBoundary}: LoginErrorProps): React.ReactNode {\n if (\n !(\n error instanceof AuthError ||\n error instanceof ConfigurationError ||\n error instanceof ClientError\n )\n )\n throw error\n\n const logout = useLogOut()\n const authState = useAuthState()\n\n const [authErrorMessage, setAuthErrorMessage] = useState(\n 'Please try again or contact support if the problem persists.',\n )\n\n const handleRetry = useCallback(async () => {\n await logout()\n resetErrorBoundary()\n }, [logout, resetErrorBoundary])\n\n useEffect(() => {\n if (error instanceof ClientError) {\n if (error.statusCode === 401) {\n handleRetry()\n } else if (error.statusCode === 404) {\n const errorMessage = error.response.body.message || ''\n if (errorMessage.startsWith('Session with sid') && errorMessage.endsWith('not found')) {\n setAuthErrorMessage('The session ID is invalid or expired.')\n } else {\n setAuthErrorMessage('The login link is invalid or expired. Please try again.')\n }\n }\n }\n if (authState.type !== AuthStateType.ERROR && error instanceof ConfigurationError) {\n setAuthErrorMessage(error.message)\n }\n }, [authState, handleRetry, error])\n\n return (\n <div className=\"sc-login-error\">\n <div className=\"sc-login-error__content\">\n <h2 className=\"sc-login-error__title\">\n {error instanceof AuthError ? 'Authentication Error' : 'Configuration Error'}\n </h2>\n <p className=\"sc-login-error__description\">{authErrorMessage}</p>\n </div>\n\n <button className=\"sc-login-error__button\" onClick={handleRetry}>\n Retry\n </button>\n </div>\n )\n}\n","import {AuthStateType} from '@sanity/sdk'\nimport {useEffect, useMemo} from 'react'\nimport {ErrorBoundary, type FallbackProps} from 'react-error-boundary'\n\nimport {ComlinkTokenRefreshProvider} from '../../context/ComlinkTokenRefresh'\nimport {useAuthState} from '../../hooks/auth/useAuthState'\nimport {useLoginUrl} from '../../hooks/auth/useLoginUrl'\nimport {useVerifyOrgProjects} from '../../hooks/auth/useVerifyOrgProjects'\nimport {isInIframe} from '../utils'\nimport {AuthError} from './AuthError'\nimport {ConfigurationError} from './ConfigurationError'\nimport {LoginCallback} from './LoginCallback'\nimport {LoginError, type LoginErrorProps} from './LoginError'\n\n// Only import bridge if we're in an iframe. This assumes that the app is\n// running within SanityOS if it is in an iframe and that the bridge hasn't already been loaded\nif (isInIframe() && !document.querySelector('[data-sanity-core]')) {\n const parsedUrl = new URL(window.location.href)\n const mode = new URLSearchParams(parsedUrl.hash.slice(1)).get('mode')\n const script = document.createElement('script')\n script.src =\n mode === 'core-ui--staging'\n ? 'https://core.sanity-cdn.work/bridge.js'\n : 'https://core.sanity-cdn.com/bridge.js'\n script.type = 'module'\n script.async = true\n document.head.appendChild(script)\n}\n\n/**\n * @internal\n */\nexport interface AuthBoundaryProps {\n /**\n * Custom component to render the login screen.\n * Receives all props. Defaults to {@link Login}.\n */\n LoginComponent?: React.ComponentType<{\n header?: React.ReactNode\n footer?: React.ReactNode\n }>\n\n /**\n * Custom component to render during OAuth callback processing.\n * Receives all props. Defaults to {@link LoginCallback}.\n */\n CallbackComponent?: React.ComponentType<{\n header?: React.ReactNode\n footer?: React.ReactNode\n }>\n\n /**\n * Custom component to render when authentication errors occur.\n * Receives error boundary props and layout props. Defaults to\n * {@link LoginError}\n */\n LoginErrorComponent?: React.ComponentType<LoginErrorProps>\n\n /** Header content to display */\n header?: React.ReactNode\n\n /**\n * The project IDs to use for organization verification.\n */\n projectIds?: string[]\n\n /** Footer content to display */\n footer?: React.ReactNode\n\n /** Protected content to render when authenticated */\n children?: React.ReactNode\n\n /**\n * Whether to verify that the project belongs to the organization specified in the dashboard context.\n * By default, organization verification is enabled when running in a dashboard context.\n *\n * WARNING: Disabling organization verification is NOT RECOMMENDED and may cause your application\n * to break in the future. This should never be disabled in production environments.\n */\n verifyOrganization?: boolean\n}\n\n/**\n * A component that handles authentication flow and error boundaries for a\n * protected section of the application.\n *\n * @remarks\n * This component manages different authentication states and renders the\n * appropriate components based on that state.\n *\n * @example\n * ```tsx\n * function App() {\n * return (\n * <AuthBoundary header={<MyLogo />}>\n * <ProtectedContent />\n * </AuthBoundary>\n * )\n * }\n * ```\n *\n * @internal\n */\nexport function AuthBoundary({\n LoginErrorComponent = LoginError,\n ...props\n}: AuthBoundaryProps): React.ReactNode {\n const FallbackComponent = useMemo(() => {\n return function LoginComponentWithLayoutProps(fallbackProps: FallbackProps) {\n return <LoginErrorComponent {...fallbackProps} />\n }\n }, [LoginErrorComponent])\n\n return (\n <ComlinkTokenRefreshProvider>\n <ErrorBoundary FallbackComponent={FallbackComponent}>\n <AuthSwitch {...props} />\n </ErrorBoundary>\n </ComlinkTokenRefreshProvider>\n )\n}\n\ninterface AuthSwitchProps {\n LoginComponent?: React.ComponentType<{\n header?: React.ReactNode\n footer?: React.ReactNode\n }>\n CallbackComponent?: React.ComponentType<{\n header?: React.ReactNode\n footer?: React.ReactNode\n }>\n header?: React.ReactNode\n footer?: React.ReactNode\n children?: React.ReactNode\n verifyOrganization?: boolean\n projectIds?: string[]\n}\n\nfunction AuthSwitch({\n CallbackComponent = LoginCallback,\n children,\n verifyOrganization = true,\n projectIds,\n ...props\n}: AuthSwitchProps) {\n const authState = useAuthState()\n const orgError = useVerifyOrgProjects(!verifyOrganization, projectIds)\n\n const isLoggedOut = authState.type === AuthStateType.LOGGED_OUT && !authState.isDestroyingSession\n const loginUrl = useLoginUrl()\n\n useEffect(() => {\n if (isLoggedOut && !isInIframe()) {\n // We don't want to redirect to login if we're in the Dashboard\n window.location.href = loginUrl\n }\n }, [isLoggedOut, loginUrl])\n\n // Only check the error if verification is enabled\n if (verifyOrganization && orgError) {\n throw new ConfigurationError({message: orgError})\n }\n\n switch (authState.type) {\n case AuthStateType.ERROR: {\n throw new AuthError(authState.error)\n }\n case AuthStateType.LOGGING_IN: {\n return <CallbackComponent {...props} />\n }\n case AuthStateType.LOGGED_IN: {\n return children\n }\n case AuthStateType.LOGGED_OUT: {\n return null\n }\n default: {\n // @ts-expect-error - This state should never happen\n throw new Error(`Invalid auth state: ${authState.type}`)\n }\n }\n}\n","import {createSanityInstance, type SanityConfig, type SanityInstance} from '@sanity/sdk'\nimport {Suspense, useContext, useEffect, useMemo, useRef} from 'react'\n\nimport {SanityInstanceContext} from './SanityInstanceContext'\n\nconst DEFAULT_FALLBACK = (\n <>\n Warning: No fallback provided. Please supply a fallback prop to ensure proper Suspense handling.\n </>\n)\n\n/**\n * Props for the ResourceProvider component\n * @internal\n */\nexport interface ResourceProviderProps extends SanityConfig {\n /**\n * React node to show while content is loading\n * Used as the fallback for the internal Suspense boundary\n */\n fallback: React.ReactNode\n children: React.ReactNode\n}\n\n/**\n * Provides a Sanity instance to child components through React Context\n *\n * @internal\n *\n * @remarks\n * The ResourceProvider creates a hierarchical structure of Sanity instances:\n * - When used as a root provider, it creates a new Sanity instance with the given config\n * - When nested inside another ResourceProvider, it creates a child instance that\n * inherits and extends the parent's configuration\n *\n * Features:\n * - Automatically manages the lifecycle of Sanity instances\n * - Disposes instances when the component unmounts\n * - Includes a Suspense boundary for data loading\n * - Enables hierarchical configuration inheritance\n *\n * Use this component to:\n * - Set up project/dataset configuration for an application\n * - Override specific configuration values in a section of your app\n * - Create isolated instance hierarchies for different features\n *\n * @example Creating a root provider\n * ```tsx\n * <ResourceProvider\n * projectId=\"your-project-id\"\n * dataset=\"production\"\n * fallback={<LoadingSpinner />}\n * >\n * <YourApp />\n * </ResourceProvider>\n * ```\n *\n * @example Creating nested providers with configuration inheritance\n * ```tsx\n * // Root provider with production config with nested provider for preview features with custom dataset\n * <ResourceProvider projectId=\"abc123\" dataset=\"production\" fallback={<Loading />}>\n * <div>...Main app content</div>\n * <Dashboard />\n * <ResourceProvider dataset=\"preview\" fallback={<Loading />}>\n * <PreviewFeatures />\n * </ResourceProvider>\n * </ResourceProvider>\n * ```\n */\nexport function ResourceProvider({\n children,\n fallback,\n ...config\n}: ResourceProviderProps): React.ReactNode {\n const parent = useContext(SanityInstanceContext)\n const instance = useMemo(\n () => (parent ? parent.createChild(config) : createSanityInstance(config)),\n [config, parent],\n )\n\n // Ref to hold the scheduled disposal timer.\n const disposal = useRef<{\n instance: SanityInstance\n timeoutId: ReturnType<typeof setTimeout>\n } | null>(null)\n\n useEffect(() => {\n // If the component remounts quickly (as in Strict Mode), cancel any pending disposal.\n if (disposal.current !== null && instance === disposal.current.instance) {\n clearTimeout(disposal.current.timeoutId)\n disposal.current = null\n }\n\n return () => {\n disposal.current = {\n instance,\n timeoutId: setTimeout(() => {\n if (!instance.isDisposed()) {\n instance.dispose()\n }\n }, 0),\n }\n }\n }, [instance])\n\n return (\n <SanityInstanceContext.Provider value={instance}>\n <Suspense fallback={fallback ?? DEFAULT_FALLBACK}>{children}</Suspense>\n </SanityInstanceContext.Provider>\n )\n}\n","import {type SanityConfig} from '@sanity/sdk'\nimport {type ReactElement, type ReactNode} from 'react'\n\nimport {ResourceProvider} from '../context/ResourceProvider'\nimport {AuthBoundary, type AuthBoundaryProps} from './auth/AuthBoundary'\n\n/**\n * @internal\n */\nexport interface SDKProviderProps extends AuthBoundaryProps {\n children: ReactNode\n config: SanityConfig | SanityConfig[]\n fallback: ReactNode\n}\n\n/**\n * @internal\n *\n * Top-level context provider that provides access to the Sanity SDK.\n * Creates a hierarchy of ResourceProviders, each providing a SanityInstance that can be\n * accessed by hooks. The first configuration in the array becomes the default instance.\n */\nexport function SDKProvider({\n children,\n config,\n fallback,\n ...props\n}: SDKProviderProps): ReactElement {\n // reverse because we want the first config to be the default, but the\n // ResourceProvider nesting makes the last one the default\n const configs = (Array.isArray(config) ? config : [config]).slice().reverse()\n const projectIds = configs.map((c) => c.projectId).filter((id): id is string => !!id)\n\n // Create a nested structure of ResourceProviders for each config\n const createNestedProviders = (index: number): ReactElement => {\n if (index >= configs.length) {\n return (\n <AuthBoundary {...props} projectIds={projectIds}>\n {children}\n </AuthBoundary>\n )\n }\n\n return (\n <ResourceProvider {...configs[index]} fallback={fallback}>\n {createNestedProviders(index + 1)}\n </ResourceProvider>\n )\n }\n\n return createNestedProviders(0)\n}\n","import {type SanityConfig} from '@sanity/sdk'\nimport {type ReactElement, useEffect} from 'react'\n\nimport {SDKProvider} from './SDKProvider'\nimport {isInIframe, isLocalUrl} from './utils'\n\n/**\n * @public\n * @category Types\n */\nexport interface SanityAppProps {\n /* One or more SanityConfig objects providing a project ID and dataset name */\n config: SanityConfig | SanityConfig[]\n /** @deprecated use the `config` prop instead. */\n sanityConfigs?: SanityConfig[]\n children: React.ReactNode\n /* Fallback content to show when child components are suspending. Same as the `fallback` prop for React Suspense. */\n fallback: React.ReactNode\n}\n\nconst REDIRECT_URL = 'https://sanity.io/welcome'\n\n/**\n * @public\n *\n * The SanityApp component provides your Sanity application with access to your Sanity configuration,\n * as well as application context and state which is used by the Sanity React hooks. Your application\n * must be wrapped with the SanityApp component to function properly.\n *\n * The `config` prop on the SanityApp component accepts either a single {@link SanityConfig} object, or an array of them.\n * This allows your app to work with one or more of your organization’s datasets.\n *\n * @remarks\n * When passing multiple SanityConfig objects to the `config` prop, the first configuration in the array becomes the default\n * configuration used by the App SDK Hooks.\n *\n * @category Components\n * @param props - Your Sanity configuration and the React children to render\n * @returns Your Sanity application, integrated with your Sanity configuration and application context\n *\n * @example\n * ```tsx\n * import { SanityApp, type SanityConfig } from '@sanity/sdk-react'\n *\n * import MyAppRoot from './Root'\n *\n * // Single project configuration\n * const mySanityConfig: SanityConfig = {\n * projectId: 'my-project-id',\n * dataset: 'production',\n * }\n *\n * // Or multiple project configurations\n * const multipleConfigs: SanityConfig[] = [\n * // Configuration for your main project. This will be used as the default project for hooks.\n * {\n * projectId: 'marketing-website-project',\n * dataset: 'production',\n * },\n * // Configuration for a separate blog project\n * {\n * projectId: 'blog-project',\n * dataset: 'production',\n * },\n * // Configuration for a separate ecommerce project\n * {\n * projectId: 'ecommerce-project',\n * dataset: 'production',\n * }\n * ]\n *\n * export default function MyApp() {\n * return (\n * <SanityApp config={mySanityConfig} fallback={<div>Loading…</div>}>\n * <MyAppRoot />\n * </SanityApp>\n * )\n * }\n * ```\n */\nexport function SanityApp({\n children,\n fallback,\n config = [],\n ...props\n}: SanityAppProps): ReactElement {\n useEffect(() => {\n let timeout: NodeJS.Timeout | undefined\n const primaryConfig = Array.isArray(config) ? config[0] : config\n\n if (!isInIframe() && !isLocalUrl(window) && !primaryConfig?.studioMode?.enabled) {\n // If the app is not running in an iframe and is not a local url, redirect to core.\n timeout = setTimeout(() => {\n // eslint-disable-next-line no-console\n console.warn('Redirecting to core', REDIRECT_URL)\n window.location.replace(REDIRECT_URL)\n }, 1000)\n }\n return () => clearTimeout(timeout)\n }, [config])\n\n return (\n <SDKProvider {...props} fallback={fallback} config={config}>\n {children}\n </SDKProvider>\n )\n}\n","import {getTokenState} from '@sanity/sdk'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\n/**\n * Hook to get the currently logged in user\n * @internal\n * @returns The current user or null if not authenticated\n */\nexport const useAuthToken = createStateSourceHook(getTokenState)\n","import {type CurrentUser, getCurrentUserState} from '@sanity/sdk'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\ntype UseCurrentUser = {\n /**\n * @public\n *\n * Provides the currently authenticated user’s profile information.\n *\n * @category Users\n * @returns The current user data\n *\n * @example Rendering a basic user profile\n * ```\n * const user = useCurrentUser()\n *\n * return (\n * <figure>\n * <img src={user?.profileImage} alt=`Profile image for ${user?.name}` />\n * <h2>{user?.name}</h2>\n * </figure>\n * )\n * ```\n */\n (): CurrentUser | null\n}\n\n/**\n * @public\n * @function\n * @TODO This should not return null — users of a custom app will always be authenticated via Core\n */\nexport const useCurrentUser: UseCurrentUser = createStateSourceHook(getCurrentUserState)\n","import {getDashboardOrganizationId} from '@sanity/sdk'\nimport {useMemo, useSyncExternalStore} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * @public\n *\n * A React hook that retrieves the dashboard organization ID that is currently selected in the Sanity Dashboard.\n *\n * @example\n * ```tsx\n * function DashboardComponent() {\n * const orgId = useDashboardOrganizationId()\n *\n * if (!orgId) return null\n *\n * return <div>Organization ID: {String(orgId)}</div>\n * }\n * ```\n *\n * @category Dashboard\n * @returns The dashboard organization ID (string | undefined)\n */\nexport function useDashboardOrganizationId(): string | undefined {\n const instance = useSanityInstance()\n const {subscribe, getCurrent} = useMemo(() => getDashboardOrganizationId(instance), [instance])\n\n return useSyncExternalStore(subscribe, getCurrent)\n}\n","import {getClientState} from '@sanity/sdk'\nimport {identity} from 'rxjs'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\n/**\n * A React hook that provides a client that subscribes to changes in your application,\n *\n * @remarks\n * This hook is intended for advanced use cases and special API calls that the React SDK\n * does not yet provide hooks for. We welcome you to get in touch with us to let us know\n * your use cases for this!\n *\n * @category Platform\n * @returns A Sanity client\n *\n * @example\n * ```tsx\n * function MyComponent() {\n * const client = useClient({apiVersion: '2024-11-12'})\n * const [document, setDocument] = useState(null)\n * useEffect(async () => {\n * const doc = client.fetch('*[_id == \"myDocumentId\"]')\n * setDocument(doc)\n * }, [])\n * return <div>{JSON.stringify(document) ?? 'Loading...'}</div>\n * }\n * ```\n *\n * @public\n * @function\n */\nexport const useClient = createStateSourceHook({\n getState: getClientState,\n getConfig: identity,\n})\n","import {type ChannelInstance, type Controller, type Status} from '@sanity/comlink'\nimport {\n type FrameMessage,\n getOrCreateChannel,\n getOrCreateController,\n releaseChannel,\n type WindowMessage,\n} from '@sanity/sdk'\nimport {useCallback, useEffect, useRef} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * @internal\n */\nexport type FrameMessageHandler<TWindowMessage extends WindowMessage> = (\n event: TWindowMessage['data'],\n) => TWindowMessage['response'] | Promise<TWindowMessage['response']>\n\n/**\n * @internal\n */\nexport interface UseFrameConnectionOptions<TWindowMessage extends WindowMessage> {\n name: string\n connectTo: string\n targetOrigin: string\n onMessage?: {\n [K in TWindowMessage['type']]: (data: Extract<TWindowMessage, {type: K}>['data']) => void\n }\n heartbeat?: boolean\n onStatus?: (status: Status) => void\n}\n\n/**\n * @internal\n */\nexport interface FrameConnection<TFrameMessage extends FrameMessage> {\n connect: (frameWindow: Window) => () => void // Return cleanup function\n sendMessage: <T extends TFrameMessage['type']>(\n ...params: Extract<TFrameMessage, {type: T}>['data'] extends undefined\n ? [type: T]\n : [type: T, data: Extract<TFrameMessage, {type: T}>['data']]\n ) => void\n}\n\n/**\n * @internal\n */\nexport function useFrameConnection<\n TFrameMessage extends FrameMessage,\n TWindowMessage extends WindowMessage,\n>(options: UseFrameConnectionOptions<TWindowMessage>): FrameConnection<TFrameMessage> {\n const {onMessage, targetOrigin, name, connectTo, heartbeat, onStatus} = options\n const instance = useSanityInstance()\n const controllerRef = useRef<Controller | null>(null)\n const channelRef = useRef<ChannelInstance<TFrameMessage, TWindowMessage> | null>(null)\n\n useEffect(() => {\n const controller = getOrCreateController(instance, targetOrigin)\n const channel = getOrCreateChannel(instance, {name, connectTo, heartbeat})\n controllerRef.current = controller\n channelRef.current = channel\n\n channel.onStatus((event) => {\n onStatus?.(event.status)\n })\n\n const messageUnsubscribers: Array<() => void> = []\n\n if (onMessage) {\n Object.entries(onMessage).forEach(([type, handler]) => {\n const unsubscribe = channel.on(type, handler as FrameMessageHandler<TWindowMessage>)\n messageUnsubscribers.push(unsubscribe)\n })\n }\n\n return () => {\n // Clean up all subscriptions and stop controller/channel\n messageUnsubscribers.forEach((unsub) => unsub())\n releaseChannel(instance, name)\n channelRef.current = null\n controllerRef.current = null\n }\n }, [targetOrigin, name, connectTo, heartbeat, onMessage, instance, onStatus])\n\n const connect = useCallback((frameWindow: Window) => {\n const removeTarget = controllerRef.current?.addTarget(frameWindow)\n return () => {\n removeTarget?.()\n }\n }, [])\n\n const sendMessage = useCallback(\n <T extends TFrameMessage['type']>(\n type: T,\n data?: Extract<TFrameMessage, {type: T}>['data'],\n ) => {\n channelRef.current?.post(type, data)\n },\n [],\n )\n\n return {\n connect,\n sendMessage,\n }\n}\n","import {type PathChangeMessage, SDK_CHANNEL_NAME, SDK_NODE_NAME} from '@sanity/message-protocol'\n\nimport {useWindowConnection} from '../comlink/useWindowConnection'\n\n/**\n * @public\n *\n * A helper hook designed to be injected into routing components for apps within the Dashboard.\n * While the Dashboard can usually handle navigation, there are special cases when you\n * are already within a target app, and need to navigate to another route inside of that app.\n *\n * For example, your user might \"favorite\" a document inside of your application.\n * If they click on the Dashboard favorites item in the sidebar, and are already within your application,\n * there needs to be some way for the dashboard to signal to your application to reroute to where that document was favorited.\n *\n * This hook is intended to receive those messages, and takes a function to route to the correct path.\n *\n * @param navigateFn - Function to handle navigation; should accept:\n * - `path`: a string, which will be a relative path (for example, 'my-route')\n * - `type`: 'push', 'replace', or 'pop', which will be the type of navigation to perform\n *\n * @example\n * ```tsx\n * import {useDashboardNavigate} from '@sanity/sdk-react'\n * import {BrowserRouter, useNavigate} from 'react-router'\n * import {Suspense} from 'react'\n *\n * function DashboardNavigationHandler() {\n * const navigate = useNavigate()\n * useDashboardNavigate(({path, type}) => {\n * navigate(path, {replace: type === 'replace'})\n * })\n * return null\n * }\n *\n * // Wrap the component with Suspense since the hook may suspend\n * function MyApp() {\n * return (\n * <BrowserRouter>\n * <Suspense>\n * <DashboardNavigationHandler />\n * </Suspense>\n * </BrowserRouter>\n * )\n * }\n * ```\n */\nexport function useDashboardNavigate(\n navigateFn: (options: PathChangeMessage['data']) => void,\n): void {\n useWindowConnection<PathChangeMessage, never>({\n name: SDK_NODE_NAME,\n connectTo: SDK_CHANNEL_NAME,\n onMessage: {\n 'dashboard/v1/history/change-path': (data: PathChangeMessage['data']) => {\n navigateFn(data)\n },\n },\n })\n}\n","import {\n type CanvasResource,\n type Events,\n type MediaResource,\n SDK_CHANNEL_NAME,\n SDK_NODE_NAME,\n type StudioResource,\n} from '@sanity/message-protocol'\nimport {\n type DocumentHandle,\n type FavoriteStatusResponse,\n type FrameMessage,\n getFavoritesState,\n resolveFavoritesState,\n} from '@sanity/sdk'\nimport {useCallback, useMemo, useSyncExternalStore} from 'react'\n\nimport {useWindowConnection} from '../comlink/useWindowConnection'\nimport {useSanityInstance} from '../context/useSanityInstance'\n\ninterface ManageFavorite extends FavoriteStatusResponse {\n favorite: () => Promise<void>\n unfavorite: () => Promise<void>\n isFavorited: boolean\n}\n\ninterface UseManageFavoriteProps extends DocumentHandle {\n resourceId?: string\n resourceType: StudioResource['type'] | MediaResource['type'] | CanvasResource['type']\n /**\n * The name of the schema collection this document belongs to.\n * Typically is the name of the workspace when used in the context of a studio.\n */\n schemaName?: string\n}\n\n/**\n * @internal\n *\n * This hook provides functionality to add and remove documents from favorites,\n * and tracks the current favorite status of the document.\n * @param documentHandle - The document handle containing document ID and type, like `{_id: '123', _type: 'book'}`\n * @returns An object containing:\n * - `favorite` - Function to add document to favorites\n * - `unfavorite` - Function to remove document from favorites\n * - `isFavorited` - Boolean indicating if document is currently favorited\n *\n * @example\n * ```tsx\n * function FavoriteButton(props: DocumentActionProps) {\n * const {documentId, documentType} = props\n * const {favorite, unfavorite, isFavorited} = useManageFavorite({\n * documentId,\n * documentType\n * })\n *\n * return (\n * <Button\n * onClick={() => isFavorited ? unfavorite() : favorite()}\n * text={isFavorited ? 'Remove from favorites' : 'Add to favorites'}\n * />\n * )\n * }\n *\n * // Wrap the component with Suspense since the hook may suspend\n * function MyDocumentAction(props: DocumentActionProps) {\n * return (\n * <Suspense\n * fallback={\n * <Button\n * text=\"Loading...\"\n * disabled\n * />\n * }\n * >\n * <FavoriteButton {...props} />\n * </Suspense>\n * )\n * }\n * ```\n */\nexport function useManageFavorite({\n documentId,\n documentType,\n projectId: paramProjectId,\n dataset: paramDataset,\n resourceId: paramResourceId,\n resourceType,\n schemaName,\n}: UseManageFavoriteProps): ManageFavorite {\n const {fetch} = useWindowConnection<Events.FavoriteMessage, FrameMessage>({\n name: SDK_NODE_NAME,\n connectTo: SDK_CHANNEL_NAME,\n })\n const instance = useSanityInstance()\n const {config} = instance\n const instanceProjectId = config?.projectId\n const instanceDataset = config?.dataset\n const projectId = paramProjectId ?? instanceProjectId\n const dataset = paramDataset ?? instanceDataset\n\n if (resourceType === 'studio' && (!projectId || !dataset)) {\n throw new Error('projectId and dataset are required for studio resources')\n }\n // Compute the final resourceId\n const resourceId =\n resourceType === 'studio' && !paramResourceId ? `${projectId}.${dataset}` : paramResourceId\n\n if (!resourceId) {\n throw new Error('resourceId is required for media-library and canvas resources')\n }\n\n // used for favoriteStore functions like getFavoritesState and resolveFavoritesState\n const context = useMemo(\n () => ({\n documentId,\n documentType,\n resourceId,\n resourceType,\n schemaName,\n }),\n [documentId, documentType, resourceId, resourceType, schemaName],\n )\n\n // Get favorite status using StateSource\n const favoriteState = getFavoritesState(instance, context)\n const state = useSyncExternalStore(favoriteState.subscribe, favoriteState.getCurrent)\n\n const isFavorited = state?.isFavorited ?? false\n\n const handleFavoriteAction = useCallback(\n async (action: 'added' | 'removed') => {\n if (!fetch || !documentId || !documentType || !resourceType) return\n\n try {\n const payload = {\n eventType: action,\n document: {\n id: documentId,\n type: documentType,\n resource: {\n ...{\n id: resourceId,\n type: resourceType,\n },\n ...(schemaName ? {schemaName} : {}),\n },\n },\n }\n\n const res = await fetch<{success: boolean}>('dashboard/v1/events/favorite/mutate', payload)\n if (res.success) {\n // Force a re-fetch of the favorite status after successful mutation\n await resolveFavoritesState(instance, context)\n }\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(`Failed to ${action === 'added' ? 'favorite' : 'unfavorite'} document:`, err)\n throw err\n }\n },\n [fetch, documentId, documentType, resourceId, resourceType, schemaName, instance, context],\n )\n\n const favorite = useCallback(() => handleFavoriteAction('added'), [handleFavoriteAction])\n const unfavorite = useCallback(() => handleFavoriteAction('removed'), [handleFavoriteAction])\n\n return {\n favorite,\n unfavorite,\n isFavorited,\n }\n}\n","import {SDK_CHANNEL_NAME, SDK_NODE_NAME} from '@sanity/message-protocol'\nimport {useEffect, useState} from 'react'\n\nimport {useWindowConnection} from '../comlink/useWindowConnection'\n\nexport interface DashboardResource {\n id: string\n name: string\n title: string\n basePath: string\n projectId: string\n dataset: string\n type: string\n userApplicationId: string\n url: string\n}\n\ninterface WorkspacesByProjectIdDataset {\n [key: `${string}:${string}`]: DashboardResource[] // key format: `${projectId}:${dataset}`\n}\n\ninterface StudioWorkspacesResult {\n workspacesByProjectIdAndDataset: WorkspacesByProjectIdDataset\n error: string | null\n}\n\n/**\n * Hook that fetches studio workspaces and organizes them by projectId:dataset\n * @internal\n *\n * @example\n * ```tsx\n * import {useStudioWorkspacesByProjectIdDataset} from '@sanity/sdk-react'\n * import {Card, Code, Button} from '@sanity/ui'\n * import {Suspense} from 'react'\n *\n * function WorkspacesCard() {\n * const {workspacesByProjectIdAndDataset, error} = useStudioWorkspacesByProjectIdDataset()\n * if (error) {\n * return <div>Error: {error}</div>\n * }\n * return (\n * <Card padding={4} radius={2} shadow={1}>\n * <Code language=\"json\">\n * {JSON.stringify(workspacesByProjectIdAndDataset, null, 2)}\n * </Code>\n * </Card>\n * )\n * }\n *\n * // Wrap the component with Suspense since the hook may suspend\n * function DashboardWorkspaces() {\n * return (\n * <Suspense fallback={<Button text=\"Loading...\" disabled />}>\n * <WorkspacesCard />\n * </Suspense>\n * )\n * }\n * ```\n */\nexport function useStudioWorkspacesByProjectIdDataset(): StudioWorkspacesResult {\n const [workspacesByProjectIdAndDataset, setWorkspacesByProjectIdAndDataset] =\n useState<WorkspacesByProjectIdDataset>({})\n const [error, setError] = useState<string | null>(null)\n\n const {fetch} = useWindowConnection({\n name: SDK_NODE_NAME,\n connectTo: SDK_CHANNEL_NAME,\n })\n\n // Once computed, this should probably be in a store and poll for changes\n // However, our stores are currently being refactored\n useEffect(() => {\n if (!fetch) return\n\n async function fetchWorkspaces(signal: AbortSignal) {\n try {\n const data = await fetch<{\n context: {availableResources: Array<DashboardResource>}\n }>('dashboard/v1/context', undefined, {signal})\n\n const workspaceMap: WorkspacesByProjectIdDataset = {}\n const noProjectIdAndDataset: DashboardResource[] = []\n\n data.context.availableResources.forEach((resource) => {\n if (resource.type !== 'studio') return\n if (!resource.projectId || !resource.dataset) {\n noProjectIdAndDataset.push(resource)\n return\n }\n const key = `${resource.projectId}:${resource.dataset}` as const\n if (!workspaceMap[key]) {\n workspaceMap[key] = []\n }\n workspaceMap[key].push(resource)\n })\n\n if (noProjectIdAndDataset.length > 0) {\n workspaceMap['NO_PROJECT_ID:NO_DATASET'] = noProjectIdAndDataset\n }\n\n setWorkspacesByProjectIdAndDataset(workspaceMap)\n setError(null)\n } catch (err: unknown) {\n if (err instanceof Error) {\n if (err.name === 'AbortError') {\n return\n }\n setError('Failed to fetch workspaces')\n }\n }\n }\n\n const controller = new AbortController()\n fetchWorkspaces(controller.signal)\n\n return () => {\n controller.abort()\n }\n }, [fetch])\n\n return {\n workspacesByProjectIdAndDataset,\n error,\n }\n}\n","import {type Bridge, SDK_CHANNEL_NAME, SDK_NODE_NAME} from '@sanity/message-protocol'\nimport {type DocumentHandle} from '@sanity/sdk'\nimport {useCallback} from 'react'\n\nimport {useWindowConnection} from '../comlink/useWindowConnection'\nimport {\n type DashboardResource,\n useStudioWorkspacesByProjectIdDataset,\n} from './useStudioWorkspacesByProjectIdDataset'\n\n/**\n * @public\n * @category Types\n */\nexport interface NavigateToStudioResult {\n navigateToStudioDocument: () => void\n}\n\n/**\n * @public\n *\n * Hook that provides a function to navigate to a given document in its parent Studio.\n *\n * Uses the `projectId` and `dataset` properties of the {@link DocumentHandle} you provide to resolve the correct Studio.\n * This will only work if you have deployed a studio with a workspace with this `projectId` / `dataset` combination.\n *\n * @remarks If you write your own Document Handle to pass to this hook (as opposed to a Document Handle generated by another hook),\n * it must include values for `documentId`, `documentType`, `projectId`, and `dataset`.\n *\n * @category Documents\n * @param documentHandle - The document handle for the document to navigate to\n * @param preferredStudioUrl - The preferred studio url to navigate to if you have multiple\n * studios with the same projectId and dataset\n * @returns An object containing:\n * - `navigateToStudioDocument` - Function that when called will navigate to the studio document\n *\n * @example\n * ```tsx\n * import {useNavigateToStudioDocument, type DocumentHandle} from '@sanity/sdk-react'\n * import {Button} from '@sanity/ui'\n * import {Suspense} from 'react'\n *\n * function NavigateButton({documentHandle}: {documentHandle: DocumentHandle}) {\n * const {navigateToStudioDocument} = useNavigateToStudioDocument(documentHandle)\n * return (\n * <Button\n * onClick={navigateToStudioDocument}\n * text=\"Navigate to Studio Document\"\n * />\n * )\n * }\n *\n * // Wrap the component with Suspense since the hook may suspend\n * function MyDocumentAction({documentHandle}: {documentHandle: DocumentHandle}) {\n * return (\n * <Suspense fallback={<Button text=\"Loading...\" disabled />}>\n * <NavigateButton documentHandle={documentHandle} />\n * </Suspense>\n * )\n * }\n * ```\n */\nexport function useNavigateToStudioDocument(\n documentHandle: DocumentHandle,\n preferredStudioUrl?: string,\n): NavigateToStudioResult {\n const {workspacesByProjectIdAndDataset} = useStudioWorkspacesByProjectIdDataset()\n const {sendMessage} = useWindowConnection<Bridge.Navigation.NavigateToResourceMessage, never>({\n name: SDK_NODE_NAME,\n connectTo: SDK_CHANNEL_NAME,\n })\n\n const navigateToStudioDocument = useCallback(() => {\n const {projectId, dataset} = documentHandle\n\n if (!projectId || !dataset) {\n // eslint-disable-next-line no-console\n console.warn('Project ID and dataset are required to navigate to a studio document')\n return\n }\n\n let workspace: DashboardResource | undefined\n\n if (preferredStudioUrl) {\n // Get workspaces matching the projectId:dataset and any workspaces without projectId/dataset,\n // in case there hasn't been a manifest loaded yet\n const allWorkspaces = [\n ...(workspacesByProjectIdAndDataset[`${projectId}:${dataset}`] || []),\n ...(workspacesByProjectIdAndDataset['NO_PROJECT_ID:NO_DATASET'] || []),\n ]\n workspace = allWorkspaces.find((w) => w.url === preferredStudioUrl)\n } else {\n const workspaces = workspacesByProjectIdAndDataset[`${projectId}:${dataset}`]\n if (workspaces?.length > 1) {\n // eslint-disable-next-line no-console\n console.warn(\n 'Multiple workspaces found for document and no preferred studio url',\n documentHandle,\n )\n // eslint-disable-next-line no-console\n console.warn('Using the first one', workspaces[0])\n }\n\n workspace = workspaces?.[0]\n }\n\n if (!workspace) {\n // eslint-disable-next-line no-console\n console.warn(\n `No workspace found for document with projectId: ${projectId} and dataset: ${dataset}${preferredStudioUrl ? ` or with preferred studio url: ${preferredStudioUrl}` : ''}`,\n )\n return\n }\n\n const message: Bridge.Navigation.NavigateToResourceMessage = {\n type: 'dashboard/v1/bridge/navigate-to-resource',\n data: {\n resourceId: workspace.id,\n resourceType: 'studio',\n path: `/intent/edit/id=${documentHandle.documentId};type=${documentHandle.documentType}`,\n },\n }\n\n sendMessage(message.type, message.data)\n }, [documentHandle, workspacesByProjectIdAndDataset, sendMessage, preferredStudioUrl])\n\n return {\n navigateToStudioDocument,\n }\n}\n","import {\n type CanvasResource,\n type Events,\n type MediaResource,\n SDK_CHANNEL_NAME,\n SDK_NODE_NAME,\n type StudioResource,\n} from '@sanity/message-protocol'\nimport {type DocumentHandle, type FrameMessage} from '@sanity/sdk'\nimport {useCallback} from 'react'\n\nimport {useWindowConnection} from '../comlink/useWindowConnection'\n\ninterface DocumentInteractionHistory {\n recordEvent: (eventType: 'viewed' | 'edited' | 'created' | 'deleted') => void\n}\n\n/**\n * @internal\n */\ninterface UseRecordDocumentHistoryEventProps extends DocumentHandle {\n resourceType: StudioResource['type'] | MediaResource['type'] | CanvasResource['type']\n resourceId?: string\n /**\n * The name of the schema collection this document belongs to.\n * Typically is the name of the workspace when used in the context of a studio.\n */\n schemaName?: string\n}\n\n/**\n * @internal\n * Hook for managing document interaction history in Sanity Studio.\n * This hook provides functionality to record document interactions.\n * @category History\n * @param documentHandle - The document handle containing document ID and type, like `{_id: '123', _type: 'book'}`\n * @returns An object containing:\n * - `recordEvent` - Function to record document interactions\n *\n * @example\n * ```tsx\n * import {useRecordDocumentHistoryEvent} from '@sanity/sdk-react'\n * import {Button} from '@sanity/ui'\n * import {Suspense} from 'react'\n *\n * function RecordEventButton(props: DocumentActionProps) {\n * const {documentId, documentType, resourceType, resourceId} = props\n * const {recordEvent} = useRecordDocumentHistoryEvent({\n * documentId,\n * documentType,\n * resourceType,\n * resourceId,\n * })\n * return (\n * <Button\n * onClick={() => recordEvent('viewed')}\n * text=\"Viewed\"\n * />\n * )\n * }\n *\n * // Wrap the component with Suspense since the hook may suspend\n * function MyDocumentAction(props: DocumentActionProps) {\n * return (\n * <Suspense fallback={<Button text=\"Loading...\" disabled />}>\n * <RecordEventButton {...props} />\n * </Suspense>\n * )\n * }\n * ```\n */\nexport function useRecordDocumentHistoryEvent({\n documentId,\n documentType,\n resourceType,\n resourceId,\n schemaName,\n}: UseRecordDocumentHistoryEventProps): DocumentInteractionHistory {\n const {sendMessage} = useWindowConnection<Events.HistoryMessage, FrameMessage>({\n name: SDK_NODE_NAME,\n connectTo: SDK_CHANNEL_NAME,\n })\n\n if (resourceType !== 'studio' && !resourceId) {\n throw new Error('resourceId is required for media-library and canvas resources')\n }\n\n const recordEvent = useCallback(\n (eventType: 'viewed' | 'edited' | 'created' | 'deleted') => {\n try {\n const message: Events.HistoryMessage = {\n type: 'dashboard/v1/events/history',\n data: {\n eventType,\n document: {\n id: documentId,\n type: documentType,\n resource: {\n id: resourceId!,\n type: resourceType,\n schemaName,\n },\n },\n },\n }\n\n sendMessage(message.type, message.data)\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error('Failed to record history event:', error)\n throw error\n }\n },\n [documentId, documentType, resourceId, resourceType, sendMessage, schemaName],\n )\n\n return {\n recordEvent,\n }\n}\n","import {type DatasetsResponse} from '@sanity/client'\nimport {\n getDatasetsState,\n type ProjectHandle,\n resolveDatasets,\n type SanityInstance,\n type StateSource,\n} from '@sanity/sdk'\nimport {identity} from 'rxjs'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\ntype UseDatasets = {\n /**\n *\n * Returns metadata for each dataset the current user has access to.\n *\n * @category Datasets\n * @returns The metadata for your the datasets\n *\n * @example\n * ```tsx\n * const datasets = useDatasets()\n *\n * return (\n * <select>\n * {datasets.map((dataset) => (\n * <option key={dataset.name}>{dataset.name}</option>\n * ))}\n * </select>\n * )\n * ```\n *\n */\n (): DatasetsResponse\n}\n\n/**\n * @public\n * @function\n */\nexport const useDatasets: UseDatasets = createStateSourceHook({\n getState: getDatasetsState as (\n instance: SanityInstance,\n projectHandle?: ProjectHandle,\n ) => StateSource<DatasetsResponse>,\n shouldSuspend: (instance, projectHandle?: ProjectHandle) =>\n // remove `undefined` since we're suspending when that is the case\n getDatasetsState(instance, projectHandle).getCurrent() === undefined,\n suspender: resolveDatasets,\n getConfig: identity as (projectHandle?: ProjectHandle) => ProjectHandle,\n})\n","import {\n type ActionsResult,\n applyDocumentActions,\n type ApplyDocumentActionsOptions,\n type DocumentAction,\n} from '@sanity/sdk'\nimport {type SanityDocument} from 'groq'\n\nimport {createCallbackHook} from '../helpers/createCallbackHook'\n// this import is used in an `{@link useEditDocument}`\n// eslint-disable-next-line unused-imports/no-unused-imports, import/consistent-type-specifier-style\nimport type {useEditDocument} from './useEditDocument'\n\n/**\n * @public\n */\ninterface UseApplyDocumentActions {\n (): <\n TDocumentType extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n >(\n action:\n | DocumentAction<TDocumentType, TDataset, TProjectId>\n | DocumentAction<TDocumentType, TDataset, TProjectId>[],\n options?: ApplyDocumentActionsOptions,\n ) => Promise<ActionsResult<SanityDocument<TDocumentType, `${TProjectId}.${TDataset}`>>>\n}\n\n/**\n * @public\n *\n * Provides a stable callback function for applying one or more document actions.\n *\n * This hook wraps the core `applyDocumentActions` functionality from `@sanity/sdk`,\n * integrating it with the React component lifecycle and {@link SanityInstance}.\n * It allows you to apply actions generated by functions like `createDocument`,\n * `editDocument`, `deleteDocument`, `publishDocument`, `unpublishDocument`,\n * and `discardDocument` to documents.\n *\n * Features:\n * - Applies one or multiple `DocumentAction` objects.\n * - Supports optimistic updates: Local state reflects changes immediately.\n * - Handles batching: Multiple actions passed together are sent as a single atomic transaction.\n * - Integrates with the collaborative editing engine for conflict resolution and state synchronization.\n *\n * @category Documents\n * @returns A stable callback function. When called with a single `DocumentAction` or an array of `DocumentAction`s,\n * it returns a promise that resolves to an {@link ActionsResult}. The `ActionsResult` contains information about the\n * outcome, including optimistic results if applicable.\n *\n * @remarks\n * This hook is a fundamental part of interacting with document state programmatically.\n * It operates within the same unified pipeline as other document hooks like `useDocument` (for reading state)\n * and {@link useEditDocument} (a higher-level hook specifically for edits).\n *\n * When multiple actions are provided in a single call, they are guaranteed to be submitted\n * as a single transaction to Content Lake. This ensures atomicity for related operations (e.g., creating and publishing a document).\n *\n * @function\n *\n * @example Publish or unpublish a document\n * ```tsx\n * import {\n * publishDocument,\n * unpublishDocument,\n * useApplyDocumentActions,\n * type DocumentHandle\n * } from '@sanity/sdk-react'\n *\n * // Define props using the DocumentHandle type\n * interface PublishControlsProps {\n * doc: DocumentHandle\n * }\n *\n * function PublishControls({doc}: PublishControlsProps) {\n * const apply = useApplyDocumentActions()\n *\n * const handlePublish = () => apply(publishDocument(doc))\n * const handleUnpublish = () => apply(unpublishDocument(doc))\n *\n * return (\n * <>\n * <button onClick={handlePublish}>Publish</button>\n * <button onClick={handleUnpublish}>Unpublish</button>\n * </>\n * )\n * }\n * ```\n *\n * @example Create and publish a new document\n * ```tsx\n * import {\n * createDocument,\n * publishDocument,\n * createDocumentHandle,\n * useApplyDocumentActions\n * } from '@sanity/sdk-react'\n *\n * function CreateAndPublishButton({documentType}: {documentType: string}) {\n * const apply = useApplyDocumentActions()\n *\n * const handleCreateAndPublish = () => {\n * // Create a new handle inside the handler\n * const newDocHandle = createDocumentHandle({ documentId: crypto.randomUUID(), documentType })\n *\n * // Apply multiple actions for the new handle as a single transaction\n * apply([\n * createDocument(newDocHandle),\n * publishDocument(newDocHandle),\n * ])\n * }\n *\n * return (\n * <button onClick={handleCreateAndPublish}>\n * I'm feeling lucky\n * </button>\n * )\n * }\n * ```\n */\nexport const useApplyDocumentActions = createCallbackHook(\n applyDocumentActions,\n) as UseApplyDocumentActions\n","import {type DocumentOptions, getDocumentState, type JsonMatch, resolveDocument} from '@sanity/sdk'\nimport {type SanityDocument} from 'groq'\nimport {identity} from 'rxjs'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n// used in an `{@link useDocumentProjection}` and `{@link useQuery}`\n// eslint-disable-next-line import/consistent-type-specifier-style, unused-imports/no-unused-imports\nimport type {useDocumentProjection} from '../projection/useDocumentProjection'\n// eslint-disable-next-line import/consistent-type-specifier-style, unused-imports/no-unused-imports\nimport type {useQuery} from '../query/useQuery'\n\nconst useDocumentValue = createStateSourceHook({\n // Pass options directly to getDocumentState\n getState: (instance, options: DocumentOptions<string | undefined>) =>\n getDocumentState(instance, options),\n // Pass options directly to getDocumentState for checking current value\n shouldSuspend: (instance, {path: _path, ...options}: DocumentOptions<string | undefined>) =>\n getDocumentState(instance, options).getCurrent() === undefined,\n // Extract handle part for resolveDocument\n suspender: (instance, options: DocumentOptions<string | undefined>) =>\n resolveDocument(instance, options),\n getConfig: identity as (\n options: DocumentOptions<string | undefined>,\n ) => DocumentOptions<string | undefined>,\n})\n\nconst wrapHookWithData = <TParams extends unknown[], TReturn>(\n useValue: (...params: TParams) => TReturn,\n) => {\n function useHook(...params: TParams) {\n return {data: useValue(...params)}\n }\n return useHook\n}\n\ninterface UseDocument {\n /** @internal */\n <TDocumentType extends string, TDataset extends string, TProjectId extends string = string>(\n options: DocumentOptions<undefined, TDocumentType, TDataset, TProjectId>,\n ): {data: SanityDocument<TDocumentType, `${TProjectId}.${TDataset}`> | null}\n\n /** @internal */\n <\n TPath extends string,\n TDocumentType extends string,\n TDataset extends string = string,\n TProjectId extends string = string,\n >(\n options: DocumentOptions<TPath, TDocumentType, TDataset, TProjectId>,\n ): {\n data: JsonMatch<SanityDocument<TDocumentType, `${TProjectId}.${TDataset}`>, TPath> | undefined\n }\n\n /** @internal */\n <TData>(options: DocumentOptions<undefined>): {data: TData | null}\n /** @internal */\n <TData>(options: DocumentOptions<string>): {data: TData | undefined}\n\n /**\n * ## useDocument via Type Inference (Recommended)\n *\n * @public\n *\n * The preferred way to use this hook when working with Sanity Typegen.\n *\n * Features:\n * - Automatically infers document types from your schema\n * - Provides type-safe access to documents and nested fields\n * - Supports project/dataset-specific type inference\n * - Works seamlessly with Typegen-generated types\n *\n * This hook will suspend while the document data is being fetched and loaded.\n *\n * When fetching a full document:\n * - Returns the complete document object if it exists\n * - Returns `null` if the document doesn't exist\n *\n * When fetching with a path:\n * - Returns the value at the specified path if both the document and path exist\n * - Returns `undefined` if either the document doesn't exist or the path doesn't exist in the document\n *\n * @category Documents\n * @param options - Configuration including `documentId`, `documentType`, and optionally:\n * - `path`: To select a nested value (returns typed value at path)\n * - `projectId`/`dataset`: For multi-project/dataset setups\n * @returns The document state (or nested value if path provided).\n *\n * @example Basic document fetch\n * ```tsx\n * import {useDocument, type DocumentHandle} from '@sanity/sdk-react'\n *\n * interface ProductViewProps {\n * doc: DocumentHandle<'product'> // Typegen infers product type\n * }\n *\n * function ProductView({doc}: ProductViewProps) {\n * const {data: product} = useDocument({...doc}) // Fully typed product\n * return <h1>{product.title ?? 'Untitled'}</h1>\n * }\n * ```\n *\n * @example Fetching a specific field\n * ```tsx\n * import {useDocument, type DocumentHandle} from '@sanity/sdk-react'\n *\n * interface ProductTitleProps {\n * doc: DocumentHandle<'product'>\n * }\n *\n * function ProductTitle({doc}: ProductTitleProps) {\n * const {data: title} = useDocument({\n * ...doc,\n * path: 'title' // Returns just the title field\n * })\n * return <h1>{title ?? 'Untitled'}</h1>\n * }\n * ```\n *\n * @inlineType DocumentOptions\n */\n <\n TPath extends string | undefined = undefined,\n TDocumentType extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n >(\n options: DocumentOptions<TPath, TDocumentType, TDataset, TProjectId>,\n ): TPath extends string\n ? {\n data:\n | JsonMatch<SanityDocument<TDocumentType, `${TProjectId}.${TDataset}`>, TPath>\n | undefined\n }\n : {data: SanityDocument<TDocumentType, `${TProjectId}.${TDataset}`> | null}\n\n /**\n * @public\n *\n * ## useDocument via Explicit Types\n *\n * Use this version when:\n * - You're not using Sanity Typegen\n * - You need to manually specify document types\n * - You're working with dynamic document types\n *\n * Key differences from Typegen version:\n * - Requires manual type specification via `TData`\n * - Returns `TData | null` for full documents\n * - Returns `TData | undefined` for nested values\n *\n * This hook will suspend while the document data is being fetched.\n *\n * @typeParam TData - The explicit type for the document or field\n * @typeParam TPath - Optional path to a nested value\n * @param options - Configuration including `documentId` and optionally:\n * - `path`: To select a nested value\n * - `projectId`/`dataset`: For multi-project/dataset setups\n * @returns The document state (or nested value if path provided)\n *\n * @example Basic document fetch with explicit type\n * ```tsx\n * import {useDocument, type DocumentHandle, type SanityDocument} from '@sanity/sdk-react'\n *\n * interface Book extends SanityDocument {\n * _type: 'book'\n * title: string\n * author: string\n * }\n *\n * interface BookViewProps {\n * doc: DocumentHandle\n * }\n *\n * function BookView({doc}: BookViewProps) {\n * const {data: book} = useDocument<Book>({...doc})\n * return <h1>{book?.title ?? 'Untitled'} by {book?.author ?? 'Unknown'}</h1>\n * }\n * ```\n *\n * @example Fetching a specific field with explicit type\n * ```tsx\n * import {useDocument, type DocumentHandle} from '@sanity/sdk-react'\n *\n * interface BookTitleProps {\n * doc: DocumentHandle\n * }\n *\n * function BookTitle({doc}: BookTitleProps) {\n * const {data: title} = useDocument<string>({...doc, path: 'title'})\n * return <h1>{title ?? 'Untitled'}</h1>\n * }\n * ```\n *\n * @inlineType DocumentOptions\n */\n <TData, TPath extends string>(\n options: DocumentOptions<TPath>,\n ): TPath extends string ? {data: TData | undefined} : {data: TData | null}\n\n /**\n * @internal\n */\n (options: DocumentOptions): {data: unknown}\n}\n\n/**\n * @public\n * Reads and subscribes to a document's realtime state, incorporating both local and remote changes.\n *\n * This hook comes in two main flavors to suit your needs:\n *\n * 1. **[Type Inference](#usedocument-via-type-inference-recommended)** (Recommended) - Automatically gets types from your Sanity schema\n * 2. **[Explicit Types](#usedocument-via-explicit-types)** - Manually specify types when needed\n *\n * @remarks\n * `useDocument` is ideal for realtime editing interfaces where you need immediate feedback on changes.\n * However, it can be resource-intensive since it maintains a realtime connection.\n *\n * For simpler cases where:\n * - You only need to display content\n * - Realtime updates aren't critical\n * - You want better performance\n *\n * …consider using {@link useDocumentProjection} or {@link useQuery} instead. These hooks are more efficient\n * for read-heavy applications.\n *\n * @function\n */\nexport const useDocument = wrapHookWithData(useDocumentValue) as UseDocument\n","import {type DatasetHandle, type DocumentEvent, subscribeDocumentEvents} from '@sanity/sdk'\nimport {useCallback, useEffect, useInsertionEffect, useRef} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * @public\n */\nexport interface UseDocumentEventOptions<\n TDataset extends string = string,\n TProjectId extends string = string,\n> extends DatasetHandle<TDataset, TProjectId> {\n onEvent: (documentEvent: DocumentEvent) => void\n}\n\n/**\n *\n * @public\n *\n * Subscribes an event handler to events in your application's document store.\n *\n * @category Documents\n * @param options - An object containing the event handler (`onEvent`) and optionally a `DatasetHandle` (projectId and dataset). If the handle is not provided, the nearest Sanity instance from context will be used.\n * @example Creating a custom hook for document event toasts\n * ```tsx\n * import {createDatasetHandle, type DatasetHandle, type DocumentEvent, useDocumentEvent} from '@sanity/sdk-react'\n * import {useToast} from './my-ui-library'\n *\n * // Define options for the custom hook, extending DatasetHandle\n * interface DocumentToastsOptions extends DatasetHandle {\n * // Could add more options, e.g., { includeEvents: DocumentEvent['type'][] }\n * }\n *\n * // Define the custom hook\n * function useDocumentToasts({...datasetHandle}: DocumentToastsOptions = {}) {\n * const showToast = useToast() // Get the toast function\n *\n * // Define the event handler logic to show toasts on specific events\n * const handleEvent = (event: DocumentEvent) => {\n * if (event.type === 'published') {\n * showToast(`Document ${event.documentId} published.`)\n * } else if (event.type === 'unpublished') {\n * showToast(`Document ${event.documentId} unpublished.`)\n * } else if (event.type === 'deleted') {\n * showToast(`Document ${event.documentId} deleted.`)\n * } else {\n * // Optionally log other events for debugging\n * console.log('Document Event:', event.type, event.documentId)\n * }\n * }\n *\n * // Call the original hook, spreading the handle properties\n * useDocumentEvent({\n * ...datasetHandle, // Spread the dataset handle (projectId, dataset)\n * onEvent: handleEvent,\n * })\n * }\n *\n * function MyComponentWithToasts() {\n * // Use the custom hook, passing specific handle info\n * const specificHandle = createDatasetHandle({ projectId: 'p1', dataset: 'ds1' })\n * useDocumentToasts(specificHandle)\n *\n * // // Or use it relying on context for the handle\n * // useDocumentToasts()\n *\n * return <div>...</div>\n * }\n * ```\n */\nexport function useDocumentEvent<\n TDataset extends string = string,\n TProjectId extends string = string,\n>(\n // Single options object parameter\n options: UseDocumentEventOptions<TDataset, TProjectId>,\n): void {\n // Destructure handler and datasetHandle from options\n const {onEvent, ...datasetHandle} = options\n const ref = useRef(onEvent)\n\n useInsertionEffect(() => {\n ref.current = onEvent\n })\n\n const stableHandler = useCallback((documentEvent: DocumentEvent) => {\n return ref.current(documentEvent)\n }, [])\n\n const instance = useSanityInstance(datasetHandle)\n useEffect(() => {\n return subscribeDocumentEvents(instance, stableHandler)\n }, [instance, stableHandler])\n}\n","import {type DocumentAction, type DocumentPermissionsResult, getPermissionsState} from '@sanity/sdk'\nimport {useCallback, useMemo, useSyncExternalStore} from 'react'\nimport {filter, firstValueFrom} from 'rxjs'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n *\n * @public\n *\n * Check if the current user has the specified permissions for the given document actions.\n *\n * @category Permissions\n * @param actionOrActions - One or more document action functions (e.g., `publishDocument(handle)`).\n * @returns An object that specifies whether the action is allowed; if the action is not allowed, an explanatory message and list of reasons is also provided.\n *\n * @remarks\n * When passing multiple actions, all actions must belong to the same project and dataset.\n * Note, however, that you can check permissions on multiple documents from the same project and dataset (as in the second example below).\n *\n * @example Checking for permission to publish a document\n * ```tsx\n * import {\n * useDocumentPermissions,\n * useApplyDocumentActions,\n * publishDocument,\n * createDocumentHandle,\n * type DocumentHandle\n * } from '@sanity/sdk-react'\n *\n * // Define props using the DocumentHandle type\n * interface PublishButtonProps {\n * doc: DocumentHandle\n * }\n *\n * function PublishButton({doc}: PublishButtonProps) {\n * const publishAction = publishDocument(doc)\n *\n * // Pass the same action call to check permissions\n * const publishPermissions = useDocumentPermissions(publishAction)\n * const apply = useApplyDocumentActions()\n *\n * return (\n * <>\n * <button\n * disabled={!publishPermissions.allowed}\n * // Pass the same action call to apply the action\n * onClick={() => apply(publishAction)}\n * popoverTarget={`${publishPermissions.allowed ? undefined : 'publishButtonPopover'}`}\n * >\n * Publish\n * </button>\n * {!publishPermissions.allowed && (\n * <div popover id=\"publishButtonPopover\">\n * {publishPermissions.message}\n * </div>\n * )}\n * </>\n * )\n * }\n *\n * // Usage:\n * // const doc = createDocumentHandle({ documentId: 'doc1', documentType: 'myType' })\n * // <PublishButton doc={doc} />\n * ```\n *\n * @example Checking for permissions to edit multiple documents\n * ```tsx\n * import {\n * useDocumentPermissions,\n * editDocument,\n * type DocumentHandle\n * } from '@sanity/sdk-react'\n *\n * export default function canEditMultiple(docHandles: DocumentHandle[]) {\n * // Create an array containing an editDocument action for each of the document handles\n * const editActions = docHandles.map(doc => editDocument(doc))\n *\n * // Return the result of checking for edit permissions on all of the document handles\n * return useDocumentPermissions(editActions)\n * }\n * ```\n */\nexport function useDocumentPermissions(\n actionOrActions: DocumentAction | DocumentAction[],\n): DocumentPermissionsResult {\n const actions = Array.isArray(actionOrActions) ? actionOrActions : [actionOrActions]\n // if actions is an array, we need to check that all actions belong to the same project and dataset\n let projectId\n let dataset\n\n for (const action of actions) {\n if (action.projectId) {\n if (!projectId) projectId = action.projectId\n if (action.projectId !== projectId) {\n throw new Error(\n `Mismatched project IDs found in actions. All actions must belong to the same project. Found \"${action.projectId}\" but expected \"${projectId}\".`,\n )\n }\n\n if (action.dataset) {\n if (!dataset) dataset = action.dataset\n if (action.dataset !== dataset) {\n throw new Error(\n `Mismatched datasets found in actions. All actions must belong to the same dataset. Found \"${action.dataset}\" but expected \"${dataset}\".`,\n )\n }\n }\n }\n }\n\n const instance = useSanityInstance({projectId, dataset})\n const isDocumentReady = useCallback(\n () => getPermissionsState(instance, actionOrActions).getCurrent() !== undefined,\n [actionOrActions, instance],\n )\n if (!isDocumentReady()) {\n throw firstValueFrom(\n getPermissionsState(instance, actionOrActions).observable.pipe(\n filter((result) => result !== undefined),\n ),\n )\n }\n\n const {subscribe, getCurrent} = useMemo(\n () => getPermissionsState(instance, actionOrActions),\n [actionOrActions, instance],\n )\n\n return useSyncExternalStore(subscribe, getCurrent) as DocumentPermissionsResult\n}\n","import {\n type DocumentHandle,\n getDocumentSyncStatus,\n resolveDocument,\n type SanityInstance,\n type StateSource,\n} from '@sanity/sdk'\nimport {identity} from 'rxjs'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\ntype UseDocumentSyncStatus = {\n /**\n * Exposes the document's sync status between local and remote document states.\n *\n * @category Documents\n * @param doc - The document handle to get sync status for. If you pass a `DocumentHandle` with specified `projectId` and `dataset`,\n * the document will be read from the specified Sanity project and dataset that is included in the handle. If no `projectId` or `dataset` is provided,\n * the document will use the nearest instance from context.\n * @returns `true` if local changes are synced with remote, `false` if changes are pending. Note: Suspense handles loading states.\n * @example Show sync status indicator\n * ```tsx\n * import {useDocumentSyncStatus, createDocumentHandle, type DocumentHandle} from '@sanity/sdk-react'\n *\n * // Define props including the DocumentHandle type\n * interface SyncIndicatorProps {\n * doc: DocumentHandle\n * }\n *\n * function SyncIndicator({doc}: SyncIndicatorProps) {\n * const isSynced = useDocumentSyncStatus(doc)\n *\n * return (\n * <div className={`sync-status ${isSynced ? 'synced' : 'pending'}`}>\n * {isSynced ? '✓ Synced' : 'Saving changes...'}\n * </div>\n * )\n * }\n *\n * // Usage:\n * // const doc = createDocumentHandle({ documentId: 'doc1', documentType: 'myType' })\n * // <SyncIndicator doc={doc} />\n * ```\n */\n (doc: DocumentHandle): boolean\n}\n\n/**\n * @public\n * @function\n */\nexport const useDocumentSyncStatus: UseDocumentSyncStatus = createStateSourceHook({\n getState: getDocumentSyncStatus as (\n instance: SanityInstance,\n doc: DocumentHandle,\n ) => StateSource<boolean>,\n shouldSuspend: (instance, doc: DocumentHandle) =>\n getDocumentSyncStatus(instance, doc).getCurrent() === undefined,\n suspender: (instance, doc: DocumentHandle) => resolveDocument(instance, doc),\n getConfig: identity,\n})\n","import {\n type ActionsResult,\n type DocumentOptions,\n editDocument,\n getDocumentState,\n type JsonMatch,\n resolveDocument,\n} from '@sanity/sdk'\nimport {type SanityDocument} from 'groq'\nimport {useCallback} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\nimport {useApplyDocumentActions} from './useApplyDocumentActions'\n\nconst ignoredKeys = ['_id', '_type', '_createdAt', '_updatedAt', '_rev']\n\ntype Updater<TValue> = TValue | ((currentValue: TValue) => TValue)\n\n// Overload 1: No path, relies on Typegen\n/**\n * @public\n * Edit an entire document, relying on Typegen for the type.\n *\n * @param options - Document options including `documentId`, `documentType`, and optionally `projectId`/`dataset`.\n * @returns A stable function to update the document state. Accepts either the new document state or an updater function `(currentValue) => nextValue`.\n * Returns a promise resolving to the {@link ActionsResult}.\n */\nexport function useEditDocument<\n TDocumentType extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n>(\n options: DocumentOptions<undefined, TDocumentType, TDataset, TProjectId>,\n): (\n nextValue: Updater<SanityDocument<TDocumentType, `${TProjectId}.${TDataset}`>>,\n) => Promise<ActionsResult<SanityDocument<TDocumentType, `${TProjectId}.${TDataset}`>>>\n\n// Overload 2: Path provided, relies on Typegen\n/**\n * @public\n * Edit a specific path within a document, relying on Typegen for the type.\n *\n * @param options - Document options including `documentId`, `documentType`, `path`, and optionally `projectId`/`dataset`.\n * @returns A stable function to update the value at the specified path. Accepts either the new value or an updater function `(currentValue) => nextValue`.\n * Returns a promise resolving to the {@link ActionsResult}.\n */\nexport function useEditDocument<\n TPath extends string = string,\n TDocumentType extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n>(\n options: DocumentOptions<TPath, TDocumentType, TDataset, TProjectId>,\n): (\n nextValue: Updater<JsonMatch<SanityDocument<TDocumentType, `${TProjectId}.${TDataset}`>, TPath>>,\n) => Promise<ActionsResult<SanityDocument<TDocumentType, `${TProjectId}.${TDataset}`>>>\n\n// Overload 3: Explicit type, no path\n/**\n * @public\n * Edit an entire document with an explicit type `TData`.\n *\n * @param options - Document options including `documentId` and optionally `projectId`/`dataset`.\n * @returns A stable function to update the document state. Accepts either the new document state (`TData`) or an updater function `(currentValue: TData) => nextValue: TData`.\n * Returns a promise resolving to the {@link ActionsResult}.\n */\nexport function useEditDocument<TData>(\n options: DocumentOptions<undefined>,\n): (nextValue: Updater<TData>) => Promise<ActionsResult>\n\n// Overload 4: Explicit type, path provided\n/**\n * @public\n * Edit a specific path within a document with an explicit type `TData`.\n *\n * @param options - Document options including `documentId`, `path`, and optionally `projectId`/`dataset`.\n * @returns A stable function to update the value at the specified path. Accepts either the new value (`TData`) or an updater function `(currentValue: TData) => nextValue: TData`.\n * Returns a promise resolving to the {@link ActionsResult}.\n */\nexport function useEditDocument<TData>(\n options: DocumentOptions<string>,\n): (nextValue: Updater<TData>) => Promise<ActionsResult>\n\n/**\n * @public\n * Provides a stable function to apply edits to a document or a specific path within it.\n *\n * @category Documents\n * @remarks\n * This hook simplifies editing documents by automatically:\n * - Comparing the current and next states to determine the minimal set of `set` and `unset` operations required for the update via `editDocument`.\n * - Handling both full document updates and specific path updates.\n * - Supporting functional updates (e.g., `edit(prev => ({...prev, title: 'New'}))`).\n * - Integrating with the active {@link SanityInstance} context.\n * - Utilizing `useApplyDocumentActions` internally for optimistic updates and transaction handling.\n *\n * It offers several overloads for flexibility:\n * 1. **Typegen (Full Document):** Edit the entire document, inferring types from your schema.\n * 2. **Typegen (Specific Path):** Edit a specific field, inferring types.\n * 3. **Explicit Type (Full Document):** Edit the entire document with a manually specified type.\n * 4. **Explicit Type (Specific Path):** Edit a specific field with a manually specified type.\n *\n * This hook relies on the document state being loaded. If the document is not yet available\n * (e.g., during initial load), the component using this hook will suspend.\n *\n * @example Basic Usage (Typegen, Full Document)\n * ```tsx\n * import {useCallback} from 'react';\n * import {useEditDocument, useDocument, type DocumentHandle} from '@sanity/sdk-react'\n *\n * // Assume 'product' schema has a 'title' field (string)\n * interface ProductEditorProps {\n * productHandle: DocumentHandle<'product'> // Typegen infers 'product' type\n * }\n *\n * function ProductEditor({ productHandle }: ProductEditorProps) {\n * // Fetch the document to display its current state (optional)\n * const {data: product} = useDocument(productHandle);\n * // Get the edit function for the full document\n * const editProduct = useEditDocument(productHandle);\n *\n * // Use useCallback for stable event handlers\n * const handleTitleChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {\n * const newTitle = event.target.value;\n * // Use the functional updater for safe partial updates\n * editProduct(prev => ({\n * ...prev,\n * title: newTitle,\n * })).\n * }, [editProduct]);\n *\n * return (\n * <div>\n * <label>\n * Product Title:\n * <input\n * type=\"text\"\n * value={product?.title ?? ''}\n * onChange={handleTitleChange}\n * />\n * </label>\n * </div>\n * );\n * }\n * ```\n *\n * @example Editing a Specific Path (Typegen)\n * ```tsx\n * import React, { useCallback } from 'react';\n * import {useEditDocument, useDocument, type DocumentHandle, type DocumentOptions} from '@sanity/sdk-react'\n *\n * // Assume 'product' schema has a 'price' field (number)\n * interface ProductPriceEditorProps {\n * productHandle: DocumentHandle<'product'>;\n * }\n *\n * function ProductPriceEditor({ productHandle }: ProductPriceEditorProps) {\n * // Construct DocumentOptions internally, combining the handle and a hardcoded path\n * const priceOptions {\n * ...productHandle,\n * path: 'price', // Hardcode the path to edit\n * };\n *\n * // Fetch the current price to display it\n * const {data: currentPrice} = useDocument(priceOptions);\n * // Get the edit function for the specific path 'price'\n * const editPrice = useEditDocument(priceOptions);\n *\n * const handleSetFixedPrice = useCallback(() => {\n * // Update the price directly to a hardcoded value\n * editPrice(99.99)\n * }, [editPrice]);\n *\n * return (\n * <div>\n * <p>Current Price: {currentPrice}</p>\n * <button onClick={handleSetFixedPrice}>\n * Set Price to $99.99\n * </button>\n * </div>\n * );\n * }\n *\n * ```\n *\n * @example Usage with Explicit Types (Full Document)\n * ```tsx\n * import React, { useCallback } from 'react';\n * import {useEditDocument, useDocument, type DocumentHandle, type SanityDocument} from '@sanity/sdk-react'\n *\n * interface Book extends SanityDocument { _type: 'book', title: string, author: string }\n *\n * interface BookEditorProps {\n * bookHandle: DocumentHandle // No documentType needed if providing TData\n * }\n *\n * function BookEditor({ bookHandle }: BookEditorProps) {\n * const {data: book} = useDocument<Book>(bookHandle);\n * // Provide the explicit type <Book>\n * const editBook = useEditDocument<Book>(bookHandle);\n *\n * const handleAuthorChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {\n * const newAuthor = event.target.value;\n * editBook(prev => ({\n * ...prev,\n * author: newAuthor\n * }))\n * }, [editBook]);\n *\n * return (\n * <div>\n * <label>\n * Book Author:\n * <input\n * type=\"text\"\n * value={book?.author ?? ''}\n * onChange={handleAuthorChange}\n * />\n * </label>\n * </div>\n * );\n * }\n *\n * ```\n *\n * @example Usage with Explicit Types (Specific Path)\n * ```tsx\n * import React, { useCallback } from 'react';\n * import {useEditDocument, useDocument, type DocumentHandle, type DocumentOptions} from '@sanity/sdk-react'\n *\n * // Assume 'book' has 'author.name' (string)\n * interface AuthorNameEditorProps {\n * bookHandle: DocumentHandle; // No documentType needed if providing TData for path\n * }\n *\n * function AuthorNameEditor({ bookHandle }: AuthorNameEditorProps) {*\n * // Fetch current value\n * const {data: currentName} = useDocument<string>({...bookHandle, path: 'author.name'});\n * // Provide the explicit type <string> for the path's value\n * const editAuthorName = useEditDocument<string>({...bookHandle, path: 'author.name'});\n *\n * const handleUpdate = useCallback(() => {\n * // Update with a hardcoded string directly\n * editAuthorName('Jane Doe')\n * }, [editAuthorName]);\n *\n * return (\n * <div>\n * <p>Current Author Name: {currentName}</p>\n * <button onClick={handleUpdate} disabled={currentName === undefined}>\n * Set Author Name to Jane Doe\n * </button>\n * </div>\n * );\n * }\n *\n * ```\n */\nexport function useEditDocument({\n path,\n ...doc\n}: DocumentOptions<string | undefined>): (updater: Updater<unknown>) => Promise<ActionsResult> {\n const instance = useSanityInstance(doc)\n const apply = useApplyDocumentActions()\n const isDocumentReady = useCallback(\n () => getDocumentState(instance, doc).getCurrent() !== undefined,\n [instance, doc],\n )\n if (!isDocumentReady()) throw resolveDocument(instance, doc)\n\n return (updater: Updater<unknown>) => {\n const currentPath = path\n\n if (currentPath) {\n const stateWithOptions = getDocumentState(instance, {...doc, path})\n const currentValue = stateWithOptions.getCurrent()\n\n const nextValue =\n typeof updater === 'function'\n ? (updater as (prev: typeof currentValue) => typeof currentValue)(currentValue)\n : updater\n\n return apply(editDocument(doc, {set: {[currentPath]: nextValue}}))\n }\n\n const fullDocState = getDocumentState(instance, {...doc, path})\n const current = fullDocState.getCurrent() as object | null | undefined\n const nextValue =\n typeof updater === 'function'\n ? (updater as (prev: typeof current) => typeof current)(current)\n : updater\n\n if (typeof nextValue !== 'object' || !nextValue) {\n throw new Error(\n `No path was provided to \\`useEditDocument\\` and the value provided was not a document object.`,\n )\n }\n\n const allKeys = Object.keys({...current, ...nextValue})\n const editActions = allKeys\n .filter((key) => !ignoredKeys.includes(key))\n .filter(\n (key) =>\n current?.[key as keyof typeof current] !== (nextValue as Record<string, unknown>)[key],\n )\n .map((key) =>\n key in nextValue\n ? editDocument(doc, {set: {[key]: (nextValue as Record<string, unknown>)[key]}})\n : editDocument(doc, {unset: [key]}),\n )\n\n return apply(editActions)\n }\n}\n","import {\n getQueryKey,\n getQueryState,\n parseQueryKey,\n type QueryOptions,\n resolveQuery,\n} from '@sanity/sdk'\nimport {type SanityQueryResult} from 'groq'\nimport {useEffect, useMemo, useRef, useState, useSyncExternalStore, useTransition} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n// Overload 1: Inferred Type (using Typegen)\n/**\n * @public\n * Executes a GROQ query, inferring the result type from the query string and options.\n * Leverages Sanity Typegen if configured for enhanced type safety.\n *\n * @param options - Configuration for the query, including `query`, optional `params`, `projectId`, `dataset`, etc.\n * @returns An object containing `data` (typed based on the query) and `isPending` (for transitions).\n *\n * @example Basic usage (Inferred Type)\n * ```tsx\n * import {useQuery} from '@sanity/sdk-react'\n * import {defineQuery} from 'groq'\n *\n * const myQuery = defineQuery(`*[_type == \"movie\"]{_id, title}`)\n *\n * function MovieList() {\n * // Typegen infers the return type for data\n * const {data} = useQuery({ query: myQuery })\n *\n * return (\n * <div>\n * <h2>Movies</h2>\n * <ul>\n * {data.map(movie => <li key={movie._id}>{movie.title}</li>)}\n * </ul>\n * </div>\n * )\n * }\n * // Suspense boundary should wrap <MovieList /> for initial load\n * ```\n *\n * @example Using parameters (Inferred Type)\n * ```tsx\n * import {useQuery} from '@sanity/sdk-react'\n * import {defineQuery} from 'groq'\n *\n * const myQuery = defineQuery(`*[_type == \"movie\" && _id == $id][0]`)\n *\n * function MovieDetails({movieId}: {movieId: string}) {\n * // Typegen infers the return type based on query and params\n * const {data, isPending} = useQuery({\n * query: myQuery,\n * params: { id: movieId }\n * })\n *\n * return (\n * // utilize `isPending` to signal to users that new data is coming in\n * // (e.g. the `movieId` changed and we're loading in the new one)\n * <div style={{ opacity: isPending ? 0.5 : 1 }}>\n * {data ? <h1>{data.title}</h1> : <p>Movie not found</p>}\n * </div>\n * )\n * }\n * ```\n */\nexport function useQuery<\n TQuery extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n>(\n options: QueryOptions<TQuery, TDataset, TProjectId>,\n): {\n /** The query result, typed based on the GROQ query string */\n data: SanityQueryResult<TQuery, `${TProjectId}.${TDataset}`>\n /** True if a query transition is in progress */\n isPending: boolean\n}\n\n// Overload 2: Explicit Type Provided\n/**\n * @public\n * Executes a GROQ query with an explicitly provided result type `TData`.\n *\n * @param options - Configuration for the query, including `query`, optional `params`, `projectId`, `dataset`, etc.\n * @returns An object containing `data` (cast to `TData`) and `isPending` (indicates whether a query resolution is pending; note that Suspense handles initial loading states). *\n * @example Manually typed query result\n * ```tsx\n * import {useQuery} from '@sanity/sdk-react'\n *\n * interface CustomMovieTitle {\n * movieTitle?: string\n * }\n *\n * function FirstMovieTitle() {\n * // Provide the explicit type TData\n * const {data, isPending} = useQuery<CustomMovieTitle>({\n * query: '*[_type == \"movie\"][0]{ \"movieTitle\": title }'\n * })\n *\n * return (\n * <h1 style={{ opacity: isPending ? 0.5 : 1 }}>\n * {data?.movieTitle ?? 'No title found'}\n * </h1>\n * )\n * }\n * ```\n */\nexport function useQuery<TData>(options: QueryOptions): {\n /** The query result, cast to the provided type TData */\n data: TData\n /** True if another query is resolving in the background (suspense handles the initial loading state) */\n isPending: boolean\n}\n\n/**\n * @public\n * Fetches data and subscribes to real-time updates using a GROQ query.\n *\n * @remarks\n * This hook provides a convenient way to fetch data from your Sanity dataset and\n * automatically receive updates in real-time when the queried data changes.\n *\n * Features:\n * - Executes any valid GROQ query.\n * - Subscribes to changes, providing real-time updates.\n * - Integrates with React Suspense for handling initial loading states.\n * - Uses React Transitions for managing loading states during query/parameter changes (indicated by `isPending`).\n * - Supports type inference based on the GROQ query when using Sanity Typegen.\n * - Allows specifying an explicit return type `TData` for the query result.\n *\n * @category GROQ\n */\nexport function useQuery(options: QueryOptions): {data: unknown; isPending: boolean} {\n // Implementation returns unknown, overloads define specifics\n const instance = useSanityInstance(options)\n\n // Use React's useTransition to avoid UI jank when queries change\n const [isPending, startTransition] = useTransition()\n\n // Get the unique key for this query and its options\n const queryKey = getQueryKey(options)\n // Use a deferred state to avoid immediate re-renders when the query changes\n const [deferredQueryKey, setDeferredQueryKey] = useState(queryKey)\n // Parse the deferred query key back into a query and options\n const deferred = useMemo(() => parseQueryKey(deferredQueryKey), [deferredQueryKey])\n\n // Create an AbortController to cancel in-flight requests when needed\n const ref = useRef<AbortController>(new AbortController())\n\n // When the query or options change, start a transition to update the query\n useEffect(() => {\n if (queryKey === deferredQueryKey) return\n\n startTransition(() => {\n // Abort any in-flight requests for the previous query\n if (ref && !ref.current.signal.aborted) {\n ref.current.abort()\n ref.current = new AbortController()\n }\n\n setDeferredQueryKey(queryKey)\n })\n }, [deferredQueryKey, queryKey])\n\n // Get the state source for this query from the query store\n const {getCurrent, subscribe} = useMemo(\n () => getQueryState(instance, deferred),\n [instance, deferred],\n )\n\n // If data isn't available yet, suspend rendering\n if (getCurrent() === undefined) {\n // Normally, reading from a mutable ref during render can be risky in concurrent mode.\n // However, it is safe here because:\n // 1. React guarantees that while the component is suspended (via throwing a promise),\n // no effects or state updates occur during that render pass.\n // 2. We immediately capture the current abort signal in a local variable (currentSignal).\n // 3. Even if a background render updates ref.current (for example, due to a query change),\n // the captured signal remains unchanged for this suspended render.\n // Thus, the promise thrown here uses a stable abort signal, ensuring correct behavior.\n const currentSignal = ref.current.signal\n\n throw resolveQuery(instance, {...deferred, signal: currentSignal})\n }\n\n // Subscribe to updates and get the current data\n // useSyncExternalStore ensures the component re-renders when the data changes\n const data = useSyncExternalStore(subscribe, getCurrent) as SanityQueryResult\n return useMemo(() => ({data, isPending}), [data, isPending])\n}\n","import {\n createGroqSearchFilter,\n type DatasetHandle,\n type DocumentHandle,\n type QueryOptions,\n} from '@sanity/sdk'\nimport {type SortOrderingItem} from '@sanity/types'\nimport {pick} from 'lodash-es'\nimport {useCallback, useEffect, useMemo, useState} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\nimport {useQuery} from '../query/useQuery'\n\nconst DEFAULT_BATCH_SIZE = 25\n\n/**\n * Configuration options for the useDocuments hook\n *\n * @public\n * @category Types\n */\nexport interface DocumentsOptions<\n TDocumentType extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n> extends DatasetHandle<TDataset, TProjectId>,\n Pick<QueryOptions, 'perspective' | 'params'> {\n /**\n * Filter documents by their `_type`. Can be a single type or an array of types.\n */\n documentType?: TDocumentType | TDocumentType[]\n /**\n * GROQ filter expression to apply to the query\n */\n filter?: string\n /**\n * Number of items to load per batch (defaults to 25)\n */\n batchSize?: number\n /**\n * Sorting configuration for the results\n */\n orderings?: SortOrderingItem[]\n /**\n * Text search query to filter results\n */\n search?: string\n}\n\n/**\n * Return value from the useDocuments hook\n *\n * @public\n * @category Types\n */\nexport interface DocumentsResponse<\n TDocumentType extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n> {\n /**\n * Array of document handles for the current batch\n */\n data: DocumentHandle<TDocumentType, TDataset, TProjectId>[]\n /**\n * Whether there are more items available to load\n */\n hasMore: boolean\n /**\n * Total count of items matching the query\n */\n count: number\n /**\n * Whether a query is currently in progress\n */\n isPending: boolean\n /**\n * Function to load the next batch of results\n */\n loadMore: () => void\n}\n\n/**\n * Retrieves batches of {@link DocumentHandle}s, narrowed by optional filters, text searches, and custom ordering,\n * with infinite scrolling support. The number of document handles returned per batch is customizable,\n * and additional batches can be loaded using the supplied `loadMore` function.\n *\n * @public\n * @category Documents\n * @param options - Configuration options for the infinite list\n * @returns An object containing the list of document handles, the loading state, the total count of retrieved document handles, and a function to load more\n *\n * @remarks\n * - The returned document handles include projectId and dataset information from the current Sanity instance\n * - This makes them ready to use with document operations and other document hooks\n * - The hook automatically uses the correct Sanity instance based on the projectId and dataset in the options\n *\n * @example Basic infinite list with loading more\n * ```tsx\n * import {\n * useDocuments,\n * createDatasetHandle,\n * type DatasetHandle,\n * type DocumentHandle,\n * type SortOrderingItem\n * } from '@sanity/sdk-react'\n * import {Suspense} from 'react'\n *\n * // Define a component to display a single document (using useDocumentProjection for efficiency)\n * function MyDocumentComponent({doc}: {doc: DocumentHandle}) {\n * const {data} = useDocumentProjection<{title?: string}>({\n * ...doc, // Pass the full handle\n * projection: '{title}'\n * })\n *\n * return <>{data?.title || 'Untitled'}</>\n * }\n *\n * // Define props for the list component\n * interface DocumentListProps {\n * dataset: DatasetHandle\n * documentType: string\n * search?: string\n * }\n *\n * function DocumentList({dataset, documentType, search}: DocumentListProps) {\n * const { data, hasMore, isPending, loadMore, count } = useDocuments({\n * ...dataset,\n * documentType,\n * search,\n * batchSize: 10,\n * orderings: [{field: '_createdAt', direction: 'desc'}],\n * })\n *\n * return (\n * <div>\n * <p>Total documents: {count}</p>\n * <ol>\n * {data.map((docHandle) => (\n * <li key={docHandle.documentId}>\n * <Suspense fallback=\"Loading…\">\n * <MyDocumentComponent docHandle={docHandle} />\n * </Suspense>\n * </li>\n * ))}\n * </ol>\n * {hasMore && (\n * <button onClick={loadMore}>\n * {isPending ? 'Loading...' : 'Load More'}\n * </button>\n * )}\n * </div>\n * )\n * }\n *\n * // Usage:\n * // const myDatasetHandle = createDatasetHandle({ projectId: 'p1', dataset: 'production' })\n * // <DocumentList dataset={myDatasetHandle} documentType=\"post\" search=\"Sanity\" />\n * ```\n *\n * @example Using `filter` and `params` options for narrowing a collection\n * ```tsx\n * import {useState} from 'react'\n * import {useDocuments} from '@sanity/sdk-react'\n *\n * export default function FilteredAuthors() {\n * const [max, setMax] = useState(2)\n * const {data} = useDocuments({\n * documentType: 'author',\n * filter: 'length(books) <= $max',\n * params: {max},\n * })\n *\n * return (\n * <>\n * <input\n * id=\"maxBooks\"\n * type=\"number\"\n * value={max}\n * onChange={e => setMax(e.currentTarget.value)}\n * />\n * {data.map(author => (\n * <Suspense key={author.documentId}>\n * <MyAuthorComponent documentHandle={author} />\n * </Suspense>\n * ))}\n * </>\n * )\n * }\n * ```\n */\nexport function useDocuments<\n TDocumentType extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n>({\n batchSize = DEFAULT_BATCH_SIZE,\n params,\n search,\n filter,\n orderings,\n documentType,\n ...options\n}: DocumentsOptions<TDocumentType, TDataset, TProjectId>): DocumentsResponse<\n TDocumentType,\n TDataset,\n TProjectId\n> {\n const instance = useSanityInstance(options)\n const [limit, setLimit] = useState(batchSize)\n const documentTypes = useMemo(\n () =>\n (Array.isArray(documentType) ? documentType : [documentType]).filter(\n (i): i is TDocumentType => typeof i === 'string',\n ),\n [documentType],\n )\n\n // Reset the limit to the current batchSize whenever any query parameters\n // (filter, search, params, orderings) or batchSize changes\n const key = JSON.stringify({\n filter,\n search,\n params,\n orderings,\n batchSize,\n types: documentTypes,\n ...options,\n })\n useEffect(() => {\n setLimit(batchSize)\n }, [key, batchSize])\n\n const filterClause = useMemo(() => {\n const conditions: string[] = []\n const trimmedSearch = search?.trim()\n\n // Add search query filter if specified\n if (trimmedSearch) {\n const searchFilter = createGroqSearchFilter(trimmedSearch)\n if (searchFilter) {\n conditions.push(searchFilter)\n }\n }\n\n // Add type filter if specified\n if (documentTypes?.length) {\n conditions.push(`(_type in $__types)`)\n }\n\n // Add additional filter if specified\n if (filter) {\n conditions.push(`(${filter})`)\n }\n\n return conditions.length ? `[${conditions.join(' && ')}]` : ''\n }, [filter, search, documentTypes])\n\n const orderClause = orderings\n ? `| order(${orderings\n .map((ordering) =>\n [ordering.field, ordering.direction.toLowerCase()]\n .map((str) => str.trim())\n .filter(Boolean)\n .join(' '),\n )\n .join(',')})`\n : ''\n\n const dataQuery = `*${filterClause}${orderClause}[0...${limit}]{\"documentId\":_id,\"documentType\":_type,...$__handle}`\n const countQuery = `count(*${filterClause})`\n\n const {\n data: {count, data},\n isPending,\n } = useQuery<{count: number; data: DocumentHandle<TDocumentType, TDataset, TProjectId>[]}>({\n ...options,\n query: `{\"count\":${countQuery},\"data\":${dataQuery}}`,\n params: {\n ...params,\n __handle: {\n ...pick(instance.config, 'projectId', 'dataset', 'perspective'),\n ...pick(options, 'projectId', 'dataset', 'perspective'),\n },\n __types: documentTypes,\n },\n })\n\n // Now use the correctly typed variables\n const hasMore = data.length < count\n\n const loadMore = useCallback(() => {\n setLimit((prev) => Math.min(prev + batchSize, count))\n }, [count, batchSize])\n\n return useMemo(\n () => ({data, hasMore, count, isPending, loadMore}),\n [count, data, hasMore, isPending, loadMore],\n )\n}\n","import {createGroqSearchFilter, type DocumentHandle, type QueryOptions} from '@sanity/sdk'\nimport {type SortOrderingItem} from '@sanity/types'\nimport {pick} from 'lodash-es'\nimport {useCallback, useEffect, useMemo, useState} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\nimport {useQuery} from '../query/useQuery'\n\n/**\n * Configuration options for the usePaginatedDocuments hook\n *\n * @public\n * @category Types\n */\nexport interface PaginatedDocumentsOptions<\n TDocumentType extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n> extends Omit<QueryOptions<TDocumentType, TDataset, TProjectId>, 'query'> {\n documentType?: TDocumentType | TDocumentType[]\n /**\n * GROQ filter expression to apply to the query\n */\n filter?: string\n /**\n * Number of items to display per page (defaults to 25)\n */\n pageSize?: number\n /**\n * Sorting configuration for the results\n */\n orderings?: SortOrderingItem[]\n /**\n * Text search query to filter results\n */\n search?: string\n}\n\n/**\n * Return value from the usePaginatedDocuments hook\n *\n * @public\n * @category Types\n */\nexport interface PaginatedDocumentsResponse<\n TDocumentType extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n> {\n /**\n * Array of document handles for the current page\n */\n data: DocumentHandle<TDocumentType, TDataset, TProjectId>[]\n /**\n * Whether a query is currently in progress\n */\n isPending: boolean\n\n /**\n * Number of items displayed per page\n */\n pageSize: number\n /**\n * Current page number (1-indexed)\n */\n currentPage: number\n /**\n * Total number of pages available\n */\n totalPages: number\n\n /**\n * Starting index of the current page (0-indexed)\n */\n startIndex: number\n /**\n * Ending index of the current page (exclusive, 0-indexed)\n */\n endIndex: number\n /**\n * Total count of items matching the query\n */\n count: number\n\n /**\n * Navigate to the first page\n */\n firstPage: () => void\n /**\n * Whether there is a first page available to navigate to\n */\n hasFirstPage: boolean\n\n /**\n * Navigate to the previous page\n */\n previousPage: () => void\n /**\n * Whether there is a previous page available to navigate to\n */\n hasPreviousPage: boolean\n\n /**\n * Navigate to the next page\n */\n nextPage: () => void\n /**\n * Whether there is a next page available to navigate to\n */\n hasNextPage: boolean\n\n /**\n * Navigate to the last page\n */\n lastPage: () => void\n /**\n * Whether there is a last page available to navigate to\n */\n hasLastPage: boolean\n\n /**\n * Navigate to a specific page number\n * @param pageNumber - The page number to navigate to (1-indexed)\n */\n goToPage: (pageNumber: number) => void\n}\n\n/**\n * Retrieves pages of {@link DocumentHandle}s, narrowed by optional filters, text searches, and custom ordering,\n * with support for traditional paginated interfaces. The number of document handles returned per page is customizable,\n * while page navigation is handled via the included navigation functions.\n *\n * @public\n * @category Documents\n * @param options - Configuration options for the paginated list\n * @returns An object containing the list of document handles, pagination details, and functions to navigate between pages\n *\n * @remarks\n * - The returned document handles include projectId and dataset information from the current Sanity instance\n * - This makes them ready to use with document operations and other document hooks\n * - The hook automatically uses the correct Sanity instance based on the projectId and dataset in the options\n *\n * @example Paginated list of documents with navigation\n * ```tsx\n * import {\n * usePaginatedDocuments,\n * createDatasetHandle,\n * type DatasetHandle,\n * type DocumentHandle,\n * type SortOrderingItem,\n * useDocumentProjection\n * } from '@sanity/sdk-react'\n * import {Suspense} from 'react'\n * import {ErrorBoundary} from 'react-error-boundary'\n *\n * // Define a component to display a single document row\n * function MyTableRowComponent({doc}: {doc: DocumentHandle}) {\n * const {data} = useDocumentProjection<{title?: string}>({\n * ...doc,\n * projection: '{title}',\n * })\n *\n * return (\n * <tr>\n * <td>{data?.title ?? 'Untitled'}</td>\n * </tr>\n * )\n * }\n *\n * // Define props for the list component\n * interface PaginatedDocumentListProps {\n * documentType: string\n * dataset?: DatasetHandle\n * }\n *\n * function PaginatedDocumentList({documentType, dataset}: PaginatedDocumentListProps) {\n * const {\n * data,\n * isPending,\n * currentPage,\n * totalPages,\n * nextPage,\n * previousPage,\n * hasNextPage,\n * hasPreviousPage\n * } = usePaginatedDocuments({\n * ...dataset,\n * documentType,\n * pageSize: 10,\n * orderings: [{field: '_createdAt', direction: 'desc'}],\n * })\n *\n * return (\n * <div>\n * <table>\n * <thead>\n * <tr><th>Title</th></tr>\n * </thead>\n * <tbody>\n * {data.map(doc => (\n * <ErrorBoundary key={doc.documentId} fallback={<tr><td>Error loading document</td></tr>}>\n * <Suspense fallback={<tr><td>Loading...</td></tr>}>\n * <MyTableRowComponent doc={doc} />\n * </Suspense>\n * </ErrorBoundary>\n * ))}\n * </tbody>\n * </table>\n * <div style={{opacity: isPending ? 0.5 : 1}}>\n * <button onClick={previousPage} disabled={!hasPreviousPage || isPending}>Previous</button>\n * <span>Page {currentPage} / {totalPages}</span>\n * <button onClick={nextPage} disabled={!hasNextPage || isPending}>Next</button>\n * </div>\n * </div>\n * )\n * }\n *\n * // Usage:\n * // const myDatasetHandle = createDatasetHandle({ projectId: 'p1', dataset: 'production' })\n * // <PaginatedDocumentList dataset={myDatasetHandle} documentType=\"post\" />\n * ```\n */\nexport function usePaginatedDocuments<\n TDocumentType extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n>({\n documentType,\n filter = '',\n pageSize = 25,\n params = {},\n orderings,\n search,\n ...options\n}: PaginatedDocumentsOptions<TDocumentType, TDataset, TProjectId>): PaginatedDocumentsResponse<\n TDocumentType,\n TDataset,\n TProjectId\n> {\n const instance = useSanityInstance(options)\n const [pageIndex, setPageIndex] = useState(0)\n const key = JSON.stringify({filter, search, params, orderings, pageSize})\n // Reset the pageIndex to 0 whenever any query parameters (filter, search,\n // params, orderings) or pageSize changes\n useEffect(() => {\n setPageIndex(0)\n }, [key])\n\n const startIndex = pageIndex * pageSize\n const endIndex = (pageIndex + 1) * pageSize\n const documentTypes = (Array.isArray(documentType) ? documentType : [documentType]).filter(\n (i) => typeof i === 'string',\n )\n\n const filterClause = useMemo(() => {\n const conditions: string[] = []\n const trimmedSearch = search?.trim()\n\n // Add search query filter if specified\n if (trimmedSearch) {\n const searchFilter = createGroqSearchFilter(trimmedSearch)\n if (searchFilter) {\n conditions.push(searchFilter)\n }\n }\n\n if (documentTypes?.length) {\n conditions.push(`(_type in $__types)`)\n }\n\n // Add additional filter if specified\n if (filter) {\n conditions.push(`(${filter})`)\n }\n\n return conditions.length ? `[${conditions.join(' && ')}]` : ''\n }, [filter, search, documentTypes?.length])\n\n const orderClause = orderings\n ? `| order(${orderings\n .map((ordering) =>\n [ordering.field, ordering.direction.toLowerCase()]\n .map((str) => str.trim())\n .filter(Boolean)\n .join(' '),\n )\n .join(',')})`\n : ''\n\n const dataQuery = `*${filterClause}${orderClause}[${startIndex}...${endIndex}]{\"documentId\":_id,\"documentType\":_type,...$__handle}`\n const countQuery = `count(*${filterClause})`\n\n const {\n data: {data, count},\n isPending,\n } = useQuery<{data: DocumentHandle<TDocumentType, TDataset, TProjectId>[]; count: number}>({\n ...options,\n query: `{\"data\":${dataQuery},\"count\":${countQuery}}`,\n params: {\n ...params,\n __types: documentTypes,\n __handle: {\n ...pick(instance.config, 'projectId', 'dataset', 'perspective'),\n ...pick(options, 'projectId', 'dataset', 'perspective'),\n },\n },\n })\n\n const totalPages = Math.ceil(count / pageSize)\n const currentPage = pageIndex + 1\n\n // Navigation methods\n const firstPage = useCallback(() => setPageIndex(0), [])\n const previousPage = useCallback(() => setPageIndex((prev) => Math.max(prev - 1, 0)), [])\n const nextPage = useCallback(\n () => setPageIndex((prev) => Math.min(prev + 1, totalPages - 1)),\n [totalPages],\n )\n const lastPage = useCallback(() => setPageIndex(totalPages - 1), [totalPages])\n const goToPage = useCallback(\n (pageNumber: number) => {\n if (pageNumber < 1 || pageNumber > totalPages) return\n setPageIndex(pageNumber - 1)\n },\n [totalPages],\n )\n\n // Boolean flags for page availability\n const hasFirstPage = pageIndex > 0\n const hasPreviousPage = pageIndex > 0\n const hasNextPage = pageIndex < totalPages - 1\n const hasLastPage = pageIndex < totalPages - 1\n\n return {\n data,\n isPending,\n pageSize,\n currentPage,\n totalPages,\n startIndex,\n endIndex,\n count,\n firstPage,\n hasFirstPage,\n previousPage,\n hasPreviousPage,\n nextPage,\n hasNextPage,\n lastPage,\n hasLastPage,\n goToPage,\n }\n}\n","import {getPresence, type UserPresence} from '@sanity/sdk'\nimport {useCallback, useMemo, useSyncExternalStore} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * A hook for subscribing to presence information for the current project.\n * @public\n */\nexport function usePresence(): {\n locations: UserPresence[]\n} {\n const sanityInstance = useSanityInstance()\n const source = useMemo(() => getPresence(sanityInstance), [sanityInstance])\n const subscribe = useCallback((callback: () => void) => source.subscribe(callback), [source])\n const locations = useSyncExternalStore(\n subscribe,\n () => source.getCurrent(),\n () => source.getCurrent(),\n )\n\n return {locations: locations || []}\n}\n","import {type DocumentHandle, getPreviewState, type PreviewValue, resolvePreview} from '@sanity/sdk'\nimport {useCallback, useSyncExternalStore} from 'react'\nimport {distinctUntilChanged, EMPTY, Observable, startWith, switchMap} from 'rxjs'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * @public\n * @category Types\n */\nexport interface useDocumentPreviewOptions extends DocumentHandle {\n /**\n * Optional ref object to track visibility. When provided, preview resolution\n * only occurs when the referenced element is visible in the viewport.\n */\n ref?: React.RefObject<unknown>\n}\n\n/**\n * @public\n * @category Types\n */\nexport interface useDocumentPreviewResults {\n /** The results of inferring the document’s preview values */\n data: PreviewValue\n /** True when inferred preview values are being refreshed */\n isPending: boolean\n}\n\n/**\n * @public\n *\n * Attempts to infer preview values of a document (specified via a `DocumentHandle`),\n * including the document’s `title`, `subtitle`, `media`, and `status`. These values are live and will update in realtime.\n * To reduce unnecessary network requests for resolving the preview values, an optional `ref` can be passed to the hook so that preview\n * resolution will only occur if the `ref` is intersecting the current viewport.\n *\n * See remarks below for futher information.\n *\n * @remarks\n * Values returned by this hook may not be as expected. It is currently unable to read preview values as defined in your schema;\n * instead, it attempts to infer these preview values by checking against a basic set of potential fields on your document.\n * We are anticipating being able to significantly improve this hook’s functionality and output in a future release.\n * For now, we recommend using {@link useDocumentProjection} for rendering individual document fields (or projections of those fields).\n *\n * @category Documents\n * @param options - The document handle for the document you want to infer preview values for, and an optional ref\n * @returns The inferred values for the given document and a boolean to indicate whether the resolution is pending\n *\n * @example Combining with useDocuments to render a collection of document previews\n * ```\n * // PreviewComponent.jsx\n * export default function PreviewComponent({ document }) {\n * const { data: { title, subtitle, media }, isPending } = useDocumentPreview({ document })\n * return (\n * <article style={{ opacity: isPending ? 0.5 : 1}}>\n * {media?.type === 'image-asset' ? <img src={media.url} alt='' /> : ''}\n * <h2>{title}</h2>\n * <p>{subtitle}</p>\n * </article>\n * )\n * }\n *\n * // DocumentList.jsx\n * const { data } = useDocuments({ filter: '_type == \"movie\"' })\n * return (\n * <div>\n * <h1>Movies</h1>\n * <ul>\n * {data.map(movie => (\n * <li key={movie._id}>\n * <Suspense fallback='Loading…'>\n * <PreviewComponent document={movie} />\n * </Suspense>\n * </li>\n * ))}\n * </ul>\n * </div>\n * )\n * ```\n */\nexport function useDocumentPreview({\n ref,\n ...docHandle\n}: useDocumentPreviewOptions): useDocumentPreviewResults {\n const instance = useSanityInstance(docHandle)\n const stateSource = getPreviewState(instance, docHandle)\n\n // Create subscribe function for useSyncExternalStore\n const subscribe = useCallback(\n (onStoreChanged: () => void) => {\n const subscription = new Observable<boolean>((observer) => {\n // For environments that don't have an intersection observer (e.g. server-side),\n // we pass true to always subscribe since we can't detect visibility\n if (typeof IntersectionObserver === 'undefined' || typeof HTMLElement === 'undefined') {\n observer.next(true)\n return\n }\n\n const intersectionObserver = new IntersectionObserver(\n ([entry]) => observer.next(entry.isIntersecting),\n {rootMargin: '0px', threshold: 0},\n )\n if (ref?.current && ref.current instanceof HTMLElement) {\n intersectionObserver.observe(ref.current)\n } else {\n // If no ref is provided or ref.current isn't an HTML element,\n // pass true to always subscribe since we can't track visibility\n observer.next(true)\n }\n return () => intersectionObserver.disconnect()\n })\n .pipe(\n startWith(false),\n distinctUntilChanged(),\n switchMap((isVisible) =>\n isVisible\n ? new Observable<void>((obs) => {\n return stateSource.subscribe(() => obs.next())\n })\n : EMPTY,\n ),\n )\n .subscribe({next: onStoreChanged})\n\n return () => subscription.unsubscribe()\n },\n [stateSource, ref],\n )\n\n // Create getSnapshot function to return current state\n const getSnapshot = useCallback(() => {\n const currentState = stateSource.getCurrent()\n if (currentState.data === null) throw resolvePreview(instance, docHandle)\n return currentState as useDocumentPreviewResults\n }, [docHandle, instance, stateSource])\n\n return useSyncExternalStore(subscribe, getSnapshot)\n}\n","import {\n type DocumentHandle,\n getProjectionState,\n resolveProjection,\n type ValidProjection,\n} from '@sanity/sdk'\nimport {type SanityProjectionResult} from 'groq'\nimport {useCallback, useSyncExternalStore} from 'react'\nimport {distinctUntilChanged, EMPTY, Observable, startWith, switchMap} from 'rxjs'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * @public\n * @category Types\n */\nexport interface useDocumentProjectionOptions<\n TProjection extends ValidProjection = ValidProjection,\n TDocumentType extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n> extends DocumentHandle<TDocumentType, TDataset, TProjectId> {\n /** The GROQ projection string */\n projection: TProjection\n /** Optional parameters for the projection query */\n params?: Record<string, unknown>\n /** Optional ref to track viewport intersection for lazy loading */\n ref?: React.RefObject<unknown>\n}\n\n/**\n * @public\n * @category Types\n */\nexport interface useDocumentProjectionResults<TData> {\n /** The projected data */\n data: TData\n /** True if the projection is currently being resolved */\n isPending: boolean\n}\n\n/**\n * @public\n *\n * Returns the projected values of a document based on the provided projection string.\n * These values are live and will update in realtime.\n * To optimize network requests, an optional `ref` can be passed to only resolve the projection\n * when the referenced element is intersecting the viewport.\n *\n * @category Documents\n * @remarks\n * This hook has multiple signatures allowing for fine-grained control over type inference:\n * - Using Typegen: Infers the return type based on the `documentType`, `dataset`, `projectId`, and `projection`.\n * - Using explicit type parameter: Allows specifying a custom return type `TData`.\n *\n * @param options - An object containing the `DocumentHandle` properties (`documentId`, `documentType`, etc.), the `projection` string, optional `params`, and an optional `ref`.\n * @returns An object containing the projection results (`data`) and a boolean indicating whether the resolution is pending (`isPending`). Note: Suspense handles initial loading states; `data` being `undefined` after initial loading means the document doesn't exist or the projection yielded no result.\n */\n\n// Overload 1: Relies on Typegen\n/**\n * @public\n * Fetch a projection, relying on Typegen for the return type based on the handle and projection.\n *\n * @category Documents\n * @param options - Options including the document handle properties (`documentId`, `documentType`, etc.) and the `projection`.\n * @returns The projected data, typed based on Typegen.\n *\n * @example Using Typegen for a book preview\n * ```tsx\n * // ProjectionComponent.tsx\n * import {useDocumentProjection, type DocumentHandle} from '@sanity/sdk-react'\n * import {useRef} from 'react'\n * import {defineProjection} from 'groq'\n *\n * // Define props using DocumentHandle with the specific document type\n * type ProjectionComponentProps = {\n * doc: DocumentHandle<'book'> // Typegen knows 'book'\n * }\n *\n * // This is required for typegen to generate the correct return type\n * const myProjection = defineProjection(`{\n * title,\n * 'coverImage': cover.asset->url,\n * 'authors': array::join(authors[]->{'name': firstName + ' ' + lastName}.name, ', ')\n * }`)\n *\n * export default function ProjectionComponent({ doc }: ProjectionComponentProps) {\n * const ref = useRef(null) // Optional ref to track viewport intersection for lazy loading\n *\n * // Spread the doc handle into the options\n * // Typegen infers the return type based on 'book' and the projection\n * const { data } = useDocumentProjection({\n * ...doc, // Pass the handle properties\n * ref,\n * projection: myProjection,\n * })\n *\n * // Suspense handles initial load, check for data existence after\n * return (\n * <article ref={ref}>\n * <h2>{data.title ?? 'Untitled'}</h2>\n * {data.coverImage && <img src={data.coverImage} alt={data.title} />}\n * <p>{data.authors ?? 'Unknown authors'}</p>\n * </article>\n * )\n * }\n *\n * // Usage:\n * // import {createDocumentHandle} from '@sanity/sdk-react'\n * // const myDocHandle = createDocumentHandle({ documentId: 'book123', documentType: 'book' })\n * // <Suspense fallback='Loading preview...'>\n * // <ProjectionComponent doc={myDocHandle} />\n * // </Suspense>\n * ```\n */\nexport function useDocumentProjection<\n TProjection extends ValidProjection = ValidProjection,\n TDocumentType extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n>(\n options: useDocumentProjectionOptions<TProjection, TDocumentType, TDataset, TProjectId>,\n): useDocumentProjectionResults<\n SanityProjectionResult<TProjection, TDocumentType, `${TProjectId}.${TDataset}`>\n>\n\n// Overload 2: Explicit type provided\n/**\n * @public\n * Fetch a projection with an explicitly defined return type `TData`.\n *\n * @param options - Options including the document handle properties (`documentId`, etc.) and the `projection`.\n * @returns The projected data, cast to the explicit type `TData`.\n *\n * @example Explicitly typing the projection result\n * ```tsx\n * import {useDocumentProjection, type DocumentHandle} from '@sanity/sdk-react'\n * import {useRef} from 'react'\n *\n * interface SimpleBookPreview {\n * title?: string;\n * authorName?: string;\n * }\n *\n * type BookPreviewProps = {\n * doc: DocumentHandle\n * }\n *\n * function BookPreview({ doc }: BookPreviewProps) {\n * const ref = useRef(null)\n * const { data } = useDocumentProjection<SimpleBookPreview>({\n * ...doc,\n * ref,\n * projection: `{ title, 'authorName': author->name }`\n * })\n *\n * return (\n * <div ref={ref}>\n * <h3>{data.title ?? 'No Title'}</h3>\n * <p>By: {data.authorName ?? 'Unknown'}</p>\n * </div>\n * )\n * }\n *\n * // Usage:\n * // import {createDocumentHandle} from '@sanity/sdk-react'\n * // const doc = createDocumentHandle({ documentId: 'abc', documentType: 'book' })\n * // <Suspense fallback='Loading...'>\n * // <BookPreview doc={doc} />\n * // </Suspense>\n * ```\n */\nexport function useDocumentProjection<TData extends object>(\n options: useDocumentProjectionOptions, // Uses base options type\n): useDocumentProjectionResults<TData>\n\n// Implementation (no JSDoc needed here as it's covered by overloads)\nexport function useDocumentProjection<TData extends object>({\n ref,\n projection,\n ...docHandle\n}: useDocumentProjectionOptions): useDocumentProjectionResults<TData> {\n const instance = useSanityInstance(docHandle)\n const stateSource = getProjectionState<TData>(instance, {...docHandle, projection})\n\n if (stateSource.getCurrent()?.data === null) {\n throw resolveProjection(instance, {...docHandle, projection})\n }\n\n // Create subscribe function for useSyncExternalStore\n const subscribe = useCallback(\n (onStoreChanged: () => void) => {\n const subscription = new Observable<boolean>((observer) => {\n // For environments that don't have an intersection observer (e.g. server-side),\n // we pass true to always subscribe since we can't detect visibility\n if (typeof IntersectionObserver === 'undefined' || typeof HTMLElement === 'undefined') {\n observer.next(true)\n return\n }\n\n const intersectionObserver = new IntersectionObserver(\n ([entry]) => observer.next(entry.isIntersecting),\n {rootMargin: '0px', threshold: 0},\n )\n if (ref?.current && ref.current instanceof HTMLElement) {\n intersectionObserver.observe(ref.current)\n } else {\n // If no ref is provided or ref.current isn't an HTML element,\n // pass true to always subscribe since we can't track visibility\n observer.next(true)\n }\n return () => intersectionObserver.disconnect()\n })\n .pipe(\n startWith(false),\n distinctUntilChanged(),\n switchMap((isVisible) =>\n isVisible\n ? new Observable<void>((obs) => {\n return stateSource.subscribe(() => obs.next())\n })\n : EMPTY,\n ),\n )\n .subscribe({next: onStoreChanged})\n\n return () => subscription.unsubscribe()\n },\n [stateSource, ref],\n )\n\n return useSyncExternalStore(\n subscribe,\n stateSource.getCurrent,\n ) as useDocumentProjectionResults<TData>\n}\n","import {\n getProjectState,\n type ProjectHandle,\n resolveProject,\n type SanityInstance,\n type SanityProject,\n type StateSource,\n} from '@sanity/sdk'\nimport {identity} from 'rxjs'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\ntype UseProject = {\n /**\n *\n * Returns metadata for a given project\n *\n * @category Projects\n * @param projectId - The ID of the project to retrieve metadata for\n * @returns The metadata for the project\n * @example\n * ```tsx\n * function ProjectMetadata({ projectId }: { projectId: string }) {\n * const project = useProject(projectId)\n *\n * return (\n * <figure style={{ backgroundColor: project.metadata.color || 'lavender'}}>\n * <h1>{project.displayName}</h1>\n * </figure>\n * )\n * }\n * ```\n */\n (projectHandle?: ProjectHandle): SanityProject\n}\n\n/**\n * @public\n * @function\n */\nexport const useProject: UseProject = createStateSourceHook({\n // remove `undefined` since we're suspending when that is the case\n getState: getProjectState as (\n instance: SanityInstance,\n projectHandle?: ProjectHandle,\n ) => StateSource<SanityProject>,\n shouldSuspend: (instance, projectHandle) =>\n getProjectState(instance, projectHandle).getCurrent() === undefined,\n suspender: resolveProject,\n getConfig: identity,\n})\n","import {type SanityProject} from '@sanity/client'\nimport {getProjectsState, resolveProjects, type SanityInstance, type StateSource} from '@sanity/sdk'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\n/**\n * @public\n * @category Types\n * @interface\n */\nexport type ProjectWithoutMembers = Omit<SanityProject, 'members'>\n\n/**\n * @public\n * @category Types\n */\ntype UseProjects = <TIncludeMembers extends boolean = false>(options?: {\n organizationId?: string\n includeMembers?: TIncludeMembers\n}) => TIncludeMembers extends true ? SanityProject[] : ProjectWithoutMembers[]\n\n/**\n * Returns metadata for each project you have access to.\n *\n * @category Projects\n * @param options - Configuration options\n * @returns An array of project metadata. If includeMembers is true, returns full SanityProject objects. Otherwise, returns ProjectWithoutMembers objects.\n * @example\n * ```tsx\n * const projects = useProjects()\n *\n * return (\n * <select>\n * {projects.map((project) => (\n * <option key={project.id}>{project.displayName}</option>\n * ))}\n * </select>\n * )\n * ```\n * @example\n * ```tsx\n * const projectsWithMembers = useProjects({ includeMembers: true })\n * const projectsWithoutMembers = useProjects({ includeMembers: false })\n * ```\n * @public\n * @function\n */\nexport const useProjects: UseProjects = createStateSourceHook({\n getState: getProjectsState as (\n instance: SanityInstance,\n options?: {organizationId?: string; includeMembers?: boolean},\n ) => StateSource<SanityProject[] | ProjectWithoutMembers[]>,\n shouldSuspend: (instance, options) =>\n getProjectsState(instance, options).getCurrent() === undefined,\n suspender: resolveProjects,\n}) as UseProjects\n","import {\n getActiveReleasesState,\n type ReleaseDocument,\n type SanityInstance,\n type StateSource,\n} from '@sanity/sdk'\nimport {filter, firstValueFrom} from 'rxjs'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\n/**\n * @public\n */\ntype UseActiveReleases = {\n (): ReleaseDocument[]\n}\n\n/**\n * @public\n\n * Returns the active releases for the current project,\n * represented as a list of release documents.\n *\n * @returns The active releases for the current project.\n * @category Projects\n * @example\n * ```tsx\n * import {useActiveReleases} from '@sanity/sdk-react'\n *\n * const activeReleases = useActiveReleases()\n * ```\n */\nexport const useActiveReleases: UseActiveReleases = createStateSourceHook({\n getState: getActiveReleasesState as (instance: SanityInstance) => StateSource<ReleaseDocument[]>,\n shouldSuspend: (instance: SanityInstance) =>\n getActiveReleasesState(instance).getCurrent() === undefined,\n suspender: (instance: SanityInstance) =>\n firstValueFrom(getActiveReleasesState(instance).observable.pipe(filter(Boolean))),\n})\n","import {\n getActiveReleasesState,\n getPerspectiveState,\n type PerspectiveHandle,\n type SanityInstance,\n type StateSource,\n} from '@sanity/sdk'\nimport {filter, firstValueFrom} from 'rxjs'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\n/**\n * @public\n */\ntype UsePerspective = {\n (perspectiveHandle: PerspectiveHandle): string | string[]\n}\n\n/**\n * @public\n * @function\n *\n * Returns a single or stack of perspectives for the given perspective handle,\n * which can then be used to correctly query the documents\n * via the `perspective` parameter in the client.\n *\n * @param perspectiveHandle - The perspective handle to get the perspective for.\n * @category Documents\n * @example\n * ```tsx\n * import {usePerspective, useQuery} from '@sanity/sdk-react'\n\n * const perspective = usePerspective({perspective: 'rxg1346', projectId: 'abc123', dataset: 'production'})\n * const {data} = useQuery<Movie[]>('*[_type == \"movie\"]', {\n * perspective: perspective,\n * })\n * ```\n *\n * @returns The perspective for the given perspective handle.\n */\nexport const usePerspective: UsePerspective = createStateSourceHook({\n getState: getPerspectiveState as (\n instance: SanityInstance,\n perspectiveHandle?: PerspectiveHandle,\n ) => StateSource<string | string[]>,\n shouldSuspend: (instance: SanityInstance, options?: PerspectiveHandle): boolean =>\n getPerspectiveState(instance, options).getCurrent() === undefined,\n suspender: (instance: SanityInstance, _options?: PerspectiveHandle) =>\n firstValueFrom(getActiveReleasesState(instance).observable.pipe(filter(Boolean))),\n})\n","import {\n type GetUserOptions,\n getUsersKey,\n getUsersState,\n parseUsersKey,\n resolveUsers,\n type SanityUser,\n} from '@sanity/sdk'\nimport {useEffect, useMemo, useState, useSyncExternalStore, useTransition} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * @public\n * @category Types\n */\nexport interface UserResult {\n /**\n * The user data fetched, or undefined if not found.\n */\n data: SanityUser | undefined\n /**\n * Whether a user request is currently in progress\n */\n isPending: boolean\n}\n\n/**\n *\n * @public\n *\n * Retrieves a single user by ID for a given resource (either a project or an organization).\n *\n * @category Users\n * @param options - The user ID, resource type, project ID, or organization ID\n * @returns The user data and loading state\n *\n * @example\n * ```\n * const { data, isPending } = useUser({\n * userId: 'gabc123',\n * resourceType: 'project',\n * projectId: 'my-project-id',\n * })\n *\n * return (\n * <div>\n * {isPending && <p>Loading...</p>}\n * {data && (\n * <figure>\n * <img src={data.profile.imageUrl} alt='' />\n * <figcaption>{data.profile.displayName}</figcaption>\n * <address>{data.profile.email}</address>\n * </figure>\n * )}\n * </div>\n * )\n * ```\n */\nexport function useUser(options: GetUserOptions): UserResult {\n const instance = useSanityInstance(options)\n // Use React's useTransition to avoid UI jank when user options change\n const [isPending, startTransition] = useTransition()\n\n // Get the unique key for this user request and its options\n const key = getUsersKey(instance, options)\n // Use a deferred state to avoid immediate re-renders when the user request changes\n const [deferredKey, setDeferredKey] = useState(key)\n // Parse the deferred user key back into user options\n const deferred = useMemo(() => parseUsersKey(deferredKey), [deferredKey])\n\n // Create an AbortController to cancel in-flight requests when needed\n const [ref, setRef] = useState<AbortController>(new AbortController())\n\n // When the user request or options change, start a transition to update the request\n useEffect(() => {\n if (key === deferredKey) return\n\n startTransition(() => {\n if (!ref.signal.aborted) {\n ref.abort()\n setRef(new AbortController())\n }\n\n setDeferredKey(key)\n })\n }, [deferredKey, key, ref])\n\n // Get the state source for this user request from the users store\n // We pass the userId as part of options to getUsersState\n const {getCurrent, subscribe} = useMemo(() => {\n return getUsersState(instance, deferred as GetUserOptions)\n }, [instance, deferred])\n\n // If data isn't available yet, suspend rendering until it is\n // This is the React Suspense integration - throwing a promise\n // will cause React to show the nearest Suspense fallback\n if (getCurrent() === undefined) {\n throw resolveUsers(instance, {...(deferred as GetUserOptions), signal: ref.signal})\n }\n\n // Subscribe to updates and get the current data\n // useSyncExternalStore ensures the component re-renders when the data changes\n // Extract the first user from the users array (since we're fetching by userId, there should be only one)\n const result = useSyncExternalStore(subscribe, getCurrent)\n const data = result?.data[0]\n\n return {data, isPending}\n}\n","import {\n getUsersKey,\n type GetUsersOptions,\n getUsersState,\n loadMoreUsers,\n parseUsersKey,\n resolveUsers,\n type SanityUser,\n} from '@sanity/sdk'\nimport {useCallback, useEffect, useMemo, useState, useSyncExternalStore, useTransition} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * @public\n * @category Types\n */\nexport interface UsersResult {\n /**\n * The users fetched.\n */\n data: SanityUser[]\n /**\n * Whether there are more users to fetch.\n */\n hasMore: boolean\n\n /**\n * Whether a users request is currently in progress\n */\n isPending: boolean\n /**\n * Load more users.\n */\n loadMore: () => void\n}\n\n/**\n *\n * @public\n *\n * Retrieves the users for a given resource (either a project or an organization).\n *\n * @category Users\n * @param params - The resource type, project ID, and the limit of users to fetch\n * @returns A list of users, a boolean indicating whether there are more users to fetch, and a function to load more users\n *\n * @example\n * ```\n * const { data, hasMore, loadMore, isPending } = useUsers({\n * resourceType: 'organization',\n * organizationId: 'my-org-id',\n * batchSize: 10,\n * })\n *\n * return (\n * <div>\n * {data.map(user => (\n * <figure key={user.sanityUserId}>\n * <img src={user.profile.imageUrl} alt='' />\n * <figcaption>{user.profile.displayName}</figcaption>\n * <address>{user.profile.email}</address>\n * </figure>\n * ))}\n * {hasMore && <button onClick={loadMore}>{isPending ? 'Loading...' : 'Load More'</button>}\n * </div>\n * )\n * ```\n */\nexport function useUsers(options?: GetUsersOptions): UsersResult {\n const instance = useSanityInstance(options)\n // Use React's useTransition to avoid UI jank when user options change\n const [isPending, startTransition] = useTransition()\n\n // Get the unique key for this users request and its options\n const key = getUsersKey(instance, options)\n // Use a deferred state to avoid immediate re-renders when the users request changes\n const [deferredKey, setDeferredKey] = useState(key)\n // Parse the deferred users key back into users options\n const deferred = useMemo(() => parseUsersKey(deferredKey), [deferredKey])\n\n // Create an AbortController to cancel in-flight requests when needed\n const [ref, setRef] = useState<AbortController>(new AbortController())\n\n // When the users request or options change, start a transition to update the request\n useEffect(() => {\n if (key === deferredKey) return\n\n startTransition(() => {\n if (!ref.signal.aborted) {\n ref.abort()\n setRef(new AbortController())\n }\n\n setDeferredKey(key)\n })\n }, [deferredKey, key, ref])\n\n // Get the state source for this users request from the users store\n const {getCurrent, subscribe} = useMemo(() => {\n return getUsersState(instance, deferred)\n }, [instance, deferred])\n\n // If data isn't available yet, suspend rendering until it is\n // This is the React Suspense integration - throwing a promise\n // will cause React to show the nearest Suspense fallback\n if (getCurrent() === undefined) {\n throw resolveUsers(instance, {...deferred, signal: ref.signal})\n }\n\n // Subscribe to updates and get the current data\n // useSyncExternalStore ensures the component re-renders when the data changes\n const {data, hasMore} = useSyncExternalStore(subscribe, getCurrent)!\n\n const loadMore = useCallback(() => {\n loadMoreUsers(instance, options)\n }, [instance, options])\n\n return {data, hasMore, isPending, loadMore}\n}\n","// Local type declaration for Remix\ntype WindowWithEnv = Window &\n typeof globalThis & {\n ENV?: Record<string, unknown>\n }\n\ntype KnownEnvVar = 'DEV' | 'PKG_VERSION'\n\nexport function getEnv(key: KnownEnvVar): unknown {\n if (typeof import.meta !== 'undefined' && import.meta.env) {\n // Vite environment variables\n return (import.meta.env as unknown as Record<string, unknown>)[key]\n } else if (typeof process !== 'undefined' && process.env) {\n // Node.js or server-side environment variables\n return process.env[key]\n } else if (typeof window !== 'undefined' && (window as WindowWithEnv).ENV) {\n // Remix-style client-side environment variables\n return (window as WindowWithEnv).ENV?.[key]\n }\n return undefined\n}\n","import {version} from '../package.json'\nimport {getEnv} from './utils/getEnv'\n\n/**\n * This version is provided by pkg-utils at build time\n * @internal\n */\nexport const REACT_SDK_VERSION = getEnv('PKG_VERSION') || `${version}-development`\n"],"names":["SanityInstanceContext","createContext","useSanityInstance","config","$","_c","instance","useContext","Error","JSON","stringify","t0","match","createStateSourceHook","options","getState","getConfig","undefined","suspense","useHook","params","t1","suspender","shouldSuspend","t2","state","useSyncExternalStore","subscribe","getCurrent","useAuthState","getAuthState","useNodeState","getNodeState","nodeInput","firstValueFrom","observable","pipe","filter","Boolean","useWindowConnection","name","connectTo","onMessage","node","Symbol","for","messageUnsubscribers","useRef","t3","Object","entries","forEach","t4","type","handler","messageUnsubscribe","on","current","push","_temp","useEffect","t5","type_0","data","post","sendMessage","t6","type_1","data_0","fetchOptions","fetch","t7","unsubscribe","DEFAULT_RESPONSE_TIMEOUT","DashboardTokenRefresh","children","isTokenRefreshInProgress","timeoutRef","processed401ErrorRef","authState","clearTimeout","clearRefreshTimeout","SDK_NODE_NAME","SDK_CHANNEL_NAME","windowConnection","setTimeout","res","token","errorContainer","document","getElementById","Array","from","getElementsByTagName","some","remove","requestNewToken","error","has401Error","AuthStateType","ERROR","statusCode","isLoggedOut","LOGGED_OUT","div","textContent","includes","ComlinkTokenRefreshProvider","getIsInDashboardState","useLoginUrl","getLoginUrlState","useVerifyOrgProjects","projectIds","disabled","setError","useState","length","subscription","observeOrganizationVerificationState","result","isInIframe","window","self","top","isLocalUrl","url","location","href","startsWith","AuthError","constructor","message","cause","ConfigurationError","createCallbackHook","callback","useHandleAuthCallback","handleAuthCallback","LoginCallback","URL","toString","then","replacementLocation","history","replaceState","useLogOut","logout","LoginError","resetErrorBoundary","ClientError","authErrorMessage","setAuthErrorMessage","handleRetry","errorMessage","response","body","endsWith","t8","t9","querySelector","parsedUrl","mode","URLSearchParams","hash","slice","get","script","createElement","src","async","head","appendChild","AuthBoundary","props","LoginErrorComponent","fallbackProps","FallbackComponent","AuthSwitch","CallbackComponent","verifyOrganization","orgError","isDestroyingSession","loginUrl","LOGGING_IN","LOGGED_IN","DEFAULT_FALLBACK","ResourceProvider","fallback","parent","createChild","createSanityInstance","disposal","timeoutId","isDisposed","dispose","SDKProvider","configs","isArray","reverse","map","c","projectId","id","createNestedProviders","index","REDIRECT_URL","SanityApp","timeout","primaryConfig","studioMode","enabled","console","warn","replace","useAuthToken","getTokenState","useCurrentUser","getCurrentUserState","useDashboardOrganizationId","getDashboardOrganizationId","useClient","getClientState","identity","useFrameConnection","targetOrigin","heartbeat","onStatus","controllerRef","channelRef","controller","getOrCreateController","channel","getOrCreateChannel","event","status","releaseChannel","frameWindow","removeTarget","addTarget","connect","unsub","useDashboardNavigate","navigateFn","useManageFavorite","documentId","documentType","paramProjectId","dataset","paramDataset","resourceId","paramResourceId","resourceType","schemaName","instanceProjectId","instanceDataset","context","useMemo","favoriteState","getFavoritesState","isFavorited","handleFavoriteAction","useCallback","action","payload","eventType","resource","success","resolveFavoritesState","err","favorite","unfavorite","useStudioWorkspacesByProjectIdDataset","workspacesByProjectIdAndDataset","setWorkspacesByProjectIdAndDataset","fetchWorkspaces","signal","workspaceMap","noProjectIdAndDataset","availableResources","key","AbortController","abort","useNavigateToStudioDocument","documentHandle","preferredStudioUrl","workspace","find","w","workspaces","path","navigateToStudioDocument","useRecordDocumentHistoryEvent","recordEvent","useDatasets","getDatasetsState","projectHandle","resolveDatasets","useApplyDocumentActions","applyDocumentActions","useDocumentValue","getDocumentState","_path","resolveDocument","wrapHookWithData","useValue","useDocument","useDocumentEvent","datasetHandle","onEvent","ref","useInsertionEffect","documentEvent","stableHandler","subscribeDocumentEvents","useDocumentPermissions","actionOrActions","actions","getPermissionsState","useDocumentSyncStatus","getDocumentSyncStatus","doc","ignoredKeys","useEditDocument","apply","updater","currentPath","currentValue","nextValue","editDocument","set","nextValue_0","editActions","keys","key_0","key_1","unset","useQuery","isPending","startTransition","useTransition","queryKey","getQueryKey","deferredQueryKey","setDeferredQueryKey","deferred","parseQueryKey","aborted","getQueryState","currentSignal","resolveQuery","DEFAULT_BATCH_SIZE","useDocuments","batchSize","search","orderings","limit","setLimit","documentTypes","i","types","filterClause","conditions","trimmedSearch","trim","searchFilter","createGroqSearchFilter","join","orderClause","ordering","field","direction","toLowerCase","str","dataQuery","countQuery","count","query","__handle","pick","__types","hasMore","loadMore","prev","Math","min","usePaginatedDocuments","pageSize","pageIndex","setPageIndex","startIndex","endIndex","t10","_temp3","t11","t12","t13","t14","t15","t16","t17","totalPages","ceil","currentPage","t18","firstPage","t19","_temp4","previousPage","t20","prev_0","nextPage","t21","lastPage","t22","pageNumber","goToPage","hasFirstPage","hasPreviousPage","hasNextPage","hasLastPage","t23","max","_temp2","usePresence","sanityInstance","getPresence","source","locations","useDocumentPreview","docHandle","getPreviewState","stateSource","onStoreChanged","Observable","observer","IntersectionObserver","HTMLElement","next","intersectionObserver","entry","isIntersecting","rootMargin","threshold","observe","disconnect","startWith","distinctUntilChanged","switchMap","isVisible","obs","EMPTY","currentState","resolvePreview","useDocumentProjection","projection","getProjectionState","resolveProjection","useProject","getProjectState","resolveProject","useProjects","getProjectsState","resolveProjects","useActiveReleases","getActiveReleasesState","usePerspective","getPerspectiveState","_options","useUser","getUsersKey","deferredKey","setDeferredKey","parseUsersKey","setRef","getUsersState","resolveUsers","useUsers","loadMoreUsers","getEnv","import","env","process","ENV","REACT_SDK_VERSION","version"],"mappings":";;;;;;;;;;AAGaA,MAAAA,wBAAwBC,cAAqC,IAAI,GCwDjEC,oBAAoBC,CAAA,WAAA;AAAA,QAAAC,IAAAC,EAAA,CAAA,GAC/BC,WAAiBC,WAAAP,qBAAgC;AAAC,MAAA,CAE7CM;AAAQ,UAAA,IAAAE,MAET,qCAAqCL,SAAS,qBAAqBM,KAAAC,UAAeP,QAAe,MAAA,CAAA,CAAC,OAAO,EAAE,8FAA8F;AAAA,MAAA,CAIxMA;AAAeG,WAAAA;AAAQK,MAAAA;AAAAP,IAAAD,CAAAA,MAAAA,UAAAC,SAAAE,YAEdK,KAAAL,SAAQM,MAAOT,MAAM,GAACC,OAAAD,Q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A;AACnB,UAAM0c,aAAard,UAAU;AAAA,MAAC,GAAGkV;AAAAA,MAAUrE,QAAQkC,IAAIlC;AAAAA,IAAAA,CAAO;AAK1D,QAAA;AAAA,IAACpN;AAAAA,IAAM6T;AAAAA,EAAAA,IAAWlW,qBAAqBC,WAAWC,UAAU,GAE5DiW,WAAWxH,YAAY,MAAM;AACjCwN,kBAAcvd,UAAUQ,OAAO;AAAA,EAAA,GAC9B,CAACR,UAAUQ,OAAO,CAAC;AAEf,SAAA;AAAA,IAACiD;AAAAA,IAAM6T;AAAAA,IAAS3C;AAAAA,IAAW4C;AAAAA,EAAQ;AAC5C;;AC/GO,SAASiG,OAAOvM,KAA2B;AAC5C,MAAA,OAAOwM,cAAgB,OAAeA,YAAYC;AAE5CD,WAAAA,YAAYC,IAA2CzM,GAAG;AACzD,MAAA,OAAO0M,UAAY,OAAeA,QAAQD;AAE5CC,WAAAA,QAAQD,IAAIzM,GAAG;AACb,MAAA,OAAO9J,SAAW,OAAgBA,OAAyByW;AAE5DzW,WAAAA,OAAyByW,MAAM3M,GAAG;AAG9C;ACbO,MAAM4M,oBAAoBL,OAAO,aAAa,KAAK,GAAGM,OAAO;"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../src/context/SanityInstanceContext.ts","../src/hooks/context/useSanityInstance.ts","../src/hooks/helpers/createStateSourceHook.tsx","../src/hooks/auth/useAuthState.tsx","../src/hooks/comlink/useWindowConnection.ts","../src/context/ComlinkTokenRefresh.tsx","../src/hooks/auth/useLoginUrl.tsx","../src/hooks/auth/useVerifyOrgProjects.tsx","../src/components/errors/Error.styles.ts","../src/components/errors/Error.tsx","../src/components/errors/CorsErrorComponent.tsx","../src/components/utils.ts","../src/components/auth/AuthError.ts","../src/components/auth/ConfigurationError.ts","../src/hooks/helpers/createCallbackHook.tsx","../src/hooks/auth/useHandleAuthCallback.tsx","../src/components/auth/LoginCallback.tsx","../src/hooks/auth/useLogOut.tsx","../src/components/auth/LoginError.tsx","../src/components/auth/AuthBoundary.tsx","../src/context/ResourceProvider.tsx","../src/components/SDKProvider.tsx","../src/components/SanityApp.tsx","../src/hooks/auth/useAuthToken.tsx","../src/hooks/auth/useCurrentUser.tsx","../src/hooks/auth/useDashboardOrganizationId.tsx","../src/hooks/client/useClient.ts","../src/hooks/comlink/useFrameConnection.ts","../src/hooks/dashboard/useDashboardNavigate.ts","../src/hooks/dashboard/useManageFavorite.ts","../src/hooks/dashboard/useStudioWorkspacesByProjectIdDataset.ts","../src/hooks/dashboard/useNavigateToStudioDocument.ts","../src/hooks/dashboard/useRecordDocumentHistoryEvent.ts","../src/hooks/datasets/useDatasets.ts","../src/hooks/document/useApplyDocumentActions.ts","../src/hooks/document/useDocument.ts","../src/hooks/document/useDocumentEvent.ts","../src/hooks/document/useDocumentPermissions.ts","../src/hooks/document/useDocumentSyncStatus.ts","../src/hooks/document/useEditDocument.ts","../src/hooks/query/useQuery.ts","../src/hooks/documents/useDocuments.ts","../src/hooks/paginatedDocuments/usePaginatedDocuments.ts","../src/hooks/presence/usePresence.ts","../src/hooks/preview/useDocumentPreview.tsx","../src/hooks/projection/useDocumentProjection.ts","../src/hooks/projects/useProject.ts","../src/hooks/projects/useProjects.ts","../src/hooks/releases/useActiveReleases.ts","../src/hooks/releases/usePerspective.ts","../src/hooks/users/useUser.ts","../src/hooks/users/useUsers.ts","../src/utils/getEnv.ts","../src/version.ts"],"sourcesContent":["import {type SanityInstance} from '@sanity/sdk'\nimport {createContext} from 'react'\n\nexport const SanityInstanceContext = createContext<SanityInstance | null>(null)\n","import {type SanityConfig, type SanityInstance} from '@sanity/sdk'\nimport {useContext} from 'react'\n\nimport {SanityInstanceContext} from '../../context/SanityInstanceContext'\n\n/**\n * Retrieves the current Sanity instance or finds a matching instance from the hierarchy\n *\n * @public\n *\n * @category Platform\n * @param config - Optional configuration to match against when finding an instance\n * @returns The current or matching Sanity instance\n *\n * @remarks\n * This hook accesses the nearest Sanity instance from the React context. When provided with\n * a configuration object, it traverses up the instance hierarchy to find the closest instance\n * that matches the specified configuration using shallow comparison of properties.\n *\n * The hook must be used within a component wrapped by a `ResourceProvider` or `SanityApp`.\n *\n * Use this hook when you need to:\n * - Access the current SanityInstance from context\n * - Find a specific instance with matching project/dataset configuration\n * - Access a parent instance with specific configuration values\n *\n * @example Get the current instance\n * ```tsx\n * // Get the current instance from context\n * const instance = useSanityInstance()\n * console.log(instance.config.projectId)\n * ```\n *\n * @example Find an instance with specific configuration\n * ```tsx\n * // Find an instance matching the given project and dataset\n * const instance = useSanityInstance({\n * projectId: 'abc123',\n * dataset: 'production'\n * })\n *\n * // Use instance for API calls\n * const fetchDocument = (docId) => {\n * // Instance is guaranteed to have the matching config\n * return client.fetch(`*[_id == $id][0]`, { id: docId })\n * }\n * ```\n *\n * @example Match partial configuration\n * ```tsx\n * // Find an instance with specific auth configuration\n * const instance = useSanityInstance({\n * auth: { requireLogin: true }\n * })\n * ```\n *\n * @throws Error if no SanityInstance is found in context\n * @throws Error if no matching instance is found for the provided config\n */\nexport const useSanityInstance = (config?: SanityConfig): SanityInstance => {\n const instance = useContext(SanityInstanceContext)\n\n if (!instance) {\n throw new Error(\n `SanityInstance context not found. ${config ? `Requested config: ${JSON.stringify(config, null, 2)}. ` : ''}Please ensure that your component is wrapped in a ResourceProvider or a SanityApp component.`,\n )\n }\n\n if (!config) return instance\n\n const match = instance.match(config)\n if (!match) {\n throw new Error(\n `Could not find a matching Sanity instance for the requested configuration: ${JSON.stringify(config, null, 2)}.\nPlease ensure there is a ResourceProvider component with a matching configuration in the component hierarchy.`,\n )\n }\n\n return match\n}\n","import {type SanityConfig, type SanityInstance, type StateSource} from '@sanity/sdk'\nimport {useSyncExternalStore} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\ntype StateSourceFactory<TParams extends unknown[], TState> = (\n instance: SanityInstance,\n ...params: TParams\n) => StateSource<TState>\n\ninterface CreateStateSourceHookOptions<TParams extends unknown[], TState> {\n getState: StateSourceFactory<TParams, TState>\n shouldSuspend?: (instance: SanityInstance, ...params: TParams) => boolean\n suspender?: (instance: SanityInstance, ...params: TParams) => Promise<unknown>\n getConfig?: (...params: TParams) => SanityConfig | undefined\n}\n\nexport function createStateSourceHook<TParams extends unknown[], TState>(\n options: StateSourceFactory<TParams, TState> | CreateStateSourceHookOptions<TParams, TState>,\n): (...params: TParams) => TState {\n const getState = typeof options === 'function' ? options : options.getState\n const getConfig = 'getConfig' in options ? options.getConfig : undefined\n const suspense = 'shouldSuspend' in options && 'suspender' in options ? options : undefined\n\n function useHook(...params: TParams) {\n const instance = useSanityInstance(getConfig?.(...params))\n\n if (suspense?.suspender && suspense?.shouldSuspend?.(instance, ...params)) {\n throw suspense.suspender(instance, ...params)\n }\n\n const state = getState(instance, ...params)\n return useSyncExternalStore(state.subscribe, state.getCurrent)\n }\n\n return useHook\n}\n","import {type AuthState, getAuthState} from '@sanity/sdk'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\n/**\n * @internal\n * A React hook that subscribes to authentication state changes.\n *\n * This hook provides access to the current authentication state type from the Sanity auth store.\n * It automatically re-renders when the authentication state changes.\n *\n * @remarks\n * The hook uses `useSyncExternalStore` to safely subscribe to auth state changes\n * and ensure consistency between server and client rendering.\n *\n * @returns The current authentication state type\n *\n * @example\n * ```tsx\n * function AuthStatus() {\n * const authState = useAuthState()\n * return <div>Current auth state: {authState}</div>\n * }\n * ```\n */\nexport const useAuthState: () => AuthState = createStateSourceHook(getAuthState)\n","import {type MessageData, type NodeInput} from '@sanity/comlink'\nimport {\n type FrameMessage,\n getNodeState,\n type NodeState,\n type SanityInstance,\n type StateSource,\n type WindowMessage,\n} from '@sanity/sdk'\nimport {useCallback, useEffect, useRef} from 'react'\nimport {filter, firstValueFrom} from 'rxjs'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\n/**\n * @internal\n */\nexport type WindowMessageHandler<TFrameMessage extends FrameMessage> = (\n event: TFrameMessage['data'],\n) => TFrameMessage['response']\n\n/**\n * @internal\n */\nexport interface UseWindowConnectionOptions<TMessage extends FrameMessage> {\n name: string\n connectTo: string\n onMessage?: Record<TMessage['type'], WindowMessageHandler<TMessage>>\n}\n\n/**\n * @internal\n */\nexport interface WindowConnection<TMessage extends WindowMessage> {\n sendMessage: <TType extends TMessage['type']>(\n type: TType,\n data?: Extract<TMessage, {type: TType}>['data'],\n ) => void\n fetch: <TResponse>(\n type: string,\n data?: MessageData,\n options?: {\n signal?: AbortSignal\n suppressWarnings?: boolean\n responseTimeout?: number\n },\n ) => Promise<TResponse>\n}\n\nconst useNodeState = createStateSourceHook({\n getState: getNodeState as (\n instance: SanityInstance,\n nodeInput: NodeInput,\n ) => StateSource<NodeState>,\n shouldSuspend: (instance: SanityInstance, nodeInput: NodeInput) =>\n getNodeState(instance, nodeInput).getCurrent() === undefined,\n suspender: (instance: SanityInstance, nodeInput: NodeInput) => {\n return firstValueFrom(getNodeState(instance, nodeInput).observable.pipe(filter(Boolean)))\n },\n})\n\n/**\n * @internal\n * Hook to wrap a Comlink node in a React hook.\n * Our store functionality takes care of the lifecycle of the node,\n * as well as sharing a single node between invocations if they share the same name.\n *\n * Generally not to be used directly, but to be used as a dependency of\n * Comlink-powered hooks like `useManageFavorite`.\n */\nexport function useWindowConnection<\n TWindowMessage extends WindowMessage,\n TFrameMessage extends FrameMessage,\n>({\n name,\n connectTo,\n onMessage,\n}: UseWindowConnectionOptions<TFrameMessage>): WindowConnection<TWindowMessage> {\n const {node} = useNodeState({name, connectTo})\n const messageUnsubscribers = useRef<(() => void)[]>([])\n const instance = useSanityInstance()\n\n useEffect(() => {\n if (onMessage) {\n Object.entries(onMessage).forEach(([type, handler]) => {\n const messageUnsubscribe = node.on(type, handler as WindowMessageHandler<TFrameMessage>)\n if (messageUnsubscribe) {\n messageUnsubscribers.current.push(messageUnsubscribe)\n }\n })\n }\n\n return () => {\n messageUnsubscribers.current.forEach((unsubscribe) => unsubscribe())\n messageUnsubscribers.current = []\n }\n }, [instance, name, onMessage, node])\n\n const sendMessage = useCallback(\n (type: TWindowMessage['type'], data?: Extract<TWindowMessage, {type: typeof type}>['data']) => {\n node.post(type, data)\n },\n [node],\n )\n\n const fetch = useCallback(\n <TResponse>(\n type: string,\n data?: MessageData,\n fetchOptions?: {\n responseTimeout?: number\n signal?: AbortSignal\n suppressWarnings?: boolean\n },\n ): Promise<TResponse> => {\n return node.fetch(type, data, fetchOptions ?? {}) as Promise<TResponse>\n },\n [node],\n )\n return {\n sendMessage,\n fetch,\n }\n}\n","import {type ClientError} from '@sanity/client'\nimport {SDK_CHANNEL_NAME, SDK_NODE_NAME} from '@sanity/message-protocol'\nimport {\n AuthStateType,\n type FrameMessage,\n getIsInDashboardState,\n type NewTokenResponseMessage,\n type RequestNewTokenMessage,\n setAuthToken,\n type WindowMessage,\n} from '@sanity/sdk'\nimport React, {type PropsWithChildren, useCallback, useEffect, useMemo, useRef} from 'react'\n\nimport {useAuthState} from '../hooks/auth/useAuthState'\nimport {useWindowConnection} from '../hooks/comlink/useWindowConnection'\nimport {useSanityInstance} from '../hooks/context/useSanityInstance'\n\n// Define specific message types extending the base types for clarity\ntype SdkParentComlinkMessage = NewTokenResponseMessage | WindowMessage // Messages received by SDK\ntype SdkChildComlinkMessage = RequestNewTokenMessage | FrameMessage // Messages sent by SDK\n\nconst DEFAULT_RESPONSE_TIMEOUT = 10000 // 10 seconds\n\n/**\n * Component that handles token refresh in dashboard mode\n */\nfunction DashboardTokenRefresh({children}: PropsWithChildren) {\n const instance = useSanityInstance()\n const isTokenRefreshInProgress = useRef(false)\n const timeoutRef = useRef<NodeJS.Timeout | null>(null)\n const processed401ErrorRef = useRef<unknown | null>(null)\n const authState = useAuthState()\n\n const clearRefreshTimeout = useCallback(() => {\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current)\n timeoutRef.current = null\n }\n }, [])\n\n const windowConnection = useWindowConnection<SdkParentComlinkMessage, SdkChildComlinkMessage>({\n name: SDK_NODE_NAME,\n connectTo: SDK_CHANNEL_NAME,\n })\n\n const requestNewToken = useCallback(async () => {\n if (isTokenRefreshInProgress.current) {\n return\n }\n\n isTokenRefreshInProgress.current = true\n clearRefreshTimeout()\n\n timeoutRef.current = setTimeout(() => {\n if (isTokenRefreshInProgress.current) {\n isTokenRefreshInProgress.current = false\n }\n timeoutRef.current = null\n }, DEFAULT_RESPONSE_TIMEOUT)\n\n try {\n const res = await windowConnection.fetch<{token: string | null; error?: string}>(\n 'dashboard/v1/auth/tokens/create',\n )\n clearRefreshTimeout()\n\n if (res.token) {\n setAuthToken(instance, res.token)\n\n // Remove the unauthorized error from the error container\n const errorContainer = document.getElementById('__sanityError')\n if (errorContainer) {\n const hasUnauthorizedError = Array.from(errorContainer.getElementsByTagName('div')).some(\n (div) =>\n div.textContent?.includes(\n 'Uncaught error: Unauthorized - A valid session is required for this endpoint',\n ),\n )\n\n if (hasUnauthorizedError) {\n errorContainer.remove()\n }\n }\n }\n isTokenRefreshInProgress.current = false\n } catch {\n isTokenRefreshInProgress.current = false\n clearRefreshTimeout()\n }\n }, [windowConnection, clearRefreshTimeout, instance])\n\n useEffect(() => {\n return () => {\n clearRefreshTimeout()\n }\n }, [clearRefreshTimeout])\n\n useEffect(() => {\n const has401Error =\n authState.type === AuthStateType.ERROR &&\n authState.error &&\n (authState.error as ClientError)?.statusCode === 401 &&\n !isTokenRefreshInProgress.current &&\n processed401ErrorRef.current !== authState.error\n\n const isLoggedOut =\n authState.type === AuthStateType.LOGGED_OUT && !isTokenRefreshInProgress.current\n\n if (has401Error || isLoggedOut) {\n processed401ErrorRef.current =\n authState.type === AuthStateType.ERROR ? authState.error : undefined\n requestNewToken()\n } else if (\n authState.type !== AuthStateType.ERROR ||\n processed401ErrorRef.current !==\n (authState.type === AuthStateType.ERROR ? authState.error : undefined)\n ) {\n processed401ErrorRef.current = null\n }\n }, [authState, requestNewToken])\n\n return children\n}\n\n/**\n * This provider is used to provide the Comlink token refresh feature.\n * It is used to automatically request a new token on 401 error if enabled.\n * @public\n */\nexport const ComlinkTokenRefreshProvider: React.FC<PropsWithChildren> = ({children}) => {\n const instance = useSanityInstance()\n const isInDashboard = useMemo(() => getIsInDashboardState(instance).getCurrent(), [instance])\n const studioModeEnabled = !!instance.config.studioMode?.enabled\n\n if (isInDashboard && !studioModeEnabled) {\n return <DashboardTokenRefresh>{children}</DashboardTokenRefresh>\n }\n\n // If we're not in the dashboard, we don't need to do anything\n return children\n}\n","import {getLoginUrlState} from '@sanity/sdk'\nimport {useMemo, useSyncExternalStore} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * @internal\n */\nexport function useLoginUrl(): string {\n const instance = useSanityInstance()\n const {subscribe, getCurrent} = useMemo(() => getLoginUrlState(instance), [instance])\n\n return useSyncExternalStore(subscribe, getCurrent as () => string)\n}\n","import {observeOrganizationVerificationState, type OrgVerificationResult} from '@sanity/sdk'\nimport {useEffect, useState} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * Hook that verifies the current projects belongs to the organization ID specified in the dashboard context.\n *\n * @public\n * @param disabled - When true, disables verification and skips project verification API calls\n * @returns Error message if the project doesn't match the organization ID, or null if all match or verification isn't needed\n * @category Projects\n * @example\n * ```tsx\n * function OrgVerifier() {\n * const error = useVerifyOrgProjects()\n *\n * if (error) {\n * return <div className=\"error\">{error}</div>\n * }\n *\n * return <div>Organization projects verified!</div>\n * }\n * ```\n */\nexport function useVerifyOrgProjects(disabled = false, projectIds?: string[]): string | null {\n const instance = useSanityInstance()\n const [error, setError] = useState<string | null>(null)\n\n useEffect(() => {\n if (disabled || !projectIds || projectIds.length === 0) {\n if (error !== null) setError(null)\n return\n }\n\n const verificationObservable$ = observeOrganizationVerificationState(instance, projectIds)\n\n const subscription = verificationObservable$.subscribe((result: OrgVerificationResult) => {\n setError(result.error)\n })\n\n return () => {\n subscription.unsubscribe()\n }\n }, [instance, disabled, error, projectIds])\n\n return error\n}\n","const FONT_SANS_SERIF = `-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Helvetica, Arial, system-ui, sans-serif`\nconst FONT_MONOSPACE = `-apple-system-ui-monospace, 'SF Mono', Menlo, Monaco, Consolas, monospace`\n\nconst styles: Record<string, React.CSSProperties> = {\n container: {\n padding: '28px',\n fontFamily: FONT_SANS_SERIF,\n display: 'flex',\n flexDirection: 'column',\n gap: '21px',\n fontSize: '14px',\n },\n heading: {\n margin: 0,\n fontSize: '28px',\n fontWeight: 700,\n },\n paragraph: {\n margin: 0,\n },\n link: {\n appearance: 'none',\n background: 'transparent',\n border: 0,\n padding: 0,\n font: 'inherit',\n textDecoration: 'underline',\n cursor: 'pointer',\n },\n code: {\n fontFamily: FONT_MONOSPACE,\n },\n}\n\nexport default styles\n","import styles from './Error.styles'\n\ntype ErrorProps = {\n heading: string\n description?: string\n code?: string\n cta?: {\n text: string\n href?: string\n onClick?: () => void\n }\n}\n\nexport function Error({heading, description, code, cta}: ErrorProps): React.ReactNode {\n return (\n <div style={styles['container']}>\n <h1 style={styles['heading']}>{heading}</h1>\n\n {description && (\n <p style={styles['paragraph']} dangerouslySetInnerHTML={{__html: description}} />\n )}\n\n {code && <code style={styles['code']}>{code}</code>}\n\n {cta && (cta.href || cta.onClick) && (\n <p style={styles['paragraph']}>\n {cta.href ? (\n <a style={styles['link']} href={cta.href} target=\"_blank\" rel=\"noopener noreferrer\">\n {cta.text}\n </a>\n ) : (\n <button style={styles['link']} onClick={cta.onClick}>\n {cta.text}\n </button>\n )}\n </p>\n )}\n </div>\n )\n}\n","import {useMemo} from 'react'\nimport {type FallbackProps} from 'react-error-boundary'\n\nimport {Error} from './Error'\n\ntype CorsErrorComponentProps = FallbackProps & {\n projectId: string | null\n}\n\nexport function CorsErrorComponent({projectId, error}: CorsErrorComponentProps): React.ReactNode {\n const origin = window.location.origin\n const corsUrl = useMemo(() => {\n const url = new URL(`https://sanity.io/manage/project/${projectId}/api`)\n url.searchParams.set('cors', 'add')\n url.searchParams.set('origin', origin)\n url.searchParams.set('credentials', 'include')\n return url.toString()\n }, [origin, projectId])\n return (\n <Error\n heading=\"Before you continue…\"\n {...(projectId\n ? {\n description:\n 'To access your content, you need to <strong>add the following URL as a CORS origin</strong> to your Sanity project.',\n code: origin,\n cta: {\n text: 'Manage CORS configuration',\n href: corsUrl,\n },\n }\n : {\n description: error?.message,\n })}\n />\n )\n}\n","export function isInIframe(): boolean {\n return typeof window !== 'undefined' && window.self !== window.top\n}\n\n/**\n * @internal\n *\n * Checks if the current URL is a local URL.\n *\n * @param window - The window object\n * @returns True if the current URL is a local URL, false otherwise\n */\nexport function isLocalUrl(window: Window): boolean {\n const url = typeof window !== 'undefined' ? window.location.href : ''\n\n return (\n url.startsWith('http://localhost') ||\n url.startsWith('https://localhost') ||\n url.startsWith('http://127.0.0.1') ||\n url.startsWith('https://127.0.0.1')\n )\n}\n","/**\n * Error class for authentication-related errors. Wraps errors thrown during the\n * authentication flow.\n *\n * @remarks\n * This class provides a consistent error type for authentication failures while\n * preserving the original error as the cause. If the original error has a\n * message property, it will be used as the error message.\n *\n * @alpha\n */\nexport class AuthError extends Error {\n constructor(error: unknown) {\n if (\n typeof error === 'object' &&\n !!error &&\n 'message' in error &&\n typeof error.message === 'string'\n ) {\n super(error.message)\n } else {\n super()\n }\n\n this.cause = error\n }\n}\n","/**\n * Error class for configuration-related errors. Wraps errors thrown during the\n * configuration flow.\n *\n * @alpha\n */\nexport class ConfigurationError extends Error {\n constructor(error: unknown) {\n if (\n typeof error === 'object' &&\n !!error &&\n 'message' in error &&\n typeof error.message === 'string'\n ) {\n super(error.message)\n } else {\n super()\n }\n\n this.cause = error\n }\n}\n","import {type SanityInstance} from '@sanity/sdk'\nimport {useCallback} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\nexport function createCallbackHook<TParams extends unknown[], TReturn>(\n callback: (instance: SanityInstance, ...params: TParams) => TReturn,\n): () => (...params: TParams) => TReturn {\n function useHook() {\n const instance = useSanityInstance()\n return useCallback((...params: TParams) => callback(instance, ...params), [instance])\n }\n\n return useHook\n}\n","import {handleAuthCallback} from '@sanity/sdk'\n\nimport {createCallbackHook} from '../helpers/createCallbackHook'\n\n/**\n * @internal\n * A React hook that returns a function for handling authentication callbacks.\n *\n * @remarks\n * This hook provides access to the authentication store's callback handler,\n * which processes auth redirects by extracting the session ID and fetching the\n * authentication token. If fetching the long-lived token is successful,\n * `handleAuthCallback` will return a Promise that resolves a new location that\n * removes the short-lived token from the URL. Use this in combination with\n * `history.replaceState` or your own router's `replace` function to update the\n * current location without triggering a reload.\n *\n * @example\n * ```tsx\n * function AuthCallback() {\n * const handleAuthCallback = useHandleAuthCallback()\n * const router = useRouter() // Example router\n *\n * useEffect(() => {\n * async function processCallback() {\n * // Handle the callback and get the cleaned URL\n * const newUrl = await handleAuthCallback(window.location.href)\n *\n * if (newUrl) {\n * // Replace URL without triggering navigation\n * router.replace(newUrl, {shallow: true})\n * }\n * }\n *\n * processCallback().catch(console.error)\n * }, [handleAuthCallback, router])\n *\n * return <div>Completing login...</div>\n * }\n * ```\n *\n * @returns A callback handler function that processes OAuth redirects\n * @public\n */\nexport const useHandleAuthCallback = createCallbackHook(handleAuthCallback)\n","import {useEffect} from 'react'\n\nimport {useHandleAuthCallback} from '../../hooks/auth/useHandleAuthCallback'\n\n/**\n * Component shown during auth callback processing that handles login completion.\n * Automatically processes the auth callback when mounted and updates the URL\n * to remove callback parameters without triggering a page reload.\n *\n * @alpha\n */\nexport function LoginCallback(): React.ReactNode {\n const handleAuthCallback = useHandleAuthCallback()\n\n useEffect(() => {\n const url = new URL(location.href)\n handleAuthCallback(url.toString()).then((replacementLocation) => {\n if (replacementLocation) {\n // history API with `replaceState` is used to prevent a reload but still\n // remove the short-lived token from the URL\n history.replaceState(null, '', replacementLocation)\n }\n })\n }, [handleAuthCallback])\n\n return null\n}\n","import {logout} from '@sanity/sdk'\n\nimport {createCallbackHook} from '../helpers/createCallbackHook'\n\n/**\n * Hook to log out of the current session\n * @internal\n * @returns A function to log out of the current session\n */\nexport const useLogOut = createCallbackHook(logout)\n","import {ClientError} from '@sanity/client'\nimport {AuthStateType} from '@sanity/sdk'\nimport {useCallback, useEffect, useState} from 'react'\nimport {type FallbackProps} from 'react-error-boundary'\n\nimport {useAuthState} from '../../hooks/auth/useAuthState'\nimport {useLogOut} from '../../hooks/auth/useLogOut'\nimport {Error} from '../errors/Error'\nimport {AuthError} from './AuthError'\nimport {ConfigurationError} from './ConfigurationError'\n/**\n * @alpha\n */\nexport type LoginErrorProps = FallbackProps\n\n/**\n * Displays authentication error details and provides retry functionality.\n * Only handles {@link AuthError} instances - rethrows other error types.\n *\n * @alpha\n */\nexport function LoginError({error, resetErrorBoundary}: LoginErrorProps): React.ReactNode {\n if (\n !(\n error instanceof AuthError ||\n error instanceof ConfigurationError ||\n error instanceof ClientError\n )\n )\n throw error\n\n const logout = useLogOut()\n const authState = useAuthState()\n\n const [authErrorMessage, setAuthErrorMessage] = useState(\n 'Please try again or contact support if the problem persists.',\n )\n\n const handleRetry = useCallback(async () => {\n await logout()\n resetErrorBoundary()\n }, [logout, resetErrorBoundary])\n\n useEffect(() => {\n if (error instanceof ClientError) {\n if (error.statusCode === 401) {\n handleRetry()\n } else if (error.statusCode === 404) {\n const errorMessage = error.response.body.message || ''\n if (errorMessage.startsWith('Session with sid') && errorMessage.endsWith('not found')) {\n setAuthErrorMessage('The session ID is invalid or expired.')\n } else {\n setAuthErrorMessage('The login link is invalid or expired. Please try again.')\n }\n }\n }\n if (authState.type !== AuthStateType.ERROR && error instanceof ConfigurationError) {\n setAuthErrorMessage(error.message)\n }\n }, [authState, handleRetry, error])\n\n return (\n <Error\n heading={error instanceof AuthError ? 'Authentication Error' : 'Configuration Error'}\n description={authErrorMessage}\n cta={{\n text: 'Retry',\n onClick: handleRetry,\n }}\n />\n )\n}\n","import {CorsOriginError} from '@sanity/client'\nimport {AuthStateType, getCorsErrorProjectId} from '@sanity/sdk'\nimport {useEffect, useMemo} from 'react'\nimport {ErrorBoundary, type FallbackProps} from 'react-error-boundary'\n\nimport {ComlinkTokenRefreshProvider} from '../../context/ComlinkTokenRefresh'\nimport {useAuthState} from '../../hooks/auth/useAuthState'\nimport {useLoginUrl} from '../../hooks/auth/useLoginUrl'\nimport {useVerifyOrgProjects} from '../../hooks/auth/useVerifyOrgProjects'\nimport {useSanityInstance} from '../../hooks/context/useSanityInstance'\nimport {CorsErrorComponent} from '../errors/CorsErrorComponent'\nimport {isInIframe} from '../utils'\nimport {AuthError} from './AuthError'\nimport {ConfigurationError} from './ConfigurationError'\nimport {LoginCallback} from './LoginCallback'\nimport {LoginError, type LoginErrorProps} from './LoginError'\n\n// Only import bridge if we're in an iframe. This assumes that the app is\n// running within SanityOS if it is in an iframe and that the bridge hasn't already been loaded\nif (isInIframe() && !document.querySelector('[data-sanity-core]')) {\n const parsedUrl = new URL(window.location.href)\n const mode = new URLSearchParams(parsedUrl.hash.slice(1)).get('mode')\n const script = document.createElement('script')\n script.src =\n mode === 'core-ui--staging'\n ? 'https://core.sanity-cdn.work/bridge.js'\n : 'https://core.sanity-cdn.com/bridge.js'\n script.type = 'module'\n script.async = true\n document.head.appendChild(script)\n}\n\n/**\n * @internal\n */\nexport interface AuthBoundaryProps {\n /**\n * Custom component to render the login screen.\n * Receives all props. Defaults to {@link Login}.\n */\n LoginComponent?: React.ComponentType<{\n header?: React.ReactNode\n footer?: React.ReactNode\n }>\n\n /**\n * Custom component to render during OAuth callback processing.\n * Receives all props. Defaults to {@link LoginCallback}.\n */\n CallbackComponent?: React.ComponentType<{\n header?: React.ReactNode\n footer?: React.ReactNode\n }>\n\n /**\n * Custom component to render when authentication errors occur.\n * Receives error boundary props and layout props. Defaults to\n * {@link LoginError}\n */\n LoginErrorComponent?: React.ComponentType<LoginErrorProps>\n\n /** Header content to display */\n header?: React.ReactNode\n\n /**\n * The project IDs to use for organization verification.\n */\n projectIds?: string[]\n\n /** Footer content to display */\n footer?: React.ReactNode\n\n /** Protected content to render when authenticated */\n children?: React.ReactNode\n\n /**\n * Whether to verify that the project belongs to the organization specified in the dashboard context.\n * By default, organization verification is enabled when running in a dashboard context.\n *\n * WARNING: Disabling organization verification is NOT RECOMMENDED and may cause your application\n * to break in the future. This should never be disabled in production environments.\n */\n verifyOrganization?: boolean\n}\n\n/**\n * A component that handles authentication flow and error boundaries for a\n * protected section of the application.\n *\n * @remarks\n * This component manages different authentication states and renders the\n * appropriate components based on that state.\n *\n * @example\n * ```tsx\n * function App() {\n * return (\n * <AuthBoundary header={<MyLogo />}>\n * <ProtectedContent />\n * </AuthBoundary>\n * )\n * }\n * ```\n *\n * @internal\n */\nexport function AuthBoundary({\n LoginErrorComponent = LoginError,\n ...props\n}: AuthBoundaryProps): React.ReactNode {\n const FallbackComponent = useMemo(() => {\n return function LoginComponentWithLayoutProps(fallbackProps: FallbackProps) {\n if (fallbackProps.error instanceof CorsOriginError) {\n return (\n <CorsErrorComponent\n {...fallbackProps}\n projectId={getCorsErrorProjectId(fallbackProps.error)}\n />\n )\n }\n return <LoginErrorComponent {...fallbackProps} />\n }\n }, [LoginErrorComponent])\n\n return (\n <ComlinkTokenRefreshProvider>\n <ErrorBoundary FallbackComponent={FallbackComponent}>\n <AuthSwitch {...props} />\n </ErrorBoundary>\n </ComlinkTokenRefreshProvider>\n )\n}\n\ninterface AuthSwitchProps {\n LoginComponent?: React.ComponentType<{\n header?: React.ReactNode\n footer?: React.ReactNode\n }>\n CallbackComponent?: React.ComponentType<{\n header?: React.ReactNode\n footer?: React.ReactNode\n }>\n header?: React.ReactNode\n footer?: React.ReactNode\n children?: React.ReactNode\n verifyOrganization?: boolean\n projectIds?: string[]\n}\n\nfunction AuthSwitch({\n CallbackComponent = LoginCallback,\n children,\n verifyOrganization = true,\n projectIds,\n ...props\n}: AuthSwitchProps) {\n const authState = useAuthState()\n const instance = useSanityInstance()\n const studioModeEnabled = instance.config.studioMode?.enabled\n const disableVerifyOrg =\n !verifyOrganization || studioModeEnabled || authState.type !== AuthStateType.LOGGED_IN\n const orgError = useVerifyOrgProjects(disableVerifyOrg, projectIds)\n\n const isLoggedOut = authState.type === AuthStateType.LOGGED_OUT && !authState.isDestroyingSession\n const loginUrl = useLoginUrl()\n\n useEffect(() => {\n if (isLoggedOut && !isInIframe() && !studioModeEnabled) {\n // We don't want to redirect to login if we're in the Dashboard nor in studio mode\n window.location.href = loginUrl\n }\n }, [isLoggedOut, loginUrl, studioModeEnabled])\n\n // Only check the error if verification is enabled\n if (verifyOrganization && orgError) {\n throw new ConfigurationError({message: orgError})\n }\n\n switch (authState.type) {\n case AuthStateType.ERROR: {\n throw new AuthError(authState.error)\n }\n case AuthStateType.LOGGING_IN: {\n return <CallbackComponent {...props} />\n }\n case AuthStateType.LOGGED_IN: {\n return children\n }\n case AuthStateType.LOGGED_OUT: {\n return null\n }\n default: {\n // @ts-expect-error - This state should never happen\n throw new Error(`Invalid auth state: ${authState.type}`)\n }\n }\n}\n","import {createSanityInstance, type SanityConfig, type SanityInstance} from '@sanity/sdk'\nimport {Suspense, useContext, useEffect, useMemo, useRef} from 'react'\n\nimport {SanityInstanceContext} from './SanityInstanceContext'\n\nconst DEFAULT_FALLBACK = (\n <>\n Warning: No fallback provided. Please supply a fallback prop to ensure proper Suspense handling.\n </>\n)\n\n/**\n * Props for the ResourceProvider component\n * @internal\n */\nexport interface ResourceProviderProps extends SanityConfig {\n /**\n * React node to show while content is loading\n * Used as the fallback for the internal Suspense boundary\n */\n fallback: React.ReactNode\n children: React.ReactNode\n}\n\n/**\n * Provides a Sanity instance to child components through React Context\n *\n * @internal\n *\n * @remarks\n * The ResourceProvider creates a hierarchical structure of Sanity instances:\n * - When used as a root provider, it creates a new Sanity instance with the given config\n * - When nested inside another ResourceProvider, it creates a child instance that\n * inherits and extends the parent's configuration\n *\n * Features:\n * - Automatically manages the lifecycle of Sanity instances\n * - Disposes instances when the component unmounts\n * - Includes a Suspense boundary for data loading\n * - Enables hierarchical configuration inheritance\n *\n * Use this component to:\n * - Set up project/dataset configuration for an application\n * - Override specific configuration values in a section of your app\n * - Create isolated instance hierarchies for different features\n *\n * @example Creating a root provider\n * ```tsx\n * <ResourceProvider\n * projectId=\"your-project-id\"\n * dataset=\"production\"\n * fallback={<LoadingSpinner />}\n * >\n * <YourApp />\n * </ResourceProvider>\n * ```\n *\n * @example Creating nested providers with configuration inheritance\n * ```tsx\n * // Root provider with production config with nested provider for preview features with custom dataset\n * <ResourceProvider projectId=\"abc123\" dataset=\"production\" fallback={<Loading />}>\n * <div>...Main app content</div>\n * <Dashboard />\n * <ResourceProvider dataset=\"preview\" fallback={<Loading />}>\n * <PreviewFeatures />\n * </ResourceProvider>\n * </ResourceProvider>\n * ```\n */\nexport function ResourceProvider({\n children,\n fallback,\n ...config\n}: ResourceProviderProps): React.ReactNode {\n const parent = useContext(SanityInstanceContext)\n const instance = useMemo(\n () => (parent ? parent.createChild(config) : createSanityInstance(config)),\n [config, parent],\n )\n\n // Ref to hold the scheduled disposal timer.\n const disposal = useRef<{\n instance: SanityInstance\n timeoutId: ReturnType<typeof setTimeout>\n } | null>(null)\n\n useEffect(() => {\n // If the component remounts quickly (as in Strict Mode), cancel any pending disposal.\n if (disposal.current !== null && instance === disposal.current.instance) {\n clearTimeout(disposal.current.timeoutId)\n disposal.current = null\n }\n\n return () => {\n disposal.current = {\n instance,\n timeoutId: setTimeout(() => {\n if (!instance.isDisposed()) {\n instance.dispose()\n }\n }, 0),\n }\n }\n }, [instance])\n\n return (\n <SanityInstanceContext.Provider value={instance}>\n <Suspense fallback={fallback ?? DEFAULT_FALLBACK}>{children}</Suspense>\n </SanityInstanceContext.Provider>\n )\n}\n","import {type SanityConfig} from '@sanity/sdk'\nimport {type ReactElement, type ReactNode} from 'react'\n\nimport {ResourceProvider} from '../context/ResourceProvider'\nimport {AuthBoundary, type AuthBoundaryProps} from './auth/AuthBoundary'\n\n/**\n * @internal\n */\nexport interface SDKProviderProps extends AuthBoundaryProps {\n children: ReactNode\n config: SanityConfig | SanityConfig[]\n fallback: ReactNode\n}\n\n/**\n * @internal\n *\n * Top-level context provider that provides access to the Sanity SDK.\n * Creates a hierarchy of ResourceProviders, each providing a SanityInstance that can be\n * accessed by hooks. The first configuration in the array becomes the default instance.\n */\nexport function SDKProvider({\n children,\n config,\n fallback,\n ...props\n}: SDKProviderProps): ReactElement {\n // reverse because we want the first config to be the default, but the\n // ResourceProvider nesting makes the last one the default\n const configs = (Array.isArray(config) ? config : [config]).slice().reverse()\n const projectIds = configs.map((c) => c.projectId).filter((id): id is string => !!id)\n\n // Create a nested structure of ResourceProviders for each config\n const createNestedProviders = (index: number): ReactElement => {\n if (index >= configs.length) {\n return (\n <AuthBoundary {...props} projectIds={projectIds}>\n {children}\n </AuthBoundary>\n )\n }\n\n return (\n <ResourceProvider {...configs[index]} fallback={fallback}>\n {createNestedProviders(index + 1)}\n </ResourceProvider>\n )\n }\n\n return createNestedProviders(0)\n}\n","import {type SanityConfig} from '@sanity/sdk'\nimport {type ReactElement, useEffect} from 'react'\n\nimport {SDKProvider} from './SDKProvider'\nimport {isInIframe, isLocalUrl} from './utils'\n\n/**\n * @public\n * @category Types\n */\nexport interface SanityAppProps {\n /* One or more SanityConfig objects providing a project ID and dataset name */\n config: SanityConfig | SanityConfig[]\n /** @deprecated use the `config` prop instead. */\n sanityConfigs?: SanityConfig[]\n children: React.ReactNode\n /* Fallback content to show when child components are suspending. Same as the `fallback` prop for React Suspense. */\n fallback: React.ReactNode\n}\n\nconst REDIRECT_URL = 'https://sanity.io/welcome'\n\n/**\n * @public\n *\n * The SanityApp component provides your Sanity application with access to your Sanity configuration,\n * as well as application context and state which is used by the Sanity React hooks. Your application\n * must be wrapped with the SanityApp component to function properly.\n *\n * The `config` prop on the SanityApp component accepts either a single {@link SanityConfig} object, or an array of them.\n * This allows your app to work with one or more of your organization’s datasets.\n *\n * @remarks\n * When passing multiple SanityConfig objects to the `config` prop, the first configuration in the array becomes the default\n * configuration used by the App SDK Hooks.\n *\n * @category Components\n * @param props - Your Sanity configuration and the React children to render\n * @returns Your Sanity application, integrated with your Sanity configuration and application context\n *\n * @example\n * ```tsx\n * import { SanityApp, type SanityConfig } from '@sanity/sdk-react'\n *\n * import MyAppRoot from './Root'\n *\n * // Single project configuration\n * const mySanityConfig: SanityConfig = {\n * projectId: 'my-project-id',\n * dataset: 'production',\n * }\n *\n * // Or multiple project configurations\n * const multipleConfigs: SanityConfig[] = [\n * // Configuration for your main project. This will be used as the default project for hooks.\n * {\n * projectId: 'marketing-website-project',\n * dataset: 'production',\n * },\n * // Configuration for a separate blog project\n * {\n * projectId: 'blog-project',\n * dataset: 'production',\n * },\n * // Configuration for a separate ecommerce project\n * {\n * projectId: 'ecommerce-project',\n * dataset: 'production',\n * }\n * ]\n *\n * export default function MyApp() {\n * return (\n * <SanityApp config={mySanityConfig} fallback={<div>Loading…</div>}>\n * <MyAppRoot />\n * </SanityApp>\n * )\n * }\n * ```\n */\nexport function SanityApp({\n children,\n fallback,\n config = [],\n ...props\n}: SanityAppProps): ReactElement {\n useEffect(() => {\n let timeout: NodeJS.Timeout | undefined\n const primaryConfig = Array.isArray(config) ? config[0] : config\n\n if (!isInIframe() && !isLocalUrl(window) && !primaryConfig?.studioMode?.enabled) {\n // If the app is not running in an iframe and is not a local url, redirect to core.\n timeout = setTimeout(() => {\n // eslint-disable-next-line no-console\n console.warn('Redirecting to core', REDIRECT_URL)\n window.location.replace(REDIRECT_URL)\n }, 1000)\n }\n return () => clearTimeout(timeout)\n }, [config])\n\n return (\n <SDKProvider {...props} fallback={fallback} config={config}>\n {children}\n </SDKProvider>\n )\n}\n","import {getTokenState} from '@sanity/sdk'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\n/**\n * Hook to get the currently logged in user\n * @internal\n * @returns The current user or null if not authenticated\n */\nexport const useAuthToken = createStateSourceHook(getTokenState)\n","import {type CurrentUser, getCurrentUserState} from '@sanity/sdk'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\ntype UseCurrentUser = {\n /**\n * @public\n *\n * Provides the currently authenticated user’s profile information.\n *\n * @category Users\n * @returns The current user data\n *\n * @example Rendering a basic user profile\n * ```\n * const user = useCurrentUser()\n *\n * return (\n * <figure>\n * <img src={user?.profileImage} alt=`Profile image for ${user?.name}` />\n * <h2>{user?.name}</h2>\n * </figure>\n * )\n * ```\n */\n (): CurrentUser | null\n}\n\n/**\n * @public\n * @function\n * @TODO This should not return null — users of a custom app will always be authenticated via Core\n */\nexport const useCurrentUser: UseCurrentUser = createStateSourceHook(getCurrentUserState)\n","import {getDashboardOrganizationId} from '@sanity/sdk'\nimport {useMemo, useSyncExternalStore} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * @public\n *\n * A React hook that retrieves the dashboard organization ID that is currently selected in the Sanity Dashboard.\n *\n * @example\n * ```tsx\n * function DashboardComponent() {\n * const orgId = useDashboardOrganizationId()\n *\n * if (!orgId) return null\n *\n * return <div>Organization ID: {String(orgId)}</div>\n * }\n * ```\n *\n * @category Dashboard\n * @returns The dashboard organization ID (string | undefined)\n */\nexport function useDashboardOrganizationId(): string | undefined {\n const instance = useSanityInstance()\n const {subscribe, getCurrent} = useMemo(() => getDashboardOrganizationId(instance), [instance])\n\n return useSyncExternalStore(subscribe, getCurrent)\n}\n","import {getClientState} from '@sanity/sdk'\nimport {identity} from 'rxjs'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\n/**\n * A React hook that provides a client that subscribes to changes in your application,\n *\n * @remarks\n * This hook is intended for advanced use cases and special API calls that the React SDK\n * does not yet provide hooks for. We welcome you to get in touch with us to let us know\n * your use cases for this!\n *\n * @category Platform\n * @returns A Sanity client\n *\n * @example\n * ```tsx\n * function MyComponent() {\n * const client = useClient({apiVersion: '2024-11-12'})\n * const [document, setDocument] = useState(null)\n * useEffect(async () => {\n * const doc = client.fetch('*[_id == \"myDocumentId\"]')\n * setDocument(doc)\n * }, [])\n * return <div>{JSON.stringify(document) ?? 'Loading...'}</div>\n * }\n * ```\n *\n * @public\n * @function\n */\nexport const useClient = createStateSourceHook({\n getState: getClientState,\n getConfig: identity,\n})\n","import {type ChannelInstance, type Controller, type Status} from '@sanity/comlink'\nimport {\n type FrameMessage,\n getOrCreateChannel,\n getOrCreateController,\n releaseChannel,\n type WindowMessage,\n} from '@sanity/sdk'\nimport {useCallback, useEffect, useRef} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * @internal\n */\nexport type FrameMessageHandler<TWindowMessage extends WindowMessage> = (\n event: TWindowMessage['data'],\n) => TWindowMessage['response'] | Promise<TWindowMessage['response']>\n\n/**\n * @internal\n */\nexport interface UseFrameConnectionOptions<TWindowMessage extends WindowMessage> {\n name: string\n connectTo: string\n targetOrigin: string\n onMessage?: {\n [K in TWindowMessage['type']]: (data: Extract<TWindowMessage, {type: K}>['data']) => void\n }\n heartbeat?: boolean\n onStatus?: (status: Status) => void\n}\n\n/**\n * @internal\n */\nexport interface FrameConnection<TFrameMessage extends FrameMessage> {\n connect: (frameWindow: Window) => () => void // Return cleanup function\n sendMessage: <T extends TFrameMessage['type']>(\n ...params: Extract<TFrameMessage, {type: T}>['data'] extends undefined\n ? [type: T]\n : [type: T, data: Extract<TFrameMessage, {type: T}>['data']]\n ) => void\n}\n\n/**\n * @internal\n */\nexport function useFrameConnection<\n TFrameMessage extends FrameMessage,\n TWindowMessage extends WindowMessage,\n>(options: UseFrameConnectionOptions<TWindowMessage>): FrameConnection<TFrameMessage> {\n const {onMessage, targetOrigin, name, connectTo, heartbeat, onStatus} = options\n const instance = useSanityInstance()\n const controllerRef = useRef<Controller | null>(null)\n const channelRef = useRef<ChannelInstance<TFrameMessage, TWindowMessage> | null>(null)\n\n useEffect(() => {\n const controller = getOrCreateController(instance, targetOrigin)\n const channel = getOrCreateChannel(instance, {name, connectTo, heartbeat})\n controllerRef.current = controller\n channelRef.current = channel\n\n channel.onStatus((event) => {\n onStatus?.(event.status)\n })\n\n const messageUnsubscribers: Array<() => void> = []\n\n if (onMessage) {\n Object.entries(onMessage).forEach(([type, handler]) => {\n const unsubscribe = channel.on(type, handler as FrameMessageHandler<TWindowMessage>)\n messageUnsubscribers.push(unsubscribe)\n })\n }\n\n return () => {\n // Clean up all subscriptions and stop controller/channel\n messageUnsubscribers.forEach((unsub) => unsub())\n releaseChannel(instance, name)\n channelRef.current = null\n controllerRef.current = null\n }\n }, [targetOrigin, name, connectTo, heartbeat, onMessage, instance, onStatus])\n\n const connect = useCallback((frameWindow: Window) => {\n const removeTarget = controllerRef.current?.addTarget(frameWindow)\n return () => {\n removeTarget?.()\n }\n }, [])\n\n const sendMessage = useCallback(\n <T extends TFrameMessage['type']>(\n type: T,\n data?: Extract<TFrameMessage, {type: T}>['data'],\n ) => {\n channelRef.current?.post(type, data)\n },\n [],\n )\n\n return {\n connect,\n sendMessage,\n }\n}\n","import {type PathChangeMessage, SDK_CHANNEL_NAME, SDK_NODE_NAME} from '@sanity/message-protocol'\n\nimport {useWindowConnection} from '../comlink/useWindowConnection'\n\n/**\n * @public\n *\n * A helper hook designed to be injected into routing components for apps within the Dashboard.\n * While the Dashboard can usually handle navigation, there are special cases when you\n * are already within a target app, and need to navigate to another route inside of that app.\n *\n * For example, your user might \"favorite\" a document inside of your application.\n * If they click on the Dashboard favorites item in the sidebar, and are already within your application,\n * there needs to be some way for the dashboard to signal to your application to reroute to where that document was favorited.\n *\n * This hook is intended to receive those messages, and takes a function to route to the correct path.\n *\n * @param navigateFn - Function to handle navigation; should accept:\n * - `path`: a string, which will be a relative path (for example, 'my-route')\n * - `type`: 'push', 'replace', or 'pop', which will be the type of navigation to perform\n *\n * @example\n * ```tsx\n * import {useDashboardNavigate} from '@sanity/sdk-react'\n * import {BrowserRouter, useNavigate} from 'react-router'\n * import {Suspense} from 'react'\n *\n * function DashboardNavigationHandler() {\n * const navigate = useNavigate()\n * useDashboardNavigate(({path, type}) => {\n * navigate(path, {replace: type === 'replace'})\n * })\n * return null\n * }\n *\n * // Wrap the component with Suspense since the hook may suspend\n * function MyApp() {\n * return (\n * <BrowserRouter>\n * <Suspense>\n * <DashboardNavigationHandler />\n * </Suspense>\n * </BrowserRouter>\n * )\n * }\n * ```\n */\nexport function useDashboardNavigate(\n navigateFn: (options: PathChangeMessage['data']) => void,\n): void {\n useWindowConnection<PathChangeMessage, never>({\n name: SDK_NODE_NAME,\n connectTo: SDK_CHANNEL_NAME,\n onMessage: {\n 'dashboard/v1/history/change-path': (data: PathChangeMessage['data']) => {\n navigateFn(data)\n },\n },\n })\n}\n","import {\n type CanvasResource,\n type Events,\n type MediaResource,\n SDK_CHANNEL_NAME,\n SDK_NODE_NAME,\n type StudioResource,\n} from '@sanity/message-protocol'\nimport {\n type DocumentHandle,\n type FavoriteStatusResponse,\n type FrameMessage,\n getFavoritesState,\n resolveFavoritesState,\n} from '@sanity/sdk'\nimport {useCallback, useMemo, useSyncExternalStore} from 'react'\n\nimport {useWindowConnection} from '../comlink/useWindowConnection'\nimport {useSanityInstance} from '../context/useSanityInstance'\n\ninterface ManageFavorite extends FavoriteStatusResponse {\n favorite: () => Promise<void>\n unfavorite: () => Promise<void>\n isFavorited: boolean\n}\n\ninterface UseManageFavoriteProps extends DocumentHandle {\n resourceId?: string\n resourceType: StudioResource['type'] | MediaResource['type'] | CanvasResource['type']\n /**\n * The name of the schema collection this document belongs to.\n * Typically is the name of the workspace when used in the context of a studio.\n */\n schemaName?: string\n}\n\n/**\n * @internal\n *\n * This hook provides functionality to add and remove documents from favorites,\n * and tracks the current favorite status of the document.\n * @param documentHandle - The document handle containing document ID and type, like `{_id: '123', _type: 'book'}`\n * @returns An object containing:\n * - `favorite` - Function to add document to favorites\n * - `unfavorite` - Function to remove document from favorites\n * - `isFavorited` - Boolean indicating if document is currently favorited\n *\n * @example\n * ```tsx\n * function FavoriteButton(props: DocumentActionProps) {\n * const {documentId, documentType} = props\n * const {favorite, unfavorite, isFavorited} = useManageFavorite({\n * documentId,\n * documentType\n * })\n *\n * return (\n * <Button\n * onClick={() => isFavorited ? unfavorite() : favorite()}\n * text={isFavorited ? 'Remove from favorites' : 'Add to favorites'}\n * />\n * )\n * }\n *\n * // Wrap the component with Suspense since the hook may suspend\n * function MyDocumentAction(props: DocumentActionProps) {\n * return (\n * <Suspense\n * fallback={\n * <Button\n * text=\"Loading...\"\n * disabled\n * />\n * }\n * >\n * <FavoriteButton {...props} />\n * </Suspense>\n * )\n * }\n * ```\n */\nexport function useManageFavorite({\n documentId,\n documentType,\n projectId: paramProjectId,\n dataset: paramDataset,\n resourceId: paramResourceId,\n resourceType,\n schemaName,\n}: UseManageFavoriteProps): ManageFavorite {\n const {fetch} = useWindowConnection<Events.FavoriteMessage, FrameMessage>({\n name: SDK_NODE_NAME,\n connectTo: SDK_CHANNEL_NAME,\n })\n const instance = useSanityInstance()\n const {config} = instance\n const instanceProjectId = config?.projectId\n const instanceDataset = config?.dataset\n const projectId = paramProjectId ?? instanceProjectId\n const dataset = paramDataset ?? instanceDataset\n\n if (resourceType === 'studio' && (!projectId || !dataset)) {\n throw new Error('projectId and dataset are required for studio resources')\n }\n // Compute the final resourceId\n const resourceId =\n resourceType === 'studio' && !paramResourceId ? `${projectId}.${dataset}` : paramResourceId\n\n if (!resourceId) {\n throw new Error('resourceId is required for media-library and canvas resources')\n }\n\n // used for favoriteStore functions like getFavoritesState and resolveFavoritesState\n const context = useMemo(\n () => ({\n documentId,\n documentType,\n resourceId,\n resourceType,\n schemaName,\n }),\n [documentId, documentType, resourceId, resourceType, schemaName],\n )\n\n // Get favorite status using StateSource\n const favoriteState = getFavoritesState(instance, context)\n const state = useSyncExternalStore(favoriteState.subscribe, favoriteState.getCurrent)\n\n const isFavorited = state?.isFavorited ?? false\n\n const handleFavoriteAction = useCallback(\n async (action: 'added' | 'removed') => {\n if (!fetch || !documentId || !documentType || !resourceType) return\n\n try {\n const payload = {\n eventType: action,\n document: {\n id: documentId,\n type: documentType,\n resource: {\n ...{\n id: resourceId,\n type: resourceType,\n },\n ...(schemaName ? {schemaName} : {}),\n },\n },\n }\n\n const res = await fetch<{success: boolean}>('dashboard/v1/events/favorite/mutate', payload)\n if (res.success) {\n // Force a re-fetch of the favorite status after successful mutation\n await resolveFavoritesState(instance, context)\n }\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(`Failed to ${action === 'added' ? 'favorite' : 'unfavorite'} document:`, err)\n throw err\n }\n },\n [fetch, documentId, documentType, resourceId, resourceType, schemaName, instance, context],\n )\n\n const favorite = useCallback(() => handleFavoriteAction('added'), [handleFavoriteAction])\n const unfavorite = useCallback(() => handleFavoriteAction('removed'), [handleFavoriteAction])\n\n return {\n favorite,\n unfavorite,\n isFavorited,\n }\n}\n","import {SDK_CHANNEL_NAME, SDK_NODE_NAME} from '@sanity/message-protocol'\nimport {useEffect, useState} from 'react'\n\nimport {useWindowConnection} from '../comlink/useWindowConnection'\n\nexport interface DashboardResource {\n id: string\n name: string\n title: string\n basePath: string\n projectId: string\n dataset: string\n type: string\n userApplicationId: string\n url: string\n}\n\ninterface WorkspacesByProjectIdDataset {\n [key: `${string}:${string}`]: DashboardResource[] // key format: `${projectId}:${dataset}`\n}\n\ninterface StudioWorkspacesResult {\n workspacesByProjectIdAndDataset: WorkspacesByProjectIdDataset\n error: string | null\n}\n\n/**\n * Hook that fetches studio workspaces and organizes them by projectId:dataset\n * @internal\n *\n * @example\n * ```tsx\n * import {useStudioWorkspacesByProjectIdDataset} from '@sanity/sdk-react'\n * import {Card, Code, Button} from '@sanity/ui'\n * import {Suspense} from 'react'\n *\n * function WorkspacesCard() {\n * const {workspacesByProjectIdAndDataset, error} = useStudioWorkspacesByProjectIdDataset()\n * if (error) {\n * return <div>Error: {error}</div>\n * }\n * return (\n * <Card padding={4} radius={2} shadow={1}>\n * <Code language=\"json\">\n * {JSON.stringify(workspacesByProjectIdAndDataset, null, 2)}\n * </Code>\n * </Card>\n * )\n * }\n *\n * // Wrap the component with Suspense since the hook may suspend\n * function DashboardWorkspaces() {\n * return (\n * <Suspense fallback={<Button text=\"Loading...\" disabled />}>\n * <WorkspacesCard />\n * </Suspense>\n * )\n * }\n * ```\n */\nexport function useStudioWorkspacesByProjectIdDataset(): StudioWorkspacesResult {\n const [workspacesByProjectIdAndDataset, setWorkspacesByProjectIdAndDataset] =\n useState<WorkspacesByProjectIdDataset>({})\n const [error, setError] = useState<string | null>(null)\n\n const {fetch} = useWindowConnection({\n name: SDK_NODE_NAME,\n connectTo: SDK_CHANNEL_NAME,\n })\n\n // Once computed, this should probably be in a store and poll for changes\n // However, our stores are currently being refactored\n useEffect(() => {\n if (!fetch) return\n\n async function fetchWorkspaces(signal: AbortSignal) {\n try {\n const data = await fetch<{\n context: {availableResources: Array<DashboardResource>}\n }>('dashboard/v1/context', undefined, {signal})\n\n const workspaceMap: WorkspacesByProjectIdDataset = {}\n const noProjectIdAndDataset: DashboardResource[] = []\n\n data.context.availableResources.forEach((resource) => {\n if (resource.type !== 'studio') return\n if (!resource.projectId || !resource.dataset) {\n noProjectIdAndDataset.push(resource)\n return\n }\n const key = `${resource.projectId}:${resource.dataset}` as const\n if (!workspaceMap[key]) {\n workspaceMap[key] = []\n }\n workspaceMap[key].push(resource)\n })\n\n if (noProjectIdAndDataset.length > 0) {\n workspaceMap['NO_PROJECT_ID:NO_DATASET'] = noProjectIdAndDataset\n }\n\n setWorkspacesByProjectIdAndDataset(workspaceMap)\n setError(null)\n } catch (err: unknown) {\n if (err instanceof Error) {\n if (err.name === 'AbortError') {\n return\n }\n setError('Failed to fetch workspaces')\n }\n }\n }\n\n const controller = new AbortController()\n fetchWorkspaces(controller.signal)\n\n return () => {\n controller.abort()\n }\n }, [fetch])\n\n return {\n workspacesByProjectIdAndDataset,\n error,\n }\n}\n","import {type Bridge, SDK_CHANNEL_NAME, SDK_NODE_NAME} from '@sanity/message-protocol'\nimport {type DocumentHandle} from '@sanity/sdk'\nimport {useCallback} from 'react'\n\nimport {useWindowConnection} from '../comlink/useWindowConnection'\nimport {\n type DashboardResource,\n useStudioWorkspacesByProjectIdDataset,\n} from './useStudioWorkspacesByProjectIdDataset'\n\n/**\n * @public\n * @category Types\n */\nexport interface NavigateToStudioResult {\n navigateToStudioDocument: () => void\n}\n\n/**\n * @public\n *\n * Hook that provides a function to navigate to a given document in its parent Studio.\n *\n * Uses the `projectId` and `dataset` properties of the {@link DocumentHandle} you provide to resolve the correct Studio.\n * This will only work if you have deployed a studio with a workspace with this `projectId` / `dataset` combination.\n *\n * @remarks If you write your own Document Handle to pass to this hook (as opposed to a Document Handle generated by another hook),\n * it must include values for `documentId`, `documentType`, `projectId`, and `dataset`.\n *\n * @category Documents\n * @param documentHandle - The document handle for the document to navigate to\n * @param preferredStudioUrl - The preferred studio url to navigate to if you have multiple\n * studios with the same projectId and dataset\n * @returns An object containing:\n * - `navigateToStudioDocument` - Function that when called will navigate to the studio document\n *\n * @example\n * ```tsx\n * import {useNavigateToStudioDocument, type DocumentHandle} from '@sanity/sdk-react'\n * import {Button} from '@sanity/ui'\n * import {Suspense} from 'react'\n *\n * function NavigateButton({documentHandle}: {documentHandle: DocumentHandle}) {\n * const {navigateToStudioDocument} = useNavigateToStudioDocument(documentHandle)\n * return (\n * <Button\n * onClick={navigateToStudioDocument}\n * text=\"Navigate to Studio Document\"\n * />\n * )\n * }\n *\n * // Wrap the component with Suspense since the hook may suspend\n * function MyDocumentAction({documentHandle}: {documentHandle: DocumentHandle}) {\n * return (\n * <Suspense fallback={<Button text=\"Loading...\" disabled />}>\n * <NavigateButton documentHandle={documentHandle} />\n * </Suspense>\n * )\n * }\n * ```\n */\nexport function useNavigateToStudioDocument(\n documentHandle: DocumentHandle,\n preferredStudioUrl?: string,\n): NavigateToStudioResult {\n const {workspacesByProjectIdAndDataset} = useStudioWorkspacesByProjectIdDataset()\n const {sendMessage} = useWindowConnection<Bridge.Navigation.NavigateToResourceMessage, never>({\n name: SDK_NODE_NAME,\n connectTo: SDK_CHANNEL_NAME,\n })\n\n const navigateToStudioDocument = useCallback(() => {\n const {projectId, dataset} = documentHandle\n\n if (!projectId || !dataset) {\n // eslint-disable-next-line no-console\n console.warn('Project ID and dataset are required to navigate to a studio document')\n return\n }\n\n let workspace: DashboardResource | undefined\n\n if (preferredStudioUrl) {\n // Get workspaces matching the projectId:dataset and any workspaces without projectId/dataset,\n // in case there hasn't been a manifest loaded yet\n const allWorkspaces = [\n ...(workspacesByProjectIdAndDataset[`${projectId}:${dataset}`] || []),\n ...(workspacesByProjectIdAndDataset['NO_PROJECT_ID:NO_DATASET'] || []),\n ]\n workspace = allWorkspaces.find((w) => w.url === preferredStudioUrl)\n } else {\n const workspaces = workspacesByProjectIdAndDataset[`${projectId}:${dataset}`]\n if (workspaces?.length > 1) {\n // eslint-disable-next-line no-console\n console.warn(\n 'Multiple workspaces found for document and no preferred studio url',\n documentHandle,\n )\n // eslint-disable-next-line no-console\n console.warn('Using the first one', workspaces[0])\n }\n\n workspace = workspaces?.[0]\n }\n\n if (!workspace) {\n // eslint-disable-next-line no-console\n console.warn(\n `No workspace found for document with projectId: ${projectId} and dataset: ${dataset}${preferredStudioUrl ? ` or with preferred studio url: ${preferredStudioUrl}` : ''}`,\n )\n return\n }\n\n const message: Bridge.Navigation.NavigateToResourceMessage = {\n type: 'dashboard/v1/bridge/navigate-to-resource',\n data: {\n resourceId: workspace.id,\n resourceType: 'studio',\n path: `/intent/edit/id=${documentHandle.documentId};type=${documentHandle.documentType}`,\n },\n }\n\n sendMessage(message.type, message.data)\n }, [documentHandle, workspacesByProjectIdAndDataset, sendMessage, preferredStudioUrl])\n\n return {\n navigateToStudioDocument,\n }\n}\n","import {\n type CanvasResource,\n type Events,\n type MediaResource,\n SDK_CHANNEL_NAME,\n SDK_NODE_NAME,\n type StudioResource,\n} from '@sanity/message-protocol'\nimport {type DocumentHandle, type FrameMessage} from '@sanity/sdk'\nimport {useCallback} from 'react'\n\nimport {useWindowConnection} from '../comlink/useWindowConnection'\n\ninterface DocumentInteractionHistory {\n recordEvent: (eventType: 'viewed' | 'edited' | 'created' | 'deleted') => void\n}\n\n/**\n * @internal\n */\ninterface UseRecordDocumentHistoryEventProps extends DocumentHandle {\n resourceType: StudioResource['type'] | MediaResource['type'] | CanvasResource['type']\n resourceId?: string\n /**\n * The name of the schema collection this document belongs to.\n * Typically is the name of the workspace when used in the context of a studio.\n */\n schemaName?: string\n}\n\n/**\n * @internal\n * Hook for managing document interaction history in Sanity Studio.\n * This hook provides functionality to record document interactions.\n * @category History\n * @param documentHandle - The document handle containing document ID and type, like `{_id: '123', _type: 'book'}`\n * @returns An object containing:\n * - `recordEvent` - Function to record document interactions\n *\n * @example\n * ```tsx\n * import {useRecordDocumentHistoryEvent} from '@sanity/sdk-react'\n * import {Button} from '@sanity/ui'\n * import {Suspense} from 'react'\n *\n * function RecordEventButton(props: DocumentActionProps) {\n * const {documentId, documentType, resourceType, resourceId} = props\n * const {recordEvent} = useRecordDocumentHistoryEvent({\n * documentId,\n * documentType,\n * resourceType,\n * resourceId,\n * })\n * return (\n * <Button\n * onClick={() => recordEvent('viewed')}\n * text=\"Viewed\"\n * />\n * )\n * }\n *\n * // Wrap the component with Suspense since the hook may suspend\n * function MyDocumentAction(props: DocumentActionProps) {\n * return (\n * <Suspense fallback={<Button text=\"Loading...\" disabled />}>\n * <RecordEventButton {...props} />\n * </Suspense>\n * )\n * }\n * ```\n */\nexport function useRecordDocumentHistoryEvent({\n documentId,\n documentType,\n resourceType,\n resourceId,\n schemaName,\n}: UseRecordDocumentHistoryEventProps): DocumentInteractionHistory {\n const {sendMessage} = useWindowConnection<Events.HistoryMessage, FrameMessage>({\n name: SDK_NODE_NAME,\n connectTo: SDK_CHANNEL_NAME,\n })\n\n if (resourceType !== 'studio' && !resourceId) {\n throw new Error('resourceId is required for media-library and canvas resources')\n }\n\n const recordEvent = useCallback(\n (eventType: 'viewed' | 'edited' | 'created' | 'deleted') => {\n try {\n const message: Events.HistoryMessage = {\n type: 'dashboard/v1/events/history',\n data: {\n eventType,\n document: {\n id: documentId,\n type: documentType,\n resource: {\n id: resourceId!,\n type: resourceType,\n schemaName,\n },\n },\n },\n }\n\n sendMessage(message.type, message.data)\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error('Failed to record history event:', error)\n throw error\n }\n },\n [documentId, documentType, resourceId, resourceType, sendMessage, schemaName],\n )\n\n return {\n recordEvent,\n }\n}\n","import {type DatasetsResponse} from '@sanity/client'\nimport {\n getDatasetsState,\n type ProjectHandle,\n resolveDatasets,\n type SanityInstance,\n type StateSource,\n} from '@sanity/sdk'\nimport {identity} from 'rxjs'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\ntype UseDatasets = {\n /**\n *\n * Returns metadata for each dataset the current user has access to.\n *\n * @category Datasets\n * @returns The metadata for your the datasets\n *\n * @example\n * ```tsx\n * const datasets = useDatasets()\n *\n * return (\n * <select>\n * {datasets.map((dataset) => (\n * <option key={dataset.name}>{dataset.name}</option>\n * ))}\n * </select>\n * )\n * ```\n *\n */\n (): DatasetsResponse\n}\n\n/**\n * @public\n * @function\n */\nexport const useDatasets: UseDatasets = createStateSourceHook({\n getState: getDatasetsState as (\n instance: SanityInstance,\n projectHandle?: ProjectHandle,\n ) => StateSource<DatasetsResponse>,\n shouldSuspend: (instance, projectHandle?: ProjectHandle) =>\n // remove `undefined` since we're suspending when that is the case\n getDatasetsState(instance, projectHandle).getCurrent() === undefined,\n suspender: resolveDatasets,\n getConfig: identity as (projectHandle?: ProjectHandle) => ProjectHandle,\n})\n","import {\n type ActionsResult,\n applyDocumentActions,\n type ApplyDocumentActionsOptions,\n type DocumentAction,\n} from '@sanity/sdk'\nimport {type SanityDocument} from 'groq'\n\nimport {createCallbackHook} from '../helpers/createCallbackHook'\n// this import is used in an `{@link useEditDocument}`\n// eslint-disable-next-line unused-imports/no-unused-imports, import/consistent-type-specifier-style\nimport type {useEditDocument} from './useEditDocument'\n\n/**\n * @public\n */\ninterface UseApplyDocumentActions {\n (): <\n TDocumentType extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n >(\n action:\n | DocumentAction<TDocumentType, TDataset, TProjectId>\n | DocumentAction<TDocumentType, TDataset, TProjectId>[],\n options?: ApplyDocumentActionsOptions,\n ) => Promise<ActionsResult<SanityDocument<TDocumentType, `${TProjectId}.${TDataset}`>>>\n}\n\n/**\n * @public\n *\n * Provides a stable callback function for applying one or more document actions.\n *\n * This hook wraps the core `applyDocumentActions` functionality from `@sanity/sdk`,\n * integrating it with the React component lifecycle and {@link SanityInstance}.\n * It allows you to apply actions generated by functions like `createDocument`,\n * `editDocument`, `deleteDocument`, `publishDocument`, `unpublishDocument`,\n * and `discardDocument` to documents.\n *\n * Features:\n * - Applies one or multiple `DocumentAction` objects.\n * - Supports optimistic updates: Local state reflects changes immediately.\n * - Handles batching: Multiple actions passed together are sent as a single atomic transaction.\n * - Integrates with the collaborative editing engine for conflict resolution and state synchronization.\n *\n * @category Documents\n * @returns A stable callback function. When called with a single `DocumentAction` or an array of `DocumentAction`s,\n * it returns a promise that resolves to an {@link ActionsResult}. The `ActionsResult` contains information about the\n * outcome, including optimistic results if applicable.\n *\n * @remarks\n * This hook is a fundamental part of interacting with document state programmatically.\n * It operates within the same unified pipeline as other document hooks like `useDocument` (for reading state)\n * and {@link useEditDocument} (a higher-level hook specifically for edits).\n *\n * When multiple actions are provided in a single call, they are guaranteed to be submitted\n * as a single transaction to Content Lake. This ensures atomicity for related operations (e.g., creating and publishing a document).\n *\n * @function\n *\n * @example Publish or unpublish a document\n * ```tsx\n * import {\n * publishDocument,\n * unpublishDocument,\n * useApplyDocumentActions,\n * type DocumentHandle\n * } from '@sanity/sdk-react'\n *\n * // Define props using the DocumentHandle type\n * interface PublishControlsProps {\n * doc: DocumentHandle\n * }\n *\n * function PublishControls({doc}: PublishControlsProps) {\n * const apply = useApplyDocumentActions()\n *\n * const handlePublish = () => apply(publishDocument(doc))\n * const handleUnpublish = () => apply(unpublishDocument(doc))\n *\n * return (\n * <>\n * <button onClick={handlePublish}>Publish</button>\n * <button onClick={handleUnpublish}>Unpublish</button>\n * </>\n * )\n * }\n * ```\n *\n * @example Create and publish a new document\n * ```tsx\n * import {\n * createDocument,\n * publishDocument,\n * createDocumentHandle,\n * useApplyDocumentActions\n * } from '@sanity/sdk-react'\n *\n * function CreateAndPublishButton({documentType}: {documentType: string}) {\n * const apply = useApplyDocumentActions()\n *\n * const handleCreateAndPublish = () => {\n * // Create a new handle inside the handler\n * const newDocHandle = createDocumentHandle({ documentId: crypto.randomUUID(), documentType })\n *\n * // Apply multiple actions for the new handle as a single transaction\n * apply([\n * createDocument(newDocHandle),\n * publishDocument(newDocHandle),\n * ])\n * }\n *\n * return (\n * <button onClick={handleCreateAndPublish}>\n * I'm feeling lucky\n * </button>\n * )\n * }\n * ```\n */\nexport const useApplyDocumentActions = createCallbackHook(\n applyDocumentActions,\n) as UseApplyDocumentActions\n","import {type DocumentOptions, getDocumentState, type JsonMatch, resolveDocument} from '@sanity/sdk'\nimport {type SanityDocument} from 'groq'\nimport {identity} from 'rxjs'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n// used in an `{@link useDocumentProjection}` and `{@link useQuery}`\n// eslint-disable-next-line import/consistent-type-specifier-style, unused-imports/no-unused-imports\nimport type {useDocumentProjection} from '../projection/useDocumentProjection'\n// eslint-disable-next-line import/consistent-type-specifier-style, unused-imports/no-unused-imports\nimport type {useQuery} from '../query/useQuery'\n\nconst useDocumentValue = createStateSourceHook({\n // Pass options directly to getDocumentState\n getState: (instance, options: DocumentOptions<string | undefined>) =>\n getDocumentState(instance, options),\n // Pass options directly to getDocumentState for checking current value\n shouldSuspend: (instance, {path: _path, ...options}: DocumentOptions<string | undefined>) =>\n getDocumentState(instance, options).getCurrent() === undefined,\n // Extract handle part for resolveDocument\n suspender: (instance, options: DocumentOptions<string | undefined>) =>\n resolveDocument(instance, options),\n getConfig: identity as (\n options: DocumentOptions<string | undefined>,\n ) => DocumentOptions<string | undefined>,\n})\n\nconst wrapHookWithData = <TParams extends unknown[], TReturn>(\n useValue: (...params: TParams) => TReturn,\n) => {\n function useHook(...params: TParams) {\n return {data: useValue(...params)}\n }\n return useHook\n}\n\ninterface UseDocument {\n /** @internal */\n <TDocumentType extends string, TDataset extends string, TProjectId extends string = string>(\n options: DocumentOptions<undefined, TDocumentType, TDataset, TProjectId>,\n ): {data: SanityDocument<TDocumentType, `${TProjectId}.${TDataset}`> | null}\n\n /** @internal */\n <\n TPath extends string,\n TDocumentType extends string,\n TDataset extends string = string,\n TProjectId extends string = string,\n >(\n options: DocumentOptions<TPath, TDocumentType, TDataset, TProjectId>,\n ): {\n data: JsonMatch<SanityDocument<TDocumentType, `${TProjectId}.${TDataset}`>, TPath> | undefined\n }\n\n /** @internal */\n <TData>(options: DocumentOptions<undefined>): {data: TData | null}\n /** @internal */\n <TData>(options: DocumentOptions<string>): {data: TData | undefined}\n\n /**\n * ## useDocument via Type Inference (Recommended)\n *\n * @public\n *\n * The preferred way to use this hook when working with Sanity Typegen.\n *\n * Features:\n * - Automatically infers document types from your schema\n * - Provides type-safe access to documents and nested fields\n * - Supports project/dataset-specific type inference\n * - Works seamlessly with Typegen-generated types\n *\n * This hook will suspend while the document data is being fetched and loaded.\n *\n * When fetching a full document:\n * - Returns the complete document object if it exists\n * - Returns `null` if the document doesn't exist\n *\n * When fetching with a path:\n * - Returns the value at the specified path if both the document and path exist\n * - Returns `undefined` if either the document doesn't exist or the path doesn't exist in the document\n *\n * @category Documents\n * @param options - Configuration including `documentId`, `documentType`, and optionally:\n * - `path`: To select a nested value (returns typed value at path)\n * - `projectId`/`dataset`: For multi-project/dataset setups\n * @returns The document state (or nested value if path provided).\n *\n * @example Basic document fetch\n * ```tsx\n * import {useDocument, type DocumentHandle} from '@sanity/sdk-react'\n *\n * interface ProductViewProps {\n * doc: DocumentHandle<'product'> // Typegen infers product type\n * }\n *\n * function ProductView({doc}: ProductViewProps) {\n * const {data: product} = useDocument({...doc}) // Fully typed product\n * return <h1>{product.title ?? 'Untitled'}</h1>\n * }\n * ```\n *\n * @example Fetching a specific field\n * ```tsx\n * import {useDocument, type DocumentHandle} from '@sanity/sdk-react'\n *\n * interface ProductTitleProps {\n * doc: DocumentHandle<'product'>\n * }\n *\n * function ProductTitle({doc}: ProductTitleProps) {\n * const {data: title} = useDocument({\n * ...doc,\n * path: 'title' // Returns just the title field\n * })\n * return <h1>{title ?? 'Untitled'}</h1>\n * }\n * ```\n *\n * @inlineType DocumentOptions\n */\n <\n TPath extends string | undefined = undefined,\n TDocumentType extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n >(\n options: DocumentOptions<TPath, TDocumentType, TDataset, TProjectId>,\n ): TPath extends string\n ? {\n data:\n | JsonMatch<SanityDocument<TDocumentType, `${TProjectId}.${TDataset}`>, TPath>\n | undefined\n }\n : {data: SanityDocument<TDocumentType, `${TProjectId}.${TDataset}`> | null}\n\n /**\n * @public\n *\n * ## useDocument via Explicit Types\n *\n * Use this version when:\n * - You're not using Sanity Typegen\n * - You need to manually specify document types\n * - You're working with dynamic document types\n *\n * Key differences from Typegen version:\n * - Requires manual type specification via `TData`\n * - Returns `TData | null` for full documents\n * - Returns `TData | undefined` for nested values\n *\n * This hook will suspend while the document data is being fetched.\n *\n * @typeParam TData - The explicit type for the document or field\n * @typeParam TPath - Optional path to a nested value\n * @param options - Configuration including `documentId` and optionally:\n * - `path`: To select a nested value\n * - `projectId`/`dataset`: For multi-project/dataset setups\n * @returns The document state (or nested value if path provided)\n *\n * @example Basic document fetch with explicit type\n * ```tsx\n * import {useDocument, type DocumentHandle, type SanityDocument} from '@sanity/sdk-react'\n *\n * interface Book extends SanityDocument {\n * _type: 'book'\n * title: string\n * author: string\n * }\n *\n * interface BookViewProps {\n * doc: DocumentHandle\n * }\n *\n * function BookView({doc}: BookViewProps) {\n * const {data: book} = useDocument<Book>({...doc})\n * return <h1>{book?.title ?? 'Untitled'} by {book?.author ?? 'Unknown'}</h1>\n * }\n * ```\n *\n * @example Fetching a specific field with explicit type\n * ```tsx\n * import {useDocument, type DocumentHandle} from '@sanity/sdk-react'\n *\n * interface BookTitleProps {\n * doc: DocumentHandle\n * }\n *\n * function BookTitle({doc}: BookTitleProps) {\n * const {data: title} = useDocument<string>({...doc, path: 'title'})\n * return <h1>{title ?? 'Untitled'}</h1>\n * }\n * ```\n *\n * @inlineType DocumentOptions\n */\n <TData, TPath extends string>(\n options: DocumentOptions<TPath>,\n ): TPath extends string ? {data: TData | undefined} : {data: TData | null}\n\n /**\n * @internal\n */\n (options: DocumentOptions): {data: unknown}\n}\n\n/**\n * @public\n * Reads and subscribes to a document's realtime state, incorporating both local and remote changes.\n *\n * This hook comes in two main flavors to suit your needs:\n *\n * 1. **[Type Inference](#usedocument-via-type-inference-recommended)** (Recommended) - Automatically gets types from your Sanity schema\n * 2. **[Explicit Types](#usedocument-via-explicit-types)** - Manually specify types when needed\n *\n * @remarks\n * `useDocument` is ideal for realtime editing interfaces where you need immediate feedback on changes.\n * However, it can be resource-intensive since it maintains a realtime connection.\n *\n * For simpler cases where:\n * - You only need to display content\n * - Realtime updates aren't critical\n * - You want better performance\n *\n * …consider using {@link useDocumentProjection} or {@link useQuery} instead. These hooks are more efficient\n * for read-heavy applications.\n *\n * @function\n */\nexport const useDocument = wrapHookWithData(useDocumentValue) as UseDocument\n","import {type DatasetHandle, type DocumentEvent, subscribeDocumentEvents} from '@sanity/sdk'\nimport {useCallback, useEffect, useInsertionEffect, useRef} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * @public\n */\nexport interface UseDocumentEventOptions<\n TDataset extends string = string,\n TProjectId extends string = string,\n> extends DatasetHandle<TDataset, TProjectId> {\n onEvent: (documentEvent: DocumentEvent) => void\n}\n\n/**\n *\n * @public\n *\n * Subscribes an event handler to events in your application's document store.\n *\n * @category Documents\n * @param options - An object containing the event handler (`onEvent`) and optionally a `DatasetHandle` (projectId and dataset). If the handle is not provided, the nearest Sanity instance from context will be used.\n * @example Creating a custom hook for document event toasts\n * ```tsx\n * import {createDatasetHandle, type DatasetHandle, type DocumentEvent, useDocumentEvent} from '@sanity/sdk-react'\n * import {useToast} from './my-ui-library'\n *\n * // Define options for the custom hook, extending DatasetHandle\n * interface DocumentToastsOptions extends DatasetHandle {\n * // Could add more options, e.g., { includeEvents: DocumentEvent['type'][] }\n * }\n *\n * // Define the custom hook\n * function useDocumentToasts({...datasetHandle}: DocumentToastsOptions = {}) {\n * const showToast = useToast() // Get the toast function\n *\n * // Define the event handler logic to show toasts on specific events\n * const handleEvent = (event: DocumentEvent) => {\n * if (event.type === 'published') {\n * showToast(`Document ${event.documentId} published.`)\n * } else if (event.type === 'unpublished') {\n * showToast(`Document ${event.documentId} unpublished.`)\n * } else if (event.type === 'deleted') {\n * showToast(`Document ${event.documentId} deleted.`)\n * } else {\n * // Optionally log other events for debugging\n * console.log('Document Event:', event.type, event.documentId)\n * }\n * }\n *\n * // Call the original hook, spreading the handle properties\n * useDocumentEvent({\n * ...datasetHandle, // Spread the dataset handle (projectId, dataset)\n * onEvent: handleEvent,\n * })\n * }\n *\n * function MyComponentWithToasts() {\n * // Use the custom hook, passing specific handle info\n * const specificHandle = createDatasetHandle({ projectId: 'p1', dataset: 'ds1' })\n * useDocumentToasts(specificHandle)\n *\n * // // Or use it relying on context for the handle\n * // useDocumentToasts()\n *\n * return <div>...</div>\n * }\n * ```\n */\nexport function useDocumentEvent<\n TDataset extends string = string,\n TProjectId extends string = string,\n>(\n // Single options object parameter\n options: UseDocumentEventOptions<TDataset, TProjectId>,\n): void {\n // Destructure handler and datasetHandle from options\n const {onEvent, ...datasetHandle} = options\n const ref = useRef(onEvent)\n\n useInsertionEffect(() => {\n ref.current = onEvent\n })\n\n const stableHandler = useCallback((documentEvent: DocumentEvent) => {\n return ref.current(documentEvent)\n }, [])\n\n const instance = useSanityInstance(datasetHandle)\n useEffect(() => {\n return subscribeDocumentEvents(instance, stableHandler)\n }, [instance, stableHandler])\n}\n","import {type DocumentAction, type DocumentPermissionsResult, getPermissionsState} from '@sanity/sdk'\nimport {useCallback, useMemo, useSyncExternalStore} from 'react'\nimport {filter, firstValueFrom} from 'rxjs'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n *\n * @public\n *\n * Check if the current user has the specified permissions for the given document actions.\n *\n * @category Permissions\n * @param actionOrActions - One or more document action functions (e.g., `publishDocument(handle)`).\n * @returns An object that specifies whether the action is allowed; if the action is not allowed, an explanatory message and list of reasons is also provided.\n *\n * @remarks\n * When passing multiple actions, all actions must belong to the same project and dataset.\n * Note, however, that you can check permissions on multiple documents from the same project and dataset (as in the second example below).\n *\n * @example Checking for permission to publish a document\n * ```tsx\n * import {\n * useDocumentPermissions,\n * useApplyDocumentActions,\n * publishDocument,\n * createDocumentHandle,\n * type DocumentHandle\n * } from '@sanity/sdk-react'\n *\n * // Define props using the DocumentHandle type\n * interface PublishButtonProps {\n * doc: DocumentHandle\n * }\n *\n * function PublishButton({doc}: PublishButtonProps) {\n * const publishAction = publishDocument(doc)\n *\n * // Pass the same action call to check permissions\n * const publishPermissions = useDocumentPermissions(publishAction)\n * const apply = useApplyDocumentActions()\n *\n * return (\n * <>\n * <button\n * disabled={!publishPermissions.allowed}\n * // Pass the same action call to apply the action\n * onClick={() => apply(publishAction)}\n * popoverTarget={`${publishPermissions.allowed ? undefined : 'publishButtonPopover'}`}\n * >\n * Publish\n * </button>\n * {!publishPermissions.allowed && (\n * <div popover id=\"publishButtonPopover\">\n * {publishPermissions.message}\n * </div>\n * )}\n * </>\n * )\n * }\n *\n * // Usage:\n * // const doc = createDocumentHandle({ documentId: 'doc1', documentType: 'myType' })\n * // <PublishButton doc={doc} />\n * ```\n *\n * @example Checking for permissions to edit multiple documents\n * ```tsx\n * import {\n * useDocumentPermissions,\n * editDocument,\n * type DocumentHandle\n * } from '@sanity/sdk-react'\n *\n * export default function canEditMultiple(docHandles: DocumentHandle[]) {\n * // Create an array containing an editDocument action for each of the document handles\n * const editActions = docHandles.map(doc => editDocument(doc))\n *\n * // Return the result of checking for edit permissions on all of the document handles\n * return useDocumentPermissions(editActions)\n * }\n * ```\n */\nexport function useDocumentPermissions(\n actionOrActions: DocumentAction | DocumentAction[],\n): DocumentPermissionsResult {\n const actions = Array.isArray(actionOrActions) ? actionOrActions : [actionOrActions]\n // if actions is an array, we need to check that all actions belong to the same project and dataset\n let projectId\n let dataset\n\n for (const action of actions) {\n if (action.projectId) {\n if (!projectId) projectId = action.projectId\n if (action.projectId !== projectId) {\n throw new Error(\n `Mismatched project IDs found in actions. All actions must belong to the same project. Found \"${action.projectId}\" but expected \"${projectId}\".`,\n )\n }\n\n if (action.dataset) {\n if (!dataset) dataset = action.dataset\n if (action.dataset !== dataset) {\n throw new Error(\n `Mismatched datasets found in actions. All actions must belong to the same dataset. Found \"${action.dataset}\" but expected \"${dataset}\".`,\n )\n }\n }\n }\n }\n\n const instance = useSanityInstance({projectId, dataset})\n const isDocumentReady = useCallback(\n () => getPermissionsState(instance, actionOrActions).getCurrent() !== undefined,\n [actionOrActions, instance],\n )\n if (!isDocumentReady()) {\n throw firstValueFrom(\n getPermissionsState(instance, actionOrActions).observable.pipe(\n filter((result) => result !== undefined),\n ),\n )\n }\n\n const {subscribe, getCurrent} = useMemo(\n () => getPermissionsState(instance, actionOrActions),\n [actionOrActions, instance],\n )\n\n return useSyncExternalStore(subscribe, getCurrent) as DocumentPermissionsResult\n}\n","import {\n type DocumentHandle,\n getDocumentSyncStatus,\n resolveDocument,\n type SanityInstance,\n type StateSource,\n} from '@sanity/sdk'\nimport {identity} from 'rxjs'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\ntype UseDocumentSyncStatus = {\n /**\n * Exposes the document's sync status between local and remote document states.\n *\n * @category Documents\n * @param doc - The document handle to get sync status for. If you pass a `DocumentHandle` with specified `projectId` and `dataset`,\n * the document will be read from the specified Sanity project and dataset that is included in the handle. If no `projectId` or `dataset` is provided,\n * the document will use the nearest instance from context.\n * @returns `true` if local changes are synced with remote, `false` if changes are pending. Note: Suspense handles loading states.\n * @example Show sync status indicator\n * ```tsx\n * import {useDocumentSyncStatus, createDocumentHandle, type DocumentHandle} from '@sanity/sdk-react'\n *\n * // Define props including the DocumentHandle type\n * interface SyncIndicatorProps {\n * doc: DocumentHandle\n * }\n *\n * function SyncIndicator({doc}: SyncIndicatorProps) {\n * const isSynced = useDocumentSyncStatus(doc)\n *\n * return (\n * <div className={`sync-status ${isSynced ? 'synced' : 'pending'}`}>\n * {isSynced ? '✓ Synced' : 'Saving changes...'}\n * </div>\n * )\n * }\n *\n * // Usage:\n * // const doc = createDocumentHandle({ documentId: 'doc1', documentType: 'myType' })\n * // <SyncIndicator doc={doc} />\n * ```\n */\n (doc: DocumentHandle): boolean\n}\n\n/**\n * @public\n * @function\n */\nexport const useDocumentSyncStatus: UseDocumentSyncStatus = createStateSourceHook({\n getState: getDocumentSyncStatus as (\n instance: SanityInstance,\n doc: DocumentHandle,\n ) => StateSource<boolean>,\n shouldSuspend: (instance, doc: DocumentHandle) =>\n getDocumentSyncStatus(instance, doc).getCurrent() === undefined,\n suspender: (instance, doc: DocumentHandle) => resolveDocument(instance, doc),\n getConfig: identity,\n})\n","import {\n type ActionsResult,\n type DocumentOptions,\n editDocument,\n getDocumentState,\n type JsonMatch,\n resolveDocument,\n} from '@sanity/sdk'\nimport {type SanityDocument} from 'groq'\nimport {useCallback} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\nimport {useApplyDocumentActions} from './useApplyDocumentActions'\n\nconst ignoredKeys = ['_id', '_type', '_createdAt', '_updatedAt', '_rev']\n\ntype Updater<TValue> = TValue | ((currentValue: TValue) => TValue)\n\n// Overload 1: No path, relies on Typegen\n/**\n * @public\n * Edit an entire document, relying on Typegen for the type.\n *\n * @param options - Document options including `documentId`, `documentType`, and optionally `projectId`/`dataset`.\n * @returns A stable function to update the document state. Accepts either the new document state or an updater function `(currentValue) => nextValue`.\n * Returns a promise resolving to the {@link ActionsResult}.\n */\nexport function useEditDocument<\n TDocumentType extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n>(\n options: DocumentOptions<undefined, TDocumentType, TDataset, TProjectId>,\n): (\n nextValue: Updater<SanityDocument<TDocumentType, `${TProjectId}.${TDataset}`>>,\n) => Promise<ActionsResult<SanityDocument<TDocumentType, `${TProjectId}.${TDataset}`>>>\n\n// Overload 2: Path provided, relies on Typegen\n/**\n * @public\n * Edit a specific path within a document, relying on Typegen for the type.\n *\n * @param options - Document options including `documentId`, `documentType`, `path`, and optionally `projectId`/`dataset`.\n * @returns A stable function to update the value at the specified path. Accepts either the new value or an updater function `(currentValue) => nextValue`.\n * Returns a promise resolving to the {@link ActionsResult}.\n */\nexport function useEditDocument<\n TPath extends string = string,\n TDocumentType extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n>(\n options: DocumentOptions<TPath, TDocumentType, TDataset, TProjectId>,\n): (\n nextValue: Updater<JsonMatch<SanityDocument<TDocumentType, `${TProjectId}.${TDataset}`>, TPath>>,\n) => Promise<ActionsResult<SanityDocument<TDocumentType, `${TProjectId}.${TDataset}`>>>\n\n// Overload 3: Explicit type, no path\n/**\n * @public\n * Edit an entire document with an explicit type `TData`.\n *\n * @param options - Document options including `documentId` and optionally `projectId`/`dataset`.\n * @returns A stable function to update the document state. Accepts either the new document state (`TData`) or an updater function `(currentValue: TData) => nextValue: TData`.\n * Returns a promise resolving to the {@link ActionsResult}.\n */\nexport function useEditDocument<TData>(\n options: DocumentOptions<undefined>,\n): (nextValue: Updater<TData>) => Promise<ActionsResult>\n\n// Overload 4: Explicit type, path provided\n/**\n * @public\n * Edit a specific path within a document with an explicit type `TData`.\n *\n * @param options - Document options including `documentId`, `path`, and optionally `projectId`/`dataset`.\n * @returns A stable function to update the value at the specified path. Accepts either the new value (`TData`) or an updater function `(currentValue: TData) => nextValue: TData`.\n * Returns a promise resolving to the {@link ActionsResult}.\n */\nexport function useEditDocument<TData>(\n options: DocumentOptions<string>,\n): (nextValue: Updater<TData>) => Promise<ActionsResult>\n\n/**\n * @public\n * Provides a stable function to apply edits to a document or a specific path within it.\n *\n * @category Documents\n * @remarks\n * This hook simplifies editing documents by automatically:\n * - Comparing the current and next states to determine the minimal set of `set` and `unset` operations required for the update via `editDocument`.\n * - Handling both full document updates and specific path updates.\n * - Supporting functional updates (e.g., `edit(prev => ({...prev, title: 'New'}))`).\n * - Integrating with the active {@link SanityInstance} context.\n * - Utilizing `useApplyDocumentActions` internally for optimistic updates and transaction handling.\n *\n * It offers several overloads for flexibility:\n * 1. **Typegen (Full Document):** Edit the entire document, inferring types from your schema.\n * 2. **Typegen (Specific Path):** Edit a specific field, inferring types.\n * 3. **Explicit Type (Full Document):** Edit the entire document with a manually specified type.\n * 4. **Explicit Type (Specific Path):** Edit a specific field with a manually specified type.\n *\n * This hook relies on the document state being loaded. If the document is not yet available\n * (e.g., during initial load), the component using this hook will suspend.\n *\n * @example Basic Usage (Typegen, Full Document)\n * ```tsx\n * import {useCallback} from 'react';\n * import {useEditDocument, useDocument, type DocumentHandle} from '@sanity/sdk-react'\n *\n * // Assume 'product' schema has a 'title' field (string)\n * interface ProductEditorProps {\n * productHandle: DocumentHandle<'product'> // Typegen infers 'product' type\n * }\n *\n * function ProductEditor({ productHandle }: ProductEditorProps) {\n * // Fetch the document to display its current state (optional)\n * const {data: product} = useDocument(productHandle);\n * // Get the edit function for the full document\n * const editProduct = useEditDocument(productHandle);\n *\n * // Use useCallback for stable event handlers\n * const handleTitleChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {\n * const newTitle = event.target.value;\n * // Use the functional updater for safe partial updates\n * editProduct(prev => ({\n * ...prev,\n * title: newTitle,\n * })).\n * }, [editProduct]);\n *\n * return (\n * <div>\n * <label>\n * Product Title:\n * <input\n * type=\"text\"\n * value={product?.title ?? ''}\n * onChange={handleTitleChange}\n * />\n * </label>\n * </div>\n * );\n * }\n * ```\n *\n * @example Editing a Specific Path (Typegen)\n * ```tsx\n * import React, { useCallback } from 'react';\n * import {useEditDocument, useDocument, type DocumentHandle, type DocumentOptions} from '@sanity/sdk-react'\n *\n * // Assume 'product' schema has a 'price' field (number)\n * interface ProductPriceEditorProps {\n * productHandle: DocumentHandle<'product'>;\n * }\n *\n * function ProductPriceEditor({ productHandle }: ProductPriceEditorProps) {\n * // Construct DocumentOptions internally, combining the handle and a hardcoded path\n * const priceOptions {\n * ...productHandle,\n * path: 'price', // Hardcode the path to edit\n * };\n *\n * // Fetch the current price to display it\n * const {data: currentPrice} = useDocument(priceOptions);\n * // Get the edit function for the specific path 'price'\n * const editPrice = useEditDocument(priceOptions);\n *\n * const handleSetFixedPrice = useCallback(() => {\n * // Update the price directly to a hardcoded value\n * editPrice(99.99)\n * }, [editPrice]);\n *\n * return (\n * <div>\n * <p>Current Price: {currentPrice}</p>\n * <button onClick={handleSetFixedPrice}>\n * Set Price to $99.99\n * </button>\n * </div>\n * );\n * }\n *\n * ```\n *\n * @example Usage with Explicit Types (Full Document)\n * ```tsx\n * import React, { useCallback } from 'react';\n * import {useEditDocument, useDocument, type DocumentHandle, type SanityDocument} from '@sanity/sdk-react'\n *\n * interface Book extends SanityDocument { _type: 'book', title: string, author: string }\n *\n * interface BookEditorProps {\n * bookHandle: DocumentHandle // No documentType needed if providing TData\n * }\n *\n * function BookEditor({ bookHandle }: BookEditorProps) {\n * const {data: book} = useDocument<Book>(bookHandle);\n * // Provide the explicit type <Book>\n * const editBook = useEditDocument<Book>(bookHandle);\n *\n * const handleAuthorChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {\n * const newAuthor = event.target.value;\n * editBook(prev => ({\n * ...prev,\n * author: newAuthor\n * }))\n * }, [editBook]);\n *\n * return (\n * <div>\n * <label>\n * Book Author:\n * <input\n * type=\"text\"\n * value={book?.author ?? ''}\n * onChange={handleAuthorChange}\n * />\n * </label>\n * </div>\n * );\n * }\n *\n * ```\n *\n * @example Usage with Explicit Types (Specific Path)\n * ```tsx\n * import React, { useCallback } from 'react';\n * import {useEditDocument, useDocument, type DocumentHandle, type DocumentOptions} from '@sanity/sdk-react'\n *\n * // Assume 'book' has 'author.name' (string)\n * interface AuthorNameEditorProps {\n * bookHandle: DocumentHandle; // No documentType needed if providing TData for path\n * }\n *\n * function AuthorNameEditor({ bookHandle }: AuthorNameEditorProps) {*\n * // Fetch current value\n * const {data: currentName} = useDocument<string>({...bookHandle, path: 'author.name'});\n * // Provide the explicit type <string> for the path's value\n * const editAuthorName = useEditDocument<string>({...bookHandle, path: 'author.name'});\n *\n * const handleUpdate = useCallback(() => {\n * // Update with a hardcoded string directly\n * editAuthorName('Jane Doe')\n * }, [editAuthorName]);\n *\n * return (\n * <div>\n * <p>Current Author Name: {currentName}</p>\n * <button onClick={handleUpdate} disabled={currentName === undefined}>\n * Set Author Name to Jane Doe\n * </button>\n * </div>\n * );\n * }\n *\n * ```\n */\nexport function useEditDocument({\n path,\n ...doc\n}: DocumentOptions<string | undefined>): (updater: Updater<unknown>) => Promise<ActionsResult> {\n const instance = useSanityInstance(doc)\n const apply = useApplyDocumentActions()\n const isDocumentReady = useCallback(\n () => getDocumentState(instance, doc).getCurrent() !== undefined,\n [instance, doc],\n )\n if (!isDocumentReady()) throw resolveDocument(instance, doc)\n\n return (updater: Updater<unknown>) => {\n const currentPath = path\n\n if (currentPath) {\n const stateWithOptions = getDocumentState(instance, {...doc, path})\n const currentValue = stateWithOptions.getCurrent()\n\n const nextValue =\n typeof updater === 'function'\n ? (updater as (prev: typeof currentValue) => typeof currentValue)(currentValue)\n : updater\n\n return apply(editDocument(doc, {set: {[currentPath]: nextValue}}))\n }\n\n const fullDocState = getDocumentState(instance, {...doc, path})\n const current = fullDocState.getCurrent() as object | null | undefined\n const nextValue =\n typeof updater === 'function'\n ? (updater as (prev: typeof current) => typeof current)(current)\n : updater\n\n if (typeof nextValue !== 'object' || !nextValue) {\n throw new Error(\n `No path was provided to \\`useEditDocument\\` and the value provided was not a document object.`,\n )\n }\n\n const allKeys = Object.keys({...current, ...nextValue})\n const editActions = allKeys\n .filter((key) => !ignoredKeys.includes(key))\n .filter(\n (key) =>\n current?.[key as keyof typeof current] !== (nextValue as Record<string, unknown>)[key],\n )\n .map((key) =>\n key in nextValue\n ? editDocument(doc, {set: {[key]: (nextValue as Record<string, unknown>)[key]}})\n : editDocument(doc, {unset: [key]}),\n )\n\n return apply(editActions)\n }\n}\n","import {\n getQueryKey,\n getQueryState,\n parseQueryKey,\n type QueryOptions,\n resolveQuery,\n} from '@sanity/sdk'\nimport {type SanityQueryResult} from 'groq'\nimport {useEffect, useMemo, useRef, useState, useSyncExternalStore, useTransition} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n// Overload 1: Inferred Type (using Typegen)\n/**\n * @public\n * Executes a GROQ query, inferring the result type from the query string and options.\n * Leverages Sanity Typegen if configured for enhanced type safety.\n *\n * @param options - Configuration for the query, including `query`, optional `params`, `projectId`, `dataset`, etc.\n * @returns An object containing `data` (typed based on the query) and `isPending` (for transitions).\n *\n * @example Basic usage (Inferred Type)\n * ```tsx\n * import {useQuery} from '@sanity/sdk-react'\n * import {defineQuery} from 'groq'\n *\n * const myQuery = defineQuery(`*[_type == \"movie\"]{_id, title}`)\n *\n * function MovieList() {\n * // Typegen infers the return type for data\n * const {data} = useQuery({ query: myQuery })\n *\n * return (\n * <div>\n * <h2>Movies</h2>\n * <ul>\n * {data.map(movie => <li key={movie._id}>{movie.title}</li>)}\n * </ul>\n * </div>\n * )\n * }\n * // Suspense boundary should wrap <MovieList /> for initial load\n * ```\n *\n * @example Using parameters (Inferred Type)\n * ```tsx\n * import {useQuery} from '@sanity/sdk-react'\n * import {defineQuery} from 'groq'\n *\n * const myQuery = defineQuery(`*[_type == \"movie\" && _id == $id][0]`)\n *\n * function MovieDetails({movieId}: {movieId: string}) {\n * // Typegen infers the return type based on query and params\n * const {data, isPending} = useQuery({\n * query: myQuery,\n * params: { id: movieId }\n * })\n *\n * return (\n * // utilize `isPending` to signal to users that new data is coming in\n * // (e.g. the `movieId` changed and we're loading in the new one)\n * <div style={{ opacity: isPending ? 0.5 : 1 }}>\n * {data ? <h1>{data.title}</h1> : <p>Movie not found</p>}\n * </div>\n * )\n * }\n * ```\n */\nexport function useQuery<\n TQuery extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n>(\n options: QueryOptions<TQuery, TDataset, TProjectId>,\n): {\n /** The query result, typed based on the GROQ query string */\n data: SanityQueryResult<TQuery, `${TProjectId}.${TDataset}`>\n /** True if a query transition is in progress */\n isPending: boolean\n}\n\n// Overload 2: Explicit Type Provided\n/**\n * @public\n * Executes a GROQ query with an explicitly provided result type `TData`.\n *\n * @param options - Configuration for the query, including `query`, optional `params`, `projectId`, `dataset`, etc.\n * @returns An object containing `data` (cast to `TData`) and `isPending` (indicates whether a query resolution is pending; note that Suspense handles initial loading states). *\n * @example Manually typed query result\n * ```tsx\n * import {useQuery} from '@sanity/sdk-react'\n *\n * interface CustomMovieTitle {\n * movieTitle?: string\n * }\n *\n * function FirstMovieTitle() {\n * // Provide the explicit type TData\n * const {data, isPending} = useQuery<CustomMovieTitle>({\n * query: '*[_type == \"movie\"][0]{ \"movieTitle\": title }'\n * })\n *\n * return (\n * <h1 style={{ opacity: isPending ? 0.5 : 1 }}>\n * {data?.movieTitle ?? 'No title found'}\n * </h1>\n * )\n * }\n * ```\n */\nexport function useQuery<TData>(options: QueryOptions): {\n /** The query result, cast to the provided type TData */\n data: TData\n /** True if another query is resolving in the background (suspense handles the initial loading state) */\n isPending: boolean\n}\n\n/**\n * @public\n * Fetches data and subscribes to real-time updates using a GROQ query.\n *\n * @remarks\n * This hook provides a convenient way to fetch data from your Sanity dataset and\n * automatically receive updates in real-time when the queried data changes.\n *\n * Features:\n * - Executes any valid GROQ query.\n * - Subscribes to changes, providing real-time updates.\n * - Integrates with React Suspense for handling initial loading states.\n * - Uses React Transitions for managing loading states during query/parameter changes (indicated by `isPending`).\n * - Supports type inference based on the GROQ query when using Sanity Typegen.\n * - Allows specifying an explicit return type `TData` for the query result.\n *\n * @category GROQ\n */\nexport function useQuery(options: QueryOptions): {data: unknown; isPending: boolean} {\n // Implementation returns unknown, overloads define specifics\n const instance = useSanityInstance(options)\n\n // Use React's useTransition to avoid UI jank when queries change\n const [isPending, startTransition] = useTransition()\n\n // Get the unique key for this query and its options\n const queryKey = getQueryKey(options)\n // Use a deferred state to avoid immediate re-renders when the query changes\n const [deferredQueryKey, setDeferredQueryKey] = useState(queryKey)\n // Parse the deferred query key back into a query and options\n const deferred = useMemo(() => parseQueryKey(deferredQueryKey), [deferredQueryKey])\n\n // Create an AbortController to cancel in-flight requests when needed\n const ref = useRef<AbortController>(new AbortController())\n\n // When the query or options change, start a transition to update the query\n useEffect(() => {\n if (queryKey === deferredQueryKey) return\n\n startTransition(() => {\n // Abort any in-flight requests for the previous query\n if (ref && !ref.current.signal.aborted) {\n ref.current.abort()\n ref.current = new AbortController()\n }\n\n setDeferredQueryKey(queryKey)\n })\n }, [deferredQueryKey, queryKey])\n\n // Get the state source for this query from the query store\n const {getCurrent, subscribe} = useMemo(\n () => getQueryState(instance, deferred),\n [instance, deferred],\n )\n\n // If data isn't available yet, suspend rendering\n if (getCurrent() === undefined) {\n // Normally, reading from a mutable ref during render can be risky in concurrent mode.\n // However, it is safe here because:\n // 1. React guarantees that while the component is suspended (via throwing a promise),\n // no effects or state updates occur during that render pass.\n // 2. We immediately capture the current abort signal in a local variable (currentSignal).\n // 3. Even if a background render updates ref.current (for example, due to a query change),\n // the captured signal remains unchanged for this suspended render.\n // Thus, the promise thrown here uses a stable abort signal, ensuring correct behavior.\n const currentSignal = ref.current.signal\n\n throw resolveQuery(instance, {...deferred, signal: currentSignal})\n }\n\n // Subscribe to updates and get the current data\n // useSyncExternalStore ensures the component re-renders when the data changes\n const data = useSyncExternalStore(subscribe, getCurrent) as SanityQueryResult\n return useMemo(() => ({data, isPending}), [data, isPending])\n}\n","import {\n createGroqSearchFilter,\n type DatasetHandle,\n type DocumentHandle,\n type QueryOptions,\n} from '@sanity/sdk'\nimport {type SortOrderingItem} from '@sanity/types'\nimport {pick} from 'lodash-es'\nimport {useCallback, useEffect, useMemo, useState} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\nimport {useQuery} from '../query/useQuery'\n\nconst DEFAULT_BATCH_SIZE = 25\n\n/**\n * Configuration options for the useDocuments hook\n *\n * @public\n * @category Types\n */\nexport interface DocumentsOptions<\n TDocumentType extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n> extends DatasetHandle<TDataset, TProjectId>,\n Pick<QueryOptions, 'perspective' | 'params'> {\n /**\n * Filter documents by their `_type`. Can be a single type or an array of types.\n */\n documentType?: TDocumentType | TDocumentType[]\n /**\n * GROQ filter expression to apply to the query\n */\n filter?: string\n /**\n * Number of items to load per batch (defaults to 25)\n */\n batchSize?: number\n /**\n * Sorting configuration for the results\n */\n orderings?: SortOrderingItem[]\n /**\n * Text search query to filter results\n */\n search?: string\n}\n\n/**\n * Return value from the useDocuments hook\n *\n * @public\n * @category Types\n */\nexport interface DocumentsResponse<\n TDocumentType extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n> {\n /**\n * Array of document handles for the current batch\n */\n data: DocumentHandle<TDocumentType, TDataset, TProjectId>[]\n /**\n * Whether there are more items available to load\n */\n hasMore: boolean\n /**\n * Total count of items matching the query\n */\n count: number\n /**\n * Whether a query is currently in progress\n */\n isPending: boolean\n /**\n * Function to load the next batch of results\n */\n loadMore: () => void\n}\n\n/**\n * Retrieves batches of {@link DocumentHandle}s, narrowed by optional filters, text searches, and custom ordering,\n * with infinite scrolling support. The number of document handles returned per batch is customizable,\n * and additional batches can be loaded using the supplied `loadMore` function.\n *\n * @public\n * @category Documents\n * @param options - Configuration options for the infinite list\n * @returns An object containing the list of document handles, the loading state, the total count of retrieved document handles, and a function to load more\n *\n * @remarks\n * - The returned document handles include projectId and dataset information from the current Sanity instance\n * - This makes them ready to use with document operations and other document hooks\n * - The hook automatically uses the correct Sanity instance based on the projectId and dataset in the options\n *\n * @example Basic infinite list with loading more\n * ```tsx\n * import {\n * useDocuments,\n * createDatasetHandle,\n * type DatasetHandle,\n * type DocumentHandle,\n * type SortOrderingItem\n * } from '@sanity/sdk-react'\n * import {Suspense} from 'react'\n *\n * // Define a component to display a single document (using useDocumentProjection for efficiency)\n * function MyDocumentComponent({doc}: {doc: DocumentHandle}) {\n * const {data} = useDocumentProjection<{title?: string}>({\n * ...doc, // Pass the full handle\n * projection: '{title}'\n * })\n *\n * return <>{data?.title || 'Untitled'}</>\n * }\n *\n * // Define props for the list component\n * interface DocumentListProps {\n * dataset: DatasetHandle\n * documentType: string\n * search?: string\n * }\n *\n * function DocumentList({dataset, documentType, search}: DocumentListProps) {\n * const { data, hasMore, isPending, loadMore, count } = useDocuments({\n * ...dataset,\n * documentType,\n * search,\n * batchSize: 10,\n * orderings: [{field: '_createdAt', direction: 'desc'}],\n * })\n *\n * return (\n * <div>\n * <p>Total documents: {count}</p>\n * <ol>\n * {data.map((docHandle) => (\n * <li key={docHandle.documentId}>\n * <Suspense fallback=\"Loading…\">\n * <MyDocumentComponent docHandle={docHandle} />\n * </Suspense>\n * </li>\n * ))}\n * </ol>\n * {hasMore && (\n * <button onClick={loadMore}>\n * {isPending ? 'Loading...' : 'Load More'}\n * </button>\n * )}\n * </div>\n * )\n * }\n *\n * // Usage:\n * // const myDatasetHandle = createDatasetHandle({ projectId: 'p1', dataset: 'production' })\n * // <DocumentList dataset={myDatasetHandle} documentType=\"post\" search=\"Sanity\" />\n * ```\n *\n * @example Using `filter` and `params` options for narrowing a collection\n * ```tsx\n * import {useState} from 'react'\n * import {useDocuments} from '@sanity/sdk-react'\n *\n * export default function FilteredAuthors() {\n * const [max, setMax] = useState(2)\n * const {data} = useDocuments({\n * documentType: 'author',\n * filter: 'length(books) <= $max',\n * params: {max},\n * })\n *\n * return (\n * <>\n * <input\n * id=\"maxBooks\"\n * type=\"number\"\n * value={max}\n * onChange={e => setMax(e.currentTarget.value)}\n * />\n * {data.map(author => (\n * <Suspense key={author.documentId}>\n * <MyAuthorComponent documentHandle={author} />\n * </Suspense>\n * ))}\n * </>\n * )\n * }\n * ```\n */\nexport function useDocuments<\n TDocumentType extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n>({\n batchSize = DEFAULT_BATCH_SIZE,\n params,\n search,\n filter,\n orderings,\n documentType,\n ...options\n}: DocumentsOptions<TDocumentType, TDataset, TProjectId>): DocumentsResponse<\n TDocumentType,\n TDataset,\n TProjectId\n> {\n const instance = useSanityInstance(options)\n const [limit, setLimit] = useState(batchSize)\n const documentTypes = useMemo(\n () =>\n (Array.isArray(documentType) ? documentType : [documentType]).filter(\n (i): i is TDocumentType => typeof i === 'string',\n ),\n [documentType],\n )\n\n // Reset the limit to the current batchSize whenever any query parameters\n // (filter, search, params, orderings) or batchSize changes\n const key = JSON.stringify({\n filter,\n search,\n params,\n orderings,\n batchSize,\n types: documentTypes,\n ...options,\n })\n useEffect(() => {\n setLimit(batchSize)\n }, [key, batchSize])\n\n const filterClause = useMemo(() => {\n const conditions: string[] = []\n const trimmedSearch = search?.trim()\n\n // Add search query filter if specified\n if (trimmedSearch) {\n const searchFilter = createGroqSearchFilter(trimmedSearch)\n if (searchFilter) {\n conditions.push(searchFilter)\n }\n }\n\n // Add type filter if specified\n if (documentTypes?.length) {\n conditions.push(`(_type in $__types)`)\n }\n\n // Add additional filter if specified\n if (filter) {\n conditions.push(`(${filter})`)\n }\n\n return conditions.length ? `[${conditions.join(' && ')}]` : ''\n }, [filter, search, documentTypes])\n\n const orderClause = orderings\n ? `| order(${orderings\n .map((ordering) =>\n [ordering.field, ordering.direction.toLowerCase()]\n .map((str) => str.trim())\n .filter(Boolean)\n .join(' '),\n )\n .join(',')})`\n : ''\n\n const dataQuery = `*${filterClause}${orderClause}[0...${limit}]{\"documentId\":_id,\"documentType\":_type,...$__handle}`\n const countQuery = `count(*${filterClause})`\n\n const {\n data: {count, data},\n isPending,\n } = useQuery<{count: number; data: DocumentHandle<TDocumentType, TDataset, TProjectId>[]}>({\n ...options,\n query: `{\"count\":${countQuery},\"data\":${dataQuery}}`,\n params: {\n ...params,\n __handle: {\n ...pick(instance.config, 'projectId', 'dataset', 'perspective'),\n ...pick(options, 'projectId', 'dataset', 'perspective'),\n },\n __types: documentTypes,\n },\n })\n\n // Now use the correctly typed variables\n const hasMore = data.length < count\n\n const loadMore = useCallback(() => {\n setLimit((prev) => Math.min(prev + batchSize, count))\n }, [count, batchSize])\n\n return useMemo(\n () => ({data, hasMore, count, isPending, loadMore}),\n [count, data, hasMore, isPending, loadMore],\n )\n}\n","import {createGroqSearchFilter, type DocumentHandle, type QueryOptions} from '@sanity/sdk'\nimport {type SortOrderingItem} from '@sanity/types'\nimport {pick} from 'lodash-es'\nimport {useCallback, useEffect, useMemo, useState} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\nimport {useQuery} from '../query/useQuery'\n\n/**\n * Configuration options for the usePaginatedDocuments hook\n *\n * @public\n * @category Types\n */\nexport interface PaginatedDocumentsOptions<\n TDocumentType extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n> extends Omit<QueryOptions<TDocumentType, TDataset, TProjectId>, 'query'> {\n documentType?: TDocumentType | TDocumentType[]\n /**\n * GROQ filter expression to apply to the query\n */\n filter?: string\n /**\n * Number of items to display per page (defaults to 25)\n */\n pageSize?: number\n /**\n * Sorting configuration for the results\n */\n orderings?: SortOrderingItem[]\n /**\n * Text search query to filter results\n */\n search?: string\n}\n\n/**\n * Return value from the usePaginatedDocuments hook\n *\n * @public\n * @category Types\n */\nexport interface PaginatedDocumentsResponse<\n TDocumentType extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n> {\n /**\n * Array of document handles for the current page\n */\n data: DocumentHandle<TDocumentType, TDataset, TProjectId>[]\n /**\n * Whether a query is currently in progress\n */\n isPending: boolean\n\n /**\n * Number of items displayed per page\n */\n pageSize: number\n /**\n * Current page number (1-indexed)\n */\n currentPage: number\n /**\n * Total number of pages available\n */\n totalPages: number\n\n /**\n * Starting index of the current page (0-indexed)\n */\n startIndex: number\n /**\n * Ending index of the current page (exclusive, 0-indexed)\n */\n endIndex: number\n /**\n * Total count of items matching the query\n */\n count: number\n\n /**\n * Navigate to the first page\n */\n firstPage: () => void\n /**\n * Whether there is a first page available to navigate to\n */\n hasFirstPage: boolean\n\n /**\n * Navigate to the previous page\n */\n previousPage: () => void\n /**\n * Whether there is a previous page available to navigate to\n */\n hasPreviousPage: boolean\n\n /**\n * Navigate to the next page\n */\n nextPage: () => void\n /**\n * Whether there is a next page available to navigate to\n */\n hasNextPage: boolean\n\n /**\n * Navigate to the last page\n */\n lastPage: () => void\n /**\n * Whether there is a last page available to navigate to\n */\n hasLastPage: boolean\n\n /**\n * Navigate to a specific page number\n * @param pageNumber - The page number to navigate to (1-indexed)\n */\n goToPage: (pageNumber: number) => void\n}\n\n/**\n * Retrieves pages of {@link DocumentHandle}s, narrowed by optional filters, text searches, and custom ordering,\n * with support for traditional paginated interfaces. The number of document handles returned per page is customizable,\n * while page navigation is handled via the included navigation functions.\n *\n * @public\n * @category Documents\n * @param options - Configuration options for the paginated list\n * @returns An object containing the list of document handles, pagination details, and functions to navigate between pages\n *\n * @remarks\n * - The returned document handles include projectId and dataset information from the current Sanity instance\n * - This makes them ready to use with document operations and other document hooks\n * - The hook automatically uses the correct Sanity instance based on the projectId and dataset in the options\n *\n * @example Paginated list of documents with navigation\n * ```tsx\n * import {\n * usePaginatedDocuments,\n * createDatasetHandle,\n * type DatasetHandle,\n * type DocumentHandle,\n * type SortOrderingItem,\n * useDocumentProjection\n * } from '@sanity/sdk-react'\n * import {Suspense} from 'react'\n * import {ErrorBoundary} from 'react-error-boundary'\n *\n * // Define a component to display a single document row\n * function MyTableRowComponent({doc}: {doc: DocumentHandle}) {\n * const {data} = useDocumentProjection<{title?: string}>({\n * ...doc,\n * projection: '{title}',\n * })\n *\n * return (\n * <tr>\n * <td>{data?.title ?? 'Untitled'}</td>\n * </tr>\n * )\n * }\n *\n * // Define props for the list component\n * interface PaginatedDocumentListProps {\n * documentType: string\n * dataset?: DatasetHandle\n * }\n *\n * function PaginatedDocumentList({documentType, dataset}: PaginatedDocumentListProps) {\n * const {\n * data,\n * isPending,\n * currentPage,\n * totalPages,\n * nextPage,\n * previousPage,\n * hasNextPage,\n * hasPreviousPage\n * } = usePaginatedDocuments({\n * ...dataset,\n * documentType,\n * pageSize: 10,\n * orderings: [{field: '_createdAt', direction: 'desc'}],\n * })\n *\n * return (\n * <div>\n * <table>\n * <thead>\n * <tr><th>Title</th></tr>\n * </thead>\n * <tbody>\n * {data.map(doc => (\n * <ErrorBoundary key={doc.documentId} fallback={<tr><td>Error loading document</td></tr>}>\n * <Suspense fallback={<tr><td>Loading...</td></tr>}>\n * <MyTableRowComponent doc={doc} />\n * </Suspense>\n * </ErrorBoundary>\n * ))}\n * </tbody>\n * </table>\n * <div style={{opacity: isPending ? 0.5 : 1}}>\n * <button onClick={previousPage} disabled={!hasPreviousPage || isPending}>Previous</button>\n * <span>Page {currentPage} / {totalPages}</span>\n * <button onClick={nextPage} disabled={!hasNextPage || isPending}>Next</button>\n * </div>\n * </div>\n * )\n * }\n *\n * // Usage:\n * // const myDatasetHandle = createDatasetHandle({ projectId: 'p1', dataset: 'production' })\n * // <PaginatedDocumentList dataset={myDatasetHandle} documentType=\"post\" />\n * ```\n */\nexport function usePaginatedDocuments<\n TDocumentType extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n>({\n documentType,\n filter = '',\n pageSize = 25,\n params = {},\n orderings,\n search,\n ...options\n}: PaginatedDocumentsOptions<TDocumentType, TDataset, TProjectId>): PaginatedDocumentsResponse<\n TDocumentType,\n TDataset,\n TProjectId\n> {\n const instance = useSanityInstance(options)\n const [pageIndex, setPageIndex] = useState(0)\n const key = JSON.stringify({filter, search, params, orderings, pageSize})\n // Reset the pageIndex to 0 whenever any query parameters (filter, search,\n // params, orderings) or pageSize changes\n useEffect(() => {\n setPageIndex(0)\n }, [key])\n\n const startIndex = pageIndex * pageSize\n const endIndex = (pageIndex + 1) * pageSize\n const documentTypes = (Array.isArray(documentType) ? documentType : [documentType]).filter(\n (i) => typeof i === 'string',\n )\n\n const filterClause = useMemo(() => {\n const conditions: string[] = []\n const trimmedSearch = search?.trim()\n\n // Add search query filter if specified\n if (trimmedSearch) {\n const searchFilter = createGroqSearchFilter(trimmedSearch)\n if (searchFilter) {\n conditions.push(searchFilter)\n }\n }\n\n if (documentTypes?.length) {\n conditions.push(`(_type in $__types)`)\n }\n\n // Add additional filter if specified\n if (filter) {\n conditions.push(`(${filter})`)\n }\n\n return conditions.length ? `[${conditions.join(' && ')}]` : ''\n }, [filter, search, documentTypes?.length])\n\n const orderClause = orderings\n ? `| order(${orderings\n .map((ordering) =>\n [ordering.field, ordering.direction.toLowerCase()]\n .map((str) => str.trim())\n .filter(Boolean)\n .join(' '),\n )\n .join(',')})`\n : ''\n\n const dataQuery = `*${filterClause}${orderClause}[${startIndex}...${endIndex}]{\"documentId\":_id,\"documentType\":_type,...$__handle}`\n const countQuery = `count(*${filterClause})`\n\n const {\n data: {data, count},\n isPending,\n } = useQuery<{data: DocumentHandle<TDocumentType, TDataset, TProjectId>[]; count: number}>({\n ...options,\n query: `{\"data\":${dataQuery},\"count\":${countQuery}}`,\n params: {\n ...params,\n __types: documentTypes,\n __handle: {\n ...pick(instance.config, 'projectId', 'dataset', 'perspective'),\n ...pick(options, 'projectId', 'dataset', 'perspective'),\n },\n },\n })\n\n const totalPages = Math.ceil(count / pageSize)\n const currentPage = pageIndex + 1\n\n // Navigation methods\n const firstPage = useCallback(() => setPageIndex(0), [])\n const previousPage = useCallback(() => setPageIndex((prev) => Math.max(prev - 1, 0)), [])\n const nextPage = useCallback(\n () => setPageIndex((prev) => Math.min(prev + 1, totalPages - 1)),\n [totalPages],\n )\n const lastPage = useCallback(() => setPageIndex(totalPages - 1), [totalPages])\n const goToPage = useCallback(\n (pageNumber: number) => {\n if (pageNumber < 1 || pageNumber > totalPages) return\n setPageIndex(pageNumber - 1)\n },\n [totalPages],\n )\n\n // Boolean flags for page availability\n const hasFirstPage = pageIndex > 0\n const hasPreviousPage = pageIndex > 0\n const hasNextPage = pageIndex < totalPages - 1\n const hasLastPage = pageIndex < totalPages - 1\n\n return {\n data,\n isPending,\n pageSize,\n currentPage,\n totalPages,\n startIndex,\n endIndex,\n count,\n firstPage,\n hasFirstPage,\n previousPage,\n hasPreviousPage,\n nextPage,\n hasNextPage,\n lastPage,\n hasLastPage,\n goToPage,\n }\n}\n","import {getPresence, type UserPresence} from '@sanity/sdk'\nimport {useCallback, useMemo, useSyncExternalStore} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * A hook for subscribing to presence information for the current project.\n * @public\n */\nexport function usePresence(): {\n locations: UserPresence[]\n} {\n const sanityInstance = useSanityInstance()\n const source = useMemo(() => getPresence(sanityInstance), [sanityInstance])\n const subscribe = useCallback((callback: () => void) => source.subscribe(callback), [source])\n const locations = useSyncExternalStore(\n subscribe,\n () => source.getCurrent(),\n () => source.getCurrent(),\n )\n\n return {locations: locations || []}\n}\n","import {type DocumentHandle, getPreviewState, type PreviewValue, resolvePreview} from '@sanity/sdk'\nimport {useCallback, useSyncExternalStore} from 'react'\nimport {distinctUntilChanged, EMPTY, Observable, startWith, switchMap} from 'rxjs'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * @public\n * @category Types\n */\nexport interface useDocumentPreviewOptions extends DocumentHandle {\n /**\n * Optional ref object to track visibility. When provided, preview resolution\n * only occurs when the referenced element is visible in the viewport.\n */\n ref?: React.RefObject<unknown>\n}\n\n/**\n * @public\n * @category Types\n */\nexport interface useDocumentPreviewResults {\n /** The results of inferring the document’s preview values */\n data: PreviewValue\n /** True when inferred preview values are being refreshed */\n isPending: boolean\n}\n\n/**\n * @public\n *\n * Attempts to infer preview values of a document (specified via a `DocumentHandle`),\n * including the document’s `title`, `subtitle`, `media`, and `status`. These values are live and will update in realtime.\n * To reduce unnecessary network requests for resolving the preview values, an optional `ref` can be passed to the hook so that preview\n * resolution will only occur if the `ref` is intersecting the current viewport.\n *\n * See remarks below for futher information.\n *\n * @remarks\n * Values returned by this hook may not be as expected. It is currently unable to read preview values as defined in your schema;\n * instead, it attempts to infer these preview values by checking against a basic set of potential fields on your document.\n * We are anticipating being able to significantly improve this hook’s functionality and output in a future release.\n * For now, we recommend using {@link useDocumentProjection} for rendering individual document fields (or projections of those fields).\n *\n * @category Documents\n * @param options - The document handle for the document you want to infer preview values for, and an optional ref\n * @returns The inferred values for the given document and a boolean to indicate whether the resolution is pending\n *\n * @example Combining with useDocuments to render a collection of document previews\n * ```\n * // PreviewComponent.jsx\n * export default function PreviewComponent({ document }) {\n * const { data: { title, subtitle, media }, isPending } = useDocumentPreview({ document })\n * return (\n * <article style={{ opacity: isPending ? 0.5 : 1}}>\n * {media?.type === 'image-asset' ? <img src={media.url} alt='' /> : ''}\n * <h2>{title}</h2>\n * <p>{subtitle}</p>\n * </article>\n * )\n * }\n *\n * // DocumentList.jsx\n * const { data } = useDocuments({ filter: '_type == \"movie\"' })\n * return (\n * <div>\n * <h1>Movies</h1>\n * <ul>\n * {data.map(movie => (\n * <li key={movie._id}>\n * <Suspense fallback='Loading…'>\n * <PreviewComponent document={movie} />\n * </Suspense>\n * </li>\n * ))}\n * </ul>\n * </div>\n * )\n * ```\n */\nexport function useDocumentPreview({\n ref,\n ...docHandle\n}: useDocumentPreviewOptions): useDocumentPreviewResults {\n const instance = useSanityInstance(docHandle)\n const stateSource = getPreviewState(instance, docHandle)\n\n // Create subscribe function for useSyncExternalStore\n const subscribe = useCallback(\n (onStoreChanged: () => void) => {\n const subscription = new Observable<boolean>((observer) => {\n // For environments that don't have an intersection observer (e.g. server-side),\n // we pass true to always subscribe since we can't detect visibility\n if (typeof IntersectionObserver === 'undefined' || typeof HTMLElement === 'undefined') {\n observer.next(true)\n return\n }\n\n const intersectionObserver = new IntersectionObserver(\n ([entry]) => observer.next(entry.isIntersecting),\n {rootMargin: '0px', threshold: 0},\n )\n if (ref?.current && ref.current instanceof HTMLElement) {\n intersectionObserver.observe(ref.current)\n } else {\n // If no ref is provided or ref.current isn't an HTML element,\n // pass true to always subscribe since we can't track visibility\n observer.next(true)\n }\n return () => intersectionObserver.disconnect()\n })\n .pipe(\n startWith(false),\n distinctUntilChanged(),\n switchMap((isVisible) =>\n isVisible\n ? new Observable<void>((obs) => {\n return stateSource.subscribe(() => obs.next())\n })\n : EMPTY,\n ),\n )\n .subscribe({next: onStoreChanged})\n\n return () => subscription.unsubscribe()\n },\n [stateSource, ref],\n )\n\n // Create getSnapshot function to return current state\n const getSnapshot = useCallback(() => {\n const currentState = stateSource.getCurrent()\n if (currentState.data === null) throw resolvePreview(instance, docHandle)\n return currentState as useDocumentPreviewResults\n }, [docHandle, instance, stateSource])\n\n return useSyncExternalStore(subscribe, getSnapshot)\n}\n","import {type DocumentHandle, getProjectionState, resolveProjection} from '@sanity/sdk'\nimport {type SanityProjectionResult} from 'groq'\nimport {useCallback, useSyncExternalStore} from 'react'\nimport {distinctUntilChanged, EMPTY, Observable, startWith, switchMap} from 'rxjs'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * @public\n * @category Types\n */\nexport interface useDocumentProjectionOptions<\n TProjection extends string = string,\n TDocumentType extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n> extends DocumentHandle<TDocumentType, TDataset, TProjectId> {\n /** The GROQ projection string */\n projection: TProjection\n /** Optional parameters for the projection query */\n params?: Record<string, unknown>\n /** Optional ref to track viewport intersection for lazy loading */\n ref?: React.RefObject<unknown>\n}\n\n/**\n * @public\n * @category Types\n */\nexport interface useDocumentProjectionResults<TData> {\n /** The projected data */\n data: TData\n /** True if the projection is currently being resolved */\n isPending: boolean\n}\n\n/**\n * @public\n *\n * Returns the projected values of a document based on the provided projection string.\n * These values are live and will update in realtime.\n * To optimize network requests, an optional `ref` can be passed to only resolve the projection\n * when the referenced element is intersecting the viewport.\n *\n * @category Documents\n * @remarks\n * This hook has multiple signatures allowing for fine-grained control over type inference:\n * - Using Typegen: Infers the return type based on the `documentType`, `dataset`, `projectId`, and `projection`.\n * - Using explicit type parameter: Allows specifying a custom return type `TData`.\n *\n * @param options - An object containing the `DocumentHandle` properties (`documentId`, `documentType`, etc.), the `projection` string, optional `params`, and an optional `ref`.\n * @returns An object containing the projection results (`data`) and a boolean indicating whether the resolution is pending (`isPending`). Note: Suspense handles initial loading states; `data` being `undefined` after initial loading means the document doesn't exist or the projection yielded no result.\n */\n\n// Overload 1: Relies on Typegen\n/**\n * @public\n * Fetch a projection, relying on Typegen for the return type based on the handle and projection.\n *\n * @category Documents\n * @param options - Options including the document handle properties (`documentId`, `documentType`, etc.) and the `projection`.\n * @returns The projected data, typed based on Typegen.\n *\n * @example Using Typegen for a book preview\n * ```tsx\n * // ProjectionComponent.tsx\n * import {useDocumentProjection, type DocumentHandle} from '@sanity/sdk-react'\n * import {useRef} from 'react'\n * import {defineProjection} from 'groq'\n *\n * // Define props using DocumentHandle with the specific document type\n * type ProjectionComponentProps = {\n * doc: DocumentHandle<'book'> // Typegen knows 'book'\n * }\n *\n * // This is required for typegen to generate the correct return type\n * const myProjection = defineProjection(`{\n * title,\n * 'coverImage': cover.asset->url,\n * 'authors': array::join(authors[]->{'name': firstName + ' ' + lastName}.name, ', ')\n * }`)\n *\n * export default function ProjectionComponent({ doc }: ProjectionComponentProps) {\n * const ref = useRef(null) // Optional ref to track viewport intersection for lazy loading\n *\n * // Spread the doc handle into the options\n * // Typegen infers the return type based on 'book' and the projection\n * const { data } = useDocumentProjection({\n * ...doc, // Pass the handle properties\n * ref,\n * projection: myProjection,\n * })\n *\n * // Suspense handles initial load, check for data existence after\n * return (\n * <article ref={ref}>\n * <h2>{data.title ?? 'Untitled'}</h2>\n * {data.coverImage && <img src={data.coverImage} alt={data.title} />}\n * <p>{data.authors ?? 'Unknown authors'}</p>\n * </article>\n * )\n * }\n *\n * // Usage:\n * // import {createDocumentHandle} from '@sanity/sdk-react'\n * // const myDocHandle = createDocumentHandle({ documentId: 'book123', documentType: 'book' })\n * // <Suspense fallback='Loading preview...'>\n * // <ProjectionComponent doc={myDocHandle} />\n * // </Suspense>\n * ```\n */\nexport function useDocumentProjection<\n TProjection extends string = string,\n TDocumentType extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n>(\n options: useDocumentProjectionOptions<TProjection, TDocumentType, TDataset, TProjectId>,\n): useDocumentProjectionResults<\n SanityProjectionResult<TProjection, TDocumentType, `${TProjectId}.${TDataset}`>\n>\n\n// Overload 2: Explicit type provided\n/**\n * @public\n * Fetch a projection with an explicitly defined return type `TData`.\n *\n * @param options - Options including the document handle properties (`documentId`, etc.) and the `projection`.\n * @returns The projected data, cast to the explicit type `TData`.\n *\n * @example Explicitly typing the projection result\n * ```tsx\n * import {useDocumentProjection, type DocumentHandle} from '@sanity/sdk-react'\n * import {useRef} from 'react'\n *\n * interface SimpleBookPreview {\n * title?: string;\n * authorName?: string;\n * }\n *\n * type BookPreviewProps = {\n * doc: DocumentHandle\n * }\n *\n * function BookPreview({ doc }: BookPreviewProps) {\n * const ref = useRef(null)\n * const { data } = useDocumentProjection<SimpleBookPreview>({\n * ...doc,\n * ref,\n * projection: `{ title, 'authorName': author->name }`\n * })\n *\n * return (\n * <div ref={ref}>\n * <h3>{data.title ?? 'No Title'}</h3>\n * <p>By: {data.authorName ?? 'Unknown'}</p>\n * </div>\n * )\n * }\n *\n * // Usage:\n * // import {createDocumentHandle} from '@sanity/sdk-react'\n * // const doc = createDocumentHandle({ documentId: 'abc', documentType: 'book' })\n * // <Suspense fallback='Loading...'>\n * // <BookPreview doc={doc} />\n * // </Suspense>\n * ```\n */\nexport function useDocumentProjection<TData extends object>(\n options: useDocumentProjectionOptions, // Uses base options type\n): useDocumentProjectionResults<TData>\n\n// Implementation (no JSDoc needed here as it's covered by overloads)\nexport function useDocumentProjection<TData extends object>({\n ref,\n projection,\n ...docHandle\n}: useDocumentProjectionOptions): useDocumentProjectionResults<TData> {\n const instance = useSanityInstance(docHandle)\n const stateSource = getProjectionState<TData>(instance, {...docHandle, projection})\n\n if (stateSource.getCurrent()?.data === null) {\n throw resolveProjection(instance, {...docHandle, projection})\n }\n\n // Create subscribe function for useSyncExternalStore\n const subscribe = useCallback(\n (onStoreChanged: () => void) => {\n const subscription = new Observable<boolean>((observer) => {\n // For environments that don't have an intersection observer (e.g. server-side),\n // we pass true to always subscribe since we can't detect visibility\n if (typeof IntersectionObserver === 'undefined' || typeof HTMLElement === 'undefined') {\n observer.next(true)\n return\n }\n\n const intersectionObserver = new IntersectionObserver(\n ([entry]) => observer.next(entry.isIntersecting),\n {rootMargin: '0px', threshold: 0},\n )\n if (ref?.current && ref.current instanceof HTMLElement) {\n intersectionObserver.observe(ref.current)\n } else {\n // If no ref is provided or ref.current isn't an HTML element,\n // pass true to always subscribe since we can't track visibility\n observer.next(true)\n }\n return () => intersectionObserver.disconnect()\n })\n .pipe(\n startWith(false),\n distinctUntilChanged(),\n switchMap((isVisible) =>\n isVisible\n ? new Observable<void>((obs) => {\n return stateSource.subscribe(() => obs.next())\n })\n : EMPTY,\n ),\n )\n .subscribe({next: onStoreChanged})\n\n return () => subscription.unsubscribe()\n },\n [stateSource, ref],\n )\n\n return useSyncExternalStore(\n subscribe,\n stateSource.getCurrent,\n ) as useDocumentProjectionResults<TData>\n}\n","import {\n getProjectState,\n type ProjectHandle,\n resolveProject,\n type SanityInstance,\n type SanityProject,\n type StateSource,\n} from '@sanity/sdk'\nimport {identity} from 'rxjs'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\ntype UseProject = {\n /**\n *\n * Returns metadata for a given project\n *\n * @category Projects\n * @param projectId - The ID of the project to retrieve metadata for\n * @returns The metadata for the project\n * @example\n * ```tsx\n * function ProjectMetadata({ projectId }: { projectId: string }) {\n * const project = useProject(projectId)\n *\n * return (\n * <figure style={{ backgroundColor: project.metadata.color || 'lavender'}}>\n * <h1>{project.displayName}</h1>\n * </figure>\n * )\n * }\n * ```\n */\n (projectHandle?: ProjectHandle): SanityProject\n}\n\n/**\n * @public\n * @function\n */\nexport const useProject: UseProject = createStateSourceHook({\n // remove `undefined` since we're suspending when that is the case\n getState: getProjectState as (\n instance: SanityInstance,\n projectHandle?: ProjectHandle,\n ) => StateSource<SanityProject>,\n shouldSuspend: (instance, projectHandle) =>\n getProjectState(instance, projectHandle).getCurrent() === undefined,\n suspender: resolveProject,\n getConfig: identity,\n})\n","import {type SanityProject} from '@sanity/client'\nimport {getProjectsState, resolveProjects, type SanityInstance, type StateSource} from '@sanity/sdk'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\n/**\n * @public\n * @category Types\n * @interface\n */\nexport type ProjectWithoutMembers = Omit<SanityProject, 'members'>\n\n/**\n * @public\n * @category Types\n */\ntype UseProjects = <TIncludeMembers extends boolean = false>(options?: {\n organizationId?: string\n includeMembers?: TIncludeMembers\n}) => TIncludeMembers extends true ? SanityProject[] : ProjectWithoutMembers[]\n\n/**\n * Returns metadata for each project you have access to.\n *\n * @category Projects\n * @param options - Configuration options\n * @returns An array of project metadata. If includeMembers is true, returns full SanityProject objects. Otherwise, returns ProjectWithoutMembers objects.\n * @example\n * ```tsx\n * const projects = useProjects()\n *\n * return (\n * <select>\n * {projects.map((project) => (\n * <option key={project.id}>{project.displayName}</option>\n * ))}\n * </select>\n * )\n * ```\n * @example\n * ```tsx\n * const projectsWithMembers = useProjects({ includeMembers: true })\n * const projectsWithoutMembers = useProjects({ includeMembers: false })\n * ```\n * @public\n * @function\n */\nexport const useProjects: UseProjects = createStateSourceHook({\n getState: getProjectsState as (\n instance: SanityInstance,\n options?: {organizationId?: string; includeMembers?: boolean},\n ) => StateSource<SanityProject[] | ProjectWithoutMembers[]>,\n shouldSuspend: (instance, options) =>\n getProjectsState(instance, options).getCurrent() === undefined,\n suspender: resolveProjects,\n}) as UseProjects\n","import {\n getActiveReleasesState,\n type ReleaseDocument,\n type SanityInstance,\n type StateSource,\n} from '@sanity/sdk'\nimport {filter, firstValueFrom} from 'rxjs'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\n/**\n * @public\n */\ntype UseActiveReleases = {\n (): ReleaseDocument[]\n}\n\n/**\n * @public\n\n * Returns the active releases for the current project,\n * represented as a list of release documents.\n *\n * @returns The active releases for the current project.\n * @category Projects\n * @example\n * ```tsx\n * import {useActiveReleases} from '@sanity/sdk-react'\n *\n * const activeReleases = useActiveReleases()\n * ```\n */\nexport const useActiveReleases: UseActiveReleases = createStateSourceHook({\n getState: getActiveReleasesState as (instance: SanityInstance) => StateSource<ReleaseDocument[]>,\n shouldSuspend: (instance: SanityInstance) =>\n getActiveReleasesState(instance).getCurrent() === undefined,\n suspender: (instance: SanityInstance) =>\n firstValueFrom(getActiveReleasesState(instance).observable.pipe(filter(Boolean))),\n})\n","import {\n getActiveReleasesState,\n getPerspectiveState,\n type PerspectiveHandle,\n type SanityInstance,\n type StateSource,\n} from '@sanity/sdk'\nimport {filter, firstValueFrom} from 'rxjs'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\n/**\n * @public\n */\ntype UsePerspective = {\n (perspectiveHandle: PerspectiveHandle): string | string[]\n}\n\n/**\n * @public\n * @function\n *\n * Returns a single or stack of perspectives for the given perspective handle,\n * which can then be used to correctly query the documents\n * via the `perspective` parameter in the client.\n *\n * @param perspectiveHandle - The perspective handle to get the perspective for.\n * @category Documents\n * @example\n * ```tsx\n * import {usePerspective, useQuery} from '@sanity/sdk-react'\n\n * const perspective = usePerspective({perspective: 'rxg1346', projectId: 'abc123', dataset: 'production'})\n * const {data} = useQuery<Movie[]>('*[_type == \"movie\"]', {\n * perspective: perspective,\n * })\n * ```\n *\n * @returns The perspective for the given perspective handle.\n */\nexport const usePerspective: UsePerspective = createStateSourceHook({\n getState: getPerspectiveState as (\n instance: SanityInstance,\n perspectiveHandle?: PerspectiveHandle,\n ) => StateSource<string | string[]>,\n shouldSuspend: (instance: SanityInstance, options?: PerspectiveHandle): boolean =>\n getPerspectiveState(instance, options).getCurrent() === undefined,\n suspender: (instance: SanityInstance, _options?: PerspectiveHandle) =>\n firstValueFrom(getActiveReleasesState(instance).observable.pipe(filter(Boolean))),\n})\n","import {\n type GetUserOptions,\n getUsersKey,\n getUsersState,\n parseUsersKey,\n resolveUsers,\n type SanityUser,\n} from '@sanity/sdk'\nimport {useEffect, useMemo, useState, useSyncExternalStore, useTransition} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * @public\n * @category Types\n */\nexport interface UserResult {\n /**\n * The user data fetched, or undefined if not found.\n */\n data: SanityUser | undefined\n /**\n * Whether a user request is currently in progress\n */\n isPending: boolean\n}\n\n/**\n *\n * @public\n *\n * Retrieves a single user by ID for a given resource (either a project or an organization).\n *\n * @category Users\n * @param options - The user ID, resource type, project ID, or organization ID\n * @returns The user data and loading state\n *\n * @example\n * ```\n * const { data, isPending } = useUser({\n * userId: 'gabc123',\n * resourceType: 'project',\n * projectId: 'my-project-id',\n * })\n *\n * return (\n * <div>\n * {isPending && <p>Loading...</p>}\n * {data && (\n * <figure>\n * <img src={data.profile.imageUrl} alt='' />\n * <figcaption>{data.profile.displayName}</figcaption>\n * <address>{data.profile.email}</address>\n * </figure>\n * )}\n * </div>\n * )\n * ```\n */\nexport function useUser(options: GetUserOptions): UserResult {\n const instance = useSanityInstance(options)\n // Use React's useTransition to avoid UI jank when user options change\n const [isPending, startTransition] = useTransition()\n\n // Get the unique key for this user request and its options\n const key = getUsersKey(instance, options)\n // Use a deferred state to avoid immediate re-renders when the user request changes\n const [deferredKey, setDeferredKey] = useState(key)\n // Parse the deferred user key back into user options\n const deferred = useMemo(() => parseUsersKey(deferredKey), [deferredKey])\n\n // Create an AbortController to cancel in-flight requests when needed\n const [ref, setRef] = useState<AbortController>(new AbortController())\n\n // When the user request or options change, start a transition to update the request\n useEffect(() => {\n if (key === deferredKey) return\n\n startTransition(() => {\n if (!ref.signal.aborted) {\n ref.abort()\n setRef(new AbortController())\n }\n\n setDeferredKey(key)\n })\n }, [deferredKey, key, ref])\n\n // Get the state source for this user request from the users store\n // We pass the userId as part of options to getUsersState\n const {getCurrent, subscribe} = useMemo(() => {\n return getUsersState(instance, deferred as GetUserOptions)\n }, [instance, deferred])\n\n // If data isn't available yet, suspend rendering until it is\n // This is the React Suspense integration - throwing a promise\n // will cause React to show the nearest Suspense fallback\n if (getCurrent() === undefined) {\n throw resolveUsers(instance, {...(deferred as GetUserOptions), signal: ref.signal})\n }\n\n // Subscribe to updates and get the current data\n // useSyncExternalStore ensures the component re-renders when the data changes\n // Extract the first user from the users array (since we're fetching by userId, there should be only one)\n const result = useSyncExternalStore(subscribe, getCurrent)\n const data = result?.data[0]\n\n return {data, isPending}\n}\n","import {\n getUsersKey,\n type GetUsersOptions,\n getUsersState,\n loadMoreUsers,\n parseUsersKey,\n resolveUsers,\n type SanityUser,\n} from '@sanity/sdk'\nimport {useCallback, useEffect, useMemo, useState, useSyncExternalStore, useTransition} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * @public\n * @category Types\n */\nexport interface UsersResult {\n /**\n * The users fetched.\n */\n data: SanityUser[]\n /**\n * Whether there are more users to fetch.\n */\n hasMore: boolean\n\n /**\n * Whether a users request is currently in progress\n */\n isPending: boolean\n /**\n * Load more users.\n */\n loadMore: () => void\n}\n\n/**\n *\n * @public\n *\n * Retrieves the users for a given resource (either a project or an organization).\n *\n * @category Users\n * @param params - The resource type, project ID, and the limit of users to fetch\n * @returns A list of users, a boolean indicating whether there are more users to fetch, and a function to load more users\n *\n * @example\n * ```\n * const { data, hasMore, loadMore, isPending } = useUsers({\n * resourceType: 'organization',\n * organizationId: 'my-org-id',\n * batchSize: 10,\n * })\n *\n * return (\n * <div>\n * {data.map(user => (\n * <figure key={user.sanityUserId}>\n * <img src={user.profile.imageUrl} alt='' />\n * <figcaption>{user.profile.displayName}</figcaption>\n * <address>{user.profile.email}</address>\n * </figure>\n * ))}\n * {hasMore && <button onClick={loadMore}>{isPending ? 'Loading...' : 'Load More'</button>}\n * </div>\n * )\n * ```\n */\nexport function useUsers(options?: GetUsersOptions): UsersResult {\n const instance = useSanityInstance(options)\n // Use React's useTransition to avoid UI jank when user options change\n const [isPending, startTransition] = useTransition()\n\n // Get the unique key for this users request and its options\n const key = getUsersKey(instance, options)\n // Use a deferred state to avoid immediate re-renders when the users request changes\n const [deferredKey, setDeferredKey] = useState(key)\n // Parse the deferred users key back into users options\n const deferred = useMemo(() => parseUsersKey(deferredKey), [deferredKey])\n\n // Create an AbortController to cancel in-flight requests when needed\n const [ref, setRef] = useState<AbortController>(new AbortController())\n\n // When the users request or options change, start a transition to update the request\n useEffect(() => {\n if (key === deferredKey) return\n\n startTransition(() => {\n if (!ref.signal.aborted) {\n ref.abort()\n setRef(new AbortController())\n }\n\n setDeferredKey(key)\n })\n }, [deferredKey, key, ref])\n\n // Get the state source for this users request from the users store\n const {getCurrent, subscribe} = useMemo(() => {\n return getUsersState(instance, deferred)\n }, [instance, deferred])\n\n // If data isn't available yet, suspend rendering until it is\n // This is the React Suspense integration - throwing a promise\n // will cause React to show the nearest Suspense fallback\n if (getCurrent() === undefined) {\n throw resolveUsers(instance, {...deferred, signal: ref.signal})\n }\n\n // Subscribe to updates and get the current data\n // useSyncExternalStore ensures the component re-renders when the data changes\n const {data, hasMore} = useSyncExternalStore(subscribe, getCurrent)!\n\n const loadMore = useCallback(() => {\n loadMoreUsers(instance, options)\n }, [instance, options])\n\n return {data, hasMore, isPending, loadMore}\n}\n","// Local type declaration for Remix\ntype WindowWithEnv = Window &\n typeof globalThis & {\n ENV?: Record<string, unknown>\n }\n\ntype KnownEnvVar = 'DEV' | 'PKG_VERSION'\n\nexport function getEnv(key: KnownEnvVar): unknown {\n if (typeof import.meta !== 'undefined' && import.meta.env) {\n // Vite environment variables\n return (import.meta.env as unknown as Record<string, unknown>)[key]\n } else if (typeof process !== 'undefined' && process.env) {\n // Node.js or server-side environment variables\n return process.env[key]\n } else if (typeof window !== 'undefined' && (window as WindowWithEnv).ENV) {\n // Remix-style client-side environment variables\n return (window as WindowWithEnv).ENV?.[key]\n }\n return undefined\n}\n","import {version} from '../package.json'\nimport {getEnv} from './utils/getEnv'\n\n/**\n * This version is provided by pkg-utils at build time\n * @internal\n */\nexport const REACT_SDK_VERSION = getEnv('PKG_VERSION') || `${version}-development`\n"],"names":["SanityInstanceContext","createContext","useSanityInstance","config","$","_c","instance","useContext","Error","JSON","stringify","t0","match","createStateSourceHook","options","getState","getConfig","undefined","suspense","useHook","params","t1","suspender","shouldSuspend","t2","state","useSyncExternalStore","subscribe","getCurrent","useAuthState","getAuthState","useNodeState","getNodeState","nodeInput","firstValueFrom","observable","pipe","filter","Boolean","useWindowConnection","name","connectTo","onMessage","node","Symbol","for","messageUnsubscribers","useRef","t3","Object","entries","forEach","t4","type","handler","messageUnsubscribe","on","current","push","_temp","useEffect","t5","type_0","data","post","sendMessage","t6","type_1","data_0","fetchOptions","fetch","t7","unsubscribe","DEFAULT_RESPONSE_TIMEOUT","DashboardTokenRefresh","children","isTokenRefreshInProgress","timeoutRef","processed401ErrorRef","authState","clearTimeout","clearRefreshTimeout","SDK_NODE_NAME","SDK_CHANNEL_NAME","windowConnection","setTimeout","res","token","errorContainer","document","getElementById","Array","from","getElementsByTagName","some","remove","requestNewToken","error","has401Error","AuthStateType","ERROR","statusCode","isLoggedOut","LOGGED_OUT","div","textContent","includes","ComlinkTokenRefreshProvider","getIsInDashboardState","isInDashboard","studioModeEnabled","studioMode","enabled","useLoginUrl","getLoginUrlState","useVerifyOrgProjects","projectIds","disabled","setError","useState","length","subscription","observeOrganizationVerificationState","result","FONT_SANS_SERIF","FONT_MONOSPACE","styles","container","padding","fontFamily","display","flexDirection","gap","fontSize","heading","margin","fontWeight","paragraph","link","appearance","background","border","font","textDecoration","cursor","code","description","cta","__html","href","onClick","text","CorsErrorComponent","projectId","origin","window","location","url","URL","searchParams","set","toString","corsUrl","message","isInIframe","self","top","isLocalUrl","startsWith","AuthError","constructor","cause","ConfigurationError","createCallbackHook","callback","useHandleAuthCallback","handleAuthCallback","LoginCallback","then","replacementLocation","history","replaceState","useLogOut","logout","LoginError","resetErrorBoundary","ClientError","authErrorMessage","setAuthErrorMessage","handleRetry","errorMessage","response","body","endsWith","querySelector","parsedUrl","mode","URLSearchParams","hash","slice","get","script","createElement","src","async","head","appendChild","AuthBoundary","props","LoginErrorComponent","fallbackProps","CorsOriginError","getCorsErrorProjectId","FallbackComponent","AuthSwitch","CallbackComponent","verifyOrganization","disableVerifyOrg","LOGGED_IN","orgError","isDestroyingSession","loginUrl","LOGGING_IN","DEFAULT_FALLBACK","ResourceProvider","fallback","parent","createChild","createSanityInstance","disposal","timeoutId","isDisposed","dispose","SDKProvider","configs","isArray","reverse","map","c","id","createNestedProviders","index","REDIRECT_URL","SanityApp","timeout","primaryConfig","console","warn","replace","useAuthToken","getTokenState","useCurrentUser","getCurrentUserState","useDashboardOrganizationId","getDashboardOrganizationId","useClient","getClientState","identity","useFrameConnection","targetOrigin","heartbeat","onStatus","controllerRef","channelRef","controller","getOrCreateController","channel","getOrCreateChannel","event","status","releaseChannel","frameWindow","removeTarget","addTarget","connect","unsub","useDashboardNavigate","navigateFn","useManageFavorite","documentId","documentType","paramProjectId","dataset","paramDataset","resourceId","paramResourceId","resourceType","schemaName","instanceProjectId","instanceDataset","context","useMemo","favoriteState","getFavoritesState","isFavorited","handleFavoriteAction","useCallback","action","payload","eventType","resource","success","resolveFavoritesState","err","favorite","unfavorite","useStudioWorkspacesByProjectIdDataset","workspacesByProjectIdAndDataset","setWorkspacesByProjectIdAndDataset","fetchWorkspaces","signal","workspaceMap","noProjectIdAndDataset","availableResources","key","AbortController","abort","useNavigateToStudioDocument","documentHandle","preferredStudioUrl","workspace","find","w","workspaces","path","navigateToStudioDocument","useRecordDocumentHistoryEvent","recordEvent","useDatasets","getDatasetsState","projectHandle","resolveDatasets","useApplyDocumentActions","applyDocumentActions","useDocumentValue","getDocumentState","_path","resolveDocument","wrapHookWithData","useValue","useDocument","useDocumentEvent","datasetHandle","onEvent","ref","useInsertionEffect","documentEvent","stableHandler","subscribeDocumentEvents","useDocumentPermissions","actionOrActions","actions","getPermissionsState","useDocumentSyncStatus","getDocumentSyncStatus","doc","ignoredKeys","useEditDocument","apply","updater","currentPath","currentValue","nextValue","editDocument","nextValue_0","editActions","keys","key_0","key_1","unset","useQuery","isPending","startTransition","useTransition","queryKey","getQueryKey","deferredQueryKey","setDeferredQueryKey","deferred","parseQueryKey","aborted","getQueryState","currentSignal","resolveQuery","DEFAULT_BATCH_SIZE","useDocuments","batchSize","search","orderings","limit","setLimit","documentTypes","i","types","filterClause","conditions","trimmedSearch","trim","searchFilter","createGroqSearchFilter","join","orderClause","ordering","field","direction","toLowerCase","str","dataQuery","countQuery","count","query","__handle","pick","__types","hasMore","loadMore","prev","Math","min","usePaginatedDocuments","pageSize","pageIndex","setPageIndex","startIndex","endIndex","t8","t9","t10","_temp3","t11","t12","t13","t14","t15","t16","t17","totalPages","ceil","currentPage","t18","firstPage","t19","_temp4","previousPage","t20","prev_0","nextPage","t21","lastPage","t22","pageNumber","goToPage","hasFirstPage","hasPreviousPage","hasNextPage","hasLastPage","t23","max","_temp2","usePresence","sanityInstance","getPresence","source","locations","useDocumentPreview","docHandle","getPreviewState","stateSource","onStoreChanged","Observable","observer","IntersectionObserver","HTMLElement","next","intersectionObserver","entry","isIntersecting","rootMargin","threshold","observe","disconnect","startWith","distinctUntilChanged","switchMap","isVisible","obs","EMPTY","currentState","resolvePreview","useDocumentProjection","projection","getProjectionState","resolveProjection","useProject","getProjectState","resolveProject","useProjects","getProjectsState","resolveProjects","useActiveReleases","getActiveReleasesState","usePerspective","getPerspectiveState","_options","useUser","getUsersKey","deferredKey","setDeferredKey","parseUsersKey","setRef","getUsersState","resolveUsers","useUsers","loadMoreUsers","getEnv","import","env","process","ENV","REACT_SDK_VERSION","version"],"mappings":";;;;;;;;;;AAGaA,MAAAA,wBAAwBC,cAAqC,IAAI,GCwDjEC,oBAAoBC,CAAA,WAAA;AAAA,QAAAC,IAAAC,EAAA,CAAA,GAC/BC,WAAiBC,WAAAP,qBAAgC;AAAC,MAAA,CAE7CM;AAAQ,UAAA,IAAAE,MAET,qCAAqCL,SAA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