@bymax-one/nest-auth 1.4.22 → 1.5.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/CHANGELOG.md +171 -1
- package/README.md +212 -2
- package/dist/client/index.cjs +117 -113
- package/dist/client/index.d.cts +97 -3
- package/dist/client/index.d.ts +97 -3
- package/dist/client/index.mjs +116 -113
- package/dist/nextjs/index.cjs +303 -330
- package/dist/nextjs/index.d.cts +76 -3
- package/dist/nextjs/index.d.ts +76 -3
- package/dist/nextjs/index.mjs +303 -331
- package/dist/react/index.cjs +378 -191
- package/dist/react/index.d.cts +121 -4
- package/dist/react/index.d.ts +121 -4
- package/dist/react/index.mjs +360 -171
- package/dist/server/index.cjs +6285 -757
- package/dist/server/index.d.cts +3234 -416
- package/dist/server/index.d.ts +3234 -416
- package/dist/server/index.mjs +6273 -759
- package/dist/shared/index.cjs +138 -66
- package/dist/shared/index.d.cts +203 -8
- package/dist/shared/index.d.ts +203 -8
- package/dist/shared/index.mjs +136 -67
- package/package.json +6 -2
package/dist/react/index.mjs
CHANGED
|
@@ -1,10 +1,8 @@
|
|
|
1
|
-
import
|
|
2
|
-
|
|
3
|
-
var __defProp = Object.defineProperty;
|
|
4
|
-
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
5
|
-
var AuthContext = createContext(null);
|
|
1
|
+
import { createContext, useReducer, useRef, useEffect, useCallback, useMemo, useContext, useState } from 'react';
|
|
2
|
+
import { jsx } from 'react/jsx-runtime';
|
|
6
3
|
|
|
7
4
|
// src/react/AuthProvider.tsx
|
|
5
|
+
var AuthContext = createContext(null);
|
|
8
6
|
var DEFAULT_REVALIDATE_INTERVAL_MS = 3e5;
|
|
9
7
|
var HTTP_STATUS_MIN = 100;
|
|
10
8
|
function clientErrorStatus(error) {
|
|
@@ -14,12 +12,10 @@ function clientErrorStatus(error) {
|
|
|
14
12
|
const code = status;
|
|
15
13
|
return code >= HTTP_STATUS_MIN ? code : void 0;
|
|
16
14
|
}
|
|
17
|
-
__name(clientErrorStatus, "clientErrorStatus");
|
|
18
15
|
function isFinalAnswer(error) {
|
|
19
16
|
const status = clientErrorStatus(error);
|
|
20
17
|
return status !== void 0 && status < 500 && status !== 429;
|
|
21
18
|
}
|
|
22
|
-
__name(isFinalAnswer, "isFinalAnswer");
|
|
23
19
|
var INITIAL_STATE = {
|
|
24
20
|
user: null,
|
|
25
21
|
status: "loading",
|
|
@@ -34,30 +30,22 @@ function authReducer(state, action) {
|
|
|
34
30
|
lastValidation: action.payload.timestamp
|
|
35
31
|
};
|
|
36
32
|
case "SET_LOADING":
|
|
37
|
-
return {
|
|
38
|
-
...state,
|
|
39
|
-
status: "loading"
|
|
40
|
-
};
|
|
33
|
+
return { ...state, status: "loading" };
|
|
41
34
|
case "CLEAR_SESSION":
|
|
42
|
-
return {
|
|
43
|
-
user: null,
|
|
44
|
-
status: "unauthenticated",
|
|
45
|
-
lastValidation: null
|
|
46
|
-
};
|
|
35
|
+
return { user: null, status: "unauthenticated", lastValidation: null };
|
|
47
36
|
case "SET_ERROR":
|
|
48
|
-
return {
|
|
49
|
-
user: null,
|
|
50
|
-
status: "unauthenticated",
|
|
51
|
-
lastValidation: state.lastValidation
|
|
52
|
-
};
|
|
37
|
+
return { user: null, status: "unauthenticated", lastValidation: state.lastValidation };
|
|
53
38
|
}
|
|
54
39
|
}
|
|
55
|
-
__name(authReducer, "authReducer");
|
|
56
40
|
function isSessionExpiredError(error) {
|
|
57
41
|
return clientErrorStatus(error) === 401;
|
|
58
42
|
}
|
|
59
|
-
|
|
60
|
-
|
|
43
|
+
function AuthProvider({
|
|
44
|
+
children,
|
|
45
|
+
client,
|
|
46
|
+
onSessionExpired,
|
|
47
|
+
revalidateInterval = DEFAULT_REVALIDATE_INTERVAL_MS
|
|
48
|
+
}) {
|
|
61
49
|
const [state, dispatch] = useReducer(authReducer, INITIAL_STATE);
|
|
62
50
|
const onSessionExpiredRef = useRef(onSessionExpired);
|
|
63
51
|
const clientRef = useRef(client);
|
|
@@ -65,14 +53,10 @@ function AuthProvider({ children, client, onSessionExpired, revalidateInterval =
|
|
|
65
53
|
const sessionGenerationRef = useRef({});
|
|
66
54
|
useEffect(() => {
|
|
67
55
|
onSessionExpiredRef.current = onSessionExpired;
|
|
68
|
-
}, [
|
|
69
|
-
onSessionExpired
|
|
70
|
-
]);
|
|
56
|
+
}, [onSessionExpired]);
|
|
71
57
|
useEffect(() => {
|
|
72
58
|
clientRef.current = client;
|
|
73
|
-
}, [
|
|
74
|
-
client
|
|
75
|
-
]);
|
|
59
|
+
}, [client]);
|
|
76
60
|
const syncedDispatch = useCallback((action) => {
|
|
77
61
|
dispatch(action);
|
|
78
62
|
switch (action.type) {
|
|
@@ -89,46 +73,38 @@ function AuthProvider({ children, client, onSessionExpired, revalidateInterval =
|
|
|
89
73
|
return;
|
|
90
74
|
}
|
|
91
75
|
}, []);
|
|
92
|
-
const revalidate = useCallback(
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
type: "SET_USER",
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
try {
|
|
110
|
-
onSessionExpiredRef.current?.();
|
|
111
|
-
} catch (callbackError) {
|
|
112
|
-
console.warn("[nest-auth] onSessionExpired callback threw:", callbackError);
|
|
76
|
+
const revalidate = useCallback(
|
|
77
|
+
async (isInitial) => {
|
|
78
|
+
const generation = sessionGenerationRef.current;
|
|
79
|
+
try {
|
|
80
|
+
const user = await clientRef.current.getMe();
|
|
81
|
+
if (sessionGenerationRef.current !== generation) return;
|
|
82
|
+
syncedDispatch({ type: "SET_USER", payload: { user, timestamp: /* @__PURE__ */ new Date() } });
|
|
83
|
+
} catch (error) {
|
|
84
|
+
if (sessionGenerationRef.current !== generation) return;
|
|
85
|
+
const wasAuthenticated = statusRef.current === "authenticated";
|
|
86
|
+
if (isSessionExpiredError(error)) {
|
|
87
|
+
if (!isInitial && wasAuthenticated) {
|
|
88
|
+
try {
|
|
89
|
+
onSessionExpiredRef.current?.();
|
|
90
|
+
} catch (callbackError) {
|
|
91
|
+
console.warn("[nest-auth] onSessionExpired callback threw:", callbackError);
|
|
92
|
+
}
|
|
113
93
|
}
|
|
94
|
+
syncedDispatch({ type: "CLEAR_SESSION" });
|
|
95
|
+
return;
|
|
114
96
|
}
|
|
115
|
-
syncedDispatch({
|
|
116
|
-
type: "CLEAR_SESSION"
|
|
117
|
-
});
|
|
118
|
-
return;
|
|
97
|
+
syncedDispatch({ type: "SET_ERROR" });
|
|
119
98
|
}
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
}
|
|
124
|
-
}, [
|
|
125
|
-
syncedDispatch
|
|
126
|
-
]);
|
|
99
|
+
},
|
|
100
|
+
[syncedDispatch]
|
|
101
|
+
);
|
|
127
102
|
useEffect(() => {
|
|
128
103
|
void revalidate(true);
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
104
|
+
return () => {
|
|
105
|
+
sessionGenerationRef.current = {};
|
|
106
|
+
};
|
|
107
|
+
}, [revalidate]);
|
|
132
108
|
useEffect(() => {
|
|
133
109
|
if (revalidateInterval <= 0) {
|
|
134
110
|
return void 0;
|
|
@@ -139,79 +115,50 @@ function AuthProvider({ children, client, onSessionExpired, revalidateInterval =
|
|
|
139
115
|
return () => {
|
|
140
116
|
clearInterval(handle);
|
|
141
117
|
};
|
|
142
|
-
}, [
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
const result = await clientRef.current.login({
|
|
152
|
-
email,
|
|
153
|
-
password,
|
|
154
|
-
...options?.tenantId !== void 0 ? {
|
|
155
|
-
tenantId: options.tenantId
|
|
156
|
-
} : {}
|
|
157
|
-
});
|
|
158
|
-
if ("mfaRequired" in result) {
|
|
159
|
-
sessionGenerationRef.current = {};
|
|
160
|
-
syncedDispatch({
|
|
161
|
-
type: "CLEAR_SESSION"
|
|
118
|
+
}, [revalidate, revalidateInterval]);
|
|
119
|
+
const login = useCallback(
|
|
120
|
+
async (email, password, options) => {
|
|
121
|
+
syncedDispatch({ type: "SET_LOADING" });
|
|
122
|
+
try {
|
|
123
|
+
const result = await clientRef.current.login({
|
|
124
|
+
email,
|
|
125
|
+
password,
|
|
126
|
+
...options?.tenantId !== void 0 ? { tenantId: options.tenantId } : {}
|
|
162
127
|
});
|
|
128
|
+
if ("mfaRequired" in result) {
|
|
129
|
+
sessionGenerationRef.current = {};
|
|
130
|
+
syncedDispatch({ type: "CLEAR_SESSION" });
|
|
131
|
+
return result;
|
|
132
|
+
}
|
|
133
|
+
sessionGenerationRef.current = {};
|
|
134
|
+
syncedDispatch({ type: "SET_USER", payload: { user: result.user, timestamp: /* @__PURE__ */ new Date() } });
|
|
163
135
|
return result;
|
|
136
|
+
} catch (error) {
|
|
137
|
+
syncedDispatch({ type: "SET_ERROR" });
|
|
138
|
+
throw error;
|
|
164
139
|
}
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
syncedDispatch
|
|
182
|
-
|
|
183
|
-
const register = useCallback(async (data) => {
|
|
184
|
-
syncedDispatch({
|
|
185
|
-
type: "SET_LOADING"
|
|
186
|
-
});
|
|
187
|
-
try {
|
|
188
|
-
const result = await clientRef.current.register(data);
|
|
189
|
-
sessionGenerationRef.current = {};
|
|
190
|
-
syncedDispatch({
|
|
191
|
-
type: "SET_USER",
|
|
192
|
-
payload: {
|
|
193
|
-
user: result.user,
|
|
194
|
-
timestamp: /* @__PURE__ */ new Date()
|
|
195
|
-
}
|
|
196
|
-
});
|
|
197
|
-
return result;
|
|
198
|
-
} catch (error) {
|
|
199
|
-
syncedDispatch({
|
|
200
|
-
type: "SET_ERROR"
|
|
201
|
-
});
|
|
202
|
-
throw error;
|
|
203
|
-
}
|
|
204
|
-
}, [
|
|
205
|
-
syncedDispatch
|
|
206
|
-
]);
|
|
140
|
+
},
|
|
141
|
+
[syncedDispatch]
|
|
142
|
+
);
|
|
143
|
+
const register = useCallback(
|
|
144
|
+
async (data) => {
|
|
145
|
+
syncedDispatch({ type: "SET_LOADING" });
|
|
146
|
+
try {
|
|
147
|
+
const result = await clientRef.current.register(data);
|
|
148
|
+
sessionGenerationRef.current = {};
|
|
149
|
+
syncedDispatch({ type: "SET_USER", payload: { user: result.user, timestamp: /* @__PURE__ */ new Date() } });
|
|
150
|
+
return result;
|
|
151
|
+
} catch (error) {
|
|
152
|
+
syncedDispatch({ type: "SET_ERROR" });
|
|
153
|
+
throw error;
|
|
154
|
+
}
|
|
155
|
+
},
|
|
156
|
+
[syncedDispatch]
|
|
157
|
+
);
|
|
207
158
|
const clearSession = useCallback(() => {
|
|
208
159
|
sessionGenerationRef.current = {};
|
|
209
|
-
syncedDispatch({
|
|
210
|
-
|
|
211
|
-
});
|
|
212
|
-
}, [
|
|
213
|
-
syncedDispatch
|
|
214
|
-
]);
|
|
160
|
+
syncedDispatch({ type: "CLEAR_SESSION" });
|
|
161
|
+
}, [syncedDispatch]);
|
|
215
162
|
const logout = useCallback(async () => {
|
|
216
163
|
try {
|
|
217
164
|
await clientRef.current.logout();
|
|
@@ -221,14 +168,10 @@ function AuthProvider({ children, client, onSessionExpired, revalidateInterval =
|
|
|
221
168
|
throw error;
|
|
222
169
|
}
|
|
223
170
|
clearSession();
|
|
224
|
-
}, [
|
|
225
|
-
clearSession
|
|
226
|
-
]);
|
|
171
|
+
}, [clearSession]);
|
|
227
172
|
const refresh = useCallback(async () => {
|
|
228
173
|
await revalidate(false);
|
|
229
|
-
}, [
|
|
230
|
-
revalidate
|
|
231
|
-
]);
|
|
174
|
+
}, [revalidate]);
|
|
232
175
|
const forgotPassword = useCallback(
|
|
233
176
|
async (email, tenantId) => {
|
|
234
177
|
await clientRef.current.forgotPassword(email, tenantId);
|
|
@@ -243,37 +186,39 @@ function AuthProvider({ children, client, onSessionExpired, revalidateInterval =
|
|
|
243
186
|
// Stryker disable next-line ArrayDeclaration: empty deps array with only stable references in scope; a constant-string array re-runs identically
|
|
244
187
|
[]
|
|
245
188
|
);
|
|
246
|
-
const value = useMemo(
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
189
|
+
const value = useMemo(
|
|
190
|
+
() => ({
|
|
191
|
+
user: state.user,
|
|
192
|
+
status: state.status,
|
|
193
|
+
isLoading: state.status === "loading",
|
|
194
|
+
lastValidation: state.lastValidation,
|
|
195
|
+
login,
|
|
196
|
+
register,
|
|
197
|
+
logout,
|
|
198
|
+
refresh,
|
|
199
|
+
forgotPassword,
|
|
200
|
+
resetPassword
|
|
201
|
+
}),
|
|
202
|
+
[
|
|
203
|
+
state.user,
|
|
204
|
+
state.status,
|
|
205
|
+
state.lastValidation,
|
|
206
|
+
login,
|
|
207
|
+
register,
|
|
208
|
+
logout,
|
|
209
|
+
refresh,
|
|
210
|
+
forgotPassword,
|
|
211
|
+
resetPassword
|
|
212
|
+
]
|
|
213
|
+
);
|
|
214
|
+
return /* @__PURE__ */ jsx(AuthContext.Provider, { value, children });
|
|
271
215
|
}
|
|
272
|
-
__name(AuthProvider, "AuthProvider");
|
|
273
216
|
function useSession() {
|
|
274
217
|
const ctx = useContext(AuthContext);
|
|
275
218
|
if (ctx === null) {
|
|
276
|
-
throw new Error(
|
|
219
|
+
throw new Error(
|
|
220
|
+
"useSession must be called within an <AuthProvider> \u2014 wrap the consuming tree in a provider built from createAuthClient()."
|
|
221
|
+
);
|
|
277
222
|
}
|
|
278
223
|
return {
|
|
279
224
|
user: ctx.user,
|
|
@@ -283,11 +228,12 @@ function useSession() {
|
|
|
283
228
|
lastValidation: ctx.lastValidation
|
|
284
229
|
};
|
|
285
230
|
}
|
|
286
|
-
__name(useSession, "useSession");
|
|
287
231
|
function useAuth() {
|
|
288
232
|
const ctx = useContext(AuthContext);
|
|
289
233
|
if (ctx === null) {
|
|
290
|
-
throw new Error(
|
|
234
|
+
throw new Error(
|
|
235
|
+
"useAuth must be called within an <AuthProvider> \u2014 wrap the consuming tree in a provider built from createAuthClient()."
|
|
236
|
+
);
|
|
291
237
|
}
|
|
292
238
|
return {
|
|
293
239
|
login: ctx.login,
|
|
@@ -297,7 +243,6 @@ function useAuth() {
|
|
|
297
243
|
resetPassword: ctx.resetPassword
|
|
298
244
|
};
|
|
299
245
|
}
|
|
300
|
-
__name(useAuth, "useAuth");
|
|
301
246
|
|
|
302
247
|
// src/react/useAuthStatus.ts
|
|
303
248
|
function useAuthStatus() {
|
|
@@ -307,6 +252,250 @@ function useAuthStatus() {
|
|
|
307
252
|
isLoading
|
|
308
253
|
};
|
|
309
254
|
}
|
|
310
|
-
|
|
255
|
+
var WorkspacesContext = createContext(null);
|
|
256
|
+
var CHANNEL_NAME = "nest-auth:workspaces";
|
|
257
|
+
var MAX_PAGES = 20;
|
|
258
|
+
var REFUSAL_CODES = /* @__PURE__ */ new Set([
|
|
259
|
+
"auth.workspace_not_found",
|
|
260
|
+
"auth.insufficient_workspace_role",
|
|
261
|
+
"auth.workspace_pending_deletion"
|
|
262
|
+
]);
|
|
263
|
+
var IDLE = {
|
|
264
|
+
owner: null,
|
|
265
|
+
status: "idle",
|
|
266
|
+
items: [],
|
|
267
|
+
lastActiveWorkspaceId: null,
|
|
268
|
+
chosen: null
|
|
269
|
+
};
|
|
270
|
+
var loadingFor = (owner) => ({ ...IDLE, owner, status: "loading" });
|
|
271
|
+
async function loadAll(client, signal) {
|
|
272
|
+
const items = [];
|
|
273
|
+
let lastActiveWorkspaceId = null;
|
|
274
|
+
let cursor;
|
|
275
|
+
for (let page = 0; page < MAX_PAGES; page += 1) {
|
|
276
|
+
const result = await client.listWorkspaces(cursor === void 0 ? void 0 : { cursor }, {
|
|
277
|
+
signal
|
|
278
|
+
});
|
|
279
|
+
if (signal.aborted) break;
|
|
280
|
+
if (page === 0) lastActiveWorkspaceId = result.lastActiveWorkspaceId;
|
|
281
|
+
items.push(...result.items);
|
|
282
|
+
if (result.nextCursor === null) break;
|
|
283
|
+
cursor = result.nextCursor;
|
|
284
|
+
}
|
|
285
|
+
return { items, lastActiveWorkspaceId };
|
|
286
|
+
}
|
|
287
|
+
function refusalCodeOf(error) {
|
|
288
|
+
if (typeof error !== "object" || error === null) return void 0;
|
|
289
|
+
const { name, code } = error;
|
|
290
|
+
if (name !== "AuthClientError" || typeof code !== "string") return void 0;
|
|
291
|
+
return REFUSAL_CODES.has(code) ? code : void 0;
|
|
292
|
+
}
|
|
293
|
+
function callHost(name, run) {
|
|
294
|
+
try {
|
|
295
|
+
run?.();
|
|
296
|
+
} catch (error) {
|
|
297
|
+
console.warn(`[nest-auth] ${name} callback threw:`, error);
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
function useReload(clientRef, statusRef, identityRef, setLoaded, controllerRef) {
|
|
301
|
+
return useCallback(async () => {
|
|
302
|
+
const owner = identityRef.current;
|
|
303
|
+
if (statusRef.current !== "authenticated") return;
|
|
304
|
+
controllerRef.current?.abort();
|
|
305
|
+
const controller = new AbortController();
|
|
306
|
+
controllerRef.current = controller;
|
|
307
|
+
try {
|
|
308
|
+
const result = await loadAll(clientRef.current, controller.signal);
|
|
309
|
+
if (!controller.signal.aborted) {
|
|
310
|
+
setLoaded((current) => ({
|
|
311
|
+
...result,
|
|
312
|
+
owner,
|
|
313
|
+
status: "ready",
|
|
314
|
+
chosen: current.chosen
|
|
315
|
+
}));
|
|
316
|
+
}
|
|
317
|
+
} catch {
|
|
318
|
+
if (!controller.signal.aborted) {
|
|
319
|
+
setLoaded((current) => ({
|
|
320
|
+
...IDLE,
|
|
321
|
+
owner,
|
|
322
|
+
status: "error",
|
|
323
|
+
chosen: current.chosen
|
|
324
|
+
}));
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
}, [clientRef, statusRef, identityRef, setLoaded, controllerRef]);
|
|
328
|
+
}
|
|
329
|
+
function useWorkspaceList(client, authStatus, identity) {
|
|
330
|
+
const [stored, setLoaded] = useState(IDLE);
|
|
331
|
+
const clientRef = useRef(client);
|
|
332
|
+
const statusRef = useRef(authStatus);
|
|
333
|
+
const identityRef = useRef(identity);
|
|
334
|
+
const controllerRef = useRef(null);
|
|
335
|
+
useEffect(() => {
|
|
336
|
+
clientRef.current = client;
|
|
337
|
+
statusRef.current = authStatus;
|
|
338
|
+
identityRef.current = identity;
|
|
339
|
+
});
|
|
340
|
+
const refresh = useReload(clientRef, statusRef, identityRef, setLoaded, controllerRef);
|
|
341
|
+
useEffect(() => {
|
|
342
|
+
if (authStatus === "authenticated" && identity !== null) {
|
|
343
|
+
setLoaded(
|
|
344
|
+
(current) => current.owner === identity && current.status === "ready" ? current : loadingFor(identity)
|
|
345
|
+
);
|
|
346
|
+
void refresh();
|
|
347
|
+
} else if (authStatus === "unauthenticated") {
|
|
348
|
+
setLoaded(IDLE);
|
|
349
|
+
}
|
|
350
|
+
return () => {
|
|
351
|
+
controllerRef.current?.abort();
|
|
352
|
+
};
|
|
353
|
+
}, [authStatus, identity, refresh]);
|
|
354
|
+
const loaded = stored.owner === identity ? stored : identity === null ? IDLE : loadingFor(identity);
|
|
355
|
+
return { loaded, setLoaded, clientRef, identityRef, refresh };
|
|
356
|
+
}
|
|
357
|
+
function useChangeNotice(status, active, optionsRef) {
|
|
358
|
+
const previousRef = useRef(
|
|
359
|
+
null
|
|
360
|
+
);
|
|
361
|
+
useEffect(() => {
|
|
362
|
+
if (status === "loading") previousRef.current = null;
|
|
363
|
+
if (status !== "ready") return;
|
|
364
|
+
const previous = previousRef.current;
|
|
365
|
+
previousRef.current = { id: active?.workspace.id ?? null, value: active };
|
|
366
|
+
if (previous === null || previous.id === (active?.workspace.id ?? null)) return;
|
|
367
|
+
callHost(
|
|
368
|
+
"onWorkspaceChanged",
|
|
369
|
+
() => optionsRef.current.onWorkspaceChanged?.(previous.value, active)
|
|
370
|
+
);
|
|
371
|
+
}, [status, active, optionsRef]);
|
|
372
|
+
}
|
|
373
|
+
function useWorkspaceChannel(refresh) {
|
|
374
|
+
const channelRef = useRef(null);
|
|
375
|
+
useEffect(() => {
|
|
376
|
+
if (typeof BroadcastChannel === "undefined") return void 0;
|
|
377
|
+
const channel = new BroadcastChannel(CHANNEL_NAME);
|
|
378
|
+
channel.onmessage = () => {
|
|
379
|
+
void refresh();
|
|
380
|
+
};
|
|
381
|
+
channelRef.current = channel;
|
|
382
|
+
return () => {
|
|
383
|
+
channelRef.current = null;
|
|
384
|
+
channel.close();
|
|
385
|
+
};
|
|
386
|
+
}, [refresh]);
|
|
387
|
+
return channelRef;
|
|
388
|
+
}
|
|
389
|
+
function useRoleHint(active, items, optionsRef) {
|
|
390
|
+
return useCallback(
|
|
391
|
+
(role, workspaceId) => {
|
|
392
|
+
const target = workspaceId === void 0 ? active : items.find((item) => item.workspace.id === workspaceId) ?? null;
|
|
393
|
+
if (target === null) return false;
|
|
394
|
+
if (target.role === role) return true;
|
|
395
|
+
const included = Object.entries(optionsRef.current.hierarchy ?? {});
|
|
396
|
+
return included.some(([held, covers]) => held === target.role && covers.includes(role));
|
|
397
|
+
},
|
|
398
|
+
[active, items, optionsRef]
|
|
399
|
+
);
|
|
400
|
+
}
|
|
401
|
+
function useRefusalHandler(activeId, optionsRef, refresh) {
|
|
402
|
+
return useCallback(
|
|
403
|
+
(workspaceId, error) => {
|
|
404
|
+
const code = refusalCodeOf(error);
|
|
405
|
+
if (code === void 0) return false;
|
|
406
|
+
if (workspaceId !== activeId) return true;
|
|
407
|
+
callHost(
|
|
408
|
+
"onWorkspaceAccessLost",
|
|
409
|
+
() => optionsRef.current.onWorkspaceAccessLost?.(workspaceId, code)
|
|
410
|
+
);
|
|
411
|
+
void refresh();
|
|
412
|
+
return true;
|
|
413
|
+
},
|
|
414
|
+
[activeId, optionsRef, refresh]
|
|
415
|
+
);
|
|
416
|
+
}
|
|
417
|
+
function useSwitch(clientRef, identityRef, setLoaded, channelRef) {
|
|
418
|
+
return useCallback(
|
|
419
|
+
async (workspaceId) => {
|
|
420
|
+
const owner = identityRef.current;
|
|
421
|
+
await clientRef.current.switchWorkspace(workspaceId);
|
|
422
|
+
if (identityRef.current !== owner) return;
|
|
423
|
+
setLoaded((current) => ({
|
|
424
|
+
...current,
|
|
425
|
+
chosen: workspaceId,
|
|
426
|
+
lastActiveWorkspaceId: workspaceId
|
|
427
|
+
}));
|
|
428
|
+
channelRef.current?.postMessage({ type: "workspaces-changed" });
|
|
429
|
+
},
|
|
430
|
+
// Stryker disable next-line ArrayDeclaration: refs and a state setter are stable references, so `[]` re-creates the callback exactly as often
|
|
431
|
+
[clientRef, identityRef, setLoaded, channelRef]
|
|
432
|
+
);
|
|
433
|
+
}
|
|
434
|
+
function WorkspaceProvider({
|
|
435
|
+
client,
|
|
436
|
+
children,
|
|
437
|
+
...options
|
|
438
|
+
}) {
|
|
439
|
+
const ctx = useContext(AuthContext);
|
|
440
|
+
if (ctx === null) {
|
|
441
|
+
throw new Error(
|
|
442
|
+
"WorkspaceProvider must be rendered within an <AuthProvider> \u2014 it follows the session the provider owns."
|
|
443
|
+
);
|
|
444
|
+
}
|
|
445
|
+
const optionsRef = useRef(options);
|
|
446
|
+
useEffect(() => {
|
|
447
|
+
optionsRef.current = options;
|
|
448
|
+
});
|
|
449
|
+
const identity = ctx.user === null ? null : JSON.stringify([ctx.user.tenantId, ctx.user.id]);
|
|
450
|
+
const { loaded, setLoaded, clientRef, identityRef, refresh } = useWorkspaceList(
|
|
451
|
+
client,
|
|
452
|
+
ctx.status,
|
|
453
|
+
identity
|
|
454
|
+
);
|
|
455
|
+
const activeId = options.activeWorkspaceId ?? loaded.chosen ?? loaded.lastActiveWorkspaceId;
|
|
456
|
+
const activeWorkspace = useMemo(
|
|
457
|
+
() => loaded.items.find((item) => item.workspace.id === activeId) ?? null,
|
|
458
|
+
[loaded.items, activeId]
|
|
459
|
+
);
|
|
460
|
+
useChangeNotice(loaded.status, activeWorkspace, optionsRef);
|
|
461
|
+
const channelRef = useWorkspaceChannel(refresh);
|
|
462
|
+
const hasWorkspaceRole = useRoleHint(activeWorkspace, loaded.items, optionsRef);
|
|
463
|
+
const handleWorkspaceError = useRefusalHandler(activeId, optionsRef, refresh);
|
|
464
|
+
const switchWorkspace = useSwitch(clientRef, identityRef, setLoaded, channelRef);
|
|
465
|
+
const value = useMemo(
|
|
466
|
+
() => ({
|
|
467
|
+
memberships: loaded.items,
|
|
468
|
+
activeWorkspace,
|
|
469
|
+
lastActiveWorkspaceId: loaded.lastActiveWorkspaceId,
|
|
470
|
+
status: loaded.status,
|
|
471
|
+
switchWorkspace,
|
|
472
|
+
hasWorkspaceRole,
|
|
473
|
+
handleWorkspaceError,
|
|
474
|
+
refresh
|
|
475
|
+
}),
|
|
476
|
+
[loaded, activeWorkspace, switchWorkspace, hasWorkspaceRole, handleWorkspaceError, refresh]
|
|
477
|
+
);
|
|
478
|
+
return /* @__PURE__ */ jsx(WorkspacesContext.Provider, { value, children });
|
|
479
|
+
}
|
|
480
|
+
var DISABLED = {
|
|
481
|
+
memberships: [],
|
|
482
|
+
activeWorkspace: null,
|
|
483
|
+
lastActiveWorkspaceId: null,
|
|
484
|
+
status: "disabled",
|
|
485
|
+
switchWorkspace: () => Promise.reject(
|
|
486
|
+
new Error("useWorkspaces: render a <WorkspaceProvider> inside <AuthProvider> to enable it.")
|
|
487
|
+
),
|
|
488
|
+
hasWorkspaceRole: () => false,
|
|
489
|
+
handleWorkspaceError: () => false,
|
|
490
|
+
refresh: () => Promise.resolve()
|
|
491
|
+
};
|
|
492
|
+
function useWorkspaces() {
|
|
493
|
+
if (useContext(AuthContext) === null) {
|
|
494
|
+
throw new Error(
|
|
495
|
+
"useWorkspaces must be called within an <AuthProvider> \u2014 wrap the consuming tree in a provider built from createAuthClient()."
|
|
496
|
+
);
|
|
497
|
+
}
|
|
498
|
+
return useContext(WorkspacesContext) ?? DISABLED;
|
|
499
|
+
}
|
|
311
500
|
|
|
312
|
-
export { AuthProvider, useAuth, useAuthStatus, useSession };
|
|
501
|
+
export { AuthProvider, WorkspaceProvider, useAuth, useAuthStatus, useSession, useWorkspaces };
|