@korajs/auth 0.4.0 → 0.6.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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/react.ts","../src/react/AuthProvider.tsx","../src/react/auth-context.ts","../src/react/hooks.ts","../src/react/org-hooks.ts"],"sourcesContent":["// @korajs/auth/react — React-specific public API\n// Every export here is a public API commitment. Be explicit.\n\n// === Provider ===\nexport { AuthProvider } from './react/AuthProvider'\nexport type { AuthProviderProps } from './react/AuthProvider'\n\n// === Hooks ===\nexport { useAuth, useCurrentUser, useAuthStatus } from './react/hooks'\nexport type { UseAuthResult, AuthStatus } from './react/hooks'\n\n// === Context (for advanced use cases) ===\nexport { AuthContext } from './react/auth-context'\nexport type { AuthContextValue } from './react/auth-context'\n\n// === Organization Hooks ===\nexport { OrgContext, useOrg, useOrgMembers, usePermission } from './react/org-hooks'\nexport type { OrgContextValue, UseOrgResult, UseOrgMembersResult } from './react/org-hooks'\n","import { createElement, useEffect, useState } from 'react'\nimport type { ReactElement, ReactNode } from 'react'\nimport type { AuthClient, AuthState } from '../client/auth-client'\nimport { AuthContext } from './auth-context'\n\n/**\n * Props for the AuthProvider component.\n */\ninterface AuthProviderProps {\n\t/** The AuthClient instance to provide to child components */\n\tclient: AuthClient\n\n\t/** Child components that will have access to auth context */\n\tchildren: ReactNode\n\n\t/**\n\t * Optional fallback content to render while the auth client is initializing.\n\t * If not provided, children are rendered with `isLoading: true` in the context.\n\t */\n\tfallback?: ReactNode\n}\n\n/**\n * React context provider that wraps the AuthClient for use with auth hooks.\n *\n * Calls `client.initialize()` on mount to restore any existing session from\n * stored tokens. Subscribes to auth state changes and re-renders children\n * when the state transitions.\n *\n * Must be placed above any component that uses {@link useAuth},\n * {@link useCurrentUser}, or {@link useAuthStatus}.\n *\n * @param props - Provider props including the AuthClient instance and children\n * @returns A React element wrapping children in the AuthContext\n *\n * @example\n * ```typescript\n * import { AuthClient } from '@korajs/auth'\n * import { AuthProvider } from '@korajs/auth/react'\n *\n * const authClient = new AuthClient({ serverUrl: 'http://localhost:3001' })\n *\n * function App() {\n * return (\n * <AuthProvider client={authClient} fallback={<div>Loading...</div>}>\n * <MyApp />\n * </AuthProvider>\n * )\n * }\n * ```\n */\nfunction AuthProvider({ client, children, fallback }: AuthProviderProps): ReactElement {\n\tconst [state, setState] = useState<AuthState>(client.state)\n\tconst [isLoading, setIsLoading] = useState(true)\n\tconst [initError, setInitError] = useState<Error | null>(null)\n\n\t// Initialize the auth client on mount\n\tuseEffect(() => {\n\t\tlet cancelled = false\n\n\t\t// Subscribe to auth state changes\n\t\tconst unsubscribe = client.onAuthChange((newState) => {\n\t\t\tif (!cancelled) {\n\t\t\t\tsetState(newState)\n\t\t\t}\n\t\t})\n\n\t\tclient\n\t\t\t.initialize()\n\t\t\t.then(() => {\n\t\t\t\tif (!cancelled) {\n\t\t\t\t\tsetState(client.state)\n\t\t\t\t\tsetIsLoading(false)\n\t\t\t\t}\n\t\t\t})\n\t\t\t.catch((error: unknown) => {\n\t\t\t\tif (!cancelled) {\n\t\t\t\t\tconst err = error instanceof Error ? error : new Error(String(error))\n\t\t\t\t\tconsole.error('[Kora Auth] Initialization failed:', err)\n\t\t\t\t\tsetInitError(err)\n\t\t\t\t\tsetIsLoading(false)\n\t\t\t\t}\n\t\t\t})\n\n\t\treturn () => {\n\t\t\tcancelled = true\n\t\t\tunsubscribe()\n\t\t}\n\t}, [client])\n\n\t// Show error if initialization failed\n\tif (initError) {\n\t\treturn createElement(\n\t\t\t'div',\n\t\t\t{\n\t\t\t\tstyle: { color: 'red', padding: '1rem', fontFamily: 'monospace' },\n\t\t\t\trole: 'alert',\n\t\t\t},\n\t\t\tcreateElement('strong', null, 'Kora Auth initialization error: '),\n\t\t\tinitError.message,\n\t\t)\n\t}\n\n\t// Show fallback while loading\n\tif (isLoading && fallback !== undefined) {\n\t\treturn fallback as ReactElement\n\t}\n\n\tconst contextValue = {\n\t\tclient,\n\t\tstate,\n\t\tisLoading,\n\t}\n\n\treturn createElement(AuthContext.Provider, { value: contextValue }, children)\n}\n\nexport { AuthProvider }\nexport type { AuthProviderProps }\n","import { createContext } from 'react'\nimport type { AuthClient } from '../client/auth-client'\n\n/**\n * Possible authentication states for the client.\n * - 'loading': Initial state while restoring tokens from storage\n * - 'authenticated': User is signed in with a valid session\n * - 'unauthenticated': No valid session exists\n */\ntype AuthState = 'loading' | 'authenticated' | 'unauthenticated'\n\n/**\n * Shape of the value provided by the AuthContext.\n * Includes the AuthClient instance, reactive state, and a loading flag.\n */\ninterface AuthContextValue {\n\t/** The underlying AuthClient instance for direct access */\n\tclient: AuthClient\n\n\t/** Current authentication state */\n\tstate: AuthState\n\n\t/** Whether the client is still initializing (restoring session from storage) */\n\tisLoading: boolean\n}\n\n/**\n * React context for Kora authentication.\n *\n * Provides the AuthClient and reactive auth state to child components.\n * Must be provided by an AuthProvider higher in the component tree.\n * Defaults to null — hooks that consume this context throw if it is missing.\n */\nconst AuthContext = createContext<AuthContextValue | null>(null)\n\nexport { AuthContext }\nexport type { AuthContextValue, AuthState }\n","import { useCallback, useContext, useEffect, useRef, useState, useSyncExternalStore } from 'react'\nimport type { AuthState, AuthUser } from '../client/auth-client'\nimport { AuthContext } from './auth-context'\n\n// ---------------------------------------------------------------------------\n// Internal context accessor\n// ---------------------------------------------------------------------------\n\n/**\n * Internal hook that reads and validates the AuthContext.\n * Throws a descriptive error if used outside an AuthProvider.\n */\nfunction useAuthContext(): {\n\tclient: import('../client/auth-client').AuthClient\n\tstate: AuthState\n\tisLoading: boolean\n} {\n\tconst ctx = useContext(AuthContext)\n\tif (ctx === null) {\n\t\tthrow new Error(\n\t\t\t'useAuth / useCurrentUser / useAuthStatus must be used within an <AuthProvider>. ' +\n\t\t\t\t'Wrap your component tree with <AuthProvider client={authClient}>.',\n\t\t)\n\t}\n\treturn ctx\n}\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/**\n * Return value of the {@link useAuth} hook.\n */\ninterface UseAuthResult {\n\t/** Current authenticated user, or null if not signed in */\n\tuser: AuthUser | null\n\n\t/** Whether the user is currently authenticated */\n\tisAuthenticated: boolean\n\n\t/** Whether the auth client is still initializing (restoring session) */\n\tisLoading: boolean\n\n\t/** Sign up a new user account */\n\tsignUp: (params: { email: string; password: string; name?: string }) => Promise<void>\n\n\t/** Sign in with email and password */\n\tsignIn: (params: { email: string; password: string }) => Promise<void>\n\n\t/** Sign out the current user */\n\tsignOut: () => Promise<void>\n\n\t/** Last error message from a sign-up, sign-in, or sign-out attempt, or null */\n\terror: string | null\n}\n\n/**\n * Auth status information returned by {@link useAuthStatus}.\n */\ninterface AuthStatus {\n\t/** Current authentication state */\n\tstate: AuthState\n\n\t/** Whether the user is currently authenticated */\n\tisAuthenticated: boolean\n\n\t/** Whether the auth client is still initializing */\n\tisLoading: boolean\n}\n\n// ---------------------------------------------------------------------------\n// useAuth\n// ---------------------------------------------------------------------------\n\n/**\n * React hook providing full authentication functionality.\n *\n * Returns the current user, loading state, error state, and methods for\n * sign-up, sign-in, and sign-out. Re-renders when auth state changes.\n *\n * Must be used within an {@link AuthProvider}.\n *\n * @returns An object with user info, auth methods, and status flags\n *\n * @example\n * ```typescript\n * function LoginPage() {\n * const { user, isAuthenticated, isLoading, signIn, error } = useAuth()\n *\n * if (isLoading) return <div>Loading...</div>\n * if (isAuthenticated) return <div>Welcome, {user?.name}</div>\n *\n * return (\n * <form onSubmit={async (e) => {\n * e.preventDefault()\n * await signIn({ email: 'user@example.com', password: 'secret' })\n * }}>\n * {error && <p>{error}</p>}\n * <button type=\"submit\">Sign In</button>\n * </form>\n * )\n * }\n * ```\n */\nfunction useAuth(): UseAuthResult {\n\tconst { client, state, isLoading } = useAuthContext()\n\tconst [error, setError] = useState<string | null>(null)\n\n\t// Use useSyncExternalStore to track the user reactively via auth state changes\n\tconst userSnapshotRef = useRef<AuthUser | null>(client.currentUser)\n\tconst stateSerializedRef = useRef<string>(JSON.stringify(client.currentUser))\n\n\tconst subscribe = useCallback(\n\t\t(onStoreChange: () => void): (() => void) => {\n\t\t\treturn client.onAuthChange(() => {\n\t\t\t\tconst newUser = client.currentUser\n\t\t\t\tconst newSerialized = JSON.stringify(newUser)\n\t\t\t\tif (newSerialized !== stateSerializedRef.current) {\n\t\t\t\t\tuserSnapshotRef.current = newUser\n\t\t\t\t\tstateSerializedRef.current = newSerialized\n\t\t\t\t\tonStoreChange()\n\t\t\t\t}\n\t\t\t})\n\t\t},\n\t\t[client],\n\t)\n\n\tconst getSnapshot = useCallback((): AuthUser | null => {\n\t\treturn userSnapshotRef.current\n\t}, [])\n\n\tconst user = useSyncExternalStore(subscribe, getSnapshot)\n\n\tconst signUp = useCallback(\n\t\tasync (params: { email: string; password: string; name?: string }): Promise<void> => {\n\t\t\tsetError(null)\n\t\t\ttry {\n\t\t\t\tawait client.signUp(params)\n\t\t\t} catch (err: unknown) {\n\t\t\t\tconst message = err instanceof Error ? err.message : String(err)\n\t\t\t\tsetError(message)\n\t\t\t}\n\t\t},\n\t\t[client],\n\t)\n\n\tconst signIn = useCallback(\n\t\tasync (params: { email: string; password: string }): Promise<void> => {\n\t\t\tsetError(null)\n\t\t\ttry {\n\t\t\t\tawait client.signIn(params)\n\t\t\t} catch (err: unknown) {\n\t\t\t\tconst message = err instanceof Error ? err.message : String(err)\n\t\t\t\tsetError(message)\n\t\t\t}\n\t\t},\n\t\t[client],\n\t)\n\n\tconst signOut = useCallback(async (): Promise<void> => {\n\t\tsetError(null)\n\t\ttry {\n\t\t\tawait client.signOut()\n\t\t} catch (err: unknown) {\n\t\t\tconst message = err instanceof Error ? err.message : String(err)\n\t\t\tsetError(message)\n\t\t}\n\t}, [client])\n\n\treturn {\n\t\tuser,\n\t\tisAuthenticated: state === 'authenticated',\n\t\tisLoading,\n\t\tsignUp,\n\t\tsignIn,\n\t\tsignOut,\n\t\terror,\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// useCurrentUser\n// ---------------------------------------------------------------------------\n\n/**\n * React hook that returns the currently authenticated user, or null.\n *\n * A lightweight alternative to {@link useAuth} when you only need the user\n * object and do not need auth methods or error state.\n *\n * Must be used within an {@link AuthProvider}.\n *\n * @returns The current AuthUser or null if not authenticated\n *\n * @example\n * ```typescript\n * function UserAvatar() {\n * const user = useCurrentUser()\n * if (!user) return null\n * return <span>{user.name ?? user.email}</span>\n * }\n * ```\n */\nfunction useCurrentUser(): AuthUser | null {\n\tconst { client } = useAuthContext()\n\n\tconst userSnapshotRef = useRef<AuthUser | null>(client.currentUser)\n\tconst stateSerializedRef = useRef<string>(JSON.stringify(client.currentUser))\n\n\tconst subscribe = useCallback(\n\t\t(onStoreChange: () => void): (() => void) => {\n\t\t\treturn client.onAuthChange(() => {\n\t\t\t\tconst newUser = client.currentUser\n\t\t\t\tconst newSerialized = JSON.stringify(newUser)\n\t\t\t\tif (newSerialized !== stateSerializedRef.current) {\n\t\t\t\t\tuserSnapshotRef.current = newUser\n\t\t\t\t\tstateSerializedRef.current = newSerialized\n\t\t\t\t\tonStoreChange()\n\t\t\t\t}\n\t\t\t})\n\t\t},\n\t\t[client],\n\t)\n\n\tconst getSnapshot = useCallback((): AuthUser | null => {\n\t\treturn userSnapshotRef.current\n\t}, [])\n\n\treturn useSyncExternalStore(subscribe, getSnapshot)\n}\n\n// ---------------------------------------------------------------------------\n// useAuthStatus\n// ---------------------------------------------------------------------------\n\n/**\n * React hook that returns the current authentication status.\n *\n * Re-renders only when the auth state changes, not on every auth event.\n * Use this for status indicators, route guards, and conditional rendering.\n *\n * Must be used within an {@link AuthProvider}.\n *\n * @returns An AuthStatus object with state, isAuthenticated, and isLoading flags\n *\n * @example\n * ```typescript\n * function AuthGuard({ children }: { children: React.ReactNode }) {\n * const { isAuthenticated, isLoading } = useAuthStatus()\n * if (isLoading) return <Spinner />\n * if (!isAuthenticated) return <Navigate to=\"/login\" />\n * return <>{children}</>\n * }\n * ```\n */\nfunction useAuthStatus(): AuthStatus {\n\tconst { state, isLoading } = useAuthContext()\n\n\treturn {\n\t\tstate,\n\t\tisAuthenticated: state === 'authenticated',\n\t\tisLoading,\n\t}\n}\n\nexport { useAuth, useCurrentUser, useAuthStatus }\nexport type { UseAuthResult, AuthStatus }\n","import {\n\tcreateContext,\n\tuseCallback,\n\tuseContext,\n\tuseEffect,\n\tuseRef,\n\tuseState,\n\tuseSyncExternalStore,\n} from 'react'\nimport type {\n\tClientInvitation,\n\tClientMembership,\n\tClientOrganization,\n\tOrgClient,\n} from '../client/org-client'\n\n// ============================================================================\n// OrgContext\n// ============================================================================\n\n/**\n * Shape of the OrgContext value.\n */\nexport interface OrgContextValue {\n\t/** The OrgClient instance */\n\tclient: OrgClient\n}\n\n/**\n * React context for organization state.\n */\nexport const OrgContext = createContext<OrgContextValue | null>(null)\n\nfunction useOrgContext(): OrgContextValue {\n\tconst ctx = useContext(OrgContext)\n\tif (ctx === null) {\n\t\tthrow new Error(\n\t\t\t'useOrg / useOrgMembers / usePermission must be used within an <OrgProvider>. ' +\n\t\t\t\t'Wrap your component tree with <OrgProvider client={orgClient}>.',\n\t\t)\n\t}\n\treturn ctx\n}\n\n// ============================================================================\n// useOrg\n// ============================================================================\n\n/**\n * Return value of the {@link useOrg} hook.\n */\nexport interface UseOrgResult {\n\t/** Currently active organization, or null */\n\torg: ClientOrganization | null\n\t/** Current user's role in the active organization, or null */\n\trole: string | null\n\t/** Active organization ID, or null */\n\torgId: string | null\n\t/** Switch to a different organization */\n\tswitchOrg: (orgId: string) => Promise<void>\n\t/** Create a new organization */\n\tcreateOrg: (params: { name: string; slug?: string }) => Promise<ClientOrganization>\n\t/** Leave the active organization */\n\tleaveOrg: () => Promise<void>\n\t/** Clear the active organization */\n\tclearOrg: () => void\n\t/** List all organizations the user belongs to */\n\tlistOrgs: () => Promise<ClientOrganization[]>\n\t/** Last error, or null */\n\terror: string | null\n}\n\n/**\n * React hook for organization management and context switching.\n *\n * Re-renders when the active organization changes.\n *\n * @example\n * ```typescript\n * function OrgSwitcher() {\n * const { org, switchOrg, listOrgs, error } = useOrg()\n * const [orgs, setOrgs] = useState<ClientOrganization[]>([])\n *\n * useEffect(() => { listOrgs().then(setOrgs) }, [listOrgs])\n *\n * return (\n * <select value={org?.id ?? ''} onChange={(e) => switchOrg(e.target.value)}>\n * <option value=\"\">Select org...</option>\n * {orgs.map(o => <option key={o.id} value={o.id}>{o.name}</option>)}\n * </select>\n * )\n * }\n * ```\n */\nexport function useOrg(): UseOrgResult {\n\tconst { client } = useOrgContext()\n\tconst [error, setError] = useState<string | null>(null)\n\n\t// Track active org reactively\n\tconst orgSnapshotRef = useRef({\n\t\torgId: client.activeOrgId,\n\t\torg: client.activeOrg,\n\t\trole: client.activeRole,\n\t})\n\n\tconst subscribe = useCallback(\n\t\t(onStoreChange: () => void): (() => void) => {\n\t\t\treturn client.onOrgChange(() => {\n\t\t\t\torgSnapshotRef.current = {\n\t\t\t\t\torgId: client.activeOrgId,\n\t\t\t\t\torg: client.activeOrg,\n\t\t\t\t\trole: client.activeRole,\n\t\t\t\t}\n\t\t\t\tonStoreChange()\n\t\t\t})\n\t\t},\n\t\t[client],\n\t)\n\n\tconst getSnapshot = useCallback(() => orgSnapshotRef.current, [])\n\n\tconst { orgId, org, role } = useSyncExternalStore(subscribe, getSnapshot)\n\n\tconst switchOrg = useCallback(\n\t\tasync (newOrgId: string): Promise<void> => {\n\t\t\tsetError(null)\n\t\t\ttry {\n\t\t\t\tawait client.switchOrg(newOrgId)\n\t\t\t} catch (err) {\n\t\t\t\tsetError(err instanceof Error ? err.message : String(err))\n\t\t\t}\n\t\t},\n\t\t[client],\n\t)\n\n\tconst createOrg = useCallback(\n\t\tasync (params: { name: string; slug?: string }): Promise<ClientOrganization> => {\n\t\t\tsetError(null)\n\t\t\ttry {\n\t\t\t\treturn await client.createOrg(params)\n\t\t\t} catch (err) {\n\t\t\t\tconst msg = err instanceof Error ? err.message : String(err)\n\t\t\t\tsetError(msg)\n\t\t\t\tthrow err\n\t\t\t}\n\t\t},\n\t\t[client],\n\t)\n\n\tconst leaveOrg = useCallback(async (): Promise<void> => {\n\t\tif (!orgId) return\n\t\tsetError(null)\n\t\ttry {\n\t\t\tawait client.leaveOrg(orgId)\n\t\t} catch (err) {\n\t\t\tsetError(err instanceof Error ? err.message : String(err))\n\t\t}\n\t}, [client, orgId])\n\n\tconst clearOrg = useCallback((): void => {\n\t\tclient.clearActiveOrg()\n\t}, [client])\n\n\tconst listOrgs = useCallback(async (): Promise<ClientOrganization[]> => {\n\t\ttry {\n\t\t\treturn await client.listOrgs()\n\t\t} catch (err) {\n\t\t\tsetError(err instanceof Error ? err.message : String(err))\n\t\t\treturn []\n\t\t}\n\t}, [client])\n\n\treturn { org, role, orgId, switchOrg, createOrg, leaveOrg, clearOrg, listOrgs, error }\n}\n\n// ============================================================================\n// useOrgMembers\n// ============================================================================\n\n/**\n * Return value of the {@link useOrgMembers} hook.\n */\nexport interface UseOrgMembersResult {\n\t/** Members of the organization (empty until loaded) */\n\tmembers: ClientMembership[]\n\t/** Whether members are being loaded */\n\tisLoading: boolean\n\t/** Reload the members list */\n\trefresh: () => Promise<void>\n\t/** Invite a user by email */\n\tinvite: (email: string, role: string) => Promise<ClientInvitation>\n\t/** Remove a member */\n\tremoveMember: (userId: string) => Promise<void>\n\t/** Update a member's role */\n\tupdateRole: (userId: string, role: string) => Promise<void>\n\t/** Last error, or null */\n\terror: string | null\n}\n\n/**\n * React hook for managing organization members.\n *\n * Automatically loads members when the orgId changes.\n *\n * @param orgId - Organization ID to manage members for\n */\nexport function useOrgMembers(orgId: string): UseOrgMembersResult {\n\tconst { client } = useOrgContext()\n\tconst [members, setMembers] = useState<ClientMembership[]>([])\n\tconst [isLoading, setIsLoading] = useState(true)\n\tconst [error, setError] = useState<string | null>(null)\n\n\tconst refresh = useCallback(async () => {\n\t\tsetIsLoading(true)\n\t\tsetError(null)\n\t\ttry {\n\t\t\tconst result = await client.listMembers(orgId)\n\t\t\tsetMembers(result)\n\t\t} catch (err) {\n\t\t\tsetError(err instanceof Error ? err.message : String(err))\n\t\t} finally {\n\t\t\tsetIsLoading(false)\n\t\t}\n\t}, [client, orgId])\n\n\tuseEffect(() => {\n\t\trefresh()\n\t}, [refresh])\n\n\tconst invite = useCallback(\n\t\tasync (email: string, role: string): Promise<ClientInvitation> => {\n\t\t\tsetError(null)\n\t\t\ttry {\n\t\t\t\tconst result = await client.inviteMember(orgId, { email, role })\n\t\t\t\treturn result\n\t\t\t} catch (err) {\n\t\t\t\tconst msg = err instanceof Error ? err.message : String(err)\n\t\t\t\tsetError(msg)\n\t\t\t\tthrow err\n\t\t\t}\n\t\t},\n\t\t[client, orgId],\n\t)\n\n\tconst removeMember = useCallback(\n\t\tasync (userId: string): Promise<void> => {\n\t\t\tsetError(null)\n\t\t\ttry {\n\t\t\t\tawait client.removeMember(orgId, userId)\n\t\t\t\tawait refresh()\n\t\t\t} catch (err) {\n\t\t\t\tsetError(err instanceof Error ? err.message : String(err))\n\t\t\t}\n\t\t},\n\t\t[client, orgId, refresh],\n\t)\n\n\tconst updateRole = useCallback(\n\t\tasync (userId: string, role: string): Promise<void> => {\n\t\t\tsetError(null)\n\t\t\ttry {\n\t\t\t\tawait client.updateMemberRole(orgId, userId, role)\n\t\t\t\tawait refresh()\n\t\t\t} catch (err) {\n\t\t\t\tsetError(err instanceof Error ? err.message : String(err))\n\t\t\t}\n\t\t},\n\t\t[client, orgId, refresh],\n\t)\n\n\treturn { members, isLoading, refresh, invite, removeMember, updateRole, error }\n}\n\n// ============================================================================\n// usePermission\n// ============================================================================\n\n/**\n * React hook that checks if the current user has a specific role level\n * in the active organization.\n *\n * @param requiredRole - Minimum role required (uses ROLE_HIERARCHY from org-types)\n * @returns true if the user's role is at least requiredRole\n *\n * @example\n * ```typescript\n * function AdminPanel() {\n * const canManage = usePermission('admin')\n * if (!canManage) return <p>Access denied</p>\n * return <AdminSettings />\n * }\n * ```\n */\nexport function usePermission(requiredRole: string): boolean {\n\tconst { client } = useOrgContext()\n\n\tconst snapshotRef = useRef(checkPermission(client.activeRole, requiredRole))\n\n\tconst subscribe = useCallback(\n\t\t(onStoreChange: () => void): (() => void) => {\n\t\t\treturn client.onOrgChange(() => {\n\t\t\t\tconst newValue = checkPermission(client.activeRole, requiredRole)\n\t\t\t\tif (newValue !== snapshotRef.current) {\n\t\t\t\t\tsnapshotRef.current = newValue\n\t\t\t\t\tonStoreChange()\n\t\t\t\t}\n\t\t\t})\n\t\t},\n\t\t[client, requiredRole],\n\t)\n\n\tconst getSnapshot = useCallback(() => snapshotRef.current, [])\n\n\treturn useSyncExternalStore(subscribe, getSnapshot)\n}\n\n// Simple role hierarchy check (mirrors ROLE_HIERARCHY from org-types)\nconst ROLE_LEVELS: Record<string, number> = {\n\tviewer: 10,\n\tbilling: 15,\n\tmember: 20,\n\tadmin: 30,\n\towner: 40,\n}\n\nfunction checkPermission(currentRole: string | null, requiredRole: string): boolean {\n\tif (!currentRole) return false\n\tconst currentLevel = ROLE_LEVELS[currentRole] ?? 0\n\tconst requiredLevel = ROLE_LEVELS[requiredRole] ?? 0\n\treturn currentLevel >= requiredLevel\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,gBAAmD;;;ACAnD,mBAA8B;AAiC9B,IAAM,kBAAc,4BAAuC,IAAI;;;ADkB/D,SAAS,aAAa,EAAE,QAAQ,UAAU,SAAS,GAAoC;AACtF,QAAM,CAAC,OAAO,QAAQ,QAAI,wBAAoB,OAAO,KAAK;AAC1D,QAAM,CAAC,WAAW,YAAY,QAAI,wBAAS,IAAI;AAC/C,QAAM,CAAC,WAAW,YAAY,QAAI,wBAAuB,IAAI;AAG7D,+BAAU,MAAM;AACf,QAAI,YAAY;AAGhB,UAAM,cAAc,OAAO,aAAa,CAAC,aAAa;AACrD,UAAI,CAAC,WAAW;AACf,iBAAS,QAAQ;AAAA,MAClB;AAAA,I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,gBAAgB,aAA4B,cAA+B;AACnF,MAAI,CAAC,YAAa,QAAO;AACzB,QAAM,eAAe,YAAY,WAAW,KAAK;AACjD,QAAM,gBAAgB,YAAY,YAAY,KAAK;AACnD,SAAO,gBAAgB;AACxB;","names":["import_react","import_react","import_react"]}
1
+ {"version":3,"sources":["../src/react.ts","../src/react/AuthProvider.tsx","../src/bindings/create-auth-session.ts","../src/react/auth-context.ts","../src/react/hooks.ts","../src/react/OrgProvider.tsx","../src/bindings/create-org-session.ts","../src/react/org-hooks.ts"],"sourcesContent":["// @korajs/auth/react — React-specific public API\n// Every export here is a public API commitment. Be explicit.\n\n// === Provider ===\nexport { AuthProvider } from './react/AuthProvider'\nexport type { AuthProviderProps } from './react/AuthProvider'\n\n// === Hooks ===\nexport { useAuth, useCurrentUser, useAuthStatus } from './react/hooks'\nexport type { UseAuthResult, AuthStatus } from './react/hooks'\n\n// === Context (for advanced use cases) ===\nexport { AuthContext } from './react/auth-context'\nexport type { AuthContextValue } from './react/auth-context'\n\n// === Organization Hooks ===\nexport { OrgProvider } from './react/OrgProvider'\nexport type { OrgProviderProps } from './react/OrgProvider'\nexport { OrgContext, useOrg, useOrgMembers, usePermission, checkOrgPermission } from './react/org-hooks'\nexport type { OrgContextValue, UseOrgResult, UseOrgMembersResult } from './react/org-hooks'\n","import { createElement, useEffect, useMemo, useSyncExternalStore } from 'react'\nimport type { ReactElement, ReactNode } from 'react'\nimport type { AuthClient } from '../client/auth-client'\nimport { createAuthSession } from '../bindings/create-auth-session'\nimport { AuthContext } from './auth-context'\n\ninterface AuthProviderProps {\n\tclient: AuthClient\n\tchildren: ReactNode\n\tfallback?: ReactNode\n}\n\nfunction AuthProvider({ client, children, fallback }: AuthProviderProps): ReactElement {\n\tconst session = useMemo(() => createAuthSession(client), [client])\n\n\tuseEffect(() => () => session.destroy(), [session])\n\n\tconst snapshot = useSyncExternalStore(\n\t\t(onStoreChange) => session.subscribe(onStoreChange),\n\t\t() => session.getSnapshot(),\n\t\t() => session.getSnapshot(),\n\t)\n\n\tif (snapshot.initError) {\n\t\treturn createElement(\n\t\t\t'div',\n\t\t\t{\n\t\t\t\tstyle: { color: 'red', padding: '1rem', fontFamily: 'monospace' },\n\t\t\t\trole: 'alert',\n\t\t\t},\n\t\t\tcreateElement('strong', null, 'Kora Auth initialization error: '),\n\t\t\tsnapshot.initError.message,\n\t\t)\n\t}\n\n\tif (snapshot.isLoading && fallback !== undefined) {\n\t\treturn fallback as ReactElement\n\t}\n\n\tconst contextValue = {\n\t\tclient,\n\t\tsession,\n\t\tstate: snapshot.state,\n\t\tisLoading: snapshot.isLoading,\n\t}\n\n\treturn createElement(AuthContext.Provider, { value: contextValue }, children)\n}\n\nexport { AuthProvider }\nexport type { AuthProviderProps }\n","import type {\n\tAuthClient,\n\tAuthState,\n\tAuthUser,\n\tLinkedOAuthAccount,\n\tOAuthAuthorizationOptions,\n\tOAuthAuthorizationResult,\n\tOAuthCallbackParams,\n} from '../client/auth-client'\n\nexport interface AuthSessionSnapshot {\n\tstate: AuthState\n\tuser: AuthUser | null\n\tisAuthenticated: boolean\n\tisLoading: boolean\n\tinitError: Error | null\n\terror: string | null\n}\n\nexport interface AuthSession {\n\treadonly client: AuthClient\n\tgetSnapshot(): AuthSessionSnapshot\n\tsubscribe(listener: () => void): () => void\n\tsignUp(params: {\n\t\temail: string\n\t\tpassword: string\n\t\tname?: string\n\t\tdeviceId?: string\n\t\tdevicePublicKey?: string\n\t}): Promise<void>\n\tsignIn(params: {\n\t\temail: string\n\t\tpassword: string\n\t\tdeviceId?: string\n\t\tdevicePublicKey?: string\n\t}): Promise<void>\n\tsignInWithOAuth(\n\t\tprovider: string,\n\t\toptions?: OAuthAuthorizationOptions,\n\t): Promise<OAuthAuthorizationResult>\n\tcompleteOAuthSignIn(provider: string, params: OAuthCallbackParams): Promise<void>\n\tgetOAuthAuthorizationUrl(\n\t\tprovider: string,\n\t\toptions?: OAuthAuthorizationOptions,\n\t): Promise<OAuthAuthorizationResult>\n\tlinkOAuth(provider: string, params: OAuthCallbackParams): Promise<LinkedOAuthAccount | null>\n\tlistLinkedAccounts(): Promise<LinkedOAuthAccount[]>\n\tunlinkOAuth(provider: string): Promise<void>\n\tsignOut(): Promise<void>\n\tdestroy(): void\n}\n\n/**\n * Framework-agnostic auth session: initialization, reactive snapshot, and client methods.\n */\nexport function createAuthSession(client: AuthClient): AuthSession {\n\tlet state: AuthState = client.state\n\tlet isLoading = true\n\tlet initError: Error | null = null\n\tlet lastError: string | null = null\n\n\tconst listeners = new Set<() => void>()\n\tlet snapshot = buildSnapshot()\n\n\tconst refreshSnapshot = (): void => {\n\t\tsnapshot = buildSnapshot()\n\t}\n\n\tconst notify = (): void => {\n\t\trefreshSnapshot()\n\t\tfor (const listener of listeners) {\n\t\t\tlistener()\n\t\t}\n\t}\n\n\tfunction buildSnapshot(): AuthSessionSnapshot {\n\t\treturn {\n\t\t\tstate,\n\t\t\tuser: client.currentUser,\n\t\t\tisAuthenticated: state === 'authenticated',\n\t\t\tisLoading,\n\t\t\tinitError,\n\t\t\terror: lastError,\n\t\t}\n\t}\n\n\tconst captureError = (error: unknown): void => {\n\t\tlastError = error instanceof Error ? error.message : String(error)\n\t\tnotify()\n\t}\n\n\tconst run = async (action: () => Promise<void>): Promise<void> => {\n\t\tlastError = null\n\t\ttry {\n\t\t\tawait action()\n\t\t} catch (error) {\n\t\t\tcaptureError(error)\n\t\t}\n\t}\n\n\tconst runWithResult = async <T>(action: () => Promise<T>): Promise<T | null> => {\n\t\tlastError = null\n\t\ttry {\n\t\t\treturn await action()\n\t\t} catch (error) {\n\t\t\tcaptureError(error)\n\t\t\treturn null\n\t\t}\n\t}\n\n\tconst unsubscribeAuth = client.onAuthChange((nextState) => {\n\t\tstate = nextState\n\t\tnotify()\n\t})\n\n\tvoid client\n\t\t.initialize()\n\t\t.then(() => {\n\t\t\tstate = client.state\n\t\t\tisLoading = false\n\t\t\tnotify()\n\t\t})\n\t\t.catch((error: unknown) => {\n\t\t\tinitError = error instanceof Error ? error : new Error(String(error))\n\t\t\tisLoading = false\n\t\t\tnotify()\n\t\t})\n\n\treturn {\n\t\tclient,\n\t\tgetSnapshot: () => snapshot,\n\t\tsubscribe(listener) {\n\t\t\tlisteners.add(listener)\n\t\t\treturn () => {\n\t\t\t\tlisteners.delete(listener)\n\t\t\t}\n\t\t},\n\t\tsignUp: (params) =>\n\t\t\trun(async () => {\n\t\t\t\tawait client.signUp(params)\n\t\t\t}),\n\t\tsignIn: (params) =>\n\t\t\trun(async () => {\n\t\t\t\tawait client.signIn(params)\n\t\t\t}),\n\t\tsignInWithOAuth: async (provider, options) => {\n\t\t\tlastError = null\n\t\t\ttry {\n\t\t\t\treturn await client.signInWithOAuth(provider, options)\n\t\t\t} catch (error) {\n\t\t\t\tcaptureError(error)\n\t\t\t\tthrow error instanceof Error ? error : new Error(String(error))\n\t\t\t}\n\t\t},\n\t\tcompleteOAuthSignIn: (provider, params) =>\n\t\t\trun(async () => {\n\t\t\t\tawait client.completeOAuthSignIn(provider, params)\n\t\t\t}),\n\t\tgetOAuthAuthorizationUrl: async (provider, options) => {\n\t\t\tlastError = null\n\t\t\ttry {\n\t\t\t\treturn await client.getOAuthAuthorizationUrl(provider, options)\n\t\t\t} catch (error) {\n\t\t\t\tcaptureError(error)\n\t\t\t\tthrow error instanceof Error ? error : new Error(String(error))\n\t\t\t}\n\t\t},\n\t\tlinkOAuth: (provider, params) =>\n\t\t\trunWithResult(async () => client.linkOAuth(provider, params)),\n\t\tlistLinkedAccounts: () =>\n\t\t\trunWithResult(async () => client.listLinkedAccounts()).then((value) => value ?? []),\n\t\tunlinkOAuth: (provider) =>\n\t\t\trun(async () => {\n\t\t\t\tawait client.unlinkOAuth(provider)\n\t\t\t}),\n\t\tsignOut: () =>\n\t\t\trun(async () => {\n\t\t\t\tawait client.signOut()\n\t\t\t}),\n\t\tdestroy() {\n\t\t\tunsubscribeAuth()\n\t\t\tlisteners.clear()\n\t\t},\n\t}\n}\n","import { createContext } from 'react'\nimport type { AuthSession } from '../bindings/create-auth-session'\nimport type { AuthClient } from '../client/auth-client'\n\n/**\n * Possible authentication states for the client.\n */\ntype AuthState = 'loading' | 'authenticated' | 'unauthenticated'\n\n/**\n * Shape of the value provided by the AuthContext.\n */\ninterface AuthContextValue {\n\tclient: AuthClient\n\tsession: AuthSession\n\tstate: AuthState\n\tisLoading: boolean\n}\n\n/**\n * React context for Kora authentication.\n */\nconst AuthContext = createContext<AuthContextValue | null>(null)\n\nexport { AuthContext }\nexport type { AuthContextValue, AuthState }\n","import { useContext, useSyncExternalStore } from 'react'\nimport type {\n\tAuthState,\n\tAuthUser,\n\tLinkedOAuthAccount,\n\tOAuthAuthorizationOptions,\n\tOAuthAuthorizationResult,\n\tOAuthCallbackParams,\n} from '../client/auth-client'\nimport { AuthContext } from './auth-context'\n\nfunction useAuthContext() {\n\tconst ctx = useContext(AuthContext)\n\tif (ctx === null) {\n\t\tthrow new Error(\n\t\t\t'useAuth / useCurrentUser / useAuthStatus must be used within an <AuthProvider>. ' +\n\t\t\t\t'Wrap your component tree with <AuthProvider client={authClient}>.',\n\t\t)\n\t}\n\treturn ctx\n}\n\ninterface UseAuthResult {\n\tuser: AuthUser | null\n\tisAuthenticated: boolean\n\tisLoading: boolean\n\tsignUp: (params: {\n\t\temail: string\n\t\tpassword: string\n\t\tname?: string\n\t\tdeviceId?: string\n\t\tdevicePublicKey?: string\n\t}) => Promise<void>\n\tsignIn: (params: {\n\t\temail: string\n\t\tpassword: string\n\t\tdeviceId?: string\n\t\tdevicePublicKey?: string\n\t}) => Promise<void>\n\tsignInWithOAuth: (\n\t\tprovider: string,\n\t\toptions?: OAuthAuthorizationOptions,\n\t) => Promise<OAuthAuthorizationResult>\n\tcompleteOAuthSignIn: (provider: string, params: OAuthCallbackParams) => Promise<void>\n\tgetOAuthAuthorizationUrl: (\n\t\tprovider: string,\n\t\toptions?: OAuthAuthorizationOptions,\n\t) => Promise<OAuthAuthorizationResult>\n\tlinkOAuth: (provider: string, params: OAuthCallbackParams) => Promise<LinkedOAuthAccount | null>\n\tlistLinkedAccounts: () => Promise<LinkedOAuthAccount[]>\n\tunlinkOAuth: (provider: string) => Promise<void>\n\tsignOut: () => Promise<void>\n\terror: string | null\n\tinitError: Error | null\n}\n\ninterface AuthStatus {\n\tstate: AuthState\n\tisAuthenticated: boolean\n\tisLoading: boolean\n}\n\nfunction useAuthSessionSnapshot() {\n\tconst { session } = useAuthContext()\n\n\treturn useSyncExternalStore(\n\t\t(onStoreChange) => session.subscribe(onStoreChange),\n\t\t() => session.getSnapshot(),\n\t\t() => session.getSnapshot(),\n\t)\n}\n\nfunction useAuth(): UseAuthResult {\n\tconst { session } = useAuthContext()\n\tconst snapshot = useAuthSessionSnapshot()\n\n\treturn {\n\t\tuser: snapshot.user,\n\t\tisAuthenticated: snapshot.isAuthenticated,\n\t\tisLoading: snapshot.isLoading,\n\t\terror: snapshot.error,\n\t\tinitError: snapshot.initError,\n\t\tsignUp: (params) => session.signUp(params),\n\t\tsignIn: (params) => session.signIn(params),\n\t\tsignInWithOAuth: (provider, options) => session.signInWithOAuth(provider, options),\n\t\tcompleteOAuthSignIn: (provider, params) => session.completeOAuthSignIn(provider, params),\n\t\tgetOAuthAuthorizationUrl: (provider, options) =>\n\t\t\tsession.getOAuthAuthorizationUrl(provider, options),\n\t\tlinkOAuth: (provider, params) => session.linkOAuth(provider, params),\n\t\tlistLinkedAccounts: () => session.listLinkedAccounts(),\n\t\tunlinkOAuth: (provider) => session.unlinkOAuth(provider),\n\t\tsignOut: () => session.signOut(),\n\t}\n}\n\nfunction useCurrentUser(): AuthUser | null {\n\treturn useAuthSessionSnapshot().user\n}\n\nfunction useAuthStatus(): AuthStatus {\n\tconst snapshot = useAuthSessionSnapshot()\n\treturn {\n\t\tstate: snapshot.state,\n\t\tisAuthenticated: snapshot.isAuthenticated,\n\t\tisLoading: snapshot.isLoading,\n\t}\n}\n\nexport { useAuth, useCurrentUser, useAuthStatus }\nexport type { UseAuthResult, AuthStatus }\n","import { useEffect, useMemo, useRef, type ReactNode } from 'react'\nimport type { OrgClient } from '../client/org-client'\nimport { createOrgSession, type OrgSession } from '../bindings/create-org-session'\nimport { OrgContext, type OrgContextValue } from './org-hooks'\n\nexport interface OrgProviderProps {\n\tclient: OrgClient\n\tchildren?: ReactNode\n}\n\n/**\n * Provides organization context for {@link useOrg}, {@link useOrgMembers}, and {@link usePermission}.\n */\nexport function OrgProvider({ client, children }: OrgProviderProps) {\n\tconst sessionRef = useRef<OrgSession | null>(null)\n\n\tif (sessionRef.current === null || sessionRef.current.client !== client) {\n\t\tsessionRef.current?.destroy()\n\t\tsessionRef.current = createOrgSession(client)\n\t}\n\n\tuseEffect(() => {\n\t\treturn () => {\n\t\t\tsessionRef.current?.destroy()\n\t\t\tsessionRef.current = null\n\t\t}\n\t}, [])\n\n\tconst value = useMemo<OrgContextValue>(\n\t\t() => ({\n\t\t\tclient,\n\t\t\tsession: sessionRef.current!,\n\t\t}),\n\t\t[client],\n\t)\n\n\treturn <OrgContext.Provider value={value}>{children}</OrgContext.Provider>\n}\n\nexport type { OrgContextValue }\n","import type {\n\tClientInvitation,\n\tClientMembership,\n\tClientOrganization,\n\tOrgClient,\n} from '../client/org-client'\n\nexport interface OrgSnapshot {\n\torgId: string | null\n\torg: ClientOrganization | null\n\trole: string | null\n}\n\nexport interface OrgSession {\n\treadonly client: OrgClient\n\tgetSnapshot(): OrgSnapshot\n\tsubscribe(listener: () => void): () => void\n\tcheckPermission(requiredRole: string): boolean\n\tdestroy(): void\n}\n\nconst ROLE_LEVELS: Record<string, number> = {\n\tviewer: 10,\n\tbilling: 15,\n\tmember: 20,\n\tadmin: 30,\n\towner: 40,\n}\n\nexport function checkOrgPermission(currentRole: string | null, requiredRole: string): boolean {\n\tif (!currentRole) return false\n\tconst currentLevel = ROLE_LEVELS[currentRole] ?? 0\n\tconst requiredLevel = ROLE_LEVELS[requiredRole] ?? 0\n\treturn currentLevel >= requiredLevel\n}\n\n/**\n * Framework-agnostic org session with reactive snapshot subscription.\n */\nexport function createOrgSession(client: OrgClient): OrgSession {\n\tlet snapshot = buildSnapshot(client)\n\tconst listeners = new Set<() => void>()\n\n\tconst notify = (): void => {\n\t\tsnapshot = buildSnapshot(client)\n\t\tfor (const listener of listeners) {\n\t\t\tlistener()\n\t\t}\n\t}\n\n\tconst unsubscribeOrgChange = client.onOrgChange(notify)\n\n\treturn {\n\t\tclient,\n\t\tgetSnapshot: () => snapshot,\n\t\tsubscribe(listener: () => void): () => void {\n\t\t\tlisteners.add(listener)\n\t\t\treturn () => {\n\t\t\t\tlisteners.delete(listener)\n\t\t\t}\n\t\t},\n\t\tcheckPermission(requiredRole: string): boolean {\n\t\t\treturn checkOrgPermission(snapshot.role, requiredRole)\n\t\t},\n\t\tdestroy(): void {\n\t\t\tunsubscribeOrgChange()\n\t\t\tlisteners.clear()\n\t\t},\n\t}\n}\n\nfunction buildSnapshot(client: OrgClient): OrgSnapshot {\n\treturn {\n\t\torgId: client.activeOrgId,\n\t\torg: client.activeOrg,\n\t\trole: client.activeRole,\n\t}\n}\n\nexport interface UseOrgMembersActions {\n\trefresh: () => Promise<void>\n\tinvite: (email: string, role: string) => Promise<ClientInvitation>\n\tremoveMember: (userId: string) => Promise<void>\n\tupdateRole: (userId: string, role: string) => Promise<void>\n}\n\n/**\n * Shared org member management actions (loading state remains framework-specific).\n */\nexport function createOrgMembersActions(\n\tclient: OrgClient,\n\torgId: string,\n\tonError: (message: string) => void,\n): UseOrgMembersActions {\n\treturn {\n\t\tasync refresh(): Promise<void> {\n\t\t\tawait client.listMembers(orgId)\n\t\t},\n\t\tasync invite(email: string, role: string): Promise<ClientInvitation> {\n\t\t\ttry {\n\t\t\t\treturn await client.inviteMember(orgId, { email, role })\n\t\t\t} catch (error) {\n\t\t\t\tconst message = error instanceof Error ? error.message : String(error)\n\t\t\t\tonError(message)\n\t\t\t\tthrow error\n\t\t\t}\n\t\t},\n\t\tasync removeMember(userId: string): Promise<void> {\n\t\t\ttry {\n\t\t\t\tawait client.removeMember(orgId, userId)\n\t\t\t} catch (error) {\n\t\t\t\tonError(error instanceof Error ? error.message : String(error))\n\t\t\t}\n\t\t},\n\t\tasync updateRole(userId: string, role: string): Promise<void> {\n\t\t\ttry {\n\t\t\t\tawait client.updateMemberRole(orgId, userId, role)\n\t\t\t} catch (error) {\n\t\t\t\tonError(error instanceof Error ? error.message : String(error))\n\t\t\t}\n\t\t},\n\t}\n}\n\nexport async function loadOrgMembers(\n\tclient: OrgClient,\n\torgId: string,\n): Promise<ClientMembership[]> {\n\treturn client.listMembers(orgId)\n}\n","import {\n\tcreateContext,\n\tuseCallback,\n\tuseContext,\n\tuseEffect,\n\tuseRef,\n\tuseState,\n\tuseSyncExternalStore,\n} from 'react'\nimport type {\n\tClientInvitation,\n\tClientMembership,\n\tClientOrganization,\n\tOrgClient,\n} from '../client/org-client'\nimport {\n\tcheckOrgPermission,\n\tcreateOrgMembersActions,\n\tcreateOrgSession,\n\tloadOrgMembers,\n\ttype OrgSession,\n\ttype OrgSnapshot,\n} from '../bindings/create-org-session'\n\nexport interface OrgContextValue {\n\tclient: OrgClient\n\tsession: OrgSession\n}\n\nexport const OrgContext = createContext<OrgContextValue | null>(null)\n\nfunction useOrgContext(): OrgContextValue {\n\tconst ctx = useContext(OrgContext)\n\tif (ctx === null) {\n\t\tthrow new Error(\n\t\t\t'useOrg / useOrgMembers / usePermission must be used within an <OrgProvider>. ' +\n\t\t\t\t'Wrap your component tree with <OrgProvider client={orgClient}>.',\n\t\t)\n\t}\n\treturn ctx\n}\n\nfunction useOrgSnapshot(session: OrgSession): OrgSnapshot {\n\tconst snapshotRef = useRef(session.getSnapshot())\n\n\tconst subscribe = useCallback(\n\t\t(onStoreChange: () => void): (() => void) => {\n\t\t\treturn session.subscribe(() => {\n\t\t\t\tsnapshotRef.current = session.getSnapshot()\n\t\t\t\tonStoreChange()\n\t\t\t})\n\t\t},\n\t\t[session],\n\t)\n\n\tconst getSnapshot = useCallback(() => snapshotRef.current, [])\n\n\treturn useSyncExternalStore(subscribe, getSnapshot)\n}\n\nexport interface UseOrgResult {\n\torg: ClientOrganization | null\n\trole: string | null\n\torgId: string | null\n\tswitchOrg: (orgId: string) => Promise<void>\n\tcreateOrg: (params: { name: string; slug?: string }) => Promise<ClientOrganization>\n\tleaveOrg: () => Promise<void>\n\tclearOrg: () => void\n\tlistOrgs: () => Promise<ClientOrganization[]>\n\terror: string | null\n}\n\nexport function useOrg(): UseOrgResult {\n\tconst { client, session } = useOrgContext()\n\tconst { orgId, org, role } = useOrgSnapshot(session)\n\tconst [error, setError] = useState<string | null>(null)\n\n\tconst switchOrg = useCallback(\n\t\tasync (newOrgId: string): Promise<void> => {\n\t\t\tsetError(null)\n\t\t\ttry {\n\t\t\t\tawait client.switchOrg(newOrgId)\n\t\t\t} catch (err) {\n\t\t\t\tsetError(err instanceof Error ? err.message : String(err))\n\t\t\t}\n\t\t},\n\t\t[client],\n\t)\n\n\tconst createOrg = useCallback(\n\t\tasync (params: { name: string; slug?: string }): Promise<ClientOrganization> => {\n\t\t\tsetError(null)\n\t\t\ttry {\n\t\t\t\treturn await client.createOrg(params)\n\t\t\t} catch (err) {\n\t\t\t\tconst msg = err instanceof Error ? err.message : String(err)\n\t\t\t\tsetError(msg)\n\t\t\t\tthrow err\n\t\t\t}\n\t\t},\n\t\t[client],\n\t)\n\n\tconst leaveOrg = useCallback(async (): Promise<void> => {\n\t\tif (!orgId) return\n\t\tsetError(null)\n\t\ttry {\n\t\t\tawait client.leaveOrg(orgId)\n\t\t} catch (err) {\n\t\t\tsetError(err instanceof Error ? err.message : String(err))\n\t\t}\n\t}, [client, orgId])\n\n\tconst clearOrg = useCallback((): void => {\n\t\tclient.clearActiveOrg()\n\t}, [client])\n\n\tconst listOrgs = useCallback(async (): Promise<ClientOrganization[]> => {\n\t\ttry {\n\t\t\treturn await client.listOrgs()\n\t\t} catch (err) {\n\t\t\tsetError(err instanceof Error ? err.message : String(err))\n\t\t\treturn []\n\t\t}\n\t}, [client])\n\n\treturn { org, role, orgId, switchOrg, createOrg, leaveOrg, clearOrg, listOrgs, error }\n}\n\nexport interface UseOrgMembersResult {\n\tmembers: ClientMembership[]\n\tisLoading: boolean\n\trefresh: () => Promise<void>\n\tinvite: (email: string, role: string) => Promise<ClientInvitation>\n\tremoveMember: (userId: string) => Promise<void>\n\tupdateRole: (userId: string, role: string) => Promise<void>\n\terror: string | null\n}\n\nexport function useOrgMembers(orgId: string): UseOrgMembersResult {\n\tconst { client } = useOrgContext()\n\tconst [members, setMembers] = useState<ClientMembership[]>([])\n\tconst [isLoading, setIsLoading] = useState(true)\n\tconst [error, setError] = useState<string | null>(null)\n\n\tconst refresh = useCallback(async () => {\n\t\tsetIsLoading(true)\n\t\tsetError(null)\n\t\ttry {\n\t\t\tsetMembers(await loadOrgMembers(client, orgId))\n\t\t} catch (err) {\n\t\t\tsetError(err instanceof Error ? err.message : String(err))\n\t\t} finally {\n\t\t\tsetIsLoading(false)\n\t\t}\n\t}, [client, orgId])\n\n\tuseEffect(() => {\n\t\tvoid refresh()\n\t}, [refresh])\n\n\tconst actions = createOrgMembersActions(client, orgId, setError)\n\n\tconst invite = useCallback(\n\t\tasync (email: string, role: string): Promise<ClientInvitation> => {\n\t\t\tconst result = await actions.invite(email, role)\n\t\t\tawait refresh()\n\t\t\treturn result\n\t\t},\n\t\t[actions, refresh],\n\t)\n\n\tconst removeMember = useCallback(\n\t\tasync (userId: string): Promise<void> => {\n\t\t\tawait actions.removeMember(userId)\n\t\t\tawait refresh()\n\t\t},\n\t\t[actions, refresh],\n\t)\n\n\tconst updateRole = useCallback(\n\t\tasync (userId: string, role: string): Promise<void> => {\n\t\t\tawait actions.updateRole(userId, role)\n\t\t\tawait refresh()\n\t\t},\n\t\t[actions, refresh],\n\t)\n\n\treturn { members, isLoading, refresh, invite, removeMember, updateRole, error }\n}\n\nexport function usePermission(requiredRole: string): boolean {\n\tconst { session } = useOrgContext()\n\tconst snapshotRef = useRef(session.checkPermission(requiredRole))\n\n\tconst subscribe = useCallback(\n\t\t(onStoreChange: () => void): (() => void) => {\n\t\t\treturn session.subscribe(() => {\n\t\t\t\tconst next = session.checkPermission(requiredRole)\n\t\t\t\tif (next !== snapshotRef.current) {\n\t\t\t\t\tsnapshotRef.current = next\n\t\t\t\t\tonStoreChange()\n\t\t\t\t}\n\t\t\t})\n\t\t},\n\t\t[session, requiredRole],\n\t)\n\n\tconst getSnapshot = useCallback(() => snapshotRef.current, [])\n\n\treturn useSyncExternalStore(subscribe, getSnapshot)\n}\n\nexport { checkOrgPermission }\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,gBAAwE;;;ACuDjE,SAAS,kBAAkB,QAAiC;AAClE,MAAI,QAAmB,OAAO;AAC9B,MAAI,YAAY;AAChB,MAAI,YAA0B;AAC9B,MAAI,YAA2B;AAE/B,QAAM,YAAY,oBAAI,IAAgB;AACtC,MAAI,WAAWC,eAAc;AAE7B,QAAM,kBAAkB,MAAY;AACnC,eAAWA,eAAc;AAAA,EAC1B;AAEA,QAAM,SAAS,MAAY;AAC1B,oBAAgB;AAChB,eAAW,YAAY,WAAW;AACjC,eAAS;AAAA,IACV;AAAA,EACD;AAEA,WAASA,iBAAqC;AAC7C,WAAO;AAAA,MACN;AAAA,MACA,MAAM,OAAO;AAAA,MACb,iBAAiB,UAAU;AAAA,MAC3B;AAAA,MACA;AAAA,MACA,OAAO;AAAA,IACR;AAAA,EACD;AAEA,QAAM,eAAe,CAAC,UAAyB;AAC9C,gBAAY,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACjE,WAAO;AAAA,EACR;AAEA,QAAM,MAAM,OAAO,WAA+C;AACjE,gBAAY;AACZ,QAAI;AACH,YAAM,OAAO;AAAA,IACd,SAAS,OAAO;AACf,mBAAa,KAAK;AAAA,IACnB;AAAA,EACD;AAEA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import_react","buildSnapshot","import_react","import_react","import_react"]}
package/dist/react.d.cts CHANGED
@@ -1,294 +1,110 @@
1
1
  import * as react from 'react';
2
2
  import { ReactNode, ReactElement } from 'react';
3
- import { A as AuthClient, c as AuthState$1, d as AuthUser, O as OrgClient, e as ClientMembership, C as ClientInvitation, f as ClientOrganization } from './org-client-BVTLKcIk.cjs';
3
+ import { d as AuthClient, e as AuthState$1, l as AuthUser, O as OAuthAuthorizationOptions, q as OAuthAuthorizationResult, r as OAuthCallbackParams, L as LinkedOAuthAccount, i as AuthSession, s as OrgClient, v as OrgSession, m as ClientMembership, C as ClientInvitation, n as ClientOrganization } from './create-org-session-RsDj9cl4.cjs';
4
+ export { x as checkOrgPermission } from './create-org-session-RsDj9cl4.cjs';
5
+ import * as react_jsx_runtime from 'react/jsx-runtime';
4
6
  import '@korajs/core';
5
7
 
6
- /**
7
- * Props for the AuthProvider component.
8
- */
9
8
  interface AuthProviderProps {
10
- /** The AuthClient instance to provide to child components */
11
9
  client: AuthClient;
12
- /** Child components that will have access to auth context */
13
10
  children: ReactNode;
14
- /**
15
- * Optional fallback content to render while the auth client is initializing.
16
- * If not provided, children are rendered with `isLoading: true` in the context.
17
- */
18
11
  fallback?: ReactNode;
19
12
  }
20
- /**
21
- * React context provider that wraps the AuthClient for use with auth hooks.
22
- *
23
- * Calls `client.initialize()` on mount to restore any existing session from
24
- * stored tokens. Subscribes to auth state changes and re-renders children
25
- * when the state transitions.
26
- *
27
- * Must be placed above any component that uses {@link useAuth},
28
- * {@link useCurrentUser}, or {@link useAuthStatus}.
29
- *
30
- * @param props - Provider props including the AuthClient instance and children
31
- * @returns A React element wrapping children in the AuthContext
32
- *
33
- * @example
34
- * ```typescript
35
- * import { AuthClient } from '@korajs/auth'
36
- * import { AuthProvider } from '@korajs/auth/react'
37
- *
38
- * const authClient = new AuthClient({ serverUrl: 'http://localhost:3001' })
39
- *
40
- * function App() {
41
- * return (
42
- * <AuthProvider client={authClient} fallback={<div>Loading...</div>}>
43
- * <MyApp />
44
- * </AuthProvider>
45
- * )
46
- * }
47
- * ```
48
- */
49
13
  declare function AuthProvider({ client, children, fallback }: AuthProviderProps): ReactElement;
50
14
 
51
- /**
52
- * Return value of the {@link useAuth} hook.
53
- */
54
15
  interface UseAuthResult {
55
- /** Current authenticated user, or null if not signed in */
56
16
  user: AuthUser | null;
57
- /** Whether the user is currently authenticated */
58
17
  isAuthenticated: boolean;
59
- /** Whether the auth client is still initializing (restoring session) */
60
18
  isLoading: boolean;
61
- /** Sign up a new user account */
62
19
  signUp: (params: {
63
20
  email: string;
64
21
  password: string;
65
22
  name?: string;
23
+ deviceId?: string;
24
+ devicePublicKey?: string;
66
25
  }) => Promise<void>;
67
- /** Sign in with email and password */
68
26
  signIn: (params: {
69
27
  email: string;
70
28
  password: string;
29
+ deviceId?: string;
30
+ devicePublicKey?: string;
71
31
  }) => Promise<void>;
72
- /** Sign out the current user */
32
+ signInWithOAuth: (provider: string, options?: OAuthAuthorizationOptions) => Promise<OAuthAuthorizationResult>;
33
+ completeOAuthSignIn: (provider: string, params: OAuthCallbackParams) => Promise<void>;
34
+ getOAuthAuthorizationUrl: (provider: string, options?: OAuthAuthorizationOptions) => Promise<OAuthAuthorizationResult>;
35
+ linkOAuth: (provider: string, params: OAuthCallbackParams) => Promise<LinkedOAuthAccount | null>;
36
+ listLinkedAccounts: () => Promise<LinkedOAuthAccount[]>;
37
+ unlinkOAuth: (provider: string) => Promise<void>;
73
38
  signOut: () => Promise<void>;
74
- /** Last error message from a sign-up, sign-in, or sign-out attempt, or null */
75
39
  error: string | null;
40
+ initError: Error | null;
76
41
  }
77
- /**
78
- * Auth status information returned by {@link useAuthStatus}.
79
- */
80
42
  interface AuthStatus {
81
- /** Current authentication state */
82
43
  state: AuthState$1;
83
- /** Whether the user is currently authenticated */
84
44
  isAuthenticated: boolean;
85
- /** Whether the auth client is still initializing */
86
45
  isLoading: boolean;
87
46
  }
88
- /**
89
- * React hook providing full authentication functionality.
90
- *
91
- * Returns the current user, loading state, error state, and methods for
92
- * sign-up, sign-in, and sign-out. Re-renders when auth state changes.
93
- *
94
- * Must be used within an {@link AuthProvider}.
95
- *
96
- * @returns An object with user info, auth methods, and status flags
97
- *
98
- * @example
99
- * ```typescript
100
- * function LoginPage() {
101
- * const { user, isAuthenticated, isLoading, signIn, error } = useAuth()
102
- *
103
- * if (isLoading) return <div>Loading...</div>
104
- * if (isAuthenticated) return <div>Welcome, {user?.name}</div>
105
- *
106
- * return (
107
- * <form onSubmit={async (e) => {
108
- * e.preventDefault()
109
- * await signIn({ email: 'user@example.com', password: 'secret' })
110
- * }}>
111
- * {error && <p>{error}</p>}
112
- * <button type="submit">Sign In</button>
113
- * </form>
114
- * )
115
- * }
116
- * ```
117
- */
118
47
  declare function useAuth(): UseAuthResult;
119
- /**
120
- * React hook that returns the currently authenticated user, or null.
121
- *
122
- * A lightweight alternative to {@link useAuth} when you only need the user
123
- * object and do not need auth methods or error state.
124
- *
125
- * Must be used within an {@link AuthProvider}.
126
- *
127
- * @returns The current AuthUser or null if not authenticated
128
- *
129
- * @example
130
- * ```typescript
131
- * function UserAvatar() {
132
- * const user = useCurrentUser()
133
- * if (!user) return null
134
- * return <span>{user.name ?? user.email}</span>
135
- * }
136
- * ```
137
- */
138
48
  declare function useCurrentUser(): AuthUser | null;
139
- /**
140
- * React hook that returns the current authentication status.
141
- *
142
- * Re-renders only when the auth state changes, not on every auth event.
143
- * Use this for status indicators, route guards, and conditional rendering.
144
- *
145
- * Must be used within an {@link AuthProvider}.
146
- *
147
- * @returns An AuthStatus object with state, isAuthenticated, and isLoading flags
148
- *
149
- * @example
150
- * ```typescript
151
- * function AuthGuard({ children }: { children: React.ReactNode }) {
152
- * const { isAuthenticated, isLoading } = useAuthStatus()
153
- * if (isLoading) return <Spinner />
154
- * if (!isAuthenticated) return <Navigate to="/login" />
155
- * return <>{children}</>
156
- * }
157
- * ```
158
- */
159
49
  declare function useAuthStatus(): AuthStatus;
160
50
 
161
51
  /**
162
52
  * Possible authentication states for the client.
163
- * - 'loading': Initial state while restoring tokens from storage
164
- * - 'authenticated': User is signed in with a valid session
165
- * - 'unauthenticated': No valid session exists
166
53
  */
167
54
  type AuthState = 'loading' | 'authenticated' | 'unauthenticated';
168
55
  /**
169
56
  * Shape of the value provided by the AuthContext.
170
- * Includes the AuthClient instance, reactive state, and a loading flag.
171
57
  */
172
58
  interface AuthContextValue {
173
- /** The underlying AuthClient instance for direct access */
174
59
  client: AuthClient;
175
- /** Current authentication state */
60
+ session: AuthSession;
176
61
  state: AuthState;
177
- /** Whether the client is still initializing (restoring session from storage) */
178
62
  isLoading: boolean;
179
63
  }
180
64
  /**
181
65
  * React context for Kora authentication.
182
- *
183
- * Provides the AuthClient and reactive auth state to child components.
184
- * Must be provided by an AuthProvider higher in the component tree.
185
- * Defaults to null — hooks that consume this context throw if it is missing.
186
66
  */
187
67
  declare const AuthContext: react.Context<AuthContextValue | null>;
188
68
 
189
- /**
190
- * Shape of the OrgContext value.
191
- */
192
69
  interface OrgContextValue {
193
- /** The OrgClient instance */
194
70
  client: OrgClient;
71
+ session: OrgSession;
195
72
  }
196
- /**
197
- * React context for organization state.
198
- */
199
73
  declare const OrgContext: react.Context<OrgContextValue | null>;
200
- /**
201
- * Return value of the {@link useOrg} hook.
202
- */
203
74
  interface UseOrgResult {
204
- /** Currently active organization, or null */
205
75
  org: ClientOrganization | null;
206
- /** Current user's role in the active organization, or null */
207
76
  role: string | null;
208
- /** Active organization ID, or null */
209
77
  orgId: string | null;
210
- /** Switch to a different organization */
211
78
  switchOrg: (orgId: string) => Promise<void>;
212
- /** Create a new organization */
213
79
  createOrg: (params: {
214
80
  name: string;
215
81
  slug?: string;
216
82
  }) => Promise<ClientOrganization>;
217
- /** Leave the active organization */
218
83
  leaveOrg: () => Promise<void>;
219
- /** Clear the active organization */
220
84
  clearOrg: () => void;
221
- /** List all organizations the user belongs to */
222
85
  listOrgs: () => Promise<ClientOrganization[]>;
223
- /** Last error, or null */
224
86
  error: string | null;
225
87
  }
226
- /**
227
- * React hook for organization management and context switching.
228
- *
229
- * Re-renders when the active organization changes.
230
- *
231
- * @example
232
- * ```typescript
233
- * function OrgSwitcher() {
234
- * const { org, switchOrg, listOrgs, error } = useOrg()
235
- * const [orgs, setOrgs] = useState<ClientOrganization[]>([])
236
- *
237
- * useEffect(() => { listOrgs().then(setOrgs) }, [listOrgs])
238
- *
239
- * return (
240
- * <select value={org?.id ?? ''} onChange={(e) => switchOrg(e.target.value)}>
241
- * <option value="">Select org...</option>
242
- * {orgs.map(o => <option key={o.id} value={o.id}>{o.name}</option>)}
243
- * </select>
244
- * )
245
- * }
246
- * ```
247
- */
248
88
  declare function useOrg(): UseOrgResult;
249
- /**
250
- * Return value of the {@link useOrgMembers} hook.
251
- */
252
89
  interface UseOrgMembersResult {
253
- /** Members of the organization (empty until loaded) */
254
90
  members: ClientMembership[];
255
- /** Whether members are being loaded */
256
91
  isLoading: boolean;
257
- /** Reload the members list */
258
92
  refresh: () => Promise<void>;
259
- /** Invite a user by email */
260
93
  invite: (email: string, role: string) => Promise<ClientInvitation>;
261
- /** Remove a member */
262
94
  removeMember: (userId: string) => Promise<void>;
263
- /** Update a member's role */
264
95
  updateRole: (userId: string, role: string) => Promise<void>;
265
- /** Last error, or null */
266
96
  error: string | null;
267
97
  }
268
- /**
269
- * React hook for managing organization members.
270
- *
271
- * Automatically loads members when the orgId changes.
272
- *
273
- * @param orgId - Organization ID to manage members for
274
- */
275
98
  declare function useOrgMembers(orgId: string): UseOrgMembersResult;
99
+ declare function usePermission(requiredRole: string): boolean;
100
+
101
+ interface OrgProviderProps {
102
+ client: OrgClient;
103
+ children?: ReactNode;
104
+ }
276
105
  /**
277
- * React hook that checks if the current user has a specific role level
278
- * in the active organization.
279
- *
280
- * @param requiredRole - Minimum role required (uses ROLE_HIERARCHY from org-types)
281
- * @returns true if the user's role is at least requiredRole
282
- *
283
- * @example
284
- * ```typescript
285
- * function AdminPanel() {
286
- * const canManage = usePermission('admin')
287
- * if (!canManage) return <p>Access denied</p>
288
- * return <AdminSettings />
289
- * }
290
- * ```
106
+ * Provides organization context for {@link useOrg}, {@link useOrgMembers}, and {@link usePermission}.
291
107
  */
292
- declare function usePermission(requiredRole: string): boolean;
108
+ declare function OrgProvider({ client, children }: OrgProviderProps): react_jsx_runtime.JSX.Element;
293
109
 
294
- export { AuthContext, type AuthContextValue, AuthProvider, type AuthProviderProps, type AuthStatus, OrgContext, type OrgContextValue, type UseAuthResult, type UseOrgMembersResult, type UseOrgResult, useAuth, useAuthStatus, useCurrentUser, useOrg, useOrgMembers, usePermission };
110
+ export { AuthContext, type AuthContextValue, AuthProvider, type AuthProviderProps, type AuthStatus, OrgContext, type OrgContextValue, OrgProvider, type OrgProviderProps, type UseAuthResult, type UseOrgMembersResult, type UseOrgResult, useAuth, useAuthStatus, useCurrentUser, useOrg, useOrgMembers, usePermission };