@mastra/react 1.15.0-alpha.9 → 1.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{experiments-B2PEqGwi.js → experiments-BUTZk3Fu.js} +2 -2
- package/dist/{experiments-B2PEqGwi.js.map → experiments-BUTZk3Fu.js.map} +1 -1
- package/dist/{experiments-beUCWMr-.cjs → experiments-CDqRm-1r.cjs} +2 -2
- package/dist/{experiments-beUCWMr-.cjs.map → experiments-CDqRm-1r.cjs.map} +1 -1
- package/dist/hooks/auth/index.cjs +2 -0
- package/dist/hooks/auth/index.cjs.map +1 -1
- package/dist/hooks/auth/index.js +3 -1
- package/dist/hooks/auth/index.js.map +1 -1
- package/dist/hooks/auth/use-auth-capabilities.d.ts.map +1 -1
- package/dist/hooks/auth/use-permission-patterns.d.ts.map +1 -1
- package/dist/hooks/datasets/index.cjs +1 -1
- package/dist/hooks/datasets/index.js +1 -1
- package/dist/hooks/experiments/index.cjs +1 -1
- package/dist/hooks/experiments/index.js +1 -1
- package/dist/hooks/logs/index.cjs +1 -1
- package/dist/hooks/logs/index.js +1 -1
- package/dist/hooks/review/index.cjs +115 -1
- package/dist/hooks/review/index.cjs.map +1 -1
- package/dist/hooks/review/index.js +115 -3
- package/dist/hooks/review/index.js.map +1 -1
- package/dist/hooks/review/use-dataset-review-items.d.ts +26 -2
- package/dist/hooks/review/use-dataset-review-items.d.ts.map +1 -1
- package/dist/hooks/schedules/index.cjs +1 -1
- package/dist/hooks/schedules/index.js +1 -1
- package/dist/hooks/scores/index.cjs +1 -1
- package/dist/hooks/scores/index.js +1 -1
- package/dist/hooks/shared/use-in-view.d.ts.map +1 -1
- package/dist/hooks/traces/index.cjs +1 -1
- package/dist/hooks/traces/index.js +1 -1
- package/dist/hooks/workflows/index.cjs +1 -1
- package/dist/hooks/workflows/index.js +1 -1
- package/dist/{use-in-view-CyjKdplM.js → use-in-view-ChEDWwE1.js} +5 -2
- package/dist/{use-in-view-CyjKdplM.js.map → use-in-view-ChEDWwE1.js.map} +1 -1
- package/dist/{use-in-view-BxdrrnCw.cjs → use-in-view-u7xWhAjL.cjs} +5 -2
- package/dist/{use-in-view-BxdrrnCw.cjs.map → use-in-view-u7xWhAjL.cjs.map} +1 -1
- package/package.json +5 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../src/hooks/auth/types.ts","../../../src/hooks/auth/fetch-with-refresh.ts","../../../src/hooks/auth/get-client-query-key.ts","../../../src/hooks/auth/sso-login.ts","../../../src/hooks/auth/use-auth-capabilities.ts","../../../src/hooks/auth/use-current-user.ts","../../../src/hooks/auth/use-permission-patterns.ts","../../../src/hooks/auth/use-credentials-login.ts","../../../src/hooks/auth/use-credentials-signup.ts","../../../src/hooks/auth/use-auth-actions.ts"],"sourcesContent":["/**\n * Auth types for EE authentication in playground-ui.\n *\n * These types mirror the server schemas from @mastra/server.\n */\n\n/**\n * SSO configuration for login\n */\nexport type SSOConfig = {\n provider: string;\n text: string;\n icon?: string;\n description?: string;\n url: string;\n};\n\n/**\n * Login configuration\n */\nexport type LoginConfig = {\n type: 'sso' | 'credentials' | 'both';\n /** Whether sign-up is enabled (defaults to true) */\n signUpEnabled?: boolean;\n /** Optional description explaining the auth requirement and what credentials to use */\n description?: string;\n sso?: SSOConfig;\n} | null;\n\n/**\n * Public capabilities (unauthenticated)\n */\nexport type PublicAuthCapabilities = {\n enabled: boolean;\n login: LoginConfig;\n};\n\n/**\n * Authenticated user information\n */\nexport type AuthenticatedUser = {\n id: string;\n email?: string;\n name?: string;\n avatarUrl?: string;\n};\n\n/**\n * Capability flags\n */\nexport type CapabilityFlags = {\n user: boolean;\n session: boolean;\n sso: boolean;\n rbac: boolean;\n acl: boolean;\n};\n\n/**\n * User access information\n */\nexport type UserAccess = {\n roles: string[];\n permissions: string[];\n} | null;\n\n/**\n * Authenticated capabilities (extends public)\n */\nexport type AuthenticatedCapabilities = PublicAuthCapabilities & {\n user: AuthenticatedUser;\n capabilities: CapabilityFlags;\n access: UserAccess;\n /** Available roles in the system (only present for admin users) */\n availableRoles?: { id: string; name: string }[];\n};\n\n/**\n * Auth capabilities response (union of public and authenticated)\n */\nexport type AuthCapabilities = PublicAuthCapabilities | AuthenticatedCapabilities;\n\n/**\n * Current user response (may be null if not authenticated)\n */\nexport type CurrentUser = {\n id: string;\n email?: string;\n name?: string;\n avatarUrl?: string;\n roles?: string[];\n permissions?: string[];\n} | null;\n\n/**\n * SSO callback response\n */\nexport type SSOCallbackResponse = {\n success: boolean;\n user?: AuthenticatedUser;\n redirectTo?: string;\n};\n\n/**\n * Logout response\n */\nexport type LogoutResponse = {\n success: boolean;\n redirectTo?: string;\n};\n\n/**\n * Type guard to check if capabilities include authenticated user\n */\nexport function isAuthenticated(capabilities: AuthCapabilities): capabilities is AuthenticatedCapabilities {\n return 'user' in capabilities && capabilities.user !== undefined;\n}\n","/**\n * Fetch wrapper for the Mastra server API.\n *\n * ⚠️ MIRRORS: `platform/frontend/src/shared/lib/fetch-with-refresh.ts`\n *\n * Both files must stay behaviourally in lockstep — the platform dashboard and\n * the embedded playground both talk to WorkOS-backed auth and both would be\n * vulnerable to the same 429 lockout loop if either regressed. If you change\n * one, change the other in the same PR (or extract to a shared package —\n * currently blocked by the platform/mastra-ai monorepo boundary).\n *\n * ---\n *\n * The server middleware already refreshes the WorkOS session transparently\n * on every protected request. There is no scenario where the client can\n * succeed by calling /auth/refresh after a 401 — that endpoint hits the\n * same broken WorkOS with the same session and would only amplify transient\n * failures into forced logout (PLTFRM-1270).\n *\n * These are pass-throughs today. The names and signatures are preserved for\n * compatibility with existing call sites (`App.tsx`, `use-current-user.ts`).\n * Transient-failure retry belongs one level up — in React Query's `retry`\n * config on individual queries — not in a fetch wrapper that would compound\n * with the query-level retry.\n */\n\nexport async function fetchWithRefresh(\n _baseUrl: string,\n input: RequestInfo | URL,\n init?: RequestInit,\n): Promise<Response> {\n return fetch(input, init);\n}\n\nexport function createFetchWithRefresh(_baseUrl?: string, _apiPrefix?: string): typeof fetch {\n return (input, init) => fetch(input, init);\n}\n","import type { MastraClient } from '@mastra/client-js';\n\nconst clientQueryKeys = new WeakMap<MastraClient, number>();\nlet nextClientQueryKey = 0;\n\n/**\n * Returns a stable, non-sensitive query key for a Mastra client instance.\n * A new client is created whenever its connection options change.\n */\nexport function getClientQueryKey(client: MastraClient) {\n const existingKey = clientQueryKeys.get(client);\n if (existingKey !== undefined) return existingKey;\n\n const queryKey = nextClientQueryKey++;\n clientQueryKeys.set(client, queryKey);\n return queryKey;\n}\n","import type { MastraClient } from '@mastra/client-js';\n\nexport type SSOLoginResponse = {\n url: string;\n};\n\nexport async function makeSSOLoginRequest(\n client: Pick<MastraClient, 'options'>,\n { redirectUri }: { redirectUri?: string },\n): Promise<SSOLoginResponse> {\n const { baseUrl = '', apiPrefix, headers: clientHeaders = {} } = client.options;\n const raw = (apiPrefix || '/api').trim();\n const prefix = (raw.startsWith('/') ? raw : `/${raw}`).replace(/\\/$/, '');\n\n const params = new URLSearchParams();\n if (redirectUri) {\n params.set('redirect_uri', redirectUri);\n }\n\n const url = `${baseUrl}${prefix}/auth/sso/login${params.toString() ? `?${params}` : ''}`;\n\n const response = await fetch(url, {\n credentials: 'include',\n headers: {\n ...clientHeaders,\n 'Content-Type': 'application/json',\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to initiate SSO login: ${response.status}`);\n }\n\n return response.json();\n}\n","import type { MastraClient } from '@mastra/client-js';\nimport type { UseQueryResult } from '@tanstack/react-query';\nimport { useQuery } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\nimport { getClientQueryKey } from './get-client-query-key';\nimport type { AuthCapabilities } from './types';\n\n/**\n * Makes a request to the auth capabilities endpoint.\n * Exported for testing purposes.\n *\n * @internal\n */\nexport async function makeAuthCapabilitiesRequest(client: MastraClient): Promise<AuthCapabilities> {\n const { baseUrl = '', headers: clientHeaders = {}, apiPrefix } = client.options;\n const raw = (apiPrefix || '/api').trim();\n const prefix = (raw.startsWith('/') ? raw : `/${raw}`).replace(/\\/$/, '');\n\n const response = await fetch(`${baseUrl}${prefix}/auth/capabilities`, {\n credentials: 'include',\n headers: {\n ...clientHeaders,\n 'Content-Type': 'application/json',\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch auth capabilities: ${response.status}`);\n }\n\n return response.json();\n}\n\n/**\n * Hook to fetch authentication capabilities.\n *\n * Returns server-authoritative capability detection including:\n * - Whether auth is enabled\n * - Login configuration (SSO, credentials, or both)\n * - Current user (if authenticated)\n * - Available capabilities (user awareness, session, SSO, RBAC, ACL, audit)\n * - User access (roles and permissions)\n *\n * @example\n * ```tsx\n * import { useAuthCapabilities } from '@mastra/react/hooks/auth';\n *\n * function AuthStatus() {\n * const { data: capabilities, isLoading } = useAuthCapabilities();\n *\n * if (isLoading) return <div>Loading...</div>;\n * if (!capabilities?.enabled) return <div>Auth not enabled</div>;\n *\n * if (isAuthenticated(capabilities)) {\n * return <div>Welcome, {capabilities.user.name}</div>;\n * }\n *\n * return <LoginButton config={capabilities.login} />;\n * }\n * ```\n */\nexport function useAuthCapabilities<TData = AuthCapabilities>({\n queryOptions,\n}: { queryOptions?: MastraQueryOptions<AuthCapabilities, TData> } = {}): UseQueryResult<TData, Error> {\n const client = useMastraClient();\n\n return useQuery<AuthCapabilities, Error, TData>({\n queryKey: ['auth', 'capabilities', getClientQueryKey(client)],\n queryFn: () => makeAuthCapabilitiesRequest(client),\n staleTime: 60 * 1000, // Cache for 1 minute\n retry: false, // Don't retry auth requests\n ...queryOptions,\n });\n}\n","import type { UseQueryResult } from '@tanstack/react-query';\nimport { useQuery } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\nimport { fetchWithRefresh } from './fetch-with-refresh';\nimport type { CurrentUser } from './types';\n\nconst AUTH_TRANSIENT_MAX_RETRIES = 3;\nconst AUTH_TRANSIENT_MAX_BACKOFF_MS = 8_000;\n\nexport class CurrentUserError extends Error {\n constructor(public readonly status: number) {\n super(`Failed to fetch current user: ${status}`);\n this.name = 'CurrentUserError';\n }\n}\n\nexport function isUnauthenticatedError(error: unknown): boolean {\n return error instanceof CurrentUserError && error.status === 401;\n}\n\n/**\n * Hook to fetch the current authenticated user.\n *\n * Returns the current user if authenticated, null otherwise.\n * Includes roles and permissions if RBAC is available.\n *\n * Uses fetchWithRefresh to automatically refresh the session on 401 errors,\n * preventing users from being logged out when the access token expires.\n *\n * @example\n * ```tsx\n * import { useCurrentUser } from '@mastra/react/hooks/auth';\n *\n * function UserMenu() {\n * const { data: user, isLoading } = useCurrentUser();\n *\n * if (isLoading) return <Skeleton />;\n * if (!user) return <LoginButton />;\n *\n * return (\n * <Menu>\n * <Avatar src={user.avatarUrl} />\n * <span>{user.name || user.email}</span>\n * </Menu>\n * );\n * }\n * ```\n */\nexport function useCurrentUser<TData = CurrentUser>({\n queryOptions,\n}: { queryOptions?: MastraQueryOptions<CurrentUser, TData> } = {}): UseQueryResult<TData, Error> {\n const client = useMastraClient();\n const baseUrl = client.options?.baseUrl || '';\n\n return useQuery<CurrentUser, Error, TData>({\n queryKey: ['auth', 'me'],\n queryFn: async () => {\n const response = await fetchWithRefresh(baseUrl, `${baseUrl}/api/auth/me`, {\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n\n if (!response.ok) {\n throw new CurrentUserError(response.status);\n }\n\n return response.json();\n },\n staleTime: 60 * 1000, // Cache for 1 minute\n // Retry the /api/auth/me query on transient auth-provider failures (HTTP 503)\n // so the UI stays in `isLoading` instead of flipping to `isError` and\n // triggering login — that redirect is what fed the WorkOS 429 lockout loop\n // (PLTFRM-1270). 401 (terminal) still fails fast.\n retry: (failureCount, error) => {\n if (!(error instanceof CurrentUserError)) return false;\n if (error.status !== 503) return false;\n return failureCount < AUTH_TRANSIENT_MAX_RETRIES;\n },\n retryDelay: attemptIndex => Math.min(AUTH_TRANSIENT_MAX_BACKOFF_MS, 500 * 2 ** attemptIndex),\n ...queryOptions,\n });\n}\n","import type { MastraClient, PermissionPattern } from '@mastra/client-js';\nimport { useQuery } from '@tanstack/react-query';\nimport { useMemo } from 'react';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\nimport { getClientQueryKey } from './get-client-query-key';\nimport { isAuthenticated } from './types';\nimport { useAuthCapabilities } from './use-auth-capabilities';\n\n/**\n * Fetches the authoritative set of permission patterns from the server\n * (`GET /auth/permission-patterns`).\n *\n * The server owns the permission source of truth (generated from the route\n * registry), so the browser never imports the server-only `@mastra/core/auth/ee`\n * code just to validate hardcoded route-permission literals.\n *\n * The request only fires when RBAC is actually enabled — when auth is off or\n * RBAC isn't configured, route gating is a no-op so the pattern vocabulary is\n * not needed, and we avoid an unnecessary (and potentially 403/401) call.\n */\ntype PermissionPatternsResponse = Awaited<ReturnType<MastraClient['getPermissionPatterns']>>;\n\nexport const usePermissionPatterns = ({\n queryOptions,\n}: { queryOptions?: MastraQueryOptions<PermissionPatternsResponse> } = {}) => {\n const client = useMastraClient();\n const { data: capabilities, isLoading: capabilitiesLoading, error: capabilitiesError } = useAuthCapabilities();\n\n const rbacEnabled = !!(capabilities && isAuthenticated(capabilities) && capabilities.capabilities.rbac);\n\n const { data, isLoading, error } = useQuery({\n queryKey: ['permission-patterns', getClientQueryKey(client)],\n queryFn: () => client.getPermissionPatterns(),\n // Only fetch the pattern vocabulary when RBAC gating is in effect.\n enabled: rbacEnabled,\n // The endpoint requires auth; on 403/401 we don't want React Query to\n // thrash with retries (which toggles isLoading and re-triggers redirect\n // guards). One attempt is enough — gating falls back to the user's\n // permissions if the pattern set is empty.\n retry: false,\n staleTime: Infinity,\n ...queryOptions,\n });\n\n const patterns = useMemo(() => new Set<PermissionPattern>(data?.patterns ?? []), [data]);\n\n // While capabilities are resolving we don't yet know whether RBAC applies, so\n // report loading. Once RBAC is ruled out, this hook is never \"loading\".\n return { patterns, isLoading: capabilitiesLoading || (rbacEnabled && isLoading), error: capabilitiesError || error };\n};\n","import type { MastraClient } from '@mastra/client-js';\nimport { useMutation, useQueryClient } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraMutationOptions } from '../shared/query-options';\n\nexport type CredentialsLoginRequest = {\n email: string;\n password: string;\n};\n\nexport type CredentialsLoginResponse = {\n user?: {\n id: string;\n email: string;\n name?: string;\n };\n error?: string;\n};\n\n/**\n * Hook to login with email/password credentials.\n *\n * Uses Better Auth's email sign-in endpoint.\n *\n * @example\n * ```tsx\n * import { useCredentialsLogin } from '@mastra/react/hooks/auth';\n *\n * function LoginForm() {\n * const { mutate: login, isPending, error } = useCredentialsLogin();\n *\n * const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {\n * e.preventDefault();\n * const formData = new FormData(e.currentTarget);\n * login({\n * email: formData.get('email') as string,\n * password: formData.get('password') as string,\n * }, {\n * onSuccess: () => {\n * window.location.href = '/';\n * },\n * });\n * };\n *\n * return (\n * <form onSubmit={handleSubmit}>\n * <input name=\"email\" type=\"email\" required />\n * <input name=\"password\" type=\"password\" required />\n * <button type=\"submit\" disabled={isPending}>\n * Sign in\n * </button>\n * {error && <p>{error.message}</p>}\n * </form>\n * );\n * }\n * ```\n */\n/**\n * Makes a credentials sign-in request.\n * Exported for testing purposes.\n *\n * @internal\n */\nexport async function makeCredentialsLoginRequest(\n client: MastraClient,\n { email, password }: CredentialsLoginRequest,\n): Promise<CredentialsLoginResponse> {\n const { baseUrl = '', apiPrefix, headers: clientHeaders = {} } = client.options || {};\n const raw = (apiPrefix ?? '/api').trim();\n const normalized = raw === '' ? '' : raw.startsWith('/') ? raw : `/${raw}`;\n const prefix = normalized.replace(/\\/+$/, '');\n\n // Generic Mastra auth endpoint - works with any credentials provider\n const response = await fetch(`${baseUrl}${prefix}/auth/credentials/sign-in`, {\n method: 'POST',\n credentials: 'include',\n headers: {\n ...clientHeaders,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ email, password }),\n });\n\n const data = await response.json();\n\n if (!response.ok) {\n throw new Error(data.message || data.error || 'Invalid email or password');\n }\n\n return data;\n}\n\nexport function useCredentialsLogin({\n queryOptions,\n}: { queryOptions?: MastraMutationOptions<CredentialsLoginResponse, CredentialsLoginRequest> } = {}) {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n return useMutation<CredentialsLoginResponse, Error, CredentialsLoginRequest>({\n mutationFn: ({ email, password }) => makeCredentialsLoginRequest(client, { email, password }),\n onSuccess: () => {\n // Invalidate auth queries to refetch user state\n void queryClient.invalidateQueries({ queryKey: ['auth'] });\n },\n ...queryOptions,\n });\n}\n","import type { MastraClient } from '@mastra/client-js';\nimport { useMutation, useQueryClient } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraMutationOptions } from '../shared/query-options';\n\nexport type CredentialsSignUpRequest = {\n email: string;\n password: string;\n name?: string;\n};\n\nexport type CredentialsSignUpResponse = {\n user?: {\n id: string;\n email: string;\n name?: string;\n };\n error?: string;\n};\n\n/**\n * Hook to sign up with email/password credentials.\n *\n * Uses Better Auth's email sign-up endpoint.\n *\n * @example\n * ```tsx\n * import { useCredentialsSignUp } from '@mastra/react/hooks/auth';\n *\n * function SignUpForm() {\n * const { mutate: signUp, isPending, error } = useCredentialsSignUp();\n *\n * const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {\n * e.preventDefault();\n * const formData = new FormData(e.currentTarget);\n * signUp({\n * email: formData.get('email') as string,\n * password: formData.get('password') as string,\n * name: formData.get('name') as string,\n * }, {\n * onSuccess: () => {\n * window.location.href = '/';\n * },\n * });\n * };\n *\n * return (\n * <form onSubmit={handleSubmit}>\n * <input name=\"name\" type=\"text\" />\n * <input name=\"email\" type=\"email\" required />\n * <input name=\"password\" type=\"password\" required />\n * <button type=\"submit\" disabled={isPending}>\n * Sign up\n * </button>\n * {error && <p>{error.message}</p>}\n * </form>\n * );\n * }\n * ```\n */\n/**\n * Makes a credentials sign-up request.\n * Exported for testing purposes.\n *\n * @internal\n */\nexport async function makeCredentialsSignUpRequest(\n client: MastraClient,\n { email, password, name }: CredentialsSignUpRequest,\n): Promise<CredentialsSignUpResponse> {\n const { baseUrl = '', apiPrefix, headers: clientHeaders = {} } = client.options || {};\n const raw = (apiPrefix ?? '/api').trim();\n const normalized = raw === '' ? '' : raw.startsWith('/') ? raw : `/${raw}`;\n const prefix = normalized.replace(/\\/+$/, '');\n\n // Generic Mastra auth endpoint - works with any credentials provider\n const response = await fetch(`${baseUrl}${prefix}/auth/credentials/sign-up`, {\n method: 'POST',\n credentials: 'include',\n headers: {\n ...clientHeaders,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ email, password, name }),\n });\n\n const data = await response.json();\n\n if (!response.ok) {\n throw new Error(data.message || data.error || 'Failed to create account');\n }\n\n return data;\n}\n\nexport function useCredentialsSignUp({\n queryOptions,\n}: { queryOptions?: MastraMutationOptions<CredentialsSignUpResponse, CredentialsSignUpRequest> } = {}) {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n return useMutation<CredentialsSignUpResponse, Error, CredentialsSignUpRequest>({\n mutationFn: ({ email, password, name }) => makeCredentialsSignUpRequest(client, { email, password, name }),\n onSuccess: () => {\n // Invalidate auth queries to refetch user state\n void queryClient.invalidateQueries({ queryKey: ['auth'] });\n },\n ...queryOptions,\n });\n}\n","import type { MastraClient } from '@mastra/client-js';\nimport { useMutation, useQueryClient } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraMutationOptions } from '../shared/query-options';\n\nimport { makeSSOLoginRequest } from './sso-login';\nimport type { LogoutResponse } from './types';\n\n/**\n * Hook to initiate SSO login.\n *\n * Returns mutation to get the SSO login URL and redirect.\n *\n * @example\n * ```tsx\n * import { useSSOLogin } from '@mastra/react/hooks/auth';\n *\n * function SSOLoginButton() {\n * const { mutate: login, isPending } = useSSOLogin();\n *\n * const handleClick = () => {\n * login({ redirectUri: window.location.href }, {\n * onSuccess: (data) => {\n * window.location.href = data.url;\n * },\n * });\n * };\n *\n * return (\n * <button onClick={handleClick} disabled={isPending}>\n * Sign in with SSO\n * </button>\n * );\n * }\n * ```\n */\ntype SSOLoginResponse = Awaited<ReturnType<typeof makeSSOLoginRequest>>;\n\nexport function useSSOLogin({\n queryOptions,\n}: { queryOptions?: MastraMutationOptions<SSOLoginResponse, { redirectUri?: string }> } = {}) {\n const client = useMastraClient();\n\n return useMutation({\n mutationFn: ({ redirectUri }: { redirectUri?: string }) => makeSSOLoginRequest(client, { redirectUri }),\n ...queryOptions,\n });\n}\n\n/**\n * Hook to logout the current user.\n *\n * Destroys the current session and optionally redirects to\n * the SSO logout URL if available.\n *\n * @example\n * ```tsx\n * import { useLogout } from '@mastra/react/hooks/auth';\n *\n * function LogoutButton({ userId }: { userId: string }) {\n * const { mutate: logout, isPending } = useLogout();\n * const queryClient = useQueryClient();\n *\n * const handleLogout = () => {\n * logout({ userId }, {\n * onSuccess: (data) => {\n * queryClient.invalidateQueries({ queryKey: ['auth'] });\n * if (data.redirectTo) {\n * window.location.href = data.redirectTo;\n * } else {\n * window.location.reload();\n * }\n * },\n * });\n * };\n *\n * return (\n * <button onClick={handleLogout} disabled={isPending}>\n * Sign out\n * </button>\n * );\n * }\n * ```\n */\n/**\n * Makes a logout request.\n * Exported for testing purposes.\n *\n * @internal\n */\nexport async function makeLogoutRequest(client: Pick<MastraClient, 'options'>): Promise<LogoutResponse> {\n const { baseUrl = '', apiPrefix, headers: clientHeaders = {} } = client.options;\n const raw = (apiPrefix || '/api').trim();\n const prefix = (raw.startsWith('/') ? raw : `/${raw}`).replace(/\\/$/, '');\n\n const response = await fetch(`${baseUrl}${prefix}/auth/logout`, {\n method: 'POST',\n credentials: 'include',\n headers: {\n ...clientHeaders,\n 'Content-Type': 'application/json',\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to logout: ${response.status}`);\n }\n\n return response.json();\n}\n\nexport interface UseLogoutOptions {\n /**\n * Runs once the server has ended the session, before the mutation resolves.\n * Failures are ignored so cleanup never turns a completed sign-out into an error.\n */\n onLoggedOut?: (variables: { userId: string }) => Promise<void>;\n queryOptions?: MastraMutationOptions<LogoutResponse, { userId: string }>;\n}\n\nexport function useLogout({ onLoggedOut, queryOptions }: UseLogoutOptions = {}) {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n return useMutation<LogoutResponse, Error, { userId: string }>({\n mutationFn: async variables => {\n const response = await makeLogoutRequest(client);\n await onLoggedOut?.(variables).catch(() => {});\n return response;\n },\n onSuccess: () => {\n // Invalidate all auth-related queries\n void queryClient.invalidateQueries({ queryKey: ['auth'] });\n },\n ...queryOptions,\n });\n}\n"],"mappings":";;;;;;;AAkHA,SAAgB,gBAAgB,cAA2E;CACzG,OAAO,UAAU,gBAAgB,aAAa,SAAS,KAAA;AACzD;;;;;;;;;;;;;;;;;;;;;;;;;;;AC1FA,eAAsB,iBACpB,UACA,OACA,MACmB;CACnB,OAAO,MAAM,OAAO,IAAI;AAC1B;AAEA,SAAgB,uBAAuB,UAAmB,YAAmC;CAC3F,QAAQ,OAAO,SAAS,MAAM,OAAO,IAAI;AAC3C;;AClCA,MAAM,kCAAkB,IAAI,QAA8B;AAC1D,IAAI,qBAAqB;;;;;AAMzB,SAAgB,kBAAkB,QAAsB;CACtD,MAAM,cAAc,gBAAgB,IAAI,MAAM;CAC9C,IAAI,gBAAgB,KAAA,GAAW,OAAO;CAEtC,MAAM,WAAW;CACjB,gBAAgB,IAAI,QAAQ,QAAQ;CACpC,OAAO;AACT;;ACVA,eAAsB,oBACpB,QACA,EAAE,eACyB;CAC3B,MAAM,EAAE,UAAU,IAAI,WAAW,SAAS,gBAAgB,CAAC,MAAM,OAAO;CACxE,MAAM,OAAO,aAAa,OAAA,CAAQ,KAAK;CACvC,MAAM,UAAU,IAAI,WAAW,GAAG,IAAI,MAAM,IAAI,MAAA,CAAO,QAAQ,OAAO,EAAE;CAExE,MAAM,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AAQ;EACR,aAAa;EACb,SAAS;GACP,GAAG;GACH,gBAAgB;EAClB;CACF,CAAC;CAED,IAAI,CAAC,SAAS,IACZ,MAAM,IAAI,MAAM,qBAAqB,SAAS,QAAQ;CAGxD,OAAO,SAAS,KAAK;AACvB;AAWA,SAAgB,UAAU,EAAE,aAAa,iBAAmC,CAAC,GAAG;CAC9E,MAAM,SAAS,gBAAgB;CAC/B,MAAM,cAAc,eAAe;CAEnC,OAAO,YAAuD;EAC5D,YAAY,OAAM,cAAa;GAC7B,MAAM,WAAW,MAAM,kBAAkB,MAAM;GAC/C,MAAM,cAAc,SAAS,CAAC,CAAC,YAAY,CAAC,CAAC;GAC7C,OAAO;EACT;EACA,iBAAiB;GAEf,YAAiB,kBAAkB,EAAE,UAAU,CAAC,MAAM,EAAE,CAAC;EAC3D;EACA,GAAG;CACL,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../src/hooks/auth/types.ts","../../../src/hooks/auth/fetch-with-refresh.ts","../../../src/hooks/auth/get-client-query-key.ts","../../../src/hooks/auth/sso-login.ts","../../../src/hooks/auth/use-auth-capabilities.ts","../../../src/hooks/auth/use-current-user.ts","../../../src/hooks/auth/use-permission-patterns.ts","../../../src/hooks/auth/use-credentials-login.ts","../../../src/hooks/auth/use-credentials-signup.ts","../../../src/hooks/auth/use-auth-actions.ts"],"sourcesContent":["/**\n * Auth types for EE authentication in playground-ui.\n *\n * These types mirror the server schemas from @mastra/server.\n */\n\n/**\n * SSO configuration for login\n */\nexport type SSOConfig = {\n provider: string;\n text: string;\n icon?: string;\n description?: string;\n url: string;\n};\n\n/**\n * Login configuration\n */\nexport type LoginConfig = {\n type: 'sso' | 'credentials' | 'both';\n /** Whether sign-up is enabled (defaults to true) */\n signUpEnabled?: boolean;\n /** Optional description explaining the auth requirement and what credentials to use */\n description?: string;\n sso?: SSOConfig;\n} | null;\n\n/**\n * Public capabilities (unauthenticated)\n */\nexport type PublicAuthCapabilities = {\n enabled: boolean;\n login: LoginConfig;\n};\n\n/**\n * Authenticated user information\n */\nexport type AuthenticatedUser = {\n id: string;\n email?: string;\n name?: string;\n avatarUrl?: string;\n};\n\n/**\n * Capability flags\n */\nexport type CapabilityFlags = {\n user: boolean;\n session: boolean;\n sso: boolean;\n rbac: boolean;\n acl: boolean;\n};\n\n/**\n * User access information\n */\nexport type UserAccess = {\n roles: string[];\n permissions: string[];\n} | null;\n\n/**\n * Authenticated capabilities (extends public)\n */\nexport type AuthenticatedCapabilities = PublicAuthCapabilities & {\n user: AuthenticatedUser;\n capabilities: CapabilityFlags;\n access: UserAccess;\n /** Available roles in the system (only present for admin users) */\n availableRoles?: { id: string; name: string }[];\n};\n\n/**\n * Auth capabilities response (union of public and authenticated)\n */\nexport type AuthCapabilities = PublicAuthCapabilities | AuthenticatedCapabilities;\n\n/**\n * Current user response (may be null if not authenticated)\n */\nexport type CurrentUser = {\n id: string;\n email?: string;\n name?: string;\n avatarUrl?: string;\n roles?: string[];\n permissions?: string[];\n} | null;\n\n/**\n * SSO callback response\n */\nexport type SSOCallbackResponse = {\n success: boolean;\n user?: AuthenticatedUser;\n redirectTo?: string;\n};\n\n/**\n * Logout response\n */\nexport type LogoutResponse = {\n success: boolean;\n redirectTo?: string;\n};\n\n/**\n * Type guard to check if capabilities include authenticated user\n */\nexport function isAuthenticated(capabilities: AuthCapabilities): capabilities is AuthenticatedCapabilities {\n return 'user' in capabilities && capabilities.user !== undefined;\n}\n","/**\n * Fetch wrapper for the Mastra server API.\n *\n * ⚠️ MIRRORS: `platform/frontend/src/shared/lib/fetch-with-refresh.ts`\n *\n * Both files must stay behaviourally in lockstep — the platform dashboard and\n * the embedded playground both talk to WorkOS-backed auth and both would be\n * vulnerable to the same 429 lockout loop if either regressed. If you change\n * one, change the other in the same PR (or extract to a shared package —\n * currently blocked by the platform/mastra-ai monorepo boundary).\n *\n * ---\n *\n * The server middleware already refreshes the WorkOS session transparently\n * on every protected request. There is no scenario where the client can\n * succeed by calling /auth/refresh after a 401 — that endpoint hits the\n * same broken WorkOS with the same session and would only amplify transient\n * failures into forced logout (PLTFRM-1270).\n *\n * These are pass-throughs today. The names and signatures are preserved for\n * compatibility with existing call sites (`App.tsx`, `use-current-user.ts`).\n * Transient-failure retry belongs one level up — in React Query's `retry`\n * config on individual queries — not in a fetch wrapper that would compound\n * with the query-level retry.\n */\n\nexport async function fetchWithRefresh(\n _baseUrl: string,\n input: RequestInfo | URL,\n init?: RequestInit,\n): Promise<Response> {\n return fetch(input, init);\n}\n\nexport function createFetchWithRefresh(_baseUrl?: string, _apiPrefix?: string): typeof fetch {\n return (input, init) => fetch(input, init);\n}\n","import type { MastraClient } from '@mastra/client-js';\n\nconst clientQueryKeys = new WeakMap<MastraClient, number>();\nlet nextClientQueryKey = 0;\n\n/**\n * Returns a stable, non-sensitive query key for a Mastra client instance.\n * A new client is created whenever its connection options change.\n */\nexport function getClientQueryKey(client: MastraClient) {\n const existingKey = clientQueryKeys.get(client);\n if (existingKey !== undefined) return existingKey;\n\n const queryKey = nextClientQueryKey++;\n clientQueryKeys.set(client, queryKey);\n return queryKey;\n}\n","import type { MastraClient } from '@mastra/client-js';\n\nexport type SSOLoginResponse = {\n url: string;\n};\n\nexport async function makeSSOLoginRequest(\n client: Pick<MastraClient, 'options'>,\n { redirectUri }: { redirectUri?: string },\n): Promise<SSOLoginResponse> {\n const { baseUrl = '', apiPrefix, headers: clientHeaders = {} } = client.options;\n const raw = (apiPrefix || '/api').trim();\n const prefix = (raw.startsWith('/') ? raw : `/${raw}`).replace(/\\/$/, '');\n\n const params = new URLSearchParams();\n if (redirectUri) {\n params.set('redirect_uri', redirectUri);\n }\n\n const url = `${baseUrl}${prefix}/auth/sso/login${params.toString() ? `?${params}` : ''}`;\n\n const response = await fetch(url, {\n credentials: 'include',\n headers: {\n ...clientHeaders,\n 'Content-Type': 'application/json',\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to initiate SSO login: ${response.status}`);\n }\n\n return response.json();\n}\n","import type { MastraClient } from '@mastra/client-js';\nimport type { UseQueryResult } from '@tanstack/react-query';\nimport { keepPreviousData, useQuery } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\nimport { getClientQueryKey } from './get-client-query-key';\nimport type { AuthCapabilities } from './types';\n\n/**\n * Makes a request to the auth capabilities endpoint.\n * Exported for testing purposes.\n *\n * @internal\n */\nexport async function makeAuthCapabilitiesRequest(client: MastraClient): Promise<AuthCapabilities> {\n const { baseUrl = '', headers: clientHeaders = {}, apiPrefix } = client.options;\n const raw = (apiPrefix || '/api').trim();\n const prefix = (raw.startsWith('/') ? raw : `/${raw}`).replace(/\\/$/, '');\n\n const response = await fetch(`${baseUrl}${prefix}/auth/capabilities`, {\n credentials: 'include',\n headers: {\n ...clientHeaders,\n 'Content-Type': 'application/json',\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch auth capabilities: ${response.status}`);\n }\n\n return response.json();\n}\n\n/**\n * Hook to fetch authentication capabilities.\n *\n * Returns server-authoritative capability detection including:\n * - Whether auth is enabled\n * - Login configuration (SSO, credentials, or both)\n * - Current user (if authenticated)\n * - Available capabilities (user awareness, session, SSO, RBAC, ACL, audit)\n * - User access (roles and permissions)\n *\n * @example\n * ```tsx\n * import { useAuthCapabilities } from '@mastra/react/hooks/auth';\n *\n * function AuthStatus() {\n * const { data: capabilities, isLoading } = useAuthCapabilities();\n *\n * if (isLoading) return <div>Loading...</div>;\n * if (!capabilities?.enabled) return <div>Auth not enabled</div>;\n *\n * if (isAuthenticated(capabilities)) {\n * return <div>Welcome, {capabilities.user.name}</div>;\n * }\n *\n * return <LoginButton config={capabilities.login} />;\n * }\n * ```\n */\nexport function useAuthCapabilities<TData = AuthCapabilities>({\n queryOptions,\n}: { queryOptions?: MastraQueryOptions<AuthCapabilities, TData> } = {}): UseQueryResult<TData, Error> {\n const client = useMastraClient();\n\n return useQuery<AuthCapabilities, Error, TData>({\n queryKey: ['auth', 'capabilities', getClientQueryKey(client)],\n queryFn: () => makeAuthCapabilitiesRequest(client),\n staleTime: 60 * 1000, // Cache for 1 minute\n retry: false, // Don't retry auth requests\n // A changed connection (Settings) makes a new client and so a new key. Keep the last answer while the\n // new one loads, so guards keep the page up instead of blanking it on every save.\n placeholderData: keepPreviousData,\n ...queryOptions,\n });\n}\n","import type { UseQueryResult } from '@tanstack/react-query';\nimport { useQuery } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\nimport { fetchWithRefresh } from './fetch-with-refresh';\nimport type { CurrentUser } from './types';\n\nconst AUTH_TRANSIENT_MAX_RETRIES = 3;\nconst AUTH_TRANSIENT_MAX_BACKOFF_MS = 8_000;\n\nexport class CurrentUserError extends Error {\n constructor(public readonly status: number) {\n super(`Failed to fetch current user: ${status}`);\n this.name = 'CurrentUserError';\n }\n}\n\nexport function isUnauthenticatedError(error: unknown): boolean {\n return error instanceof CurrentUserError && error.status === 401;\n}\n\n/**\n * Hook to fetch the current authenticated user.\n *\n * Returns the current user if authenticated, null otherwise.\n * Includes roles and permissions if RBAC is available.\n *\n * Uses fetchWithRefresh to automatically refresh the session on 401 errors,\n * preventing users from being logged out when the access token expires.\n *\n * @example\n * ```tsx\n * import { useCurrentUser } from '@mastra/react/hooks/auth';\n *\n * function UserMenu() {\n * const { data: user, isLoading } = useCurrentUser();\n *\n * if (isLoading) return <Skeleton />;\n * if (!user) return <LoginButton />;\n *\n * return (\n * <Menu>\n * <Avatar src={user.avatarUrl} />\n * <span>{user.name || user.email}</span>\n * </Menu>\n * );\n * }\n * ```\n */\nexport function useCurrentUser<TData = CurrentUser>({\n queryOptions,\n}: { queryOptions?: MastraQueryOptions<CurrentUser, TData> } = {}): UseQueryResult<TData, Error> {\n const client = useMastraClient();\n const baseUrl = client.options?.baseUrl || '';\n\n return useQuery<CurrentUser, Error, TData>({\n queryKey: ['auth', 'me'],\n queryFn: async () => {\n const response = await fetchWithRefresh(baseUrl, `${baseUrl}/api/auth/me`, {\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n\n if (!response.ok) {\n throw new CurrentUserError(response.status);\n }\n\n return response.json();\n },\n staleTime: 60 * 1000, // Cache for 1 minute\n // Retry the /api/auth/me query on transient auth-provider failures (HTTP 503)\n // so the UI stays in `isLoading` instead of flipping to `isError` and\n // triggering login — that redirect is what fed the WorkOS 429 lockout loop\n // (PLTFRM-1270). 401 (terminal) still fails fast.\n retry: (failureCount, error) => {\n if (!(error instanceof CurrentUserError)) return false;\n if (error.status !== 503) return false;\n return failureCount < AUTH_TRANSIENT_MAX_RETRIES;\n },\n retryDelay: attemptIndex => Math.min(AUTH_TRANSIENT_MAX_BACKOFF_MS, 500 * 2 ** attemptIndex),\n ...queryOptions,\n });\n}\n","import type { MastraClient, PermissionPattern } from '@mastra/client-js';\nimport { keepPreviousData, useQuery } from '@tanstack/react-query';\nimport { useMemo } from 'react';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\nimport { getClientQueryKey } from './get-client-query-key';\nimport { isAuthenticated } from './types';\nimport { useAuthCapabilities } from './use-auth-capabilities';\n\n/**\n * Fetches the authoritative set of permission patterns from the server\n * (`GET /auth/permission-patterns`).\n *\n * The server owns the permission source of truth (generated from the route\n * registry), so the browser never imports the server-only `@mastra/core/auth/ee`\n * code just to validate hardcoded route-permission literals.\n *\n * The request only fires when RBAC is actually enabled — when auth is off or\n * RBAC isn't configured, route gating is a no-op so the pattern vocabulary is\n * not needed, and we avoid an unnecessary (and potentially 403/401) call.\n */\ntype PermissionPatternsResponse = Awaited<ReturnType<MastraClient['getPermissionPatterns']>>;\n\nexport const usePermissionPatterns = ({\n queryOptions,\n}: { queryOptions?: MastraQueryOptions<PermissionPatternsResponse> } = {}) => {\n const client = useMastraClient();\n const { data: capabilities, isLoading: capabilitiesLoading, error: capabilitiesError } = useAuthCapabilities();\n\n const rbacEnabled = !!(capabilities && isAuthenticated(capabilities) && capabilities.capabilities.rbac);\n\n const { data, isLoading, error } = useQuery({\n queryKey: ['permission-patterns', getClientQueryKey(client)],\n queryFn: () => client.getPermissionPatterns(),\n // Only fetch the pattern vocabulary when RBAC gating is in effect.\n enabled: rbacEnabled,\n // The endpoint requires auth; on 403/401 we don't want React Query to\n // thrash with retries (which toggles isLoading and re-triggers redirect\n // guards). One attempt is enough — gating falls back to the user's\n // permissions if the pattern set is empty.\n retry: false,\n staleTime: Infinity,\n // A changed connection (Settings) makes a new client and so a new key. Keep the last answer while the\n // new one loads, so guards keep the page up instead of blanking it on every save.\n placeholderData: keepPreviousData,\n ...queryOptions,\n });\n\n const patterns = useMemo(() => new Set<PermissionPattern>(data?.patterns ?? []), [data]);\n\n // While capabilities are resolving we don't yet know whether RBAC applies, so\n // report loading. Once RBAC is ruled out, this hook is never \"loading\".\n return { patterns, isLoading: capabilitiesLoading || (rbacEnabled && isLoading), error: capabilitiesError || error };\n};\n","import type { MastraClient } from '@mastra/client-js';\nimport { useMutation, useQueryClient } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraMutationOptions } from '../shared/query-options';\n\nexport type CredentialsLoginRequest = {\n email: string;\n password: string;\n};\n\nexport type CredentialsLoginResponse = {\n user?: {\n id: string;\n email: string;\n name?: string;\n };\n error?: string;\n};\n\n/**\n * Hook to login with email/password credentials.\n *\n * Uses Better Auth's email sign-in endpoint.\n *\n * @example\n * ```tsx\n * import { useCredentialsLogin } from '@mastra/react/hooks/auth';\n *\n * function LoginForm() {\n * const { mutate: login, isPending, error } = useCredentialsLogin();\n *\n * const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {\n * e.preventDefault();\n * const formData = new FormData(e.currentTarget);\n * login({\n * email: formData.get('email') as string,\n * password: formData.get('password') as string,\n * }, {\n * onSuccess: () => {\n * window.location.href = '/';\n * },\n * });\n * };\n *\n * return (\n * <form onSubmit={handleSubmit}>\n * <input name=\"email\" type=\"email\" required />\n * <input name=\"password\" type=\"password\" required />\n * <button type=\"submit\" disabled={isPending}>\n * Sign in\n * </button>\n * {error && <p>{error.message}</p>}\n * </form>\n * );\n * }\n * ```\n */\n/**\n * Makes a credentials sign-in request.\n * Exported for testing purposes.\n *\n * @internal\n */\nexport async function makeCredentialsLoginRequest(\n client: MastraClient,\n { email, password }: CredentialsLoginRequest,\n): Promise<CredentialsLoginResponse> {\n const { baseUrl = '', apiPrefix, headers: clientHeaders = {} } = client.options || {};\n const raw = (apiPrefix ?? '/api').trim();\n const normalized = raw === '' ? '' : raw.startsWith('/') ? raw : `/${raw}`;\n const prefix = normalized.replace(/\\/+$/, '');\n\n // Generic Mastra auth endpoint - works with any credentials provider\n const response = await fetch(`${baseUrl}${prefix}/auth/credentials/sign-in`, {\n method: 'POST',\n credentials: 'include',\n headers: {\n ...clientHeaders,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ email, password }),\n });\n\n const data = await response.json();\n\n if (!response.ok) {\n throw new Error(data.message || data.error || 'Invalid email or password');\n }\n\n return data;\n}\n\nexport function useCredentialsLogin({\n queryOptions,\n}: { queryOptions?: MastraMutationOptions<CredentialsLoginResponse, CredentialsLoginRequest> } = {}) {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n return useMutation<CredentialsLoginResponse, Error, CredentialsLoginRequest>({\n mutationFn: ({ email, password }) => makeCredentialsLoginRequest(client, { email, password }),\n onSuccess: () => {\n // Invalidate auth queries to refetch user state\n void queryClient.invalidateQueries({ queryKey: ['auth'] });\n },\n ...queryOptions,\n });\n}\n","import type { MastraClient } from '@mastra/client-js';\nimport { useMutation, useQueryClient } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraMutationOptions } from '../shared/query-options';\n\nexport type CredentialsSignUpRequest = {\n email: string;\n password: string;\n name?: string;\n};\n\nexport type CredentialsSignUpResponse = {\n user?: {\n id: string;\n email: string;\n name?: string;\n };\n error?: string;\n};\n\n/**\n * Hook to sign up with email/password credentials.\n *\n * Uses Better Auth's email sign-up endpoint.\n *\n * @example\n * ```tsx\n * import { useCredentialsSignUp } from '@mastra/react/hooks/auth';\n *\n * function SignUpForm() {\n * const { mutate: signUp, isPending, error } = useCredentialsSignUp();\n *\n * const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {\n * e.preventDefault();\n * const formData = new FormData(e.currentTarget);\n * signUp({\n * email: formData.get('email') as string,\n * password: formData.get('password') as string,\n * name: formData.get('name') as string,\n * }, {\n * onSuccess: () => {\n * window.location.href = '/';\n * },\n * });\n * };\n *\n * return (\n * <form onSubmit={handleSubmit}>\n * <input name=\"name\" type=\"text\" />\n * <input name=\"email\" type=\"email\" required />\n * <input name=\"password\" type=\"password\" required />\n * <button type=\"submit\" disabled={isPending}>\n * Sign up\n * </button>\n * {error && <p>{error.message}</p>}\n * </form>\n * );\n * }\n * ```\n */\n/**\n * Makes a credentials sign-up request.\n * Exported for testing purposes.\n *\n * @internal\n */\nexport async function makeCredentialsSignUpRequest(\n client: MastraClient,\n { email, password, name }: CredentialsSignUpRequest,\n): Promise<CredentialsSignUpResponse> {\n const { baseUrl = '', apiPrefix, headers: clientHeaders = {} } = client.options || {};\n const raw = (apiPrefix ?? '/api').trim();\n const normalized = raw === '' ? '' : raw.startsWith('/') ? raw : `/${raw}`;\n const prefix = normalized.replace(/\\/+$/, '');\n\n // Generic Mastra auth endpoint - works with any credentials provider\n const response = await fetch(`${baseUrl}${prefix}/auth/credentials/sign-up`, {\n method: 'POST',\n credentials: 'include',\n headers: {\n ...clientHeaders,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ email, password, name }),\n });\n\n const data = await response.json();\n\n if (!response.ok) {\n throw new Error(data.message || data.error || 'Failed to create account');\n }\n\n return data;\n}\n\nexport function useCredentialsSignUp({\n queryOptions,\n}: { queryOptions?: MastraMutationOptions<CredentialsSignUpResponse, CredentialsSignUpRequest> } = {}) {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n return useMutation<CredentialsSignUpResponse, Error, CredentialsSignUpRequest>({\n mutationFn: ({ email, password, name }) => makeCredentialsSignUpRequest(client, { email, password, name }),\n onSuccess: () => {\n // Invalidate auth queries to refetch user state\n void queryClient.invalidateQueries({ queryKey: ['auth'] });\n },\n ...queryOptions,\n });\n}\n","import type { MastraClient } from '@mastra/client-js';\nimport { useMutation, useQueryClient } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraMutationOptions } from '../shared/query-options';\n\nimport { makeSSOLoginRequest } from './sso-login';\nimport type { LogoutResponse } from './types';\n\n/**\n * Hook to initiate SSO login.\n *\n * Returns mutation to get the SSO login URL and redirect.\n *\n * @example\n * ```tsx\n * import { useSSOLogin } from '@mastra/react/hooks/auth';\n *\n * function SSOLoginButton() {\n * const { mutate: login, isPending } = useSSOLogin();\n *\n * const handleClick = () => {\n * login({ redirectUri: window.location.href }, {\n * onSuccess: (data) => {\n * window.location.href = data.url;\n * },\n * });\n * };\n *\n * return (\n * <button onClick={handleClick} disabled={isPending}>\n * Sign in with SSO\n * </button>\n * );\n * }\n * ```\n */\ntype SSOLoginResponse = Awaited<ReturnType<typeof makeSSOLoginRequest>>;\n\nexport function useSSOLogin({\n queryOptions,\n}: { queryOptions?: MastraMutationOptions<SSOLoginResponse, { redirectUri?: string }> } = {}) {\n const client = useMastraClient();\n\n return useMutation({\n mutationFn: ({ redirectUri }: { redirectUri?: string }) => makeSSOLoginRequest(client, { redirectUri }),\n ...queryOptions,\n });\n}\n\n/**\n * Hook to logout the current user.\n *\n * Destroys the current session and optionally redirects to\n * the SSO logout URL if available.\n *\n * @example\n * ```tsx\n * import { useLogout } from '@mastra/react/hooks/auth';\n *\n * function LogoutButton({ userId }: { userId: string }) {\n * const { mutate: logout, isPending } = useLogout();\n * const queryClient = useQueryClient();\n *\n * const handleLogout = () => {\n * logout({ userId }, {\n * onSuccess: (data) => {\n * queryClient.invalidateQueries({ queryKey: ['auth'] });\n * if (data.redirectTo) {\n * window.location.href = data.redirectTo;\n * } else {\n * window.location.reload();\n * }\n * },\n * });\n * };\n *\n * return (\n * <button onClick={handleLogout} disabled={isPending}>\n * Sign out\n * </button>\n * );\n * }\n * ```\n */\n/**\n * Makes a logout request.\n * Exported for testing purposes.\n *\n * @internal\n */\nexport async function makeLogoutRequest(client: Pick<MastraClient, 'options'>): Promise<LogoutResponse> {\n const { baseUrl = '', apiPrefix, headers: clientHeaders = {} } = client.options;\n const raw = (apiPrefix || '/api').trim();\n const prefix = (raw.startsWith('/') ? raw : `/${raw}`).replace(/\\/$/, '');\n\n const response = await fetch(`${baseUrl}${prefix}/auth/logout`, {\n method: 'POST',\n credentials: 'include',\n headers: {\n ...clientHeaders,\n 'Content-Type': 'application/json',\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to logout: ${response.status}`);\n }\n\n return response.json();\n}\n\nexport interface UseLogoutOptions {\n /**\n * Runs once the server has ended the session, before the mutation resolves.\n * Failures are ignored so cleanup never turns a completed sign-out into an error.\n */\n onLoggedOut?: (variables: { userId: string }) => Promise<void>;\n queryOptions?: MastraMutationOptions<LogoutResponse, { userId: string }>;\n}\n\nexport function useLogout({ onLoggedOut, queryOptions }: UseLogoutOptions = {}) {\n const client = useMastraClient();\n const queryClient = useQueryClient();\n\n return useMutation<LogoutResponse, Error, { userId: string }>({\n mutationFn: async variables => {\n const response = await makeLogoutRequest(client);\n await onLoggedOut?.(variables).catch(() => {});\n return response;\n },\n onSuccess: () => {\n // Invalidate all auth-related queries\n void queryClient.invalidateQueries({ queryKey: ['auth'] });\n },\n ...queryOptions,\n });\n}\n"],"mappings":";;;;;;;AAkHA,SAAgB,gBAAgB,cAA2E;CACzG,OAAO,UAAU,gBAAgB,aAAa,SAAS,KAAA;AACzD;;;;;;;;;;;;;;;;;;;;;;;;;;;AC1FA,eAAsB,iBACpB,UACA,OACA,MACmB;CACnB,OAAO,MAAM,OAAO,IAAI;AAC1B;AAEA,SAAgB,uBAAuB,UAAmB,YAAmC;CAC3F,QA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EAAE,KAAK,CAAC,CAapG"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-permission-patterns.d.ts","sourceRoot":"","sources":["../../../src/hooks/auth/use-permission-patterns.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAqB,MAAM,mBAAmB,CAAC;AAIzE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAMlE;;;;;;;;;;;GAWG;AACH,KAAK,0BAA0B,GAAG,OAAO,CAAC,UAAU,CAAC,YAAY,CAAC,uBAAuB,CAAC,CAAC,CAAC,CAAC;AAE7F,eAAO,MAAM,qBAAqB,uBAE/B;IAAE,YAAY,CAAC,EAAE,kBAAkB,CAAC,0BAA0B,CAAC,CAAA;CAAE;;;;
|
|
1
|
+
{"version":3,"file":"use-permission-patterns.d.ts","sourceRoot":"","sources":["../../../src/hooks/auth/use-permission-patterns.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAqB,MAAM,mBAAmB,CAAC;AAIzE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAMlE;;;;;;;;;;;GAWG;AACH,KAAK,0BAA0B,GAAG,OAAO,CAAC,UAAU,CAAC,YAAY,CAAC,uBAAuB,CAAC,CAAC,CAAC,CAAC;AAE7F,eAAO,MAAM,qBAAqB,uBAE/B;IAAE,YAAY,CAAC,EAAE,kBAAkB,CAAC,0BAA0B,CAAC,CAAA;CAAE;;;;CA4BnE,CAAC"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
2
|
const require_mastra_client_context = require("../../mastra-client-context-DX8wJM9p.cjs");
|
|
3
|
-
const require_use_in_view = require("../../use-in-view-
|
|
3
|
+
const require_use_in_view = require("../../use-in-view-u7xWhAjL.cjs");
|
|
4
4
|
const require_combine_by_ids = require("../../combine-by-ids-ERVPXXBi.cjs");
|
|
5
5
|
let react = require("react");
|
|
6
6
|
let _tanstack_react_query = require("@tanstack/react-query");
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { n as useMastraClient } from "../../mastra-client-context-DQ5z_ze9.js";
|
|
2
|
-
import { t as useInView } from "../../use-in-view-
|
|
2
|
+
import { t as useInView } from "../../use-in-view-ChEDWwE1.js";
|
|
3
3
|
import { t as useCombineByIds } from "../../combine-by-ids-C-0oe4eH.js";
|
|
4
4
|
import { useEffect } from "react";
|
|
5
5
|
import { queryOptions, useInfiniteQuery, useMutation, useQueries, useQuery, useQueryClient } from "@tanstack/react-query";
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_experiments = require("../../experiments-
|
|
2
|
+
const require_experiments = require("../../experiments-CDqRm-1r.cjs");
|
|
3
3
|
exports.EXPERIMENTS_PAGE_SIZE = require_experiments.EXPERIMENTS_PAGE_SIZE;
|
|
4
4
|
exports.EXPERIMENTS_PER_PAGE = require_experiments.EXPERIMENTS_PER_PAGE;
|
|
5
5
|
exports.useExperimentMetrics = require_experiments.useExperimentMetrics;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export { i as EXPERIMENTS_PAGE_SIZE, t as EXPERIMENTS_PER_PAGE, s as useExperimentMetrics, o as useExperimentTrace, a as useExperimentsForDatasetFilter, c as useExperimentsItemUsage, r as useExperimentsListMetrics, n as useInfiniteExperiments } from "../../experiments-
|
|
1
|
+
export { i as EXPERIMENTS_PAGE_SIZE, t as EXPERIMENTS_PER_PAGE, s as useExperimentMetrics, o as useExperimentTrace, a as useExperimentsForDatasetFilter, c as useExperimentsItemUsage, r as useExperimentsListMetrics, n as useInfiniteExperiments } from "../../experiments-BUTZk3Fu.js";
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
2
|
const require_mastra_client_context = require("../../mastra-client-context-DX8wJM9p.cjs");
|
|
3
3
|
const require_query_utils = require("../../query-utils-BVgE_xxj.cjs");
|
|
4
|
-
const require_use_in_view = require("../../use-in-view-
|
|
4
|
+
const require_use_in_view = require("../../use-in-view-u7xWhAjL.cjs");
|
|
5
5
|
let react = require("react");
|
|
6
6
|
let _tanstack_react_query = require("@tanstack/react-query");
|
|
7
7
|
// src/hooks/logs/use-logs.ts
|
package/dist/hooks/logs/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { n as useMastraClient } from "../../mastra-client-context-DQ5z_ze9.js";
|
|
2
2
|
import { o as isObservabilityUnavailableError, s as isUnsupportedObservabilityOperationError } from "../../query-utils-DvMERIwf.js";
|
|
3
|
-
import { t as useInView } from "../../use-in-view-
|
|
3
|
+
import { t as useInView } from "../../use-in-view-ChEDWwE1.js";
|
|
4
4
|
import { useEffect } from "react";
|
|
5
5
|
import { useInfiniteQuery } from "@tanstack/react-query";
|
|
6
6
|
// src/hooks/logs/use-logs.ts
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
2
|
const require_mastra_client_context = require("../../mastra-client-context-DX8wJM9p.cjs");
|
|
3
|
-
const require_experiments = require("../../experiments-
|
|
3
|
+
const require_experiments = require("../../experiments-CDqRm-1r.cjs");
|
|
4
|
+
const require_use_in_view = require("../../use-in-view-u7xWhAjL.cjs");
|
|
5
|
+
let react = require("react");
|
|
4
6
|
let _tanstack_react_query = require("@tanstack/react-query");
|
|
5
7
|
// src/hooks/review/use-dataset-review-items.ts
|
|
6
8
|
/**
|
|
@@ -74,6 +76,116 @@ const useReviewItemsByStatus = (status, { experimentId, targetType, targetId, ex
|
|
|
74
76
|
const useReviewItems = (options = {}) => useReviewItemsByStatus("needs-review", options);
|
|
75
77
|
/** Loads completed review items (status='complete'), project-wide, per target or for one experiment. */
|
|
76
78
|
const useCompletedItems = (options = {}) => useReviewItemsByStatus("complete", options);
|
|
79
|
+
const RESULTS_PER_PAGE = 100;
|
|
80
|
+
const loadReviewItemsPage = async (client, status, { page, experiments }) => {
|
|
81
|
+
const pages = await Promise.all(experiments.map(async (experiment) => {
|
|
82
|
+
try {
|
|
83
|
+
const { results, pagination } = await client.listDatasetExperimentResults(experiment.datasetId, experiment.experimentId, {
|
|
84
|
+
page,
|
|
85
|
+
perPage: RESULTS_PER_PAGE,
|
|
86
|
+
status
|
|
87
|
+
});
|
|
88
|
+
return {
|
|
89
|
+
experiment,
|
|
90
|
+
results,
|
|
91
|
+
hasMore: pagination.hasMore && results.length > 0
|
|
92
|
+
};
|
|
93
|
+
} catch {
|
|
94
|
+
return {
|
|
95
|
+
experiment,
|
|
96
|
+
results: [],
|
|
97
|
+
hasMore: false
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
}));
|
|
101
|
+
const withMore = pages.filter((p) => p.hasMore).map((p) => p.experiment);
|
|
102
|
+
return {
|
|
103
|
+
items: pages.flatMap(({ experiment, results }) => results.filter((r) => r.status === status).map((r) => ({
|
|
104
|
+
id: r.id,
|
|
105
|
+
input: r.input,
|
|
106
|
+
output: r.output,
|
|
107
|
+
error: r.error,
|
|
108
|
+
itemId: r.itemId,
|
|
109
|
+
experimentId: r.experimentId,
|
|
110
|
+
datasetId: experiment.datasetId,
|
|
111
|
+
traceId: r.traceId ?? void 0,
|
|
112
|
+
scores: r.scores ? Object.fromEntries(r.scores.map((s) => [s.scorerId, s.score ?? 0])) : {},
|
|
113
|
+
tags: r.tags ?? [],
|
|
114
|
+
targetType: r.targetType,
|
|
115
|
+
createdAt: r.createdAt,
|
|
116
|
+
startedAt: r.startedAt,
|
|
117
|
+
completedAt: r.completedAt,
|
|
118
|
+
status: r.status,
|
|
119
|
+
groundTruth: r.groundTruth,
|
|
120
|
+
toolMockReport: r.toolMockReport
|
|
121
|
+
}))),
|
|
122
|
+
next: withMore.length > 0 ? {
|
|
123
|
+
page: page + 1,
|
|
124
|
+
experiments: withMore
|
|
125
|
+
} : void 0
|
|
126
|
+
};
|
|
127
|
+
};
|
|
128
|
+
/**
|
|
129
|
+
* Infinite-scroll review items with the given status. Each page holds the next results page of every
|
|
130
|
+
* scoped experiment that still has matching results.
|
|
131
|
+
*/
|
|
132
|
+
const useInfiniteReviewItemsByStatus = (status, { experimentId, targetType, targetId, experiments: suppliedExperiments, isLoadingExperiments = false, queryOptions }) => {
|
|
133
|
+
const client = require_mastra_client_context.useMastraClient();
|
|
134
|
+
const { inView: isEndOfListInView, setRef: setEndOfListElement } = require_use_in_view.useInView();
|
|
135
|
+
const hasSuppliedExperiments = suppliedExperiments !== void 0;
|
|
136
|
+
const { data: experimentsData, isLoading: isDiscoveringExperiments } = require_experiments.useExperimentsForDatasetFilter({
|
|
137
|
+
datasetId: void 0,
|
|
138
|
+
target: {
|
|
139
|
+
targetType,
|
|
140
|
+
targetId
|
|
141
|
+
},
|
|
142
|
+
queryOptions: { enabled: !hasSuppliedExperiments }
|
|
143
|
+
});
|
|
144
|
+
const experiments = hasSuppliedExperiments ? suppliedExperiments : experimentsData?.experiments;
|
|
145
|
+
const isLoadingSource = hasSuppliedExperiments ? isLoadingExperiments : isDiscoveringExperiments;
|
|
146
|
+
const scopedExperiments = experimentId ? experiments?.filter((exp) => exp.id === experimentId) : experiments;
|
|
147
|
+
const query = (0, _tanstack_react_query.useInfiniteQuery)({
|
|
148
|
+
queryKey: [
|
|
149
|
+
"review-items",
|
|
150
|
+
status,
|
|
151
|
+
"infinite",
|
|
152
|
+
experimentId ?? "all",
|
|
153
|
+
hasSuppliedExperiments ? "supplied" : "discovered",
|
|
154
|
+
hasSuppliedExperiments ? void 0 : targetType || "all",
|
|
155
|
+
hasSuppliedExperiments ? void 0 : targetId || "all",
|
|
156
|
+
scopedExperiments?.map((e) => [e.datasetId, e.id])
|
|
157
|
+
],
|
|
158
|
+
queryFn: async ({ pageParam }) => {
|
|
159
|
+
let page = await loadReviewItemsPage(client, status, pageParam);
|
|
160
|
+
while (page.items.length === 0 && page.next) page = await loadReviewItemsPage(client, status, page.next);
|
|
161
|
+
return page;
|
|
162
|
+
},
|
|
163
|
+
initialPageParam: {
|
|
164
|
+
page: 0,
|
|
165
|
+
experiments: (scopedExperiments ?? []).flatMap((exp) => exp.datasetId ? [{
|
|
166
|
+
experimentId: exp.id,
|
|
167
|
+
datasetId: exp.datasetId
|
|
168
|
+
}] : [])
|
|
169
|
+
},
|
|
170
|
+
getNextPageParam: (lastPage) => lastPage.next,
|
|
171
|
+
select: (data) => data.pages.flatMap((page) => page.items),
|
|
172
|
+
enabled: Boolean(experiments),
|
|
173
|
+
refetchOnWindowFocus: false,
|
|
174
|
+
...queryOptions
|
|
175
|
+
});
|
|
176
|
+
(0, react.useEffect)(() => {
|
|
177
|
+
if (isEndOfListInView && query.hasNextPage && !query.isFetching) query.fetchNextPage({ cancelRefetch: false });
|
|
178
|
+
}, [isEndOfListInView, query]);
|
|
179
|
+
return {
|
|
180
|
+
...query,
|
|
181
|
+
isLoading: query.isLoading || isLoadingSource,
|
|
182
|
+
setEndOfListElement
|
|
183
|
+
};
|
|
184
|
+
};
|
|
185
|
+
/** Infinite-scroll review items (status='needs-review'), project-wide, per target or for one experiment. */
|
|
186
|
+
const useInfiniteReviewItems = (options = {}) => useInfiniteReviewItemsByStatus("needs-review", options);
|
|
187
|
+
/** Infinite-scroll completed review items (status='complete'), project-wide, per target or for one experiment. */
|
|
188
|
+
const useInfiniteCompletedItems = (options = {}) => useInfiniteReviewItemsByStatus("complete", options);
|
|
77
189
|
// src/hooks/review/use-review-summary.ts
|
|
78
190
|
function useReviewSummary({ queryOptions } = {}) {
|
|
79
191
|
const client = require_mastra_client_context.useMastraClient();
|
|
@@ -84,6 +196,8 @@ function useReviewSummary({ queryOptions } = {}) {
|
|
|
84
196
|
});
|
|
85
197
|
}
|
|
86
198
|
exports.useCompletedItems = useCompletedItems;
|
|
199
|
+
exports.useInfiniteCompletedItems = useInfiniteCompletedItems;
|
|
200
|
+
exports.useInfiniteReviewItems = useInfiniteReviewItems;
|
|
87
201
|
exports.useReviewItems = useReviewItems;
|
|
88
202
|
exports.useReviewSummary = useReviewSummary;
|
|
89
203
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["useMastraClient","useExperimentsForDatasetFilter","useQuery","useMastraClient","useQuery"],"sources":["../../../src/hooks/review/use-dataset-review-items.ts","../../../src/hooks/review/use-review-summary.ts"],"sourcesContent":["import type { DatasetExperiment } from '@mastra/client-js';\nimport { useQuery } from '@tanstack/react-query';\nimport type { UseQueryResult } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport { useExperimentsForDatasetFilter } from '../experiments';\nimport type { ExperimentTargetFilter } from '../experiments';\nimport type { MastraQueryOptions } from '../shared/query-options';\nimport type { ReviewItem } from './types';\n\ntype ReviewStatus = 'needs-review' | 'complete';\n\nexport interface ReviewItemsOptions extends ExperimentTargetFilter {\n /** When set, only this experiment's results are loaded; otherwise every experiment in the project. */\n experimentId?: string;\n /** Explicit source owned by the caller; an empty list disables discovery too. */\n experiments?: DatasetExperiment[];\n isLoadingExperiments?: boolean;\n /** TanStack overrides spread last into the review-items query. */\n queryOptions?: MastraQueryOptions<ReviewItem[]>;\n}\n\n/**\n * Loads experiment results with the given review status, across the project, scoped to a target,\n * or scoped to one experiment.\n */\nconst useReviewItemsByStatus = (\n status: ReviewStatus,\n {\n experimentId,\n targetType,\n targetId,\n experiments: suppliedExperiments,\n isLoadingExperiments = false,\n queryOptions,\n }: ReviewItemsOptions,\n): UseQueryResult<ReviewItem[], Error> => {\n const client = useMastraClient();\n const hasSuppliedExperiments = suppliedExperiments !== undefined;\n const { data: experimentsData, isLoading: isDiscoveringExperiments } = useExperimentsForDatasetFilter({\n datasetId: undefined,\n target: { targetType, targetId },\n queryOptions: { enabled: !hasSuppliedExperiments },\n });\n const experiments = hasSuppliedExperiments ? suppliedExperiments : experimentsData?.experiments;\n const isLoadingSource = hasSuppliedExperiments ? isLoadingExperiments : isDiscoveringExperiments;\n const scopedExperiments = experimentId ? experiments?.filter(exp => exp.id === experimentId) : experiments;\n\n const query = useQuery({\n queryKey: [\n 'review-items',\n status,\n experimentId ?? 'all',\n hasSuppliedExperiments ? 'supplied' : 'discovered',\n hasSuppliedExperiments ? undefined : targetType || 'all',\n hasSuppliedExperiments ? undefined : targetId || 'all',\n scopedExperiments?.map(e => [e.datasetId, e.id]),\n ],\n queryFn: async () => {\n if (!scopedExperiments || scopedExperiments.length === 0) return [] as ReviewItem[];\n\n const allResults = await Promise.all(\n scopedExperiments.map(async exp => {\n if (!exp.datasetId) return [];\n try {\n const { results } = await client.listDatasetExperimentResults(exp.datasetId, exp.id);\n return results\n .filter(r => r.status === status)\n .map(r => ({\n id: r.id,\n input: r.input,\n output: r.output,\n error: r.error,\n itemId: r.itemId,\n experimentId: r.experimentId,\n datasetId: exp.datasetId ?? undefined,\n traceId: r.traceId ?? undefined,\n scores: r.scores ? Object.fromEntries(r.scores.map(s => [s.scorerId, s.score ?? 0])) : {},\n tags: r.tags ?? [],\n targetType: r.targetType,\n createdAt: r.createdAt,\n startedAt: r.startedAt,\n completedAt: r.completedAt,\n status: r.status,\n groundTruth: r.groundTruth,\n toolMockReport: r.toolMockReport,\n }));\n } catch {\n return [];\n }\n }),\n );\n\n return allResults.flat() as ReviewItem[];\n },\n enabled: Boolean(experiments),\n refetchOnWindowFocus: false,\n ...queryOptions,\n });\n\n // The results query is disabled until experiments arrive, so its own `isLoading`\n // is false during that window; surface the upstream load to avoid an empty flash.\n return { ...query, isLoading: query.isLoading || isLoadingSource } as UseQueryResult<ReviewItem[], Error>;\n};\n\n/** Loads persisted review items (status='needs-review'), project-wide, per target or for one experiment. */\nexport const useReviewItems = (options: ReviewItemsOptions = {}) => useReviewItemsByStatus('needs-review', options);\n\n/** Loads completed review items (status='complete'), project-wide, per target or for one experiment. */\nexport const useCompletedItems = (options: ReviewItemsOptions = {}) => useReviewItemsByStatus('complete', options);\n","import type { MastraClient } from '@mastra/client-js';\nimport type { UseQueryResult } from '@tanstack/react-query';\nimport { useQuery } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\ntype ReviewSummaryResponse = Awaited<ReturnType<MastraClient['getExperimentReviewSummary']>>;\n\nexport function useReviewSummary<TData = ReviewSummaryResponse>({\n queryOptions,\n}: {\n queryOptions?: MastraQueryOptions<ReviewSummaryResponse, TData>;\n} = {}): UseQueryResult<TData, Error> {\n const client = useMastraClient();\n\n return useQuery({\n queryKey: ['experiment-review-summary'],\n queryFn: () => client.getExperimentReviewSummary(),\n ...queryOptions,\n });\n}\n"],"mappings":";;;;;;;;;AAyBA,MAAM,0BACJ,QACA,EACE,cACA,YACA,UACA,aAAa,qBACb,uBAAuB,OACvB,mBAEsC;CACxC,MAAM,SAASA,8BAAAA,gBAAgB;CAC/B,MAAM,yBAAyB,wBAAwB,KAAA;CACvD,MAAM,EAAE,MAAM,iBAAiB,WAAW,6BAA6BC,oBAAAA,+BAA+B;EACpG,WAAW,KAAA;EACX,QAAQ;GAAE;GAAY;EAAS;EAC/B,cAAc,EAAE,SAAS,CAAC,uBAAuB;CACnD,CAAC;CACD,MAAM,cAAc,yBAAyB,sBAAsB,iBAAiB;CACpF,MAAM,kBAAkB,yBAAyB,uBAAuB;CACxE,MAAM,oBAAoB,eAAe,aAAa,QAAO,QAAO,IAAI,OAAO,YAAY,IAAI;CAE/F,MAAM,SAAA,GAAQC,sBAAAA,SAAAA,CAAS;EACrB,UAAU;GACR;GACA;GACA,gBAAgB;GAChB,yBAAyB,aAAa;GACtC,yBAAyB,KAAA,IAAY,cAAc;GACnD,yBAAyB,KAAA,IAAY,YAAY;GACjD,mBAAmB,KAAI,MAAK,CAAC,EAAE,WAAW,EAAE,EAAE,CAAC;EACjD;EACA,SAAS,YAAY;GACnB,IAAI,CAAC,qBAAqB,kBAAkB,WAAW,GAAG,OAAO,CAAC;GAkClE,QAAO,MAhCkB,QAAQ,IAC/B,kBAAkB,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names":["useMastraClient","useExperimentsForDatasetFilter","useQuery","useInView","useInfiniteQuery","useMastraClient","useQuery"],"sources":["../../../src/hooks/review/use-dataset-review-items.ts","../../../src/hooks/review/use-review-summary.ts"],"sourcesContent":["import type { DatasetExperiment, MastraClient } from '@mastra/client-js';\nimport { useInfiniteQuery, useQuery } from '@tanstack/react-query';\nimport type { InfiniteData, QueryKey, UseInfiniteQueryResult, UseQueryResult } from '@tanstack/react-query';\nimport { useEffect } from 'react';\nimport { useMastraClient } from '../../mastra-client-context';\nimport { useExperimentsForDatasetFilter } from '../experiments';\nimport type { ExperimentTargetFilter } from '../experiments';\nimport type { MastraInfiniteQueryOptions, MastraQueryOptions } from '../shared/query-options';\nimport { useInView } from '../shared/use-in-view';\nimport type { ReviewItem } from './types';\n\ntype ReviewStatus = 'needs-review' | 'complete';\n\nexport interface ReviewItemsOptions extends ExperimentTargetFilter {\n /** When set, only this experiment's results are loaded; otherwise every experiment in the project. */\n experimentId?: string;\n /** Explicit source owned by the caller; an empty list disables discovery too. */\n experiments?: DatasetExperiment[];\n isLoadingExperiments?: boolean;\n /** TanStack overrides spread last into the review-items query. */\n queryOptions?: MastraQueryOptions<ReviewItem[]>;\n}\n\n/**\n * Loads experiment results with the given review status, across the project, scoped to a target,\n * or scoped to one experiment.\n */\nconst useReviewItemsByStatus = (\n status: ReviewStatus,\n {\n experimentId,\n targetType,\n targetId,\n experiments: suppliedExperiments,\n isLoadingExperiments = false,\n queryOptions,\n }: ReviewItemsOptions,\n): UseQueryResult<ReviewItem[], Error> => {\n const client = useMastraClient();\n const hasSuppliedExperiments = suppliedExperiments !== undefined;\n const { data: experimentsData, isLoading: isDiscoveringExperiments } = useExperimentsForDatasetFilter({\n datasetId: undefined,\n target: { targetType, targetId },\n queryOptions: { enabled: !hasSuppliedExperiments },\n });\n const experiments = hasSuppliedExperiments ? suppliedExperiments : experimentsData?.experiments;\n const isLoadingSource = hasSuppliedExperiments ? isLoadingExperiments : isDiscoveringExperiments;\n const scopedExperiments = experimentId ? experiments?.filter(exp => exp.id === experimentId) : experiments;\n\n const query = useQuery({\n queryKey: [\n 'review-items',\n status,\n experimentId ?? 'all',\n hasSuppliedExperiments ? 'supplied' : 'discovered',\n hasSuppliedExperiments ? undefined : targetType || 'all',\n hasSuppliedExperiments ? undefined : targetId || 'all',\n scopedExperiments?.map(e => [e.datasetId, e.id]),\n ],\n queryFn: async () => {\n if (!scopedExperiments || scopedExperiments.length === 0) return [] as ReviewItem[];\n\n const allResults = await Promise.all(\n scopedExperiments.map(async exp => {\n if (!exp.datasetId) return [];\n try {\n const { results } = await client.listDatasetExperimentResults(exp.datasetId, exp.id);\n return results\n .filter(r => r.status === status)\n .map(r => ({\n id: r.id,\n input: r.input,\n output: r.output,\n error: r.error,\n itemId: r.itemId,\n experimentId: r.experimentId,\n datasetId: exp.datasetId ?? undefined,\n traceId: r.traceId ?? undefined,\n scores: r.scores ? Object.fromEntries(r.scores.map(s => [s.scorerId, s.score ?? 0])) : {},\n tags: r.tags ?? [],\n targetType: r.targetType,\n createdAt: r.createdAt,\n startedAt: r.startedAt,\n completedAt: r.completedAt,\n status: r.status,\n groundTruth: r.groundTruth,\n toolMockReport: r.toolMockReport,\n }));\n } catch {\n return [];\n }\n }),\n );\n\n return allResults.flat() as ReviewItem[];\n },\n enabled: Boolean(experiments),\n refetchOnWindowFocus: false,\n ...queryOptions,\n });\n\n // The results query is disabled until experiments arrive, so its own `isLoading`\n // is false during that window; surface the upstream load to avoid an empty flash.\n return { ...query, isLoading: query.isLoading || isLoadingSource } as UseQueryResult<ReviewItem[], Error>;\n};\n\n/** Loads persisted review items (status='needs-review'), project-wide, per target or for one experiment. */\nexport const useReviewItems = (options: ReviewItemsOptions = {}) => useReviewItemsByStatus('needs-review', options);\n\n/** Loads completed review items (status='complete'), project-wide, per target or for one experiment. */\nexport const useCompletedItems = (options: ReviewItemsOptions = {}) => useReviewItemsByStatus('complete', options);\n\nconst RESULTS_PER_PAGE = 100;\n\n/** The next results page to load, for each experiment that still has matching results. */\nexport interface ReviewItemsCursor {\n page: number;\n experiments: Array<{ experimentId: string; datasetId: string }>;\n}\n\nexport interface ReviewItemsPage {\n items: ReviewItem[];\n next?: ReviewItemsCursor;\n}\n\nexport interface InfiniteReviewItemsOptions extends Omit<ReviewItemsOptions, 'queryOptions'> {\n /** TanStack overrides spread last into the review-items infinite query. */\n queryOptions?: MastraInfiniteQueryOptions<ReviewItemsPage, ReviewItem[], QueryKey, ReviewItemsCursor>;\n}\n\nconst loadReviewItemsPage = async (\n client: MastraClient,\n status: ReviewStatus,\n { page, experiments }: ReviewItemsCursor,\n): Promise<ReviewItemsPage> => {\n const pages = await Promise.all(\n experiments.map(async experiment => {\n try {\n const { results, pagination } = await client.listDatasetExperimentResults(\n experiment.datasetId,\n experiment.experimentId,\n { page, perPage: RESULTS_PER_PAGE, status },\n );\n return { experiment, results, hasMore: pagination.hasMore && results.length > 0 };\n } catch {\n return { experiment, results: [], hasMore: false };\n }\n }),\n );\n const withMore = pages.filter(p => p.hasMore).map(p => p.experiment);\n\n return {\n // Servers without the `status` filter return every result.\n items: pages.flatMap(({ experiment, results }) =>\n results\n .filter(r => r.status === status)\n .map(r => ({\n id: r.id,\n input: r.input,\n output: r.output,\n error: r.error,\n itemId: r.itemId,\n experimentId: r.experimentId,\n datasetId: experiment.datasetId,\n traceId: r.traceId ?? undefined,\n scores: r.scores ? Object.fromEntries(r.scores.map(s => [s.scorerId, s.score ?? 0])) : {},\n tags: r.tags ?? [],\n targetType: r.targetType,\n createdAt: r.createdAt,\n startedAt: r.startedAt,\n completedAt: r.completedAt,\n status: r.status,\n groundTruth: r.groundTruth,\n toolMockReport: r.toolMockReport,\n })),\n ),\n next: withMore.length > 0 ? { page: page + 1, experiments: withMore } : undefined,\n };\n};\n\n/**\n * Infinite-scroll review items with the given status. Each page holds the next results page of every\n * scoped experiment that still has matching results.\n */\nconst useInfiniteReviewItemsByStatus = (\n status: ReviewStatus,\n {\n experimentId,\n targetType,\n targetId,\n experiments: suppliedExperiments,\n isLoadingExperiments = false,\n queryOptions,\n }: InfiniteReviewItemsOptions,\n): UseInfiniteQueryResult<ReviewItem[], Error> & {\n setEndOfListElement: (element: HTMLDivElement | null) => void;\n} => {\n const client = useMastraClient();\n const { inView: isEndOfListInView, setRef: setEndOfListElement } = useInView();\n const hasSuppliedExperiments = suppliedExperiments !== undefined;\n const { data: experimentsData, isLoading: isDiscoveringExperiments } = useExperimentsForDatasetFilter({\n datasetId: undefined,\n target: { targetType, targetId },\n queryOptions: { enabled: !hasSuppliedExperiments },\n });\n const experiments = hasSuppliedExperiments ? suppliedExperiments : experimentsData?.experiments;\n const isLoadingSource = hasSuppliedExperiments ? isLoadingExperiments : isDiscoveringExperiments;\n const scopedExperiments = experimentId ? experiments?.filter(exp => exp.id === experimentId) : experiments;\n\n const query = useInfiniteQuery({\n queryKey: [\n 'review-items',\n status,\n 'infinite',\n experimentId ?? 'all',\n hasSuppliedExperiments ? 'supplied' : 'discovered',\n hasSuppliedExperiments ? undefined : targetType || 'all',\n hasSuppliedExperiments ? undefined : targetId || 'all',\n scopedExperiments?.map(e => [e.datasetId, e.id]),\n ],\n queryFn: async ({ pageParam }) => {\n let page = await loadReviewItemsPage(client, status, pageParam);\n // An empty page would hide the end-of-list sentinel, so keep reading until something matches.\n while (page.items.length === 0 && page.next) page = await loadReviewItemsPage(client, status, page.next);\n return page;\n },\n initialPageParam: {\n page: 0,\n experiments: (scopedExperiments ?? []).flatMap(exp =>\n exp.datasetId ? [{ experimentId: exp.id, datasetId: exp.datasetId }] : [],\n ),\n },\n getNextPageParam: lastPage => lastPage.next,\n select: (data: InfiniteData<ReviewItemsPage, ReviewItemsCursor>) => data.pages.flatMap(page => page.items),\n enabled: Boolean(experiments),\n refetchOnWindowFocus: false,\n ...queryOptions,\n });\n\n // Waits for refetches too: `fetchNextPage` would cancel the refresh that follows a status change.\n useEffect(() => {\n if (isEndOfListInView && query.hasNextPage && !query.isFetching) {\n void query.fetchNextPage({ cancelRefetch: false });\n }\n }, [isEndOfListInView, query]);\n\n return { ...query, isLoading: query.isLoading || isLoadingSource, setEndOfListElement } as UseInfiniteQueryResult<\n ReviewItem[],\n Error\n > & { setEndOfListElement: (element: HTMLDivElement | null) => void };\n};\n\n/** Infinite-scroll review items (status='needs-review'), project-wide, per target or for one experiment. */\nexport const useInfiniteReviewItems = (options: InfiniteReviewItemsOptions = {}) =>\n useInfiniteReviewItemsByStatus('needs-review', options);\n\n/** Infinite-scroll completed review items (status='complete'), project-wide, per target or for one experiment. */\nexport const useInfiniteCompletedItems = (options: InfiniteReviewItemsOptions = {}) =>\n useInfiniteReviewItemsByStatus('complete', options);\n","import type { MastraClient } from '@mastra/client-js';\nimport type { UseQueryResult } from '@tanstack/react-query';\nimport { useQuery } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\ntype ReviewSummaryResponse = Awaited<ReturnType<MastraClient['getExperimentReviewSummary']>>;\n\nexport function useReviewSummary<TData = ReviewSummaryResponse>({\n queryOptions,\n}: {\n queryOptions?: MastraQueryOptions<ReviewSummaryResponse, TData>;\n} = {}): UseQueryResult<TData, Error> {\n const client = useMastraClient();\n\n return useQuery({\n queryKey: ['experiment-review-summary'],\n queryFn: () => client.getExperimentReviewSummary(),\n ...queryOptions,\n });\n}\n"],"mappings":";;;;;;;;;;;AA2BA,MAAM,0BACJ,QACA,EACE,cACA,YACA,UACA,aAAa,qBACb,uBAAuB,OACvB,mBAEsC;CACxC,MAAM,SAASA,8BAAAA,gBAAgB;CAC/B,MAAM,yBAAyB,wBAAwB,KAAA;CACvD,MAAM,EAAE,MAAM,iBAAiB,WAAW,6BAA6BC,oBAAAA,+BAA+B;EACpG,WAAW,KAAA;EACX,QAAQ;GAAE;GAAY;EAAS;EAC/B,cAAc,EAAE,SAAS,CAAC,uBAAuB;CACnD,CAAC;CACD,MAAM,cAAc,yBAAyB,sBAAsB,iBAAiB;CACpF,MAAM,kBAAkB,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AC,IAAI,CAAC,CAC1E;EACF;EACA,mBAAkB,aAAY,SAAS;EACvC,SAAS,SAA2D,KAAK,MAAM,SAAQ,SAAQ,KAAK,KAAK;EACzG,SAAS,QAAQ,WAAW;EAC5B,sBAAsB;EACtB,GAAG;CACL,CAAC;CAGD,CAAA,GAAA,MAAA,UAAA,OAAgB;EACd,IAAI,qBAAqB,MAAM,eAAe,CAAC,MAAM,YACnD,MAAW,cAAc,EAAE,eAAe,MAAM,CAAC;CAErD,GAAG,CAAC,mBAAmB,KAAK,CAAC;CAE7B,OAAO;EAAE,GAAG;EAAO,WAAW,MAAM,aAAa;EAAiB;CAAoB;AAIxF;;AAGA,MAAa,0BAA0B,UAAsC,CAAC,MAC5E,+BAA+B,gBAAgB,OAAO;;AAGxD,MAAa,6BAA6B,UAAsC,CAAC,MAC/E,+BAA+B,YAAY,OAAO;;AC1PpD,SAAgB,iBAAgD,EAC9D,iBAGE,CAAC,GAAiC;CACpC,MAAM,SAASC,8BAAAA,gBAAgB;CAE/B,QAAA,GAAOC,sBAAAA,SAAAA,CAAS;EACd,UAAU,CAAC,2BAA2B;EACtC,eAAe,OAAO,2BAA2B;EACjD,GAAG;CACL,CAAC;AACH"}
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { n as useMastraClient } from "../../mastra-client-context-DQ5z_ze9.js";
|
|
2
|
-
import { a as useExperimentsForDatasetFilter } from "../../experiments-
|
|
3
|
-
import {
|
|
2
|
+
import { a as useExperimentsForDatasetFilter } from "../../experiments-BUTZk3Fu.js";
|
|
3
|
+
import { t as useInView } from "../../use-in-view-ChEDWwE1.js";
|
|
4
|
+
import { useEffect } from "react";
|
|
5
|
+
import { useInfiniteQuery, useQuery } from "@tanstack/react-query";
|
|
4
6
|
// src/hooks/review/use-dataset-review-items.ts
|
|
5
7
|
/**
|
|
6
8
|
* Loads experiment results with the given review status, across the project, scoped to a target,
|
|
@@ -73,6 +75,116 @@ const useReviewItemsByStatus = (status, { experimentId, targetType, targetId, ex
|
|
|
73
75
|
const useReviewItems = (options = {}) => useReviewItemsByStatus("needs-review", options);
|
|
74
76
|
/** Loads completed review items (status='complete'), project-wide, per target or for one experiment. */
|
|
75
77
|
const useCompletedItems = (options = {}) => useReviewItemsByStatus("complete", options);
|
|
78
|
+
const RESULTS_PER_PAGE = 100;
|
|
79
|
+
const loadReviewItemsPage = async (client, status, { page, experiments }) => {
|
|
80
|
+
const pages = await Promise.all(experiments.map(async (experiment) => {
|
|
81
|
+
try {
|
|
82
|
+
const { results, pagination } = await client.listDatasetExperimentResults(experiment.datasetId, experiment.experimentId, {
|
|
83
|
+
page,
|
|
84
|
+
perPage: RESULTS_PER_PAGE,
|
|
85
|
+
status
|
|
86
|
+
});
|
|
87
|
+
return {
|
|
88
|
+
experiment,
|
|
89
|
+
results,
|
|
90
|
+
hasMore: pagination.hasMore && results.length > 0
|
|
91
|
+
};
|
|
92
|
+
} catch {
|
|
93
|
+
return {
|
|
94
|
+
experiment,
|
|
95
|
+
results: [],
|
|
96
|
+
hasMore: false
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
}));
|
|
100
|
+
const withMore = pages.filter((p) => p.hasMore).map((p) => p.experiment);
|
|
101
|
+
return {
|
|
102
|
+
items: pages.flatMap(({ experiment, results }) => results.filter((r) => r.status === status).map((r) => ({
|
|
103
|
+
id: r.id,
|
|
104
|
+
input: r.input,
|
|
105
|
+
output: r.output,
|
|
106
|
+
error: r.error,
|
|
107
|
+
itemId: r.itemId,
|
|
108
|
+
experimentId: r.experimentId,
|
|
109
|
+
datasetId: experiment.datasetId,
|
|
110
|
+
traceId: r.traceId ?? void 0,
|
|
111
|
+
scores: r.scores ? Object.fromEntries(r.scores.map((s) => [s.scorerId, s.score ?? 0])) : {},
|
|
112
|
+
tags: r.tags ?? [],
|
|
113
|
+
targetType: r.targetType,
|
|
114
|
+
createdAt: r.createdAt,
|
|
115
|
+
startedAt: r.startedAt,
|
|
116
|
+
completedAt: r.completedAt,
|
|
117
|
+
status: r.status,
|
|
118
|
+
groundTruth: r.groundTruth,
|
|
119
|
+
toolMockReport: r.toolMockReport
|
|
120
|
+
}))),
|
|
121
|
+
next: withMore.length > 0 ? {
|
|
122
|
+
page: page + 1,
|
|
123
|
+
experiments: withMore
|
|
124
|
+
} : void 0
|
|
125
|
+
};
|
|
126
|
+
};
|
|
127
|
+
/**
|
|
128
|
+
* Infinite-scroll review items with the given status. Each page holds the next results page of every
|
|
129
|
+
* scoped experiment that still has matching results.
|
|
130
|
+
*/
|
|
131
|
+
const useInfiniteReviewItemsByStatus = (status, { experimentId, targetType, targetId, experiments: suppliedExperiments, isLoadingExperiments = false, queryOptions }) => {
|
|
132
|
+
const client = useMastraClient();
|
|
133
|
+
const { inView: isEndOfListInView, setRef: setEndOfListElement } = useInView();
|
|
134
|
+
const hasSuppliedExperiments = suppliedExperiments !== void 0;
|
|
135
|
+
const { data: experimentsData, isLoading: isDiscoveringExperiments } = useExperimentsForDatasetFilter({
|
|
136
|
+
datasetId: void 0,
|
|
137
|
+
target: {
|
|
138
|
+
targetType,
|
|
139
|
+
targetId
|
|
140
|
+
},
|
|
141
|
+
queryOptions: { enabled: !hasSuppliedExperiments }
|
|
142
|
+
});
|
|
143
|
+
const experiments = hasSuppliedExperiments ? suppliedExperiments : experimentsData?.experiments;
|
|
144
|
+
const isLoadingSource = hasSuppliedExperiments ? isLoadingExperiments : isDiscoveringExperiments;
|
|
145
|
+
const scopedExperiments = experimentId ? experiments?.filter((exp) => exp.id === experimentId) : experiments;
|
|
146
|
+
const query = useInfiniteQuery({
|
|
147
|
+
queryKey: [
|
|
148
|
+
"review-items",
|
|
149
|
+
status,
|
|
150
|
+
"infinite",
|
|
151
|
+
experimentId ?? "all",
|
|
152
|
+
hasSuppliedExperiments ? "supplied" : "discovered",
|
|
153
|
+
hasSuppliedExperiments ? void 0 : targetType || "all",
|
|
154
|
+
hasSuppliedExperiments ? void 0 : targetId || "all",
|
|
155
|
+
scopedExperiments?.map((e) => [e.datasetId, e.id])
|
|
156
|
+
],
|
|
157
|
+
queryFn: async ({ pageParam }) => {
|
|
158
|
+
let page = await loadReviewItemsPage(client, status, pageParam);
|
|
159
|
+
while (page.items.length === 0 && page.next) page = await loadReviewItemsPage(client, status, page.next);
|
|
160
|
+
return page;
|
|
161
|
+
},
|
|
162
|
+
initialPageParam: {
|
|
163
|
+
page: 0,
|
|
164
|
+
experiments: (scopedExperiments ?? []).flatMap((exp) => exp.datasetId ? [{
|
|
165
|
+
experimentId: exp.id,
|
|
166
|
+
datasetId: exp.datasetId
|
|
167
|
+
}] : [])
|
|
168
|
+
},
|
|
169
|
+
getNextPageParam: (lastPage) => lastPage.next,
|
|
170
|
+
select: (data) => data.pages.flatMap((page) => page.items),
|
|
171
|
+
enabled: Boolean(experiments),
|
|
172
|
+
refetchOnWindowFocus: false,
|
|
173
|
+
...queryOptions
|
|
174
|
+
});
|
|
175
|
+
useEffect(() => {
|
|
176
|
+
if (isEndOfListInView && query.hasNextPage && !query.isFetching) query.fetchNextPage({ cancelRefetch: false });
|
|
177
|
+
}, [isEndOfListInView, query]);
|
|
178
|
+
return {
|
|
179
|
+
...query,
|
|
180
|
+
isLoading: query.isLoading || isLoadingSource,
|
|
181
|
+
setEndOfListElement
|
|
182
|
+
};
|
|
183
|
+
};
|
|
184
|
+
/** Infinite-scroll review items (status='needs-review'), project-wide, per target or for one experiment. */
|
|
185
|
+
const useInfiniteReviewItems = (options = {}) => useInfiniteReviewItemsByStatus("needs-review", options);
|
|
186
|
+
/** Infinite-scroll completed review items (status='complete'), project-wide, per target or for one experiment. */
|
|
187
|
+
const useInfiniteCompletedItems = (options = {}) => useInfiniteReviewItemsByStatus("complete", options);
|
|
76
188
|
// src/hooks/review/use-review-summary.ts
|
|
77
189
|
function useReviewSummary({ queryOptions } = {}) {
|
|
78
190
|
const client = useMastraClient();
|
|
@@ -82,6 +194,6 @@ function useReviewSummary({ queryOptions } = {}) {
|
|
|
82
194
|
...queryOptions
|
|
83
195
|
});
|
|
84
196
|
}
|
|
85
|
-
export { useCompletedItems, useReviewItems, useReviewSummary };
|
|
197
|
+
export { useCompletedItems, useInfiniteCompletedItems, useInfiniteReviewItems, useReviewItems, useReviewSummary };
|
|
86
198
|
|
|
87
199
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../src/hooks/review/use-dataset-review-items.ts","../../../src/hooks/review/use-review-summary.ts"],"sourcesContent":["import type { DatasetExperiment } from '@mastra/client-js';\nimport { useQuery } from '@tanstack/react-query';\nimport type { UseQueryResult } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport { useExperimentsForDatasetFilter } from '../experiments';\nimport type { ExperimentTargetFilter } from '../experiments';\nimport type { MastraQueryOptions } from '../shared/query-options';\nimport type { ReviewItem } from './types';\n\ntype ReviewStatus = 'needs-review' | 'complete';\n\nexport interface ReviewItemsOptions extends ExperimentTargetFilter {\n /** When set, only this experiment's results are loaded; otherwise every experiment in the project. */\n experimentId?: string;\n /** Explicit source owned by the caller; an empty list disables discovery too. */\n experiments?: DatasetExperiment[];\n isLoadingExperiments?: boolean;\n /** TanStack overrides spread last into the review-items query. */\n queryOptions?: MastraQueryOptions<ReviewItem[]>;\n}\n\n/**\n * Loads experiment results with the given review status, across the project, scoped to a target,\n * or scoped to one experiment.\n */\nconst useReviewItemsByStatus = (\n status: ReviewStatus,\n {\n experimentId,\n targetType,\n targetId,\n experiments: suppliedExperiments,\n isLoadingExperiments = false,\n queryOptions,\n }: ReviewItemsOptions,\n): UseQueryResult<ReviewItem[], Error> => {\n const client = useMastraClient();\n const hasSuppliedExperiments = suppliedExperiments !== undefined;\n const { data: experimentsData, isLoading: isDiscoveringExperiments } = useExperimentsForDatasetFilter({\n datasetId: undefined,\n target: { targetType, targetId },\n queryOptions: { enabled: !hasSuppliedExperiments },\n });\n const experiments = hasSuppliedExperiments ? suppliedExperiments : experimentsData?.experiments;\n const isLoadingSource = hasSuppliedExperiments ? isLoadingExperiments : isDiscoveringExperiments;\n const scopedExperiments = experimentId ? experiments?.filter(exp => exp.id === experimentId) : experiments;\n\n const query = useQuery({\n queryKey: [\n 'review-items',\n status,\n experimentId ?? 'all',\n hasSuppliedExperiments ? 'supplied' : 'discovered',\n hasSuppliedExperiments ? undefined : targetType || 'all',\n hasSuppliedExperiments ? undefined : targetId || 'all',\n scopedExperiments?.map(e => [e.datasetId, e.id]),\n ],\n queryFn: async () => {\n if (!scopedExperiments || scopedExperiments.length === 0) return [] as ReviewItem[];\n\n const allResults = await Promise.all(\n scopedExperiments.map(async exp => {\n if (!exp.datasetId) return [];\n try {\n const { results } = await client.listDatasetExperimentResults(exp.datasetId, exp.id);\n return results\n .filter(r => r.status === status)\n .map(r => ({\n id: r.id,\n input: r.input,\n output: r.output,\n error: r.error,\n itemId: r.itemId,\n experimentId: r.experimentId,\n datasetId: exp.datasetId ?? undefined,\n traceId: r.traceId ?? undefined,\n scores: r.scores ? Object.fromEntries(r.scores.map(s => [s.scorerId, s.score ?? 0])) : {},\n tags: r.tags ?? [],\n targetType: r.targetType,\n createdAt: r.createdAt,\n startedAt: r.startedAt,\n completedAt: r.completedAt,\n status: r.status,\n groundTruth: r.groundTruth,\n toolMockReport: r.toolMockReport,\n }));\n } catch {\n return [];\n }\n }),\n );\n\n return allResults.flat() as ReviewItem[];\n },\n enabled: Boolean(experiments),\n refetchOnWindowFocus: false,\n ...queryOptions,\n });\n\n // The results query is disabled until experiments arrive, so its own `isLoading`\n // is false during that window; surface the upstream load to avoid an empty flash.\n return { ...query, isLoading: query.isLoading || isLoadingSource } as UseQueryResult<ReviewItem[], Error>;\n};\n\n/** Loads persisted review items (status='needs-review'), project-wide, per target or for one experiment. */\nexport const useReviewItems = (options: ReviewItemsOptions = {}) => useReviewItemsByStatus('needs-review', options);\n\n/** Loads completed review items (status='complete'), project-wide, per target or for one experiment. */\nexport const useCompletedItems = (options: ReviewItemsOptions = {}) => useReviewItemsByStatus('complete', options);\n","import type { MastraClient } from '@mastra/client-js';\nimport type { UseQueryResult } from '@tanstack/react-query';\nimport { useQuery } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\ntype ReviewSummaryResponse = Awaited<ReturnType<MastraClient['getExperimentReviewSummary']>>;\n\nexport function useReviewSummary<TData = ReviewSummaryResponse>({\n queryOptions,\n}: {\n queryOptions?: MastraQueryOptions<ReviewSummaryResponse, TData>;\n} = {}): UseQueryResult<TData, Error> {\n const client = useMastraClient();\n\n return useQuery({\n queryKey: ['experiment-review-summary'],\n queryFn: () => client.getExperimentReviewSummary(),\n ...queryOptions,\n });\n}\n"],"mappings":";;;;;;;;AAyBA,MAAM,0BACJ,QACA,EACE,cACA,YACA,UACA,aAAa,qBACb,uBAAuB,OACvB,mBAEsC;CACxC,MAAM,SAAS,gBAAgB;CAC/B,MAAM,yBAAyB,wBAAwB,KAAA;CACvD,MAAM,EAAE,MAAM,iBAAiB,WAAW,6BAA6B,+BAA+B;EACpG,WAAW,KAAA;EACX,QAAQ;GAAE;GAAY;EAAS;EAC/B,cAAc,EAAE,SAAS,CAAC,uBAAuB;CACnD,CAAC;CACD,MAAM,cAAc,yBAAyB,sBAAsB,iBAAiB;CACpF,MAAM,kBAAkB,yBAAyB,uBAAuB;CACxE,MAAM,oBAAoB,eAAe,aAAa,QAAO,QAAO,IAAI,OAAO,YAAY,IAAI;CAE/F,MAAM,QAAQ,SAAS;EACrB,UAAU;GACR;GACA;GACA,gBAAgB;GAChB,yBAAyB,aAAa;GACtC,yBAAyB,KAAA,IAAY,cAAc;GACnD,yBAAyB,KAAA,IAAY,YAAY;GACjD,mBAAmB,KAAI,MAAK,CAAC,EAAE,WAAW,EAAE,EAAE,CAAC;EACjD;EACA,SAAS,YAAY;GACnB,IAAI,CAAC,qBAAqB,kBAAkB,WAAW,GAAG,OAAO,CAAC;GAkClE,QAAO,MAhCkB,QAAQ,IAC/B,kBAAkB,IAAI,OA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../src/hooks/review/use-review-summary.ts"],"sourcesContent":["import type { DatasetExperiment, MastraClient } from '@mastra/client-js';\nimport { useInfiniteQuery, useQuery } from '@tanstack/react-query';\nimport type { InfiniteData, QueryKey, UseInfiniteQueryResult, UseQueryResult } from '@tanstack/react-query';\nimport { useEffect } from 'react';\nimport { useMastraClient } from '../../mastra-client-context';\nimport { useExperimentsForDatasetFilter } from '../experiments';\nimport type { ExperimentTargetFilter } from '../experiments';\nimport type { MastraInfiniteQueryOptions, MastraQueryOptions } from '../shared/query-options';\nimport { useInView } from '../shared/use-in-view';\nimport type { ReviewItem } from './types';\n\ntype ReviewStatus = 'needs-review' | 'complete';\n\nexport interface ReviewItemsOptions extends ExperimentTargetFilter {\n /** When set, only this experiment's results are loaded; otherwise every experiment in the project. */\n experimentId?: string;\n /** Explicit source owned by the caller; an empty list disables discovery too. */\n experiments?: DatasetExperiment[];\n isLoadingExperiments?: boolean;\n /** TanStack overrides spread last into the review-items query. */\n queryOptions?: MastraQueryOptions<ReviewItem[]>;\n}\n\n/**\n * Loads experiment results with the given review status, across the project, scoped to a target,\n * or scoped to one experiment.\n */\nconst useReviewItemsByStatus = (\n status: ReviewStatus,\n {\n experimentId,\n targetType,\n targetId,\n experiments: suppliedExperiments,\n isLoadingExperiments = false,\n queryOptions,\n }: ReviewItemsOptions,\n): UseQueryResult<ReviewItem[], Error> => {\n const client = useMastraClient();\n const hasSuppliedExperiments = suppliedExperiments !== undefined;\n const { data: experimentsData, isLoading: isDiscoveringExperiments } = useExperimentsForDatasetFilter({\n datasetId: undefined,\n target: { targetType, targetId },\n queryOptions: { enabled: !hasSuppliedExperiments },\n });\n const experiments = hasSuppliedExperiments ? suppliedExperiments : experimentsData?.experiments;\n const isLoadingSource = hasSuppliedExperiments ? isLoadingExperiments : isDiscoveringExperiments;\n const scopedExperiments = experimentId ? experiments?.filter(exp => exp.id === experimentId) : experiments;\n\n const query = useQuery({\n queryKey: [\n 'review-items',\n status,\n experimentId ?? 'all',\n hasSuppliedExperiments ? 'supplied' : 'discovered',\n hasSuppliedExperiments ? undefined : targetType || 'all',\n hasSuppliedExperiments ? undefined : targetId || 'all',\n scopedExperiments?.map(e => [e.datasetId, e.id]),\n ],\n queryFn: async () => {\n if (!scopedExperiments || scopedExperiments.length === 0) return [] as ReviewItem[];\n\n const allResults = await Promise.all(\n scopedExperiments.map(async exp => {\n if (!exp.datasetId) return [];\n try {\n const { results } = await client.listDatasetExperimentResults(exp.datasetId, exp.id);\n return results\n .filter(r => r.status === status)\n .map(r => ({\n id: r.id,\n input: r.input,\n output: r.output,\n error: r.error,\n itemId: r.itemId,\n experimentId: r.experimentId,\n datasetId: exp.datasetId ?? undefined,\n traceId: r.traceId ?? undefined,\n scores: r.scores ? Object.fromEntries(r.scores.map(s => [s.scorerId, s.score ?? 0])) : {},\n tags: r.tags ?? [],\n targetType: r.targetType,\n createdAt: r.createdAt,\n startedAt: r.startedAt,\n completedAt: r.completedAt,\n status: r.status,\n groundTruth: r.groundTruth,\n toolMockReport: r.toolMockReport,\n }));\n } catch {\n return [];\n }\n }),\n );\n\n return allResults.flat() as ReviewItem[];\n },\n enabled: Boolean(experiments),\n refetchOnWindowFocus: false,\n ...queryOptions,\n });\n\n // The results query is disabled until experiments arrive, so its own `isLoading`\n // is false during that window; surface the upstream load to avoid an empty flash.\n return { ...query, isLoading: query.isLoading || isLoadingSource } as UseQueryResult<ReviewItem[], Error>;\n};\n\n/** Loads persisted review items (status='needs-review'), project-wide, per target or for one experiment. */\nexport const useReviewItems = (options: ReviewItemsOptions = {}) => useReviewItemsByStatus('needs-review', options);\n\n/** Loads completed review items (status='complete'), project-wide, per target or for one experiment. */\nexport const useCompletedItems = (options: ReviewItemsOptions = {}) => useReviewItemsByStatus('complete', options);\n\nconst RESULTS_PER_PAGE = 100;\n\n/** The next results page to load, for each experiment that still has matching results. */\nexport interface ReviewItemsCursor {\n page: number;\n experiments: Array<{ experimentId: string; datasetId: string }>;\n}\n\nexport interface ReviewItemsPage {\n items: ReviewItem[];\n next?: ReviewItemsCursor;\n}\n\nexport interface InfiniteReviewItemsOptions extends Omit<ReviewItemsOptions, 'queryOptions'> {\n /** TanStack overrides spread last into the review-items infinite query. */\n queryOptions?: MastraInfiniteQueryOptions<ReviewItemsPage, ReviewItem[], QueryKey, ReviewItemsCursor>;\n}\n\nconst loadReviewItemsPage = async (\n client: MastraClient,\n status: ReviewStatus,\n { page, experiments }: ReviewItemsCursor,\n): Promise<ReviewItemsPage> => {\n const pages = await Promise.all(\n experiments.map(async experiment => {\n try {\n const { results, pagination } = await client.listDatasetExperimentResults(\n experiment.datasetId,\n experiment.experimentId,\n { page, perPage: RESULTS_PER_PAGE, status },\n );\n return { experiment, results, hasMore: pagination.hasMore && results.length > 0 };\n } catch {\n return { experiment, results: [], hasMore: false };\n }\n }),\n );\n const withMore = pages.filter(p => p.hasMore).map(p => p.experiment);\n\n return {\n // Servers without the `status` filter return every result.\n items: pages.flatMap(({ experiment, results }) =>\n results\n .filter(r => r.status === status)\n .map(r => ({\n id: r.id,\n input: r.input,\n output: r.output,\n error: r.error,\n itemId: r.itemId,\n experimentId: r.experimentId,\n datasetId: experiment.datasetId,\n traceId: r.traceId ?? undefined,\n scores: r.scores ? Object.fromEntries(r.scores.map(s => [s.scorerId, s.score ?? 0])) : {},\n tags: r.tags ?? [],\n targetType: r.targetType,\n createdAt: r.createdAt,\n startedAt: r.startedAt,\n completedAt: r.completedAt,\n status: r.status,\n groundTruth: r.groundTruth,\n toolMockReport: r.toolMockReport,\n })),\n ),\n next: withMore.length > 0 ? { page: page + 1, experiments: withMore } : undefined,\n };\n};\n\n/**\n * Infinite-scroll review items with the given status. Each page holds the next results page of every\n * scoped experiment that still has matching results.\n */\nconst useInfiniteReviewItemsByStatus = (\n status: ReviewStatus,\n {\n experimentId,\n targetType,\n targetId,\n experiments: suppliedExperiments,\n isLoadingExperiments = false,\n queryOptions,\n }: InfiniteReviewItemsOptions,\n): UseInfiniteQueryResult<ReviewItem[], Error> & {\n setEndOfListElement: (element: HTMLDivElement | null) => void;\n} => {\n const client = useMastraClient();\n const { inView: isEndOfListInView, setRef: setEndOfListElement } = useInView();\n const hasSuppliedExperiments = suppliedExperiments !== undefined;\n const { data: experimentsData, isLoading: isDiscoveringExperiments } = useExperimentsForDatasetFilter({\n datasetId: undefined,\n target: { targetType, targetId },\n queryOptions: { enabled: !hasSuppliedExperiments },\n });\n const experiments = hasSuppliedExperiments ? suppliedExperiments : experimentsData?.experiments;\n const isLoadingSource = hasSuppliedExperiments ? isLoadingExperiments : isDiscoveringExperiments;\n const scopedExperiments = experimentId ? experiments?.filter(exp => exp.id === experimentId) : experiments;\n\n const query = useInfiniteQuery({\n queryKey: [\n 'review-items',\n status,\n 'infinite',\n experimentId ?? 'all',\n hasSuppliedExperiments ? 'supplied' : 'discovered',\n hasSuppliedExperiments ? undefined : targetType || 'all',\n hasSuppliedExperiments ? undefined : targetId || 'all',\n scopedExperiments?.map(e => [e.datasetId, e.id]),\n ],\n queryFn: async ({ pageParam }) => {\n let page = await loadReviewItemsPage(client, status, pageParam);\n // An empty page would hide the end-of-list sentinel, so keep reading until something matches.\n while (page.items.length === 0 && page.next) page = await loadReviewItemsPage(client, status, page.next);\n return page;\n },\n initialPageParam: {\n page: 0,\n experiments: (scopedExperiments ?? []).flatMap(exp =>\n exp.datasetId ? [{ experimentId: exp.id, datasetId: exp.datasetId }] : [],\n ),\n },\n getNextPageParam: lastPage => lastPage.next,\n select: (data: InfiniteData<ReviewItemsPage, ReviewItemsCursor>) => data.pages.flatMap(page => page.items),\n enabled: Boolean(experiments),\n refetchOnWindowFocus: false,\n ...queryOptions,\n });\n\n // Waits for refetches too: `fetchNextPage` would cancel the refresh that follows a status change.\n useEffect(() => {\n if (isEndOfListInView && query.hasNextPage && !query.isFetching) {\n void query.fetchNextPage({ cancelRefetch: false });\n }\n }, [isEndOfListInView, query]);\n\n return { ...query, isLoading: query.isLoading || isLoadingSource, setEndOfListElement } as UseInfiniteQueryResult<\n ReviewItem[],\n Error\n > & { setEndOfListElement: (element: HTMLDivElement | null) => void };\n};\n\n/** Infinite-scroll review items (status='needs-review'), project-wide, per target or for one experiment. */\nexport const useInfiniteReviewItems = (options: InfiniteReviewItemsOptions = {}) =>\n useInfiniteReviewItemsByStatus('needs-review', options);\n\n/** Infinite-scroll completed review items (status='complete'), project-wide, per target or for one experiment. */\nexport const useInfiniteCompletedItems = (options: InfiniteReviewItemsOptions = {}) =>\n useInfiniteReviewItemsByStatus('complete', options);\n","import type { MastraClient } from '@mastra/client-js';\nimport type { UseQueryResult } from '@tanstack/react-query';\nimport { useQuery } from '@tanstack/react-query';\nimport { useMastraClient } from '../../mastra-client-context';\nimport type { MastraQueryOptions } from '../shared/query-options';\n\ntype ReviewSummaryResponse = Awaited<ReturnType<MastraClient['getExperimentReviewSummary']>>;\n\nexport function useReviewSummary<TData = ReviewSummaryResponse>({\n queryOptions,\n}: {\n queryOptions?: MastraQueryOptions<ReviewSummaryResponse, TData>;\n} = {}): UseQueryResult<TData, Error> {\n const client = useMastraClient();\n\n return useQuery({\n queryKey: ['experiment-review-summary'],\n queryFn: () => client.getExperimentReviewSummary(),\n ...queryOptions,\n });\n}\n"],"mappings":";;;;;;;;;;AA2BA,MAAM,0BACJ,QACA,EACE,cACA,YACA,UACA,aAAa,qBACb,uBAAuB,OACvB,mBAEsC;CACxC,MAAM,SAAS,gBAAgB;CAC/B,MAAM,yBAAyB,wBAAwB,KAAA;CACvD,MAAM,EAAE,MAAM,iBAAiB,WAAW,6BAA6B,+BAA+B;EACpG,WAAW,KAAA;EACX,QAAQ;GAAE;GAAY;EAAS;EAC/B,cAAc,EAAE,SAAS,CAAC,uBAAuB;CACnD,CAAC;CACD,MAAM,cAAc,yBAAyB,sBAAsB,iBAAiB;CACpF,MAAM,kBAAkB,yBAAyB,uBAAuB;CACxE,MAAM,oBAAoB,eAAe,aAAa,QAAO,QAAO,IAAI,OAAO,YAAY,IAAI;CAE/F,MAAM,QAAQ,SAAS;EACrB,UAAU;G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