@korajs/auth 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +156 -0
- package/dist/auth-client-CrDNuh10.d.cts +181 -0
- package/dist/auth-client-CrDNuh10.d.ts +181 -0
- package/dist/chunk-L554ZDPY.js +174 -0
- package/dist/chunk-L554ZDPY.js.map +1 -0
- package/dist/device-identity-DiwdLsUB.d.cts +247 -0
- package/dist/device-identity-DiwdLsUB.d.ts +247 -0
- package/dist/index.cjs +740 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +80 -0
- package/dist/index.d.ts +80 -0
- package/dist/index.js +552 -0
- package/dist/index.js.map +1 -0
- package/dist/react.cjs +206 -0
- package/dist/react.cjs.map +1 -0
- package/dist/react.d.cts +189 -0
- package/dist/react.d.ts +189 -0
- package/dist/react.js +175 -0
- package/dist/react.js.map +1 -0
- package/dist/server.cjs +1040 -0
- package/dist/server.cjs.map +1 -0
- package/dist/server.d.cts +780 -0
- package/dist/server.d.ts +780 -0
- package/dist/server.js +890 -0
- package/dist/server.js.map +1 -0
- package/package.json +74 -0
package/dist/react.cjs
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/react.ts
|
|
21
|
+
var react_exports = {};
|
|
22
|
+
__export(react_exports, {
|
|
23
|
+
AuthContext: () => AuthContext,
|
|
24
|
+
AuthProvider: () => AuthProvider,
|
|
25
|
+
useAuth: () => useAuth,
|
|
26
|
+
useAuthStatus: () => useAuthStatus,
|
|
27
|
+
useCurrentUser: () => useCurrentUser
|
|
28
|
+
});
|
|
29
|
+
module.exports = __toCommonJS(react_exports);
|
|
30
|
+
|
|
31
|
+
// src/react/AuthProvider.tsx
|
|
32
|
+
var import_react2 = require("react");
|
|
33
|
+
|
|
34
|
+
// src/react/auth-context.ts
|
|
35
|
+
var import_react = require("react");
|
|
36
|
+
var AuthContext = (0, import_react.createContext)(null);
|
|
37
|
+
|
|
38
|
+
// src/react/AuthProvider.tsx
|
|
39
|
+
function AuthProvider({ client, children, fallback }) {
|
|
40
|
+
const [state, setState] = (0, import_react2.useState)(client.state);
|
|
41
|
+
const [isLoading, setIsLoading] = (0, import_react2.useState)(true);
|
|
42
|
+
const [initError, setInitError] = (0, import_react2.useState)(null);
|
|
43
|
+
(0, import_react2.useEffect)(() => {
|
|
44
|
+
let cancelled = false;
|
|
45
|
+
const unsubscribe = client.onAuthChange((newState) => {
|
|
46
|
+
if (!cancelled) {
|
|
47
|
+
setState(newState);
|
|
48
|
+
}
|
|
49
|
+
});
|
|
50
|
+
client.initialize().then(() => {
|
|
51
|
+
if (!cancelled) {
|
|
52
|
+
setState(client.state);
|
|
53
|
+
setIsLoading(false);
|
|
54
|
+
}
|
|
55
|
+
}).catch((error) => {
|
|
56
|
+
if (!cancelled) {
|
|
57
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
58
|
+
console.error("[Kora Auth] Initialization failed:", err);
|
|
59
|
+
setInitError(err);
|
|
60
|
+
setIsLoading(false);
|
|
61
|
+
}
|
|
62
|
+
});
|
|
63
|
+
return () => {
|
|
64
|
+
cancelled = true;
|
|
65
|
+
unsubscribe();
|
|
66
|
+
};
|
|
67
|
+
}, [client]);
|
|
68
|
+
if (initError) {
|
|
69
|
+
return (0, import_react2.createElement)(
|
|
70
|
+
"div",
|
|
71
|
+
{
|
|
72
|
+
style: { color: "red", padding: "1rem", fontFamily: "monospace" },
|
|
73
|
+
role: "alert"
|
|
74
|
+
},
|
|
75
|
+
(0, import_react2.createElement)("strong", null, "Kora Auth initialization error: "),
|
|
76
|
+
initError.message
|
|
77
|
+
);
|
|
78
|
+
}
|
|
79
|
+
if (isLoading && fallback !== void 0) {
|
|
80
|
+
return fallback;
|
|
81
|
+
}
|
|
82
|
+
const contextValue = {
|
|
83
|
+
client,
|
|
84
|
+
state,
|
|
85
|
+
isLoading
|
|
86
|
+
};
|
|
87
|
+
return (0, import_react2.createElement)(AuthContext.Provider, { value: contextValue }, children);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// src/react/hooks.ts
|
|
91
|
+
var import_react3 = require("react");
|
|
92
|
+
function useAuthContext() {
|
|
93
|
+
const ctx = (0, import_react3.useContext)(AuthContext);
|
|
94
|
+
if (ctx === null) {
|
|
95
|
+
throw new Error(
|
|
96
|
+
"useAuth / useCurrentUser / useAuthStatus must be used within an <AuthProvider>. Wrap your component tree with <AuthProvider client={authClient}>."
|
|
97
|
+
);
|
|
98
|
+
}
|
|
99
|
+
return ctx;
|
|
100
|
+
}
|
|
101
|
+
function useAuth() {
|
|
102
|
+
const { client, state, isLoading } = useAuthContext();
|
|
103
|
+
const [error, setError] = (0, import_react3.useState)(null);
|
|
104
|
+
const userSnapshotRef = (0, import_react3.useRef)(client.currentUser);
|
|
105
|
+
const stateSerializedRef = (0, import_react3.useRef)(JSON.stringify(client.currentUser));
|
|
106
|
+
const subscribe = (0, import_react3.useCallback)(
|
|
107
|
+
(onStoreChange) => {
|
|
108
|
+
return client.onAuthChange(() => {
|
|
109
|
+
const newUser = client.currentUser;
|
|
110
|
+
const newSerialized = JSON.stringify(newUser);
|
|
111
|
+
if (newSerialized !== stateSerializedRef.current) {
|
|
112
|
+
userSnapshotRef.current = newUser;
|
|
113
|
+
stateSerializedRef.current = newSerialized;
|
|
114
|
+
onStoreChange();
|
|
115
|
+
}
|
|
116
|
+
});
|
|
117
|
+
},
|
|
118
|
+
[client]
|
|
119
|
+
);
|
|
120
|
+
const getSnapshot = (0, import_react3.useCallback)(() => {
|
|
121
|
+
return userSnapshotRef.current;
|
|
122
|
+
}, []);
|
|
123
|
+
const user = (0, import_react3.useSyncExternalStore)(subscribe, getSnapshot);
|
|
124
|
+
const signUp = (0, import_react3.useCallback)(
|
|
125
|
+
async (params) => {
|
|
126
|
+
setError(null);
|
|
127
|
+
try {
|
|
128
|
+
await client.signUp(params);
|
|
129
|
+
} catch (err) {
|
|
130
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
131
|
+
setError(message);
|
|
132
|
+
}
|
|
133
|
+
},
|
|
134
|
+
[client]
|
|
135
|
+
);
|
|
136
|
+
const signIn = (0, import_react3.useCallback)(
|
|
137
|
+
async (params) => {
|
|
138
|
+
setError(null);
|
|
139
|
+
try {
|
|
140
|
+
await client.signIn(params);
|
|
141
|
+
} catch (err) {
|
|
142
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
143
|
+
setError(message);
|
|
144
|
+
}
|
|
145
|
+
},
|
|
146
|
+
[client]
|
|
147
|
+
);
|
|
148
|
+
const signOut = (0, import_react3.useCallback)(async () => {
|
|
149
|
+
setError(null);
|
|
150
|
+
try {
|
|
151
|
+
await client.signOut();
|
|
152
|
+
} catch (err) {
|
|
153
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
154
|
+
setError(message);
|
|
155
|
+
}
|
|
156
|
+
}, [client]);
|
|
157
|
+
return {
|
|
158
|
+
user,
|
|
159
|
+
isAuthenticated: state === "authenticated",
|
|
160
|
+
isLoading,
|
|
161
|
+
signUp,
|
|
162
|
+
signIn,
|
|
163
|
+
signOut,
|
|
164
|
+
error
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
function useCurrentUser() {
|
|
168
|
+
const { client } = useAuthContext();
|
|
169
|
+
const userSnapshotRef = (0, import_react3.useRef)(client.currentUser);
|
|
170
|
+
const stateSerializedRef = (0, import_react3.useRef)(JSON.stringify(client.currentUser));
|
|
171
|
+
const subscribe = (0, import_react3.useCallback)(
|
|
172
|
+
(onStoreChange) => {
|
|
173
|
+
return client.onAuthChange(() => {
|
|
174
|
+
const newUser = client.currentUser;
|
|
175
|
+
const newSerialized = JSON.stringify(newUser);
|
|
176
|
+
if (newSerialized !== stateSerializedRef.current) {
|
|
177
|
+
userSnapshotRef.current = newUser;
|
|
178
|
+
stateSerializedRef.current = newSerialized;
|
|
179
|
+
onStoreChange();
|
|
180
|
+
}
|
|
181
|
+
});
|
|
182
|
+
},
|
|
183
|
+
[client]
|
|
184
|
+
);
|
|
185
|
+
const getSnapshot = (0, import_react3.useCallback)(() => {
|
|
186
|
+
return userSnapshotRef.current;
|
|
187
|
+
}, []);
|
|
188
|
+
return (0, import_react3.useSyncExternalStore)(subscribe, getSnapshot);
|
|
189
|
+
}
|
|
190
|
+
function useAuthStatus() {
|
|
191
|
+
const { state, isLoading } = useAuthContext();
|
|
192
|
+
return {
|
|
193
|
+
state,
|
|
194
|
+
isAuthenticated: state === "authenticated",
|
|
195
|
+
isLoading
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
199
|
+
0 && (module.exports = {
|
|
200
|
+
AuthContext,
|
|
201
|
+
AuthProvider,
|
|
202
|
+
useAuth,
|
|
203
|
+
useAuthStatus,
|
|
204
|
+
useCurrentUser
|
|
205
|
+
});
|
|
206
|
+
//# sourceMappingURL=react.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/react.ts","../src/react/AuthProvider.tsx","../src/react/auth-context.ts","../src/react/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","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 { AuthUser, AuthState } 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(): { client: import('../client/auth-client').AuthClient; state: AuthState; isLoading: boolean } {\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"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,gBAAmD;;;ACAnD,mBAA8B;AAiC9B,IAAM,kBAAc,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 @@
|
|
|
1
|
+
import * as react from 'react';
|
|
2
|
+
import { ReactNode, ReactElement } from 'react';
|
|
3
|
+
import { A as AuthClient, c as AuthState$1, d as AuthUser } from './auth-client-CrDNuh10.cjs';
|
|
4
|
+
import '@korajs/core';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Props for the AuthProvider component.
|
|
8
|
+
*/
|
|
9
|
+
interface AuthProviderProps {
|
|
10
|
+
/** The AuthClient instance to provide to child components */
|
|
11
|
+
client: AuthClient;
|
|
12
|
+
/** Child components that will have access to auth context */
|
|
13
|
+
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
|
+
fallback?: ReactNode;
|
|
19
|
+
}
|
|
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
|
+
declare function AuthProvider({ client, children, fallback }: AuthProviderProps): ReactElement;
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Return value of the {@link useAuth} hook.
|
|
53
|
+
*/
|
|
54
|
+
interface UseAuthResult {
|
|
55
|
+
/** Current authenticated user, or null if not signed in */
|
|
56
|
+
user: AuthUser | null;
|
|
57
|
+
/** Whether the user is currently authenticated */
|
|
58
|
+
isAuthenticated: boolean;
|
|
59
|
+
/** Whether the auth client is still initializing (restoring session) */
|
|
60
|
+
isLoading: boolean;
|
|
61
|
+
/** Sign up a new user account */
|
|
62
|
+
signUp: (params: {
|
|
63
|
+
email: string;
|
|
64
|
+
password: string;
|
|
65
|
+
name?: string;
|
|
66
|
+
}) => Promise<void>;
|
|
67
|
+
/** Sign in with email and password */
|
|
68
|
+
signIn: (params: {
|
|
69
|
+
email: string;
|
|
70
|
+
password: string;
|
|
71
|
+
}) => Promise<void>;
|
|
72
|
+
/** Sign out the current user */
|
|
73
|
+
signOut: () => Promise<void>;
|
|
74
|
+
/** Last error message from a sign-up, sign-in, or sign-out attempt, or null */
|
|
75
|
+
error: string | null;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Auth status information returned by {@link useAuthStatus}.
|
|
79
|
+
*/
|
|
80
|
+
interface AuthStatus {
|
|
81
|
+
/** Current authentication state */
|
|
82
|
+
state: AuthState$1;
|
|
83
|
+
/** Whether the user is currently authenticated */
|
|
84
|
+
isAuthenticated: boolean;
|
|
85
|
+
/** Whether the auth client is still initializing */
|
|
86
|
+
isLoading: boolean;
|
|
87
|
+
}
|
|
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
|
+
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
|
+
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
|
+
declare function useAuthStatus(): AuthStatus;
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* 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
|
+
*/
|
|
167
|
+
type AuthState = 'loading' | 'authenticated' | 'unauthenticated';
|
|
168
|
+
/**
|
|
169
|
+
* Shape of the value provided by the AuthContext.
|
|
170
|
+
* Includes the AuthClient instance, reactive state, and a loading flag.
|
|
171
|
+
*/
|
|
172
|
+
interface AuthContextValue {
|
|
173
|
+
/** The underlying AuthClient instance for direct access */
|
|
174
|
+
client: AuthClient;
|
|
175
|
+
/** Current authentication state */
|
|
176
|
+
state: AuthState;
|
|
177
|
+
/** Whether the client is still initializing (restoring session from storage) */
|
|
178
|
+
isLoading: boolean;
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* 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
|
+
*/
|
|
187
|
+
declare const AuthContext: react.Context<AuthContextValue | null>;
|
|
188
|
+
|
|
189
|
+
export { AuthContext, type AuthContextValue, AuthProvider, type AuthProviderProps, type AuthStatus, type UseAuthResult, useAuth, useAuthStatus, useCurrentUser };
|
package/dist/react.d.ts
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
import * as react from 'react';
|
|
2
|
+
import { ReactNode, ReactElement } from 'react';
|
|
3
|
+
import { A as AuthClient, c as AuthState$1, d as AuthUser } from './auth-client-CrDNuh10.js';
|
|
4
|
+
import '@korajs/core';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Props for the AuthProvider component.
|
|
8
|
+
*/
|
|
9
|
+
interface AuthProviderProps {
|
|
10
|
+
/** The AuthClient instance to provide to child components */
|
|
11
|
+
client: AuthClient;
|
|
12
|
+
/** Child components that will have access to auth context */
|
|
13
|
+
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
|
+
fallback?: ReactNode;
|
|
19
|
+
}
|
|
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
|
+
declare function AuthProvider({ client, children, fallback }: AuthProviderProps): ReactElement;
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Return value of the {@link useAuth} hook.
|
|
53
|
+
*/
|
|
54
|
+
interface UseAuthResult {
|
|
55
|
+
/** Current authenticated user, or null if not signed in */
|
|
56
|
+
user: AuthUser | null;
|
|
57
|
+
/** Whether the user is currently authenticated */
|
|
58
|
+
isAuthenticated: boolean;
|
|
59
|
+
/** Whether the auth client is still initializing (restoring session) */
|
|
60
|
+
isLoading: boolean;
|
|
61
|
+
/** Sign up a new user account */
|
|
62
|
+
signUp: (params: {
|
|
63
|
+
email: string;
|
|
64
|
+
password: string;
|
|
65
|
+
name?: string;
|
|
66
|
+
}) => Promise<void>;
|
|
67
|
+
/** Sign in with email and password */
|
|
68
|
+
signIn: (params: {
|
|
69
|
+
email: string;
|
|
70
|
+
password: string;
|
|
71
|
+
}) => Promise<void>;
|
|
72
|
+
/** Sign out the current user */
|
|
73
|
+
signOut: () => Promise<void>;
|
|
74
|
+
/** Last error message from a sign-up, sign-in, or sign-out attempt, or null */
|
|
75
|
+
error: string | null;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Auth status information returned by {@link useAuthStatus}.
|
|
79
|
+
*/
|
|
80
|
+
interface AuthStatus {
|
|
81
|
+
/** Current authentication state */
|
|
82
|
+
state: AuthState$1;
|
|
83
|
+
/** Whether the user is currently authenticated */
|
|
84
|
+
isAuthenticated: boolean;
|
|
85
|
+
/** Whether the auth client is still initializing */
|
|
86
|
+
isLoading: boolean;
|
|
87
|
+
}
|
|
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
|
+
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
|
+
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
|
+
declare function useAuthStatus(): AuthStatus;
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* 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
|
+
*/
|
|
167
|
+
type AuthState = 'loading' | 'authenticated' | 'unauthenticated';
|
|
168
|
+
/**
|
|
169
|
+
* Shape of the value provided by the AuthContext.
|
|
170
|
+
* Includes the AuthClient instance, reactive state, and a loading flag.
|
|
171
|
+
*/
|
|
172
|
+
interface AuthContextValue {
|
|
173
|
+
/** The underlying AuthClient instance for direct access */
|
|
174
|
+
client: AuthClient;
|
|
175
|
+
/** Current authentication state */
|
|
176
|
+
state: AuthState;
|
|
177
|
+
/** Whether the client is still initializing (restoring session from storage) */
|
|
178
|
+
isLoading: boolean;
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* 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
|
+
*/
|
|
187
|
+
declare const AuthContext: react.Context<AuthContextValue | null>;
|
|
188
|
+
|
|
189
|
+
export { AuthContext, type AuthContextValue, AuthProvider, type AuthProviderProps, type AuthStatus, type UseAuthResult, useAuth, useAuthStatus, useCurrentUser };
|