@o/better-auth-utils 0.16.19

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.
Files changed (37) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +105 -0
  3. package/dist/cjs/createAuthClient.cjs +251 -0
  4. package/dist/cjs/createAuthClient.native.js +279 -0
  5. package/dist/cjs/createAuthClient.native.js.map +1 -0
  6. package/dist/cjs/createAuthClient.test.cjs +88 -0
  7. package/dist/cjs/createAuthClient.test.native.js +105 -0
  8. package/dist/cjs/createAuthClient.test.native.js.map +1 -0
  9. package/dist/cjs/index.cjs +20 -0
  10. package/dist/cjs/index.native.js +23 -0
  11. package/dist/cjs/index.native.js.map +1 -0
  12. package/dist/cjs/server.cjs +106 -0
  13. package/dist/cjs/server.native.js +228 -0
  14. package/dist/cjs/server.native.js.map +1 -0
  15. package/dist/esm/createAuthClient.mjs +226 -0
  16. package/dist/esm/createAuthClient.mjs.map +1 -0
  17. package/dist/esm/createAuthClient.native.js +251 -0
  18. package/dist/esm/createAuthClient.native.js.map +1 -0
  19. package/dist/esm/createAuthClient.test.mjs +89 -0
  20. package/dist/esm/createAuthClient.test.mjs.map +1 -0
  21. package/dist/esm/createAuthClient.test.native.js +103 -0
  22. package/dist/esm/createAuthClient.test.native.js.map +1 -0
  23. package/dist/esm/index.js +2 -0
  24. package/dist/esm/index.js.map +1 -0
  25. package/dist/esm/index.mjs +2 -0
  26. package/dist/esm/index.mjs.map +1 -0
  27. package/dist/esm/index.native.js +2 -0
  28. package/dist/esm/index.native.js.map +1 -0
  29. package/dist/esm/server.mjs +77 -0
  30. package/dist/esm/server.mjs.map +1 -0
  31. package/dist/esm/server.native.js +196 -0
  32. package/dist/esm/server.native.js.map +1 -0
  33. package/package.json +66 -0
  34. package/src/createAuthClient.test.ts +86 -0
  35. package/src/createAuthClient.ts +373 -0
  36. package/src/index.ts +1 -0
  37. package/src/server.ts +150 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 vxrn
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,105 @@
1
+ # @o/better-auth-utils
2
+
3
+ Auth utilities for better-auth with React/React Native support.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ bun add @o/better-auth-utils
9
+ ```
10
+
11
+ ## Client Usage
12
+
13
+ ```typescript
14
+ import { createBetterAuthClient } from '@o/better-auth-utils'
15
+
16
+ const auth = createBetterAuthClient({
17
+ baseURL: 'https://myapp.com',
18
+ plugins: [
19
+ /* better-auth plugins */
20
+ ],
21
+ // transform user object with app-specific fields
22
+ createUser: (user) => ({ ...user, role: user.role as 'admin' | undefined }),
23
+ // optional callbacks
24
+ onAuthStateChange: (state) => console.log('Auth changed:', state),
25
+ onAuthError: (error) => console.error('Auth error:', error),
26
+ })
27
+
28
+ // React hook for auth state
29
+ const { state, user, token } = auth.useAuth()
30
+
31
+ // get current auth state (non-reactive)
32
+ const { loggedIn } = auth.getAuth()
33
+
34
+ // clear all auth (localStorage + cookies)
35
+ auth.clearAllAuth()
36
+
37
+ // clear just localStorage token
38
+ auth.clearAuthClientToken()
39
+ ```
40
+
41
+ ### Client Options
42
+
43
+ | Option | Type | Default | Description |
44
+ | ------------------------- | ---------- | -------------------------------------------------- | ---------------------------------------------- |
45
+ | `baseURL` | `string` | required | Auth server URL |
46
+ | `plugins` | `array` | `[]` | better-auth client plugins |
47
+ | `createUser` | `function` | identity | Transform user object with app-specific typing |
48
+ | `onAuthStateChange` | `function` | - | Callback when auth state changes |
49
+ | `onAuthError` | `function` | - | Callback for auth errors |
50
+ | `storagePrefix` | `string` | `'auth'` | localStorage key prefix |
51
+ | `retryDelay` | `number` | `4000` | Retry delay after errors (ms) |
52
+ | `tokenValidationEndpoint` | `string` | `'/api/auth/validateToken'` | JWT validation endpoint |
53
+ | `authCookieNames` | `string[]` | `['better-auth.jwt', 'better-auth.session_token']` | Cookie names to clear on `clearAllAuth()` |
54
+
55
+ ### Client API
56
+
57
+ - `useAuth()` - React hook returning `{ state, user, session, token }`
58
+ - `getAuth()` - Get current auth state (non-reactive), includes `loggedIn` boolean
59
+ - `setAuthClientToken({ token, session })` - Set auth token and session
60
+ - `clearAuthClientToken()` - Clear localStorage token only
61
+ - `clearAllAuth()` - Clear localStorage AND cookies
62
+ - `clearState()` - Clear all auth state and storage
63
+ - `getValidToken()` - Get valid JWT, refreshing if needed
64
+ - `authState` - Emitter for subscribing to auth changes
65
+ - `authClientVersion` - Emitter that updates when auth client recreates
66
+
67
+ ## Server Usage
68
+
69
+ ```typescript
70
+ import { validateToken, isValidJWT, InvalidTokenError } from '@o/better-auth-utils/server'
71
+
72
+ // validate JWT against JWKS endpoint
73
+ try {
74
+ const payload = await validateToken(token, {
75
+ baseUrl: 'https://myapp.com',
76
+ forceIssuer: process.env.FORCE_ISSUER, // optional, for CI
77
+ jwksPath: '/api/auth/jwks', // optional, default
78
+ })
79
+ console.log('User ID:', payload.sub)
80
+ } catch (err) {
81
+ if (err instanceof InvalidTokenError) {
82
+ // token invalid (malformed, expired, signature mismatch, etc)
83
+ return Response.json({ error: 'INVALID_TOKEN' }, { status: 401 })
84
+ }
85
+ }
86
+
87
+ // simple boolean check
88
+ const valid = await isValidJWT(token, { baseUrl: 'https://myapp.com' })
89
+ ```
90
+
91
+ ### Server Exports
92
+
93
+ | Export | Description |
94
+ | ------------------------------- | ------------------------------------------ |
95
+ | `validateToken(token, options)` | Validate JWT against JWKS, returns payload |
96
+ | `isValidJWT(token, options)` | Boolean validation check |
97
+ | `InvalidTokenError` | Error thrown for invalid tokens |
98
+
99
+ ### JWKS Validation
100
+
101
+ The server validates JWTs against the JWKS endpoint (`/api/auth/jwks` by default). A fresh JWKS is fetched for each validation to avoid stale key cache issues.
102
+
103
+ ## License
104
+
105
+ MIT
@@ -0,0 +1,251 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all) __defProp(target, name, {
7
+ get: all[name],
8
+ enumerable: true
9
+ });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
14
+ get: () => from[key],
15
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
16
+ });
17
+ }
18
+ return to;
19
+ };
20
+ var __toCommonJS = mod => __copyProps(__defProp({}, "__esModule", {
21
+ value: true
22
+ }), mod);
23
+ var createAuthClient_exports = {};
24
+ __export(createAuthClient_exports, {
25
+ createBetterAuthClient: () => createBetterAuthClient
26
+ });
27
+ module.exports = __toCommonJS(createAuthClient_exports);
28
+ var import_helpers = require("@o/helpers");
29
+ var import_client = require("better-auth/client");
30
+ function createBetterAuthClient(options) {
31
+ const {
32
+ onAuthStateChange,
33
+ onAuthError,
34
+ createUser,
35
+ storagePrefix = "auth",
36
+ retryDelay = 4e3,
37
+ useJWT = false,
38
+ authCookieNames = ["better-auth.jwt", "better-auth.session_token"],
39
+ ...authClientOptions
40
+ } = options;
41
+ const empty = {
42
+ state: "logged-out",
43
+ session: null,
44
+ user: null,
45
+ token: null
46
+ };
47
+ const keysStorage = (0, import_helpers.createStorageValue)(`${storagePrefix}-keys`);
48
+ const stateStorage = (0, import_helpers.createStorageValue)(`${storagePrefix}-state`);
49
+ const createAuthClientWithSession = session => {
50
+ return (0, import_client.createAuthClient)({
51
+ ...authClientOptions,
52
+ fetchOptions: {
53
+ credentials: "include",
54
+ headers: session ? {
55
+ Authorization: `Bearer ${session}`
56
+ } : void 0
57
+ }
58
+ });
59
+ };
60
+ let authClient = (() => {
61
+ const existingSession = keysStorage.get()?.session;
62
+ return existingSession ? createAuthClientWithSession(existingSession) : (0, import_client.createAuthClient)({
63
+ ...authClientOptions,
64
+ fetchOptions: {
65
+ credentials: "include"
66
+ }
67
+ });
68
+ })();
69
+ const authState = (0, import_helpers.createEmitter)("authState", stateStorage.get() || empty, {
70
+ comparator: import_helpers.isEqualDeepLite
71
+ });
72
+ const authClientVersion = (0, import_helpers.createEmitter)("authClientVersion", 0);
73
+ const setState = update => {
74
+ const current = authState.value;
75
+ const next = {
76
+ ...current,
77
+ ...update
78
+ };
79
+ stateStorage.set(next);
80
+ authState.emit(next);
81
+ if (next.token && next.session) {
82
+ keysStorage.set({
83
+ token: next.token,
84
+ session: next.session.token
85
+ });
86
+ } else if (next.session) {
87
+ keysStorage.set({
88
+ token: "",
89
+ session: next.session.token
90
+ });
91
+ } else {
92
+ keysStorage.set({
93
+ token: "",
94
+ session: ""
95
+ });
96
+ }
97
+ onAuthStateChange?.(next);
98
+ };
99
+ const setAuthClientToken = async props => {
100
+ keysStorage.set(props);
101
+ updateAuthClient(props.session);
102
+ };
103
+ function updateAuthClient(session) {
104
+ authClient = createAuthClientWithSession(session);
105
+ authClientVersion.emit(Math.random());
106
+ subscribeToAuthEffect();
107
+ }
108
+ let dispose = null;
109
+ let retryTimer = null;
110
+ let consecutiveFailures = 0;
111
+ function subscribeToAuthEffect() {
112
+ dispose?.();
113
+ dispose = authClient.useSession.subscribe(async props => {
114
+ const {
115
+ data: dataGeneric,
116
+ isPending,
117
+ error
118
+ } = props;
119
+ if (error) {
120
+ onAuthError?.(error);
121
+ const hasPersistedSession2 = !!keysStorage.get()?.session;
122
+ if (!hasPersistedSession2) {
123
+ setState({
124
+ state: "logged-out",
125
+ session: null,
126
+ user: null
127
+ });
128
+ }
129
+ consecutiveFailures++;
130
+ scheduleAuthRetry(Math.min(retryDelay * 2 ** (consecutiveFailures - 1), 6e4));
131
+ return;
132
+ }
133
+ consecutiveFailures = 0;
134
+ const data = dataGeneric;
135
+ const hasPersistedSession = !!keysStorage.get()?.session;
136
+ const nextState = isPending ? "loading" : data?.session ? "logged-in" : hasPersistedSession && data === void 0 ? "loading" : "logged-out";
137
+ const sessionUpdate = nextState === "loading" ? {} : {
138
+ session: data?.session ?? null,
139
+ user: data?.user ? createUser ? createUser(data.user) : data.user : null
140
+ };
141
+ const previousSession = authState.value?.session;
142
+ const isNewSession = data?.session && (!previousSession || previousSession.id !== data.session.id || previousSession.userId !== data.session.userId);
143
+ setState({
144
+ state: nextState,
145
+ ...sessionUpdate
146
+ });
147
+ if (useJWT && data?.session && (isNewSession || !authState.value.token)) {
148
+ if (isNewSession && authState.value.token) {
149
+ setState({
150
+ token: null
151
+ });
152
+ }
153
+ getValidToken().then(token => {
154
+ if (token) {
155
+ setState({
156
+ token
157
+ });
158
+ }
159
+ });
160
+ }
161
+ });
162
+ }
163
+ function scheduleAuthRetry(delayMs) {
164
+ if (retryTimer) clearTimeout(retryTimer);
165
+ retryTimer = setTimeout(() => {
166
+ retryTimer = null;
167
+ subscribeToAuthEffect();
168
+ }, delayMs);
169
+ }
170
+ async function getValidToken() {
171
+ const res = await authClient.$fetch("/token");
172
+ if (res.error) {
173
+ console.error(`Error fetching token: ${res.error.statusText}`);
174
+ return void 0;
175
+ }
176
+ return res.data?.token;
177
+ }
178
+ const clearAuthClientToken = () => {
179
+ keysStorage.remove();
180
+ };
181
+ function clearAuthCookies() {
182
+ if (typeof document === "undefined") return;
183
+ for (const cookieName of authCookieNames) {
184
+ document.cookie = `${cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/`;
185
+ const domain = window.location.hostname;
186
+ document.cookie = `${cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; domain=${domain}`;
187
+ if (domain.startsWith(".")) {
188
+ document.cookie = `${cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; domain=${domain.slice(1)}`;
189
+ }
190
+ }
191
+ }
192
+ function clearAllAuth() {
193
+ clearAuthCookies();
194
+ clearState();
195
+ }
196
+ const getAuth = () => {
197
+ const state = authState?.value || empty;
198
+ return {
199
+ ...state,
200
+ loggedIn: !!state.session
201
+ };
202
+ };
203
+ const useAuth = () => {
204
+ return (0, import_helpers.useEmitterValue)(authState) || empty;
205
+ };
206
+ function clearState() {
207
+ keysStorage.remove();
208
+ stateStorage.remove();
209
+ setState(empty);
210
+ }
211
+ subscribeToAuthEffect();
212
+ if (typeof window !== "undefined" && window.addEventListener) {
213
+ const cleanup = () => {
214
+ dispose?.();
215
+ if (retryTimer) clearTimeout(retryTimer);
216
+ };
217
+ window.addEventListener("beforeunload", cleanup);
218
+ }
219
+ const proxiedAuthClient = new Proxy(authClient, {
220
+ get(_target, key) {
221
+ if (key === "signOut") {
222
+ return async () => {
223
+ const result = await authClient.$fetch("/sign-out", {
224
+ method: "POST",
225
+ body: {}
226
+ });
227
+ if (result.error) throw result.error;
228
+ clearState();
229
+ if (typeof window !== "undefined") {
230
+ window.location?.reload?.();
231
+ }
232
+ return result;
233
+ };
234
+ }
235
+ return Reflect.get(authClient, key);
236
+ }
237
+ });
238
+ return {
239
+ authClientVersion,
240
+ clearState,
241
+ authState,
242
+ authClient: proxiedAuthClient,
243
+ setAuthClientToken,
244
+ clearAuthClientToken,
245
+ clearAllAuth,
246
+ useAuth,
247
+ getAuth,
248
+ getValidToken,
249
+ updateAuthClient
250
+ };
251
+ }
@@ -0,0 +1,279 @@
1
+ "use strict";
2
+
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all) __defProp(target, name, {
9
+ get: all[name],
10
+ enumerable: true
11
+ });
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
16
+ get: () => from[key],
17
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
18
+ });
19
+ }
20
+ return to;
21
+ };
22
+ var __toCommonJS = mod => __copyProps(__defProp({}, "__esModule", {
23
+ value: true
24
+ }), mod);
25
+ var createAuthClient_exports = {};
26
+ __export(createAuthClient_exports, {
27
+ createBetterAuthClient: () => createBetterAuthClient
28
+ });
29
+ module.exports = __toCommonJS(createAuthClient_exports);
30
+ var import_helpers = require("@o/helpers");
31
+ var import_client = require("better-auth/client");
32
+ function createBetterAuthClient(options) {
33
+ var {
34
+ onAuthStateChange,
35
+ onAuthError,
36
+ createUser,
37
+ storagePrefix = "auth",
38
+ retryDelay = 4e3,
39
+ useJWT = false,
40
+ authCookieNames = ["better-auth.jwt", "better-auth.session_token"],
41
+ ...authClientOptions
42
+ } = options;
43
+ var empty = {
44
+ state: "logged-out",
45
+ session: null,
46
+ user: null,
47
+ token: null
48
+ };
49
+ var keysStorage = (0, import_helpers.createStorageValue)(`${storagePrefix}-keys`);
50
+ var stateStorage = (0, import_helpers.createStorageValue)(`${storagePrefix}-state`);
51
+ var createAuthClientWithSession = function createAuthClientWithSession2(session) {
52
+ return (0, import_client.createAuthClient)({
53
+ ...authClientOptions,
54
+ fetchOptions: {
55
+ credentials: "include",
56
+ headers: session ? {
57
+ Authorization: `Bearer ${session}`
58
+ } : void 0
59
+ }
60
+ });
61
+ };
62
+ var authClient = function () {
63
+ var _keysStorage_get;
64
+ var existingSession = (_keysStorage_get = keysStorage.get()) === null || _keysStorage_get === void 0 ? void 0 : _keysStorage_get.session;
65
+ return existingSession ? createAuthClientWithSession(existingSession) : (0, import_client.createAuthClient)({
66
+ ...authClientOptions,
67
+ fetchOptions: {
68
+ credentials: "include"
69
+ }
70
+ });
71
+ }();
72
+ var authState = (0, import_helpers.createEmitter)("authState", stateStorage.get() || empty, {
73
+ comparator: import_helpers.isEqualDeepLite
74
+ });
75
+ var authClientVersion = (0, import_helpers.createEmitter)("authClientVersion", 0);
76
+ var setState = function setState2(update) {
77
+ var current = authState.value;
78
+ var next = {
79
+ ...current,
80
+ ...update
81
+ };
82
+ stateStorage.set(next);
83
+ authState.emit(next);
84
+ if (next.token && next.session) {
85
+ keysStorage.set({
86
+ token: next.token,
87
+ session: next.session.token
88
+ });
89
+ } else if (next.session) {
90
+ keysStorage.set({
91
+ token: "",
92
+ session: next.session.token
93
+ });
94
+ } else {
95
+ keysStorage.set({
96
+ token: "",
97
+ session: ""
98
+ });
99
+ }
100
+ onAuthStateChange === null || onAuthStateChange === void 0 ? void 0 : onAuthStateChange(next);
101
+ };
102
+ var setAuthClientToken = async function setAuthClientToken2(props) {
103
+ keysStorage.set(props);
104
+ updateAuthClient(props.session);
105
+ };
106
+ function updateAuthClient(session) {
107
+ authClient = createAuthClientWithSession(session);
108
+ authClientVersion.emit(Math.random());
109
+ subscribeToAuthEffect();
110
+ }
111
+ var dispose = null;
112
+ var retryTimer = null;
113
+ var consecutiveFailures = 0;
114
+ function subscribeToAuthEffect() {
115
+ dispose === null || dispose === void 0 ? void 0 : dispose();
116
+ dispose = authClient.useSession.subscribe(async function (props) {
117
+ var _ref;
118
+ var _keysStorage_get, _authState_value;
119
+ var {
120
+ data: dataGeneric,
121
+ isPending,
122
+ error
123
+ } = props;
124
+ if (error) {
125
+ var _keysStorage_get1;
126
+ onAuthError === null || onAuthError === void 0 ? void 0 : onAuthError(error);
127
+ var hasPersistedSession = !!((_keysStorage_get1 = keysStorage.get()) === null || _keysStorage_get1 === void 0 ? void 0 : _keysStorage_get1.session);
128
+ if (!hasPersistedSession) {
129
+ setState({
130
+ state: "logged-out",
131
+ session: null,
132
+ user: null
133
+ });
134
+ }
135
+ consecutiveFailures++;
136
+ scheduleAuthRetry(Math.min(retryDelay * Math.pow(2, consecutiveFailures - 1), 6e4));
137
+ return;
138
+ }
139
+ consecutiveFailures = 0;
140
+ var data = dataGeneric;
141
+ var hasPersistedSession1 = !!((_keysStorage_get = keysStorage.get()) === null || _keysStorage_get === void 0 ? void 0 : _keysStorage_get.session);
142
+ var nextState = isPending ? "loading" : (data === null || data === void 0 ? void 0 : data.session) ? "logged-in" : hasPersistedSession1 && data === void 0 ? "loading" : "logged-out";
143
+ var sessionUpdate = nextState === "loading" ? {} : {
144
+ session: (_ref = data === null || data === void 0 ? void 0 : data.session) !== null && _ref !== void 0 ? _ref : null,
145
+ user: (data === null || data === void 0 ? void 0 : data.user) ? createUser ? createUser(data.user) : data.user : null
146
+ };
147
+ var previousSession = (_authState_value = authState.value) === null || _authState_value === void 0 ? void 0 : _authState_value.session;
148
+ var isNewSession = (data === null || data === void 0 ? void 0 : data.session) && (!previousSession || previousSession.id !== data.session.id || previousSession.userId !== data.session.userId);
149
+ setState({
150
+ state: nextState,
151
+ ...sessionUpdate
152
+ });
153
+ if (useJWT && (data === null || data === void 0 ? void 0 : data.session) && (isNewSession || !authState.value.token)) {
154
+ if (isNewSession && authState.value.token) {
155
+ setState({
156
+ token: null
157
+ });
158
+ }
159
+ getValidToken().then(function (token) {
160
+ if (token) {
161
+ setState({
162
+ token
163
+ });
164
+ }
165
+ });
166
+ }
167
+ });
168
+ }
169
+ function scheduleAuthRetry(delayMs) {
170
+ if (retryTimer) clearTimeout(retryTimer);
171
+ retryTimer = setTimeout(function () {
172
+ retryTimer = null;
173
+ subscribeToAuthEffect();
174
+ }, delayMs);
175
+ }
176
+ async function getValidToken() {
177
+ var _res_data;
178
+ var res = await authClient.$fetch("/token");
179
+ if (res.error) {
180
+ console.error(`Error fetching token: ${res.error.statusText}`);
181
+ return void 0;
182
+ }
183
+ return (_res_data = res.data) === null || _res_data === void 0 ? void 0 : _res_data.token;
184
+ }
185
+ var clearAuthClientToken = function clearAuthClientToken2() {
186
+ keysStorage.remove();
187
+ };
188
+ function clearAuthCookies() {
189
+ if (typeof document === "undefined") return;
190
+ var _iteratorNormalCompletion = true,
191
+ _didIteratorError = false,
192
+ _iteratorError = void 0;
193
+ try {
194
+ for (var _iterator = authCookieNames[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
195
+ var cookieName = _step.value;
196
+ document.cookie = `${cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/`;
197
+ var domain = window.location.hostname;
198
+ document.cookie = `${cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; domain=${domain}`;
199
+ if (domain.startsWith(".")) {
200
+ document.cookie = `${cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; domain=${domain.slice(1)}`;
201
+ }
202
+ }
203
+ } catch (err) {
204
+ _didIteratorError = true;
205
+ _iteratorError = err;
206
+ } finally {
207
+ try {
208
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
209
+ _iterator.return();
210
+ }
211
+ } finally {
212
+ if (_didIteratorError) {
213
+ throw _iteratorError;
214
+ }
215
+ }
216
+ }
217
+ }
218
+ function clearAllAuth() {
219
+ clearAuthCookies();
220
+ clearState();
221
+ }
222
+ var getAuth = function getAuth2() {
223
+ var state = (authState === null || authState === void 0 ? void 0 : authState.value) || empty;
224
+ return {
225
+ ...state,
226
+ loggedIn: !!state.session
227
+ };
228
+ };
229
+ var useAuth = function useAuth2() {
230
+ return (0, import_helpers.useEmitterValue)(authState) || empty;
231
+ };
232
+ function clearState() {
233
+ keysStorage.remove();
234
+ stateStorage.remove();
235
+ setState(empty);
236
+ }
237
+ subscribeToAuthEffect();
238
+ if (typeof window !== "undefined" && window.addEventListener) {
239
+ var cleanup = function cleanup2() {
240
+ dispose === null || dispose === void 0 ? void 0 : dispose();
241
+ if (retryTimer) clearTimeout(retryTimer);
242
+ };
243
+ window.addEventListener("beforeunload", cleanup);
244
+ }
245
+ var proxiedAuthClient = new Proxy(authClient, {
246
+ get(_target, key) {
247
+ if (key === "signOut") {
248
+ return async function () {
249
+ var result = await authClient.$fetch("/sign-out", {
250
+ method: "POST",
251
+ body: {}
252
+ });
253
+ if (result.error) throw result.error;
254
+ clearState();
255
+ if (typeof window !== "undefined") {
256
+ var _window_location_reload, _window_location;
257
+ (_window_location = window.location) === null || _window_location === void 0 ? void 0 : (_window_location_reload = _window_location.reload) === null || _window_location_reload === void 0 ? void 0 : _window_location_reload.call(_window_location);
258
+ }
259
+ return result;
260
+ };
261
+ }
262
+ return Reflect.get(authClient, key);
263
+ }
264
+ });
265
+ return {
266
+ authClientVersion,
267
+ clearState,
268
+ authState,
269
+ authClient: proxiedAuthClient,
270
+ setAuthClientToken,
271
+ clearAuthClientToken,
272
+ clearAllAuth,
273
+ useAuth,
274
+ getAuth,
275
+ getValidToken,
276
+ updateAuthClient
277
+ };
278
+ }
279
+ //# sourceMappingURL=createAuthClient.native.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"names":["__toCommonJS","mod","__copyProps","__defProp","value","createAuthClient_exports","__export","createBetterAuthClient","module","exports","import_helpers","require","import_client","options","onAuthStateChange","onAuthError","createUser","storagePrefix","retryDelay","useJWT","authCookieNames","authClientOptions","empty","state","session","user","token","keysStorage","createStorageValue","stateStorage","createAuthClientWithSession","createAuthClientWithSession2","createAuthClient","fetchOptions","credentials","headers","Authorization","authClient","_keysStorage_get","existingSession","get","authState","createEmitter","comparator","isEqualDeepLite","authClientVersion","setState","setState2","update","current","next","set","emit","setAuthClientToken","setAuthClientToken2","props","updateAuthClient","Math","random","subscribeToAuthEffect","dispose","retryTimer","consecutiveFailures","hasPersistedSession","useSession","subscribe","_ref","_authState_value","data","dataGeneric","isPending","error","_keysStorage_get1","scheduleAuthRetry","min","pow","hasPersistedSession1","nextState","sessionUpdate","previousSession","isNewSession","id","userId","getValidToken","then","delayMs","clearTimeout","setTimeout","_res_data","res","$fetch","console","statusText","clearAuthClientToken","clearAuthClientToken2","remove","clearAuthCookies","document","_iteratorNormalCompletion","_didIteratorError","_iteratorError","_iterator","Symbol","iterator","_step","done","cookieName","cookie","domain","window","location","hostname","startsWith","slice","err","return","clearAllAuth","clearState","getAuth","getAuth2","loggedIn","useAuth","useAuth2","useEmitterValue","addEventListener","cleanup","cleanup2"],"sources":["../../src/createAuthClient.ts"],"sourcesContent":[null],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA,IAAAA,YAAA,GAAAC,GAAA,IAAAC,WAAA,CAAAC,SAAA;EAAAC,KAAA;AAAA,IAAAH,GAAA;AAAA,IAAAI,wBAAA;AAAAC,QAAA,CAAAD,wBAAA;EAAAE,sBAAA,EAAAA,CAAA,KAAAA;AAAA;AAUAC,MAAA,CAAAC,OAAA,GAAAT,YAMO,CAAAK,wBAAA;AACP,IAAAK,cAAA,GAA+DC,OAAA;AAmFxD,IAAAC,aAAS,GAAAD,OAAA,qBAEsE;AAEpF,SAAMJ,uBAAAM,OAAA;EAAA,IACJ;IAAAC,iBAAA;IAAAC,WAAA;IAAAC,UAAA;IAAAC,aAAA;IAAAC,UAAA;IAAAC,MAAA;IAAAC,eAAA,IACA,mBACA;IACA,GAAAC;EAAgB,IAAAR,OAAA;EAAA,IAChBS,KAAA;IACAC,KAAA,cAAS;IACTC,OAAA;IACAC,IAAG;IACLC,KAAI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