@sanity/sdk-react 0.0.0-rc.6 → 0.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -57
- package/dist/index.d.ts +1000 -438
- package/dist/index.js +324 -258
- package/dist/index.js.map +1 -1
- package/package.json +17 -16
- package/src/_exports/sdk-react.ts +4 -1
- package/src/components/SDKProvider.tsx +6 -1
- package/src/components/SanityApp.test.tsx +29 -47
- package/src/components/SanityApp.tsx +12 -11
- package/src/components/auth/AuthBoundary.test.tsx +177 -7
- package/src/components/auth/AuthBoundary.tsx +32 -2
- package/src/components/auth/ConfigurationError.ts +22 -0
- package/src/components/auth/LoginError.tsx +9 -3
- package/src/hooks/auth/useVerifyOrgProjects.test.tsx +136 -0
- package/src/hooks/auth/useVerifyOrgProjects.tsx +48 -0
- package/src/hooks/client/useClient.ts +3 -3
- package/src/hooks/comlink/useManageFavorite.test.ts +276 -27
- package/src/hooks/comlink/useManageFavorite.ts +102 -51
- package/src/hooks/comlink/useWindowConnection.ts +3 -2
- package/src/hooks/document/useApplyDocumentActions.ts +105 -31
- package/src/hooks/document/useDocument.test.ts +41 -4
- package/src/hooks/document/useDocument.ts +198 -114
- package/src/hooks/document/useDocumentEvent.test.ts +5 -5
- package/src/hooks/document/useDocumentEvent.ts +67 -23
- package/src/hooks/document/useDocumentPermissions.ts +47 -8
- package/src/hooks/document/useDocumentSyncStatus.test.ts +12 -5
- package/src/hooks/document/useDocumentSyncStatus.ts +41 -14
- package/src/hooks/document/useEditDocument.test.ts +24 -6
- package/src/hooks/document/useEditDocument.ts +238 -133
- package/src/hooks/documents/useDocuments.test.tsx +1 -1
- package/src/hooks/documents/useDocuments.ts +153 -44
- package/src/hooks/paginatedDocuments/usePaginatedDocuments.test.tsx +1 -1
- package/src/hooks/paginatedDocuments/usePaginatedDocuments.ts +120 -47
- package/src/hooks/projection/useProjection.ts +134 -46
- package/src/hooks/query/useQuery.test.tsx +4 -4
- package/src/hooks/query/useQuery.ts +115 -43
- package/src/hooks/releases/useActiveReleases.test.tsx +84 -0
- package/src/hooks/releases/useActiveReleases.ts +39 -0
- package/src/hooks/releases/usePerspective.test.tsx +120 -0
- package/src/hooks/releases/usePerspective.ts +50 -0
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/auth/useLoginUrl.tsx","../src/components/utils.ts","../src/components/auth/AuthError.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/comlink/useWindowConnection.ts","../src/hooks/comlink/useManageFavorite.ts","../src/hooks/comlink/useRecordDocumentHistoryEvent.ts","../src/hooks/dashboard/useStudioWorkspacesByProjectIdDataset.ts","../src/hooks/dashboard/useNavigateToStudioDocument.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/preview/usePreview.tsx","../src/hooks/projection/useProjection.ts","../src/hooks/projects/useProject.ts","../src/hooks/projects/useProjects.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>.`,\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> 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 {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","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","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'\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 (!(error instanceof AuthError)) throw error\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 (authState.type === AuthStateType.ERROR && authState.error instanceof ClientError) {\n if (authState.error.statusCode === 401) {\n handleRetry()\n } else if (authState.error.statusCode === 404) {\n const errorMessage = authState.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 }, [authState, handleRetry])\n\n return (\n <div className=\"sc-login-error\">\n <div className=\"sc-login-error__content\">\n <h2 className=\"sc-login-error__title\">Authentication Error</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 {useAuthState} from '../../hooks/auth/useAuthState'\nimport {useLoginUrl} from '../../hooks/auth/useLoginUrl'\nimport {isInIframe} from '../utils'\nimport {AuthError} from './AuthError'\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 * @public\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 /** Footer content to display */\n footer?: React.ReactNode\n\n /** Protected content to render when authenticated */\n children?: React.ReactNode\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 <ErrorBoundary FallbackComponent={FallbackComponent}>\n <AuthSwitch {...props} />\n </ErrorBoundary>\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}\n\nfunction AuthSwitch({CallbackComponent = LoginCallback, children, ...props}: AuthSwitchProps) {\n const authState = useAuthState()\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 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\n // Create a nested structure of ResourceProviders for each config\n const createNestedProviders = (index: number): ReactElement => {\n if (index >= configs.length) {\n return <AuthBoundary {...props}>{children}</AuthBoundary>\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 * SanityApp 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 *\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 } from '@sanity/sdk-react'\n *\n * import MyAppRoot from './Root'\n *\n * // Single project configuration\n * const mySanityConfig = {\n * projectId: 'my-project-id',\n * dataset: 'production',\n * }\n *\n * // Or multiple project configurations\n * const multipleConfigs = [\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={<LoadingSpinner />}>\n * <MyAppRoot />\n * </SanityApp>\n * )\n * }\n * ```\n */\nexport function SanityApp({\n children,\n fallback,\n config,\n sanityConfigs,\n ...props\n}: SanityAppProps): ReactElement {\n const configs = config ?? sanityConfigs ?? []\n\n useEffect(() => {\n let timeout: NodeJS.Timeout | undefined\n\n if (!isInIframe() && !isLocalUrl(window)) {\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 }, [])\n\n return (\n <SDKProvider {...props} fallback={fallback} config={configs}>\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 * such as user authentication changes.\n *\n * @remarks\n * The hook uses `useSyncExternalStore` to safely subscribe to changes\n * and ensure consistency between server and client rendering.\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 MessageData, type Node, type Status} from '@sanity/comlink'\nimport {type FrameMessage, getOrCreateNode, releaseNode, type WindowMessage} from '@sanity/sdk'\nimport {useCallback, useEffect, useRef} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\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 onStatus?: (status: Status) => void\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\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 onStatus,\n}: UseWindowConnectionOptions<TFrameMessage>): WindowConnection<TWindowMessage> {\n const nodeRef = useRef<Node<TWindowMessage, TFrameMessage> | null>(null)\n const messageUnsubscribers = useRef<(() => void)[]>([])\n const instance = useSanityInstance()\n\n useEffect(() => {\n // the type cast is unfortunate, but the generic type of the node is not known here.\n // We know that the node is a WindowMessage node, but not the generic types.\n const node = getOrCreateNode(instance, {\n name,\n connectTo,\n }) as unknown as Node<TWindowMessage, TFrameMessage>\n nodeRef.current = node\n\n const statusUnsubscribe = node.onStatus((eventStatus) => {\n onStatus?.(eventStatus)\n })\n\n if (onMessage) {\n Object.entries(onMessage).forEach(([type, handler]) => {\n const messageUnsubscribe = node.on(type, handler as WindowMessageHandler<TFrameMessage>)\n messageUnsubscribers.current.push(messageUnsubscribe)\n })\n }\n\n return () => {\n statusUnsubscribe()\n messageUnsubscribers.current.forEach((unsubscribe) => unsubscribe())\n messageUnsubscribers.current = []\n releaseNode(instance, name)\n nodeRef.current = null\n }\n }, [instance, name, connectTo, onMessage, onStatus])\n\n const sendMessage = useCallback(\n (type: TWindowMessage['type'], data?: Extract<TWindowMessage, {type: typeof type}>['data']) => {\n if (!nodeRef.current) {\n throw new Error('Cannot send message before connection is established')\n }\n nodeRef.current.post(type, data)\n },\n [],\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 nodeRef.current?.fetch(type, data, fetchOptions ?? {}) as Promise<TResponse>\n },\n [],\n )\n return {\n sendMessage,\n fetch,\n }\n}\n","import {type Status} from '@sanity/comlink'\nimport {\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, useEffect, useState} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\nimport {useWindowConnection} from './useWindowConnection'\n\n// should we import this whole type from the message protocol?\n\ninterface ManageFavorite {\n favorite: () => void\n unfavorite: () => void\n isFavorited: boolean\n isConnected: 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 * - `isConnected` - Boolean indicating if connection to Dashboard UI is established\n *\n * @example\n * ```tsx\n * function MyDocumentAction(props: DocumentActionProps) {\n * const {documentId, documentType} = props\n * const {favorite, unfavorite, isFavorited, isConnected} = useManageFavorite({\n * documentId,\n * documentType\n * })\n *\n * return (\n * <Button\n * disabled={!isConnected}\n * onClick={() => isFavorited ? unfavorite() : favorite()}\n * text={isFavorited ? 'Remove from favorites' : 'Add to favorites'}\n * />\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 [isFavorited, setIsFavorited] = useState(false) // should load this from a comlink fetch\n const [status, setStatus] = useState<Status>('idle')\n const [resourceId, setResourceId] = useState<string>(paramResourceId || '')\n const {sendMessage} = useWindowConnection<Events.FavoriteMessage, FrameMessage>({\n name: SDK_NODE_NAME,\n connectTo: SDK_CHANNEL_NAME,\n onStatus: setStatus,\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\n useEffect(() => {\n // If resourceType is studio and the resourceId is not provided,\n // use the projectId and dataset to generate a resourceId\n if (resourceType === 'studio' && !paramResourceId) {\n setResourceId(`${projectId}.${dataset}`)\n } else if (paramResourceId) {\n setResourceId(paramResourceId)\n } else {\n // For other resource types, resourceId is required\n throw new Error('resourceId is required for media-library and canvas resources')\n }\n }, [resourceType, paramResourceId, projectId, dataset])\n\n const handleFavoriteAction = useCallback(\n (action: 'added' | 'removed', setFavoriteState: boolean) => {\n if (!documentId || !documentType || !resourceType) return\n\n try {\n const message: Events.FavoriteMessage = {\n type: 'dashboard/v1/events/favorite/mutate',\n data: {\n eventType: action,\n document: {\n id: documentId,\n type: documentType,\n resource: {\n id: resourceId,\n type: resourceType,\n schemaName,\n },\n },\n },\n response: {\n success: true,\n },\n }\n\n sendMessage(message.type, message.data)\n setIsFavorited(setFavoriteState)\n } catch (err) {\n const error = err instanceof Error ? err : new Error('Failed to update favorite status')\n // eslint-disable-next-line no-console\n console.error(\n `Failed to ${action === 'added' ? 'favorite' : 'unfavorite'} document:`,\n error,\n )\n throw error\n }\n },\n [documentId, documentType, resourceId, resourceType, sendMessage, schemaName],\n )\n\n const favorite = useCallback(() => handleFavoriteAction('added', true), [handleFavoriteAction])\n\n const unfavorite = useCallback(\n () => handleFavoriteAction('removed', false),\n [handleFavoriteAction],\n )\n\n return {\n favorite,\n unfavorite,\n isFavorited,\n isConnected: status === 'connected',\n }\n}\n","import {type Status} from '@sanity/comlink'\nimport {\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, useState} from 'react'\n\nimport {useWindowConnection} from './useWindowConnection'\n\ninterface DocumentInteractionHistory {\n recordEvent: (eventType: 'viewed' | 'edited' | 'created' | 'deleted') => void\n isConnected: boolean\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 * - `isConnected` - Boolean indicating if connection to Studio is established\n *\n * @example\n * ```tsx\n * function MyDocumentAction(props: DocumentActionProps) {\n * const {documentId, documentType, resourceType, resourceId} = props\n * const {recordEvent, isConnected} = useRecordDocumentHistoryEvent({\n * documentId,\n * documentType,\n * resourceType,\n * resourceId,\n * })\n *\n * return (\n * <Button\n * disabled={!isConnected}\n * onClick={() => recordEvent('viewed')}\n * text={'Viewed'}\n * />\n * )\n * }\n * ```\n */\nexport function useRecordDocumentHistoryEvent({\n documentId,\n documentType,\n resourceType,\n resourceId,\n schemaName,\n}: UseRecordDocumentHistoryEventProps): DocumentInteractionHistory {\n const [status, setStatus] = useState<Status>('idle')\n const {sendMessage} = useWindowConnection<Events.HistoryMessage, FrameMessage>({\n name: SDK_NODE_NAME,\n connectTo: SDK_CHANNEL_NAME,\n onStatus: setStatus,\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 isConnected: status === 'connected',\n }\n}\n","import {type Status} from '@sanity/comlink'\nimport {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 isConnected: boolean\n}\n\n/**\n * Hook that fetches studio workspaces and organizes them by projectId:dataset\n * @internal\n */\nexport function useStudioWorkspacesByProjectIdDataset(): StudioWorkspacesResult {\n const [workspacesByProjectIdAndDataset, setWorkspacesByProjectIdAndDataset] =\n useState<WorkspacesByProjectIdDataset>({})\n const [status, setStatus] = useState<Status>('idle')\n const [error, setError] = useState<string | null>(null)\n\n const {fetch} = useWindowConnection({\n name: SDK_NODE_NAME,\n connectTo: SDK_CHANNEL_NAME,\n onStatus: setStatus,\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 || status !== 'connected') return\n\n async function fetchWorkspaces(signal: AbortSignal) {\n try {\n const data = await fetch<{\n context: {availableResources: Array<DashboardResource>}\n }>('dashboard/v1/bridge/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, status])\n\n return {\n workspacesByProjectIdAndDataset,\n error,\n isConnected: status === 'connected',\n }\n}\n","import {type Status} from '@sanity/comlink'\nimport {type Bridge, SDK_CHANNEL_NAME, SDK_NODE_NAME} from '@sanity/message-protocol'\nimport {type DocumentHandle} from '@sanity/sdk'\nimport {useCallback, useState} 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 isConnected: boolean\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 * - `isConnected` - Boolean indicating if connection to Dashboard is established\n *\n * @example\n * ```ts\n * import {useNavigateToStudioDocument, type DocumentHandle} from '@sanity/sdk-react'\n *\n * function MyComponent({documentHandle}: {documentHandle: DocumentHandle}) {\n * const {navigateToStudioDocument, isConnected} = useNavigateToStudioDocument(documentHandle)\n *\n * return (\n * <button onClick={navigateToStudioDocument} disabled={!isConnected}>\n * Navigate to Studio Document\n * </button>\n * )\n * }\n * ```\n */\nexport function useNavigateToStudioDocument(\n documentHandle: DocumentHandle,\n preferredStudioUrl?: string,\n): NavigateToStudioResult {\n const {workspacesByProjectIdAndDataset, isConnected: workspacesConnected} =\n useStudioWorkspacesByProjectIdDataset()\n const [status, setStatus] = useState<Status>('idle')\n const {sendMessage} = useWindowConnection<Bridge.Navigation.NavigateToResourceMessage, never>({\n name: SDK_NODE_NAME,\n connectTo: SDK_CHANNEL_NAME,\n onStatus: setStatus,\n })\n\n const navigateToStudioDocument = useCallback(() => {\n const {projectId, dataset} = documentHandle\n\n if (!workspacesConnected || status !== 'connected') {\n // eslint-disable-next-line no-console\n console.warn('Not connected to Dashboard')\n return\n }\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 }, [\n documentHandle,\n workspacesConnected,\n status,\n workspacesByProjectIdAndDataset,\n sendMessage,\n preferredStudioUrl,\n ])\n\n return {\n navigateToStudioDocument,\n isConnected: workspacesConnected && status === 'connected',\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 {applyDocumentActions} from '@sanity/sdk'\n\nimport {createCallbackHook} from '../helpers/createCallbackHook'\n\n/**\n *\n * @beta\n *\n * Provides a callback for applying one or more actions to a document.\n *\n * @category Documents\n * @param dataset - An optional dataset handle with projectId and dataset. If not provided, the nearest SanityInstance from context will be used.\n * @returns A function that takes one more more {@link DocumentAction}s and returns a promise that resolves to an {@link ActionsResult}.\n * @example Publish or unpublish a document\n * ```\n * import { publishDocument, unpublishDocument } from '@sanity/sdk'\n * import { useApplyDocumentActions } from '@sanity/sdk-react'\n *\n * const apply = useApplyDocumentActions()\n * const myDocument = { documentId: 'my-document-id', documentType: 'my-document-type' }\n *\n * return (\n * <button onClick={() => apply(publishDocument(myDocument))}>Publish</button>\n * <button onClick={() => apply(unpublishDocument(myDocument))}>Unpublish</button>\n * )\n * ```\n *\n * @example Create and publish a new document\n * ```\n * import { createDocument, publishDocument } from '@sanity/sdk'\n * import { useApplyDocumentActions } from '@sanity/sdk-react'\n *\n * const apply = useApplyDocumentActions()\n *\n * const handleCreateAndPublish = () => {\n * const handle = { documentId: window.crypto.randomUUID(), documentType: 'my-document-type' }\n * apply([\n * createDocument(handle),\n * publishDocument(handle),\n * ])\n * }\n *\n * return (\n * <button onClick={handleCreateAndPublish}>\n * I'm feeling lucky\n * </button>\n * )\n * ```\n */\nexport const useApplyDocumentActions = createCallbackHook(applyDocumentActions)\n","import {\n type DocumentHandle,\n getDocumentState,\n type JsonMatch,\n type JsonMatchPath,\n resolveDocument,\n} from '@sanity/sdk'\nimport {type SanityDocument} from '@sanity/types'\nimport {identity} from 'rxjs'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\n/**\n * @beta\n *\n * ## useDocument(doc, path)\n * Read and subscribe to nested values in a document\n * @category Documents\n * @param doc - The document to read state from, specified as a DocumentHandle\n * @param path - The path to the nested value to read from\n * @returns The value at the specified path\n * @example\n * ```tsx\n * import {useDocument} from '@sanity/sdk-react'\n *\n * const documentHandle = {\n * documentId: 'order-123',\n * documentType: 'order',\n * projectId: 'abc123',\n * dataset: 'production'\n * }\n *\n * function OrderLink() {\n * const title = useDocument(documentHandle, 'title')\n * const id = useDocument(documentHandle, '_id')\n *\n * return (\n * <a href={`/order/${id}`}>Order {title} today!</a>\n * )\n * }\n * ```\n *\n */\nexport function useDocument<\n TDocument extends SanityDocument,\n TPath extends JsonMatchPath<TDocument>,\n>(doc: DocumentHandle<TDocument>, path: TPath): JsonMatch<TDocument, TPath> | undefined\n\n/**\n * @beta\n * ## useDocument(doc)\n * Read and subscribe to an entire document\n * @param doc - The document to read state from, specified as a DocumentHandle\n * @returns The document state as an object\n * @example\n * ```tsx\n * import {type SanityDocument, useDocument} from '@sanity/sdk-react'\n *\n * interface Book extends SanityDocument {\n * title: string\n * author: string\n * summary: string\n * }\n *\n * const documentHandle = {\n * documentId: 'book-123',\n * documentType: 'book',\n * projectId: 'abc123',\n * dataset: 'production'\n * }\n *\n * function DocumentView() {\n * const book = useDocument<Book>(documentHandle)\n *\n * if (!book) {\n * return <div>Loading...</div>\n * }\n *\n * return (\n * <article>\n * <h1>{book.title}</h1>\n * <address>By {book.author}</address>\n *\n * <h2>Summary</h2>\n * {book.summary}\n *\n * <h2>Order</h2>\n * <a href={`/order/${book._id}`}>Order {book.title} today!</a>\n * </article>\n * )\n * }\n * ```\n *\n */\nexport function useDocument<TDocument extends SanityDocument>(\n doc: DocumentHandle<TDocument>,\n): TDocument | null\n\n/**\n * @beta\n * Reads and subscribes to a document's realtime state, incorporating both local and remote changes.\n * When called with a `path` argument, the hook will return the nested value's state.\n * When called without a `path` argument, the entire document's state will be returned.\n *\n * @remarks\n * `useDocument` is designed to be used within a realtime context in which local updates to documents\n * need to be displayed before they are persisted to the remote copy. This can be useful within a collaborative\n * or realtime editing interface where local changes need to be reflected immediately.\n *\n * The hook automatically uses the correct Sanity instance based on the project and dataset\n * specified in the DocumentHandle. This makes it easy to work with documents from different\n * projects or datasets in the same component.\n *\n * However, this hook can be too resource intensive for applications where static document values simply\n * need to be displayed (or when changes to documents don't need to be reflected immediately);\n * consider using `usePreview` or `useQuery` for these use cases instead. These hooks leverage the Sanity\n * Live Content API to provide a more efficient way to read and subscribe to document state.\n */\nexport function useDocument(doc: DocumentHandle, path?: string): unknown {\n return _useDocument(doc, path)\n}\n\nconst _useDocument = createStateSourceHook<[doc: DocumentHandle, path?: string], unknown>({\n getState: getDocumentState,\n shouldSuspend: (instance, doc) => getDocumentState(instance, doc).getCurrent() === undefined,\n suspender: resolveDocument,\n getConfig: identity,\n})\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 *\n * @beta\n *\n * Subscribes an event handler to events in your application's document store, such as document\n * creation, deletion, and updates.\n *\n * @category Documents\n * @param handler - The event handler to register.\n * @param doc - The document to subscribe to events 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 * @example\n * ```\n * import {useDocumentEvent} from '@sanity/sdk-react'\n * import {type DocumentEvent} from '@sanity/sdk'\n *\n * useDocumentEvent((event) => {\n * if (event.type === DocumentEvent.DocumentDeletedEvent) {\n * alert(`Document with ID ${event.documentId} deleted!`)\n * } else {\n * console.log(event)\n * }\n * })\n * ```\n */\nexport function useDocumentEvent(\n handler: (documentEvent: DocumentEvent) => void,\n dataset: DatasetHandle,\n): void {\n const ref = useRef(handler)\n\n useInsertionEffect(() => {\n ref.current = handler\n })\n\n const stableHandler = useCallback((documentEvent: DocumentEvent) => {\n return ref.current(documentEvent)\n }, [])\n\n const instance = useSanityInstance(dataset)\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 more more calls to a particular document action function for a given document\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 * @example Checking for permission to publish a document\n * ```ts\n * import {useDocumentPermissions, useApplyDocumentActions} from '@sanity/sdk-react'\n * import {publishDocument} from '@sanity/sdk'\n *\n * export function PublishButton({doc}: {doc: DocumentHandle}) {\n * const publishPermissions = useDocumentPermissions(publishDocument(doc))\n * const applyAction = useApplyDocumentActions()\n *\n * return (\n * <>\n * <button\n * disabled={!publishPermissions.allowed}\n * onClick={() => applyAction(publishDocument(doc))}\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 */\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 {type DocumentHandle, getDocumentSyncStatus} from '@sanity/sdk'\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 the changes are not synced, and `undefined` if the document is not found\n * @example Disable a Save button when there are no changes to sync\n * ```\n * const myDocumentHandle = { documentId: 'documentId', documentType: 'documentType', projectId: 'projectId', dataset: 'dataset' }\n * const documentSynced = useDocumentSyncStatus(myDocumentHandle)\n *\n * return (\n * <button disabled={documentSynced}>\n * Save Changes\n * </button>\n * )\n * ```\n */\n (doc: DocumentHandle): boolean | undefined\n}\n\n/**\n * @beta\n * @function\n */\nexport const useDocumentSyncStatus: UseDocumentSyncStatus =\n createStateSourceHook(getDocumentSyncStatus)\n","import {\n type ActionsResult,\n type DocumentHandle,\n editDocument,\n getDocumentState,\n type JsonMatch,\n type JsonMatchPath,\n resolveDocument,\n} from '@sanity/sdk'\nimport {type SanityDocument} from '@sanity/types'\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 | ((nextValue: TValue) => TValue)\n\n/**\n *\n * @beta\n *\n * ## useEditDocument(doc, path)\n * Edit a nested value within a document\n *\n * @category Documents\n * @param docHandle - The document to be edited, specified as a DocumentHandle\n * @param path - The path to the nested value to be edited\n * @returns A function to update the nested value. Accepts either a new value, or an updater function that exposes the previous value and returns a new value.\n * @example Update a document's name by providing the new value directly\n * ```tsx\n * const handle = {\n * documentId: 'movie-123',\n * documentType: 'movie',\n * projectId: 'abc123',\n * dataset: 'production'\n * }\n *\n * const name = useDocument(handle, 'name')\n * const editName = useEditDocument(handle, 'name')\n *\n * function handleNameChange(event: React.ChangeEvent<HTMLInputElement>) {\n * editName(event.target.value)\n * }\n *\n * return (\n * <input type='text' value={name} onChange={handleNameChange} />\n * )\n * ```\n *\n * @example Update a count on a document by providing an updater function\n * ```tsx\n * const handle = {\n * documentId: 'counter-123',\n * documentType: 'counter',\n * projectId: 'abc123',\n * dataset: 'production'\n * }\n *\n * const count = useDocument(handle, 'count')\n * const editCount = useEditDocument(handle, 'count')\n *\n * function incrementCount() {\n * editCount(previousCount => previousCount + 1)\n * }\n *\n * return (\n * <>\n * <button onClick={incrementCount}>\n * Increment\n * </button>\n * Current count: {count}\n * </>\n * )\n * ```\n */\nexport function useEditDocument<\n TDocument extends SanityDocument,\n TPath extends JsonMatchPath<TDocument>,\n>(\n docHandle: DocumentHandle<TDocument>,\n path: TPath,\n): (nextValue: Updater<JsonMatch<TDocument, TPath>>) => Promise<ActionsResult<TDocument>>\n\n/**\n *\n * @beta\n *\n * ## useEditDocument(doc)\n * Edit an entire document\n * @param docHandle - The document to be edited, specified as a DocumentHandle.\n * The hook will automatically use the Sanity instance that matches the project and dataset specified in the handle.\n * @returns A function to update the document state. Accepts either a new document state, or an updater function that exposes the previous document state and returns the new document state.\n * @example\n * ```tsx\n * const myDocumentHandle = {\n * documentId: 'product-123',\n * documentType: 'product',\n * projectId: 'abc123',\n * dataset: 'production'\n * }\n *\n * const myDocument = useDocument(myDocumentHandle)\n * const { title, price } = myDocument ?? {}\n *\n * const editMyDocument = useEditDocument(myDocumentHandle)\n *\n * function handleFieldChange(e: React.ChangeEvent<HTMLInputElement>) {\n * const {name, value} = e.currentTarget\n * // Use an updater function to update the document state based on the previous state\n * editMyDocument(previousDocument => ({\n * ...previousDocument,\n * [name]: value\n * }))\n * }\n *\n * function handleSaleChange(e: React.ChangeEvent<HTMLInputElement>) {\n * const { checked } = e.currentTarget\n * if (checked) {\n * // Use an updater function to add a new salePrice field;\n * // set it at a 20% discount off the normal price\n * editMyDocument(previousDocument => ({\n * ...previousDocument,\n * salePrice: previousDocument.price * 0.8,\n * }))\n * } else {\n * // Get the document state without the salePrice field\n * const { salePrice, ...rest } = myDocument\n * // Update the document state to remove the salePrice field\n * editMyDocument(rest)\n * }\n * }\n *\n * return (\n * <>\n * <form onSubmit={e => e.preventDefault()}>\n * <input name='title' type='text' value={title} onChange={handleFieldChange} />\n * <input name='price' type='number' value={price} onChange={handleFieldChange} />\n * <input\n * name='salePrice'\n * type='checkbox'\n * checked={myDocument && 'salePrice' in myDocument}\n * onChange={handleSaleChange}\n * />\n * </form>\n * <pre><code>\n * {JSON.stringify(myDocument, null, 2)}\n * </code></pre>\n * </>\n * )\n * ```\n */\nexport function useEditDocument<TDocument extends SanityDocument>(\n docHandle: DocumentHandle<TDocument>,\n): (nextValue: Updater<TDocument>) => Promise<ActionsResult<TDocument>>\n\n/**\n *\n * @beta\n *\n * Enables editing of a document’s state.\n * When called with a `path` argument, the hook will return a function for updating a nested value.\n * When called without a `path` argument, the hook will return a function for updating the entire document.\n */\nexport function useEditDocument(\n docHandle: DocumentHandle,\n path?: string,\n): (updater: Updater<unknown>) => Promise<ActionsResult> {\n const instance = useSanityInstance(docHandle)\n const apply = useApplyDocumentActions()\n const isDocumentReady = useCallback(\n () => getDocumentState(instance, docHandle).getCurrent() !== undefined,\n [instance, docHandle],\n )\n if (!isDocumentReady()) throw resolveDocument(instance, docHandle)\n\n return (updater: Updater<unknown>) => {\n if (path) {\n const nextValue =\n typeof updater === 'function'\n ? updater(getDocumentState(instance, docHandle, path).getCurrent())\n : updater\n\n return apply(editDocument(docHandle, {set: {[path]: nextValue}}))\n }\n\n const current = getDocumentState(instance, docHandle).getCurrent() as object | null | undefined\n const nextValue = typeof updater === 'function' ? updater(current) : 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((key) => current?.[key as keyof typeof current] !== nextValue[key])\n .map((key) =>\n key in nextValue\n ? editDocument(docHandle, {set: {[key]: nextValue[key]}})\n : editDocument(docHandle, {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 {useEffect, useMemo, useRef, useState, useSyncExternalStore, useTransition} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * Executes GROQ queries against a Sanity dataset.\n *\n * This hook provides a convenient way to fetch and subscribe to real-time updates\n * for your Sanity content. Changes made to the dataset's content will trigger\n * automatic updates.\n *\n * @remarks\n * The returned `isPending` flag indicates when a React transition is in progress,\n * which can be used to show loading states for query changes.\n *\n * @beta\n * @category GROQ\n * @param query - GROQ query string to execute\n * @param options - Optional configuration for the query, including projectId and dataset\n * @returns Object containing the query result and a pending state flag\n *\n * @example Basic usage\n * ```tsx\n * const {data, isPending} = useQuery<Movie[]>('*[_type == \"movie\"]')\n * ```\n *\n * @example Using parameters\n * ```tsx\n * // With parameters\n * const {data} = useQuery<Movie>('*[_type == \"movie\" && _id == $id][0]', {\n * params: { id: 'movie-123' }\n * })\n * ```\n *\n * @example Query from a specific project/dataset\n * ```tsx\n * // Specify which project and dataset to query\n * const {data} = useQuery<Movie[]>('*[_type == \"movie\"]', {\n * projectId: 'abc123',\n * dataset: 'production'\n * })\n * ```\n *\n * @example With a loading state for transitions\n * ```tsx\n * const {data, isPending} = useQuery<Movie[]>('*[_type == \"movie\"]')\n * return (\n * <div>\n * {isPending && <div>Updating...</div>}\n * <ul>\n * {data.map(movie => <li key={movie._id}>{movie.title}</li>)}\n * </ul>\n * </div>\n * )\n * ```\n *\n */\nexport function useQuery<T>(query: string, options?: QueryOptions): {data: T; isPending: boolean} {\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(query, 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.query, deferred.options),\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 // eslint-disable-next-line react-compiler/react-compiler\n throw resolveQuery(instance, deferred.query, {...deferred.options, 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 T\n return useMemo(() => ({data, isPending}), [data, isPending])\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\nconst DEFAULT_BATCH_SIZE = 25\nconst DEFAULT_PERSPECTIVE = 'drafts'\n\n/**\n * Result structure returned from the infinite list query\n * @internal\n */\ninterface UseDocumentsQueryResult {\n count: number\n data: DocumentHandle[]\n}\n\n/**\n * Configuration options for the useDocuments hook\n *\n * @beta\n * @category Types\n */\nexport interface DocumentsOptions extends QueryOptions {\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 * @beta\n * @category Types\n */\nexport interface DocumentsResponse {\n /**\n * Array of document handles for the current batch\n */\n data: DocumentHandle[]\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 * @beta\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 * const { data, hasMore, isPending, loadMore, count } = useDocuments({\n * filter: '_type == \"post\"',\n * search: searchTerm,\n * batchSize: 10,\n * orderings: [{field: '_createdAt', direction: 'desc'}]\n * })\n *\n * return (\n * <div>\n * Total documents: {count}\n * <ol>\n * {data.map((doc) => (\n * <li key={doc.documentId}>\n * <MyDocumentComponent doc={doc} />\n * </li>\n * ))}\n * </ol>\n * {hasMore && <button onClick={loadMore} disabled={isPending}>\n * {isPending ? 'Loading...' : 'Load More'}\n * </button>}\n * </div>\n * )\n * ```\n */\nexport function useDocuments({\n batchSize = DEFAULT_BATCH_SIZE,\n params,\n search,\n filter,\n orderings,\n ...options\n}: DocumentsOptions): DocumentsResponse {\n const instance = useSanityInstance(options)\n const perspective = options.perspective ?? DEFAULT_PERSPECTIVE\n const [limit, setLimit] = useState(batchSize)\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({filter, search, params, orderings, batchSize})\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 additional filter if specified\n if (filter) {\n conditions.push(`(${filter})`)\n }\n\n return conditions.length ? `[${conditions.join(' && ')}]` : ''\n }, [filter, search])\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,...$__dataset}`\n const countQuery = `count(*${filterClause})`\n\n const {\n data: {count, data},\n isPending,\n } = useQuery<UseDocumentsQueryResult>(`{\"count\":${countQuery},\"data\":${dataQuery}}`, {\n ...options,\n params: {\n ...params,\n __dataset: pick(instance.config, 'projectId', 'dataset'),\n },\n perspective,\n })\n\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 [data, hasMore, count, 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\nconst DEFAULT_PERSPECTIVE = 'drafts'\n\n/**\n * Configuration options for the usePaginatedDocuments hook\n *\n * @beta\n * @category Types\n */\nexport interface PaginatedDocumentsOptions extends QueryOptions {\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 * @beta\n * @category Types\n */\nexport interface PaginatedDocumentsResponse {\n /**\n * Array of document handles for the current page\n */\n data: DocumentHandle[]\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 * @beta\n * @category Documents\n * @param options - Configuration options for the paginated list\n * @returns An object containing the current page of document handles, the loading and pagination state, and navigation functions\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 usage\n * ```tsx\n * const {\n * data,\n * isPending,\n * currentPage,\n * totalPages,\n * nextPage,\n * previousPage,\n * hasNextPage,\n * hasPreviousPage\n * } = usePaginatedDocuments({\n * filter: '_type == \"post\"',\n * search: searchTerm,\n * pageSize: 10,\n * orderings: [{field: '_createdAt', direction: 'desc'}]\n * })\n *\n * return (\n * <>\n * <table>\n * {data.map(doc => (\n * <MyTableRowComponent key={doc.documentId} doc={doc} />\n * ))}\n * </table>\n * {hasPreviousPage && <button onClick={previousPage}>Previous</button>}\n * {currentPage} / {totalPages}\n * {hasNextPage && <button onClick={nextPage}>Next</button>}\n * </>\n * )\n * ```\n *\n */\nexport function usePaginatedDocuments({\n filter = '',\n pageSize = 25,\n params = {},\n orderings,\n search,\n ...options\n}: PaginatedDocumentsOptions): PaginatedDocumentsResponse {\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 perspective = options.perspective ?? DEFAULT_PERSPECTIVE\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 additional filter if specified\n if (filter) {\n conditions.push(`(${filter})`)\n }\n\n return conditions.length ? `[${conditions.join(' && ')}]` : ''\n }, [filter, search])\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,...$__dataset}`\n const countQuery = `count(*${filterClause})`\n\n const {\n data: {data, count},\n isPending,\n } = useQuery<{data: DocumentHandle[]; count: number}>(\n `{\"data\":${dataQuery},\"count\":${countQuery}}`,\n {\n ...options,\n perspective,\n params: {...params, __dataset: pick(instance.config, 'projectId', 'dataset')},\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 {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 * @beta\n * @category Types\n */\nexport interface UsePreviewOptions 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 * @beta\n * @category Types\n */\nexport interface UsePreviewResults {\n /** The results of resolving the document’s preview values */\n data: PreviewValue\n /** True when preview values are being refreshed */\n isPending: boolean\n}\n\n/**\n * @beta\n *\n * Returns the 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 * @category Documents\n * @param options - The document handle for the document you want to resolve preview values for, and an optional ref\n * @returns The preview 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 } = usePreview({ 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 usePreview({ref, ...docHandle}: UsePreviewOptions): UsePreviewResults {\n const instance = useSanityInstance()\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 UsePreviewResults\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 {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 UseProjectionOptions extends DocumentHandle {\n ref?: React.RefObject<unknown>\n projection: ValidProjection\n}\n\n/**\n * @public\n * @category Types\n */\nexport interface UseProjectionResults<TData extends object> {\n data: TData\n isPending: boolean\n}\n\n/**\n * @public\n *\n * Returns the projection values of a document (specified via a `DocumentHandle`),\n * based on the provided projection string. These values are live and will update in realtime.\n * To reduce unnecessary network requests for resolving the projection values, an optional `ref` can be passed to the hook so that projection\n * resolution will only occur if the `ref` is intersecting the current viewport.\n *\n * @category Documents\n * @param options - The document handle for the document you want to project values from, the projection string, and an optional ref\n * @returns The projection values for the given document and a boolean to indicate whether the resolution is pending\n *\n * @example Using a projection to render a preview of document\n * ```\n * // ProjectionComponent.jsx\n * export default function ProjectionComponent({ document }) {\n * const ref = useRef(null)\n * const { data: { title, coverImage, authors }, isPending } = useProjection({\n * ...document,\n * ref,\n * projection: `{\n * title,\n * 'coverImage': cover.asset->url,\n * 'authors': array::join(authors[]->{'name': firstName + ' ' + lastName + ' '}.name, ', ')\n * }`,\n * })\n *\n * return (\n * <article ref={ref} style={{ opacity: isPending ? 0.5 : 1}}>\n * <h2>{title}</h2>\n * <img src={coverImage} alt={title} />\n * <p>{authors}</p>\n * </article>\n * )\n * }\n * ```\n *\n * @example Combining with useDocuments to render a collection with specific fields\n * ```\n * // DocumentList.jsx\n * const { data } = useDocuments({ filter: '_type == \"article\"' })\n * return (\n * <div>\n * <h1>Books</h1>\n * <ul>\n * {data.map(book => (\n * <li key={book._id}>\n * <Suspense fallback='Loading…'>\n * <ProjectionComponent\n * document={book}\n * />\n * </Suspense>\n * </li>\n * ))}\n * </ul>\n * </div>\n * )\n * ```\n */\nexport function useProjection<TData extends object>({\n ref,\n projection,\n ...docHandle\n}: UseProjectionOptions): UseProjectionResults<TData> {\n const instance = useSanityInstance()\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(subscribe, stateSource.getCurrent) as UseProjectionResults<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\ntype UseProjects = {\n /**\n *\n * Returns metadata for each project you have access to.\n *\n * @category Projects\n * @returns An array of metadata (minus the projects’ members) for each project\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 */\n (): ProjectWithoutMembers[]\n}\n\n/**\n * @public\n * @function\n */\nexport const useProjects: UseProjects = createStateSourceHook({\n // remove `undefined` since we're suspending when that is the case\n getState: getProjectsState as (instance: SanityInstance) => StateSource<ProjectWithoutMembers[]>,\n shouldSuspend: (instance) => getProjectsState(instance).getCurrent() === undefined,\n suspender: resolveProjects,\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","useLoginUrl","getLoginUrlState","isInIframe","window","self","top","isLocalUrl","url","location","href","startsWith","AuthError","constructor","error","message","cause","createCallbackHook","callback","useHandleAuthCallback","handleAuthCallback","LoginCallback","URL","toString","then","_temp","useEffect","replacementLocation","history","replaceState","useLogOut","logout","LoginError","resetErrorBoundary","authState","authErrorMessage","setAuthErrorMessage","useState","handleRetry","type","AuthStateType","ERROR","ClientError","statusCode","errorMessage","response","body","endsWith","t3","t4","Symbol","for","t5","t6","t7","document","querySelector","parsedUrl","mode","URLSearchParams","hash","slice","get","script","createElement","src","async","head","appendChild","AuthBoundary","props","LoginErrorComponent","fallbackProps","FallbackComponent","AuthSwitch","children","CallbackComponent","isLoggedOut","LOGGED_OUT","isDestroyingSession","loginUrl","LOGGING_IN","LOGGED_IN","DEFAULT_FALLBACK","ResourceProvider","fallback","parent","createChild","createSanityInstance","disposal","useRef","current","clearTimeout","timeoutId","setTimeout","isDisposed","dispose","SDKProvider","configs","Array","isArray","reverse","createNestedProviders","index","length","REDIRECT_URL","SanityApp","sanityConfigs","_temp2","timeout","console","warn","replace","useAuthToken","getTokenState","useCurrentUser","getCurrentUserState","useDashboardOrganizationId","getDashboardOrganizationId","useClient","getClientState","identity","useFrameConnection","onMessage","targetOrigin","name","connectTo","heartbeat","onStatus","controllerRef","channelRef","controller","getOrCreateController","channel","getOrCreateChannel","event","status","messageUnsubscribers","Object","entries","forEach","handler","unsubscribe","on","push","releaseChannel","frameWindow","removeTarget","addTarget","connect","type_0","data","post","sendMessage","unsub","useWindowConnection","nodeRef","node","getOrCreateNode","statusUnsubscribe","eventStatus","messageUnsubscribe","releaseNode","type_1","data_0","fetchOptions","fetch","useManageFavorite","documentId","documentType","projectId","paramProjectId","dataset","paramDataset","resourceId","paramResourceId","resourceType","schemaName","isFavorited","setIsFavorited","setStatus","setResourceId","SDK_NODE_NAME","SDK_CHANNEL_NAME","instanceProjectId","instanceDataset","action","setFavoriteState","eventType","id","resource","success","err","handleFavoriteAction","favorite","unfavorite","t8","isConnected","useRecordDocumentHistoryEvent","recordEvent","useStudioWorkspacesByProjectIdDataset","workspacesByProjectIdAndDataset","setWorkspacesByProjectIdAndDataset","setError","fetchWorkspaces","signal","workspaceMap","noProjectIdAndDataset","context","availableResources","key","AbortController","abort","useNavigateToStudioDocument","documentHandle","preferredStudioUrl","workspacesConnected","workspace","find","w","workspaces","path","navigateToStudioDocument","useDatasets","getDatasetsState","projectHandle","resolveDatasets","useApplyDocumentActions","applyDocumentActions","useDocument","doc","_useDocument","getDocumentState","resolveDocument","useDocumentEvent","ref","useInsertionEffect","documentEvent","stableHandler","subscribeDocumentEvents","useDocumentPermissions","actionOrActions","actions","getPermissionsState","firstValueFrom","observable","pipe","filter","result","useDocumentSyncStatus","getDocumentSyncStatus","ignoredKeys","useEditDocument","docHandle","apply","updater","nextValue","editDocument","set","nextValue_0","editActions","keys","key_0","map","key_1","unset","includes","useQuery","query","isPending","startTransition","useTransition","queryKey","getQueryKey","deferredQueryKey","setDeferredQueryKey","deferred","useMemo","parseQueryKey","aborted","getQueryState","currentSignal","resolveQuery","DEFAULT_BATCH_SIZE","DEFAULT_PERSPECTIVE","useDocuments","orderings","search","batchSize","perspective","limit","setLimit","conditions","trimmedSearch","trim","searchFilter","createGroqSearchFilter","join","filterClause","orderClause","dataQuery","countQuery","pick","__dataset","t9","count","hasMore","t10","prev","Math","min","loadMore","t11","t12","ordering","field","direction","toLowerCase","Boolean","str","usePaginatedDocuments","pageSize","pageIndex","setPageIndex","startIndex","endIndex","totalPages","ceil","currentPage","t13","firstPage","t14","_temp3","previousPage","t15","prev_0","nextPage","t16","lastPage","t17","pageNumber","goToPage","hasFirstPage","hasPreviousPage","hasNextPage","hasLastPage","t18","max","usePreview","getPreviewState","stateSource","onStoreChanged","subscription","Observable","observer","IntersectionObserver","HTMLElement","next","intersectionObserver","entry","isIntersecting","rootMargin","threshold","observe","disconnect","startWith","distinctUntilChanged","switchMap","isVisible","obs","EMPTY","currentState","resolvePreview","useProjection","projection","getProjectionState","resolveProjection","useProject","getProjectState","resolveProject","useProjects","getProjectsState","resolveProjects","useUsers","getUsersKey","deferredKey","setDeferredKey","parseUsersKey","setRef","getUsersState","resolveUsers","useCallback","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,wFAAwF;AAAA,MAAA,CAIlMA;AAAeG,WAAAA;AAAQK,MAAAA;AAAAP,IAAAD,CAAAA,MAAAA,UAAAC,SAAAE,YAEdK,KAAAL,SAAQM,MAAOT,MAAM,GAACC,OAAAD,QAAAC,OAAAE,UAAAF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AAiBX,MAAAA;AACnB,UAAMmZ,aAAa9Z,UAAU;AAAA,MAAC,GAAG4S;AAAAA,MAAUvE,QAAQ8B,IAAI9B;AAAAA,IAAAA,CAAO;AAK1D,QAAA;AAAA,IAACtD;AAAAA,IAAM2J;AAAAA,EAAAA,IAAWtT,qBAAqBC,WAAWC,UAAU,GAE5DyT,WAAWgF,YAAY,MAAM;AACjCC,kBAAcha,UAAUQ,OAAO;AAAA,EAAA,GAC9B,CAACR,UAAUQ,OAAO,CAAC;AAEf,SAAA;AAAA,IAACuK;AAAAA,IAAM2J;AAAAA,IAASrC;AAAAA,IAAW0C;AAAAA,EAAQ;AAC5C;;AC/GO,SAASkF,OAAOvL,KAA2B;AAC5C,MAAA,OAAOwL,cAAgB,OAAeA,YAAYC;AAE5CD,WAAAA,YAAYC,IAA2CzL,GAAG;AACzD,MAAA,OAAO0L,UAAY,OAAeA,QAAQD;AAE5CC,WAAAA,QAAQD,IAAIzL,GAAG;AACb,MAAA,OAAO9M,SAAW,OAAgBA,OAAyByY;AAE5DzY,WAAAA,OAAyByY,MAAM3L,GAAG;AAG9C;ACbO,MAAM4L,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/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/comlink/useWindowConnection.ts","../src/hooks/comlink/useManageFavorite.ts","../src/hooks/comlink/useRecordDocumentHistoryEvent.ts","../src/hooks/dashboard/useStudioWorkspacesByProjectIdDataset.ts","../src/hooks/dashboard/useNavigateToStudioDocument.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/preview/usePreview.tsx","../src/hooks/projection/useProjection.ts","../src/hooks/projects/useProject.ts","../src/hooks/projects/useProjects.ts","../src/hooks/releases/useActiveReleases.ts","../src/hooks/releases/usePerspective.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>.`,\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> 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 {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 (!(error instanceof AuthError || error instanceof ConfigurationError)) throw error\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 (authState.type === AuthStateType.ERROR && authState.error instanceof ClientError) {\n if (authState.error.statusCode === 401) {\n handleRetry()\n } else if (authState.error.statusCode === 404) {\n const errorMessage = authState.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 {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 <ErrorBoundary FallbackComponent={FallbackComponent}>\n <AuthSwitch {...props} />\n </ErrorBoundary>\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\n if (!isInIframe() && !isLocalUrl(window)) {\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 }, [])\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 MessageData, type Node, type Status} from '@sanity/comlink'\nimport {type FrameMessage, getOrCreateNode, releaseNode, type WindowMessage} from '@sanity/sdk'\nimport {useCallback, useEffect, useRef} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\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 onStatus?: (status: Status) => void\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\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 onStatus,\n}: UseWindowConnectionOptions<TFrameMessage>): WindowConnection<TWindowMessage> {\n const nodeRef = useRef<Node<TWindowMessage, TFrameMessage> | null>(null)\n const messageUnsubscribers = useRef<(() => void)[]>([])\n const instance = useSanityInstance()\n\n useEffect(() => {\n const node = getOrCreateNode(instance, {\n name,\n connectTo,\n }) as unknown as Node<TWindowMessage, TFrameMessage>\n nodeRef.current = node\n\n const statusUnsubscribe = node.onStatus((eventStatus) => {\n onStatus?.(eventStatus)\n })\n\n if (onMessage) {\n Object.entries(onMessage).forEach(([type, handler]) => {\n const messageUnsubscribe = node.on(type, handler as WindowMessageHandler<TFrameMessage>)\n messageUnsubscribers.current.push(messageUnsubscribe)\n })\n }\n\n return () => {\n statusUnsubscribe()\n messageUnsubscribers.current.forEach((unsubscribe) => unsubscribe())\n messageUnsubscribers.current = []\n releaseNode(instance, name)\n nodeRef.current = null\n }\n }, [instance, name, connectTo, onMessage, onStatus])\n\n const sendMessage = useCallback(\n (type: TWindowMessage['type'], data?: Extract<TWindowMessage, {type: typeof type}>['data']) => {\n if (!nodeRef.current) {\n throw new Error('Cannot send message before connection is established')\n }\n nodeRef.current.post(type, data)\n },\n [],\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 if (!nodeRef.current) {\n throw new Error('Cannot fetch before connection is established')\n }\n return nodeRef.current?.fetch(type, data, fetchOptions ?? {}) as Promise<TResponse>\n },\n [],\n )\n return {\n sendMessage,\n fetch,\n }\n}\n","import {type Status} from '@sanity/comlink'\nimport {\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, useState, useSyncExternalStore} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\nimport {useWindowConnection} from './useWindowConnection'\n\ninterface ManageFavorite extends FavoriteStatusResponse {\n favorite: () => Promise<void>\n unfavorite: () => Promise<void>\n isFavorited: boolean\n isConnected: 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 * - `isConnected` - Boolean indicating if connection to Dashboard UI is established\n *\n * @example\n * ```tsx\n * function FavoriteButton(props: DocumentActionProps) {\n * const {documentId, documentType} = props\n * const {favorite, unfavorite, isFavorited, isConnected} = useManageFavorite({\n * documentId,\n * documentType\n * })\n *\n * return (\n * <Button\n * disabled={!isConnected}\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 [status, setStatus] = useState<Status>('idle')\n const {fetch} = useWindowConnection<Events.FavoriteMessage, FrameMessage>({\n name: SDK_NODE_NAME,\n connectTo: SDK_CHANNEL_NAME,\n onStatus: setStatus,\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 (status !== 'connected' || !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 [\n fetch,\n documentId,\n documentType,\n resourceId,\n resourceType,\n schemaName,\n instance,\n context,\n status,\n ],\n )\n\n const favorite = useCallback(() => handleFavoriteAction('added'), [handleFavoriteAction])\n const unfavorite = useCallback(() => handleFavoriteAction('removed'), [handleFavoriteAction])\n\n // if state is undefined, we should suspend\n if (!state) {\n try {\n const promise = resolveFavoritesState(instance, context)\n throw promise\n } catch (err) {\n // If we get a timeout error, return a fallback state instead of suspending\n if (err instanceof Error && err.message === 'Favorites service connection timeout') {\n return {\n favorite: async () => {},\n unfavorite: async () => {},\n isFavorited: false,\n isConnected: false,\n }\n }\n // For other errors, continue with suspension\n throw err\n }\n }\n\n return {\n favorite,\n unfavorite,\n isFavorited,\n isConnected: status === 'connected',\n }\n}\n","import {type Status} from '@sanity/comlink'\nimport {\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, useState} from 'react'\n\nimport {useWindowConnection} from './useWindowConnection'\n\ninterface DocumentInteractionHistory {\n recordEvent: (eventType: 'viewed' | 'edited' | 'created' | 'deleted') => void\n isConnected: boolean\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 * - `isConnected` - Boolean indicating if connection to Studio is established\n *\n * @example\n * ```tsx\n * function MyDocumentAction(props: DocumentActionProps) {\n * const {documentId, documentType, resourceType, resourceId} = props\n * const {recordEvent, isConnected} = useRecordDocumentHistoryEvent({\n * documentId,\n * documentType,\n * resourceType,\n * resourceId,\n * })\n *\n * return (\n * <Button\n * disabled={!isConnected}\n * onClick={() => recordEvent('viewed')}\n * text={'Viewed'}\n * />\n * )\n * }\n * ```\n */\nexport function useRecordDocumentHistoryEvent({\n documentId,\n documentType,\n resourceType,\n resourceId,\n schemaName,\n}: UseRecordDocumentHistoryEventProps): DocumentInteractionHistory {\n const [status, setStatus] = useState<Status>('idle')\n const {sendMessage} = useWindowConnection<Events.HistoryMessage, FrameMessage>({\n name: SDK_NODE_NAME,\n connectTo: SDK_CHANNEL_NAME,\n onStatus: setStatus,\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 isConnected: status === 'connected',\n }\n}\n","import {type Status} from '@sanity/comlink'\nimport {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 isConnected: boolean\n}\n\n/**\n * Hook that fetches studio workspaces and organizes them by projectId:dataset\n * @internal\n */\nexport function useStudioWorkspacesByProjectIdDataset(): StudioWorkspacesResult {\n const [workspacesByProjectIdAndDataset, setWorkspacesByProjectIdAndDataset] =\n useState<WorkspacesByProjectIdDataset>({})\n const [status, setStatus] = useState<Status>('idle')\n const [error, setError] = useState<string | null>(null)\n\n const {fetch} = useWindowConnection({\n name: SDK_NODE_NAME,\n connectTo: SDK_CHANNEL_NAME,\n onStatus: setStatus,\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 || status !== 'connected') return\n\n async function fetchWorkspaces(signal: AbortSignal) {\n try {\n const data = await fetch<{\n context: {availableResources: Array<DashboardResource>}\n }>('dashboard/v1/bridge/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, status])\n\n return {\n workspacesByProjectIdAndDataset,\n error,\n isConnected: status === 'connected',\n }\n}\n","import {type Status} from '@sanity/comlink'\nimport {type Bridge, SDK_CHANNEL_NAME, SDK_NODE_NAME} from '@sanity/message-protocol'\nimport {type DocumentHandle} from '@sanity/sdk'\nimport {useCallback, useState} 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 isConnected: boolean\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 * - `isConnected` - Boolean indicating if connection to Dashboard is established\n *\n * @example\n * ```ts\n * import {useNavigateToStudioDocument, type DocumentHandle} from '@sanity/sdk-react'\n *\n * function MyComponent({documentHandle}: {documentHandle: DocumentHandle}) {\n * const {navigateToStudioDocument, isConnected} = useNavigateToStudioDocument(documentHandle)\n *\n * return (\n * <button onClick={navigateToStudioDocument} disabled={!isConnected}>\n * Navigate to Studio Document\n * </button>\n * )\n * }\n * ```\n */\nexport function useNavigateToStudioDocument(\n documentHandle: DocumentHandle,\n preferredStudioUrl?: string,\n): NavigateToStudioResult {\n const {workspacesByProjectIdAndDataset, isConnected: workspacesConnected} =\n useStudioWorkspacesByProjectIdDataset()\n const [status, setStatus] = useState<Status>('idle')\n const {sendMessage} = useWindowConnection<Bridge.Navigation.NavigateToResourceMessage, never>({\n name: SDK_NODE_NAME,\n connectTo: SDK_CHANNEL_NAME,\n onStatus: setStatus,\n })\n\n const navigateToStudioDocument = useCallback(() => {\n const {projectId, dataset} = documentHandle\n\n if (!workspacesConnected || status !== 'connected') {\n // eslint-disable-next-line no-console\n console.warn('Not connected to Dashboard')\n return\n }\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 }, [\n documentHandle,\n workspacesConnected,\n status,\n workspacesByProjectIdAndDataset,\n sendMessage,\n preferredStudioUrl,\n ])\n\n return {\n navigateToStudioDocument,\n isConnected: workspacesConnected && status === 'connected',\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 SanityDocumentResult} 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 * @beta\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<SanityDocumentResult<TDocumentType, TDataset, TProjectId>>>\n}\n\n/**\n * @beta\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 SanityDocumentResult} from 'groq'\nimport {identity} from 'rxjs'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n// used in an `{@link useProjection}` and `{@link useQuery}`\n// eslint-disable-next-line import/consistent-type-specifier-style, unused-imports/no-unused-imports\nimport type {useProjection} from '../projection/useProjection'\n// eslint-disable-next-line import/consistent-type-specifier-style, unused-imports/no-unused-imports\nimport type {useQuery} from '../query/useQuery'\n\ninterface UseDocument {\n /** @internal */\n <TDocumentType extends string, TDataset extends string, TProjectId extends string = string>(\n options: DocumentOptions<undefined, TDocumentType, TDataset, TProjectId>,\n ): SanityDocumentResult<TDocumentType, TDataset, TProjectId> | 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 ): JsonMatch<SanityDocumentResult<TDocumentType, TDataset, TProjectId>, TPath> | undefined\n\n /** @internal */\n <TData>(options: DocumentOptions<undefined>): TData | null\n /** @internal */\n <TData>(options: DocumentOptions<string>): TData | undefined\n\n /**\n * ## useDocument via Type Inference (Recommended)\n *\n * @beta\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 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 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 ? JsonMatch<SanityDocumentResult<TDocumentType, TDataset, TProjectId>, TPath> | undefined\n : SanityDocumentResult<TDocumentType, TDataset, TProjectId> | null\n\n /**\n * @beta\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 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 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 ? TData | undefined : TData | null\n\n /**\n * @internal\n */\n (options: DocumentOptions): unknown\n}\n\n/**\n * @beta\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 useProjection} or {@link useQuery} instead. These hooks are more efficient\n * for read-heavy applications.\n *\n * @function\n */\nexport const useDocument = 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}) 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 * @beta\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 * @beta\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 * @beta\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 SanityDocumentResult} 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 * @beta\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<SanityDocumentResult<TDocumentType, TDataset, TProjectId>>,\n) => Promise<ActionsResult<SanityDocumentResult<TDocumentType, TDataset, TProjectId>>>\n\n// Overload 2: Path provided, relies on Typegen\n/**\n * @beta\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<SanityDocumentResult<TDocumentType, TDataset, TProjectId>, TPath>>,\n) => Promise<ActionsResult<SanityDocumentResult<TDocumentType, TDataset, TProjectId>>>\n\n// Overload 3: Explicit type, no path\n/**\n * @beta\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 * @beta\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 * @beta\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 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 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 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 currentName = useDocument<string>({...bookHandle, path: 'author.name'});\n * // Provide the explicit type <string> for the path's value\n * const editAuthorName = useEditDocument<string>({...bookHandle, '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 * @beta\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, TDataset, TProjectId>\n /** True if a query transition is in progress */\n isPending: boolean\n}\n\n// Overload 2: Explicit Type Provided\n/**\n * @beta\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 * @beta\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 // eslint-disable-next-line react-compiler/react-compiler\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 * @beta\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 * @beta\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 * @beta\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 useProjection for efficiency)\n * function MyDocumentComponent({doc}: {doc: DocumentHandle}) {\n * const {data} = useProjection<{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 * @beta\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 * @beta\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 * @beta\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 * useProjection\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} = useProjection<{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 {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 * @beta\n * @category Types\n */\nexport interface UsePreviewOptions 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 * @beta\n * @category Types\n */\nexport interface UsePreviewResults {\n /** The results of resolving the document’s preview values */\n data: PreviewValue\n /** True when preview values are being refreshed */\n isPending: boolean\n}\n\n/**\n * @beta\n *\n * Returns the 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 * @category Documents\n * @param options - The document handle for the document you want to resolve preview values for, and an optional ref\n * @returns The preview 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 } = usePreview({ 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 usePreview({ref, ...docHandle}: UsePreviewOptions): UsePreviewResults {\n const instance = useSanityInstance()\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 UsePreviewResults\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 UseProjectionOptions<\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 UseProjectionResults<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 * @beta\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 {useProjection, 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 } = useProjection({\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 useProjection<\n TProjection extends ValidProjection = ValidProjection,\n TDocumentType extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n>(\n options: UseProjectionOptions<TProjection, TDocumentType, TDataset, TProjectId>,\n): UseProjectionResults<SanityProjectionResult<TProjection, TDocumentType, TDataset, TProjectId>>\n\n// Overload 2: Explicit type provided\n/**\n * @beta\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 {useProjection, 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 } = useProjection<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 useProjection<TData extends object>(\n options: UseProjectionOptions, // Uses base options type\n): UseProjectionResults<TData>\n\n// Implementation (no JSDoc needed here as it's covered by overloads)\nexport function useProjection<TData extends object>({\n ref,\n projection,\n ...docHandle\n}: UseProjectionOptions): UseProjectionResults<TData> {\n const instance = useSanityInstance()\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(subscribe, stateSource.getCurrent) as UseProjectionResults<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\ntype UseProjects = {\n /**\n *\n * Returns metadata for each project you have access to.\n *\n * @category Projects\n * @returns An array of metadata (minus the projects’ members) for each project\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 */\n (): ProjectWithoutMembers[]\n}\n\n/**\n * @public\n * @function\n */\nexport const useProjects: UseProjects = createStateSourceHook({\n // remove `undefined` since we're suspending when that is the case\n getState: getProjectsState as (instance: SanityInstance) => StateSource<ProjectWithoutMembers[]>,\n shouldSuspend: (instance) => getProjectsState(instance).getCurrent() === undefined,\n suspender: resolveProjects,\n})\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 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","useLoginUrl","getLoginUrlState","useVerifyOrgProjects","projectIds","disabled","error","setError","useState","length","subscription","observeOrganizationVerificationState","result","unsubscribe","useEffect","isInIframe","window","self","top","isLocalUrl","url","location","href","startsWith","AuthError","constructor","message","cause","ConfigurationError","createCallbackHook","callback","useHandleAuthCallback","handleAuthCallback","LoginCallback","URL","toString","then","_temp","replacementLocation","history","replaceState","useLogOut","logout","LoginError","resetErrorBoundary","authState","authErrorMessage","setAuthErrorMessage","handleRetry","type","AuthStateType","ERROR","ClientError","statusCode","errorMessage","response","body","endsWith","t3","t4","t5","t6","t7","t8","t9","document","querySelector","parsedUrl","mode","URLSearchParams","hash","slice","get","script","createElement","src","async","head","appendChild","AuthBoundary","props","LoginErrorComponent","fallbackProps","FallbackComponent","AuthSwitch","children","CallbackComponent","verifyOrganization","orgError","isLoggedOut","LOGGED_OUT","isDestroyingSession","loginUrl","LOGGING_IN","LOGGED_IN","DEFAULT_FALLBACK","ResourceProvider","fallback","parent","createChild","createSanityInstance","disposal","useRef","current","clearTimeout","timeoutId","setTimeout","isDisposed","dispose","SDKProvider","configs","Array","isArray","reverse","map","c","projectId","filter","id","createNestedProviders","index","REDIRECT_URL","SanityApp","Symbol","for","_temp2","timeout","console","warn","replace","useAuthToken","getTokenState","useCurrentUser","getCurrentUserState","useDashboardOrganizationId","getDashboardOrganizationId","useClient","getClientState","identity","useFrameConnection","onMessage","targetOrigin","name","connectTo","heartbeat","onStatus","controllerRef","channelRef","controller","getOrCreateController","channel","getOrCreateChannel","event","status","messageUnsubscribers","Object","entries","forEach","handler","on","push","releaseChannel","frameWindow","removeTarget","addTarget","connect","type_0","data","post","sendMessage","unsub","useWindowConnection","nodeRef","node","getOrCreateNode","statusUnsubscribe","eventStatus","messageUnsubscribe","releaseNode","type_1","data_0","fetchOptions","fetch","useManageFavorite","documentId","documentType","paramProjectId","dataset","paramDataset","resourceId","paramResourceId","resourceType","schemaName","setStatus","SDK_NODE_NAME","SDK_CHANNEL_NAME","instanceProjectId","instanceDataset","context","useMemo","favoriteState","getFavoritesState","isFavorited","handleFavoriteAction","useCallback","action","payload","eventType","resource","success","resolveFavoritesState","err","favorite","unfavorite","isConnected","useRecordDocumentHistoryEvent","recordEvent","useStudioWorkspacesByProjectIdDataset","workspacesByProjectIdAndDataset","setWorkspacesByProjectIdAndDataset","fetchWorkspaces","signal","workspaceMap","noProjectIdAndDataset","availableResources","key","AbortController","abort","useNavigateToStudioDocument","documentHandle","preferredStudioUrl","workspacesConnected","workspace","find","w","workspaces","path","navigateToStudioDocument","useDatasets","getDatasetsState","projectHandle","resolveDatasets","useApplyDocumentActions","applyDocumentActions","useDocument","getDocumentState","_path","resolveDocument","useDocumentEvent","datasetHandle","onEvent","ref","useInsertionEffect","documentEvent","stableHandler","subscribeDocumentEvents","useDocumentPermissions","actionOrActions","actions","getPermissionsState","firstValueFrom","observable","pipe","useDocumentSyncStatus","getDocumentSyncStatus","doc","ignoredKeys","useEditDocument","apply","updater","currentPath","currentValue","nextValue","editDocument","set","nextValue_0","editActions","keys","key_0","key_1","unset","includes","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","Boolean","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","usePreview","docHandle","getPreviewState","stateSource","onStoreChanged","Observable","observer","IntersectionObserver","HTMLElement","next","intersectionObserver","entry","isIntersecting","rootMargin","threshold","observe","disconnect","startWith","distinctUntilChanged","switchMap","isVisible","obs","EMPTY","currentState","resolvePreview","useProjection","projection","getProjectionState","resolveProjection","useProject","getProjectState","resolveProject","useProjects","getProjectsState","resolveProjects","useActiveReleases","getActiveReleasesState","usePerspective","getPerspectiveState","_options","useUsers","getUsersKey","deferredKey","setDeferredKey","parseUsersKey","setRef","getUsersState","resolveUsers","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,wFAAwF;AAAA,MAAA,CA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