@chemmangat/msal-next 3.1.7 → 3.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,1620 +1,2 @@
1
- "use client";
2
- "use strict";
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)
9
- __defProp(target, name, { get: all[name], enumerable: true });
10
- };
11
- var __copyProps = (to, from, except, desc) => {
12
- if (from && typeof from === "object" || typeof from === "function") {
13
- for (let key of __getOwnPropNames(from))
14
- if (!__hasOwnProp.call(to, key) && key !== except)
15
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
- }
17
- return to;
18
- };
19
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
-
21
- // src/client.ts
22
- var client_exports = {};
23
- __export(client_exports, {
24
- AuthGuard: () => AuthGuard,
25
- AuthStatus: () => AuthStatus,
26
- ErrorBoundary: () => ErrorBoundary,
27
- MSALProvider: () => MSALProvider,
28
- MicrosoftSignInButton: () => MicrosoftSignInButton,
29
- MsalAuthProvider: () => MsalAuthProvider,
30
- SignOutButton: () => SignOutButton,
31
- UserAvatar: () => UserAvatar,
32
- createAuthMiddleware: () => createAuthMiddleware,
33
- createMsalConfig: () => createMsalConfig,
34
- createRetryWrapper: () => createRetryWrapper,
35
- createScopedLogger: () => createScopedLogger,
36
- getDebugLogger: () => getDebugLogger,
37
- getMsalInstance: () => getMsalInstance,
38
- isValidAccountData: () => isValidAccountData,
39
- isValidRedirectUri: () => isValidRedirectUri,
40
- isValidScope: () => isValidScope,
41
- retryWithBackoff: () => retryWithBackoff,
42
- safeJsonParse: () => safeJsonParse,
43
- sanitizeError: () => sanitizeError,
44
- useAccount: () => import_msal_react3.useAccount,
45
- useGraphApi: () => useGraphApi,
46
- useIsAuthenticated: () => import_msal_react3.useIsAuthenticated,
47
- useMsal: () => import_msal_react3.useMsal,
48
- useMsalAuth: () => useMsalAuth,
49
- useRoles: () => useRoles,
50
- useUserProfile: () => useUserProfile,
51
- validateScopes: () => validateScopes,
52
- withAuth: () => withAuth
53
- });
54
- module.exports = __toCommonJS(client_exports);
55
-
56
- // src/components/MsalAuthProvider.tsx
57
- var import_msal_react = require("@azure/msal-react");
58
- var import_msal_browser2 = require("@azure/msal-browser");
59
- var import_react = require("react");
60
-
61
- // src/utils/createMsalConfig.ts
62
- var import_msal_browser = require("@azure/msal-browser");
63
-
64
- // src/utils/validation.ts
65
- function safeJsonParse(jsonString, validator) {
66
- try {
67
- const parsed = JSON.parse(jsonString);
68
- if (validator(parsed)) {
69
- return parsed;
70
- }
71
- console.warn("[Validation] JSON validation failed");
72
- return null;
73
- } catch (error) {
74
- console.error("[Validation] JSON parse error:", error);
75
- return null;
76
- }
77
- }
78
- function isValidAccountData(data) {
79
- return typeof data === "object" && data !== null && typeof data.homeAccountId === "string" && data.homeAccountId.length > 0 && typeof data.username === "string" && data.username.length > 0 && (data.name === void 0 || typeof data.name === "string");
80
- }
81
- function sanitizeError(error) {
82
- if (error instanceof Error) {
83
- const message = error.message;
84
- const sanitized = message.replace(/[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}/g, "[TOKEN_REDACTED]").replace(/[a-f0-9]{32,}/gi, "[SECRET_REDACTED]").replace(/Bearer\s+[^\s]+/gi, "Bearer [REDACTED]");
85
- return sanitized;
86
- }
87
- return "An unexpected error occurred";
88
- }
89
- function isValidRedirectUri(uri, allowedOrigins) {
90
- try {
91
- const url = new URL(uri);
92
- return allowedOrigins.some((allowed) => {
93
- const allowedUrl = new URL(allowed);
94
- return url.origin === allowedUrl.origin;
95
- });
96
- } catch {
97
- return false;
98
- }
99
- }
100
- function isValidScope(scope) {
101
- return /^[a-zA-Z0-9._-]+$/.test(scope);
102
- }
103
- function validateScopes(scopes) {
104
- return Array.isArray(scopes) && scopes.every(isValidScope);
105
- }
106
-
107
- // src/utils/createMsalConfig.ts
108
- function createMsalConfig(config) {
109
- if (config.msalConfig) {
110
- return config.msalConfig;
111
- }
112
- const {
113
- clientId,
114
- tenantId,
115
- authorityType = "common",
116
- redirectUri,
117
- postLogoutRedirectUri,
118
- cacheLocation = "sessionStorage",
119
- storeAuthStateInCookie = false,
120
- navigateToLoginRequestUrl = false,
121
- enableLogging = false,
122
- loggerCallback,
123
- allowedRedirectUris
124
- } = config;
125
- if (!clientId) {
126
- throw new Error("@chemmangat/msal-next: clientId is required");
127
- }
128
- const getAuthority = () => {
129
- if (authorityType === "tenant") {
130
- if (!tenantId) {
131
- throw new Error('@chemmangat/msal-next: tenantId is required when authorityType is "tenant"');
132
- }
133
- return `https://login.microsoftonline.com/${tenantId}`;
134
- }
135
- return `https://login.microsoftonline.com/${authorityType}`;
136
- };
137
- const defaultRedirectUri = typeof window !== "undefined" ? window.location.origin : "http://localhost:3000";
138
- const finalRedirectUri = redirectUri || defaultRedirectUri;
139
- if (allowedRedirectUris && allowedRedirectUris.length > 0) {
140
- if (!isValidRedirectUri(finalRedirectUri, allowedRedirectUris)) {
141
- throw new Error(
142
- `@chemmangat/msal-next: redirectUri "${finalRedirectUri}" is not in the allowed list`
143
- );
144
- }
145
- const finalPostLogoutUri = postLogoutRedirectUri || finalRedirectUri;
146
- if (!isValidRedirectUri(finalPostLogoutUri, allowedRedirectUris)) {
147
- throw new Error(
148
- `@chemmangat/msal-next: postLogoutRedirectUri "${finalPostLogoutUri}" is not in the allowed list`
149
- );
150
- }
151
- }
152
- const msalConfig = {
153
- auth: {
154
- clientId,
155
- authority: getAuthority(),
156
- redirectUri: finalRedirectUri,
157
- postLogoutRedirectUri: postLogoutRedirectUri || finalRedirectUri,
158
- navigateToLoginRequestUrl
159
- },
160
- cache: {
161
- cacheLocation,
162
- storeAuthStateInCookie
163
- },
164
- system: {
165
- loggerOptions: {
166
- loggerCallback: loggerCallback || ((level, message, containsPii) => {
167
- if (containsPii || !enableLogging) return;
168
- switch (level) {
169
- case import_msal_browser.LogLevel.Error:
170
- console.error("[MSAL]", message);
171
- break;
172
- case import_msal_browser.LogLevel.Warning:
173
- console.warn("[MSAL]", message);
174
- break;
175
- case import_msal_browser.LogLevel.Info:
176
- console.info("[MSAL]", message);
177
- break;
178
- case import_msal_browser.LogLevel.Verbose:
179
- console.debug("[MSAL]", message);
180
- break;
181
- }
182
- }),
183
- logLevel: enableLogging ? import_msal_browser.LogLevel.Verbose : import_msal_browser.LogLevel.Error
184
- }
185
- }
186
- };
187
- return msalConfig;
188
- }
189
-
190
- // src/components/MsalAuthProvider.tsx
191
- var import_jsx_runtime = require("react/jsx-runtime");
192
- var globalMsalInstance = null;
193
- function getMsalInstance() {
194
- return globalMsalInstance;
195
- }
196
- function MsalAuthProvider({ children, loadingComponent, onInitialized, ...config }) {
197
- const [msalInstance, setMsalInstance] = (0, import_react.useState)(null);
198
- const instanceRef = (0, import_react.useRef)(null);
199
- (0, import_react.useEffect)(() => {
200
- if (typeof window === "undefined") {
201
- return;
202
- }
203
- if (instanceRef.current) {
204
- return;
205
- }
206
- const initializeMsal = async () => {
207
- try {
208
- const msalConfig = createMsalConfig(config);
209
- const instance = new import_msal_browser2.PublicClientApplication(msalConfig);
210
- await instance.initialize();
211
- try {
212
- const response = await instance.handleRedirectPromise();
213
- if (response) {
214
- if (config.enableLogging) {
215
- console.log("[MSAL] Redirect authentication successful");
216
- }
217
- if (response.account) {
218
- instance.setActiveAccount(response.account);
219
- }
220
- if (window.location.hash) {
221
- window.history.replaceState(null, "", window.location.pathname + window.location.search);
222
- }
223
- }
224
- } catch (redirectError) {
225
- if (redirectError?.errorCode === "no_token_request_cache_error") {
226
- if (config.enableLogging) {
227
- console.log("[MSAL] No pending redirect found (this is normal)");
228
- }
229
- } else if (redirectError?.errorCode === "user_cancelled") {
230
- if (config.enableLogging) {
231
- console.log("[MSAL] User cancelled authentication");
232
- }
233
- } else {
234
- console.error("[MSAL] Redirect handling error:", redirectError);
235
- }
236
- if (window.location.hash && (window.location.hash.includes("code=") || window.location.hash.includes("error="))) {
237
- window.history.replaceState(null, "", window.location.pathname + window.location.search);
238
- }
239
- }
240
- const accounts = instance.getAllAccounts();
241
- if (accounts.length > 0 && !instance.getActiveAccount()) {
242
- instance.setActiveAccount(accounts[0]);
243
- }
244
- const enableLogging = config.enableLogging || false;
245
- instance.addEventCallback((event) => {
246
- if (event.eventType === import_msal_browser2.EventType.LOGIN_SUCCESS) {
247
- const payload = event.payload;
248
- if (payload?.account) {
249
- instance.setActiveAccount(payload.account);
250
- }
251
- if (enableLogging) {
252
- console.log("[MSAL] Login successful:", payload.account?.username);
253
- }
254
- }
255
- if (event.eventType === import_msal_browser2.EventType.LOGIN_FAILURE) {
256
- console.error("[MSAL] Login failed:", event.error);
257
- }
258
- if (event.eventType === import_msal_browser2.EventType.LOGOUT_SUCCESS) {
259
- instance.setActiveAccount(null);
260
- if (enableLogging) {
261
- console.log("[MSAL] Logout successful");
262
- }
263
- }
264
- if (event.eventType === import_msal_browser2.EventType.ACQUIRE_TOKEN_SUCCESS) {
265
- const payload = event.payload;
266
- if (payload?.account && !instance.getActiveAccount()) {
267
- instance.setActiveAccount(payload.account);
268
- }
269
- }
270
- if (event.eventType === import_msal_browser2.EventType.ACQUIRE_TOKEN_FAILURE) {
271
- if (enableLogging) {
272
- console.error("[MSAL] Token acquisition failed:", event.error);
273
- }
274
- }
275
- });
276
- instanceRef.current = instance;
277
- globalMsalInstance = instance;
278
- setMsalInstance(instance);
279
- if (onInitialized) {
280
- onInitialized(instance);
281
- }
282
- } catch (error) {
283
- console.error("[MSAL] Initialization failed:", error);
284
- throw error;
285
- }
286
- };
287
- initializeMsal();
288
- }, []);
289
- if (typeof window === "undefined") {
290
- return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_jsx_runtime.Fragment, { children: loadingComponent || /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { children: "Loading authentication..." }) });
291
- }
292
- if (!msalInstance) {
293
- return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_jsx_runtime.Fragment, { children: loadingComponent || /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { children: "Loading authentication..." }) });
294
- }
295
- return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_msal_react.MsalProvider, { instance: msalInstance, children });
296
- }
297
-
298
- // src/components/MSALProvider.tsx
299
- var import_jsx_runtime2 = require("react/jsx-runtime");
300
- function MSALProvider({ children, ...props }) {
301
- return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(MsalAuthProvider, { ...props, children });
302
- }
303
-
304
- // src/hooks/useMsalAuth.ts
305
- var import_msal_react2 = require("@azure/msal-react");
306
- var import_msal_browser3 = require("@azure/msal-browser");
307
- var import_react2 = require("react");
308
- var pendingTokenRequests = /* @__PURE__ */ new Map();
309
- function useMsalAuth(defaultScopes = ["User.Read"]) {
310
- const { instance, accounts, inProgress } = (0, import_msal_react2.useMsal)();
311
- const account = (0, import_msal_react2.useAccount)(accounts[0] || null);
312
- const isAuthenticated = (0, import_react2.useMemo)(() => accounts.length > 0, [accounts]);
313
- const loginRedirect = (0, import_react2.useCallback)(
314
- async (scopes = defaultScopes) => {
315
- if (inProgress !== import_msal_browser3.InteractionStatus.None) {
316
- console.warn("[MSAL] Interaction already in progress");
317
- return;
318
- }
319
- try {
320
- const request = {
321
- scopes,
322
- prompt: "select_account"
323
- };
324
- await instance.loginRedirect(request);
325
- } catch (error) {
326
- if (error?.errorCode === "user_cancelled") {
327
- console.log("[MSAL] User cancelled login");
328
- return;
329
- }
330
- console.error("[MSAL] Login redirect failed:", error);
331
- throw error;
332
- }
333
- },
334
- [instance, defaultScopes, inProgress]
335
- );
336
- const logoutRedirect = (0, import_react2.useCallback)(async () => {
337
- try {
338
- await instance.logoutRedirect({
339
- account: account || void 0
340
- });
341
- } catch (error) {
342
- console.error("[MSAL] Logout redirect failed:", error);
343
- throw error;
344
- }
345
- }, [instance, account]);
346
- const acquireTokenSilent = (0, import_react2.useCallback)(
347
- async (scopes = defaultScopes) => {
348
- if (!account) {
349
- throw new Error("[MSAL] No active account. Please login first.");
350
- }
351
- try {
352
- const request = {
353
- scopes,
354
- account,
355
- forceRefresh: false
356
- };
357
- const response = await instance.acquireTokenSilent(request);
358
- return response.accessToken;
359
- } catch (error) {
360
- console.error("[MSAL] Silent token acquisition failed:", error);
361
- throw error;
362
- }
363
- },
364
- [instance, account, defaultScopes]
365
- );
366
- const acquireTokenRedirect = (0, import_react2.useCallback)(
367
- async (scopes = defaultScopes) => {
368
- if (!account) {
369
- throw new Error("[MSAL] No active account. Please login first.");
370
- }
371
- try {
372
- const request = {
373
- scopes,
374
- account
375
- };
376
- await instance.acquireTokenRedirect(request);
377
- } catch (error) {
378
- console.error("[MSAL] Token redirect acquisition failed:", error);
379
- throw error;
380
- }
381
- },
382
- [instance, account, defaultScopes]
383
- );
384
- const acquireToken = (0, import_react2.useCallback)(
385
- async (scopes = defaultScopes) => {
386
- const requestKey = `${account?.homeAccountId || "anonymous"}-${scopes.sort().join(",")}`;
387
- const pendingRequest = pendingTokenRequests.get(requestKey);
388
- if (pendingRequest) {
389
- return pendingRequest;
390
- }
391
- const tokenRequest = (async () => {
392
- try {
393
- return await acquireTokenSilent(scopes);
394
- } catch (error) {
395
- console.warn("[MSAL] Silent token acquisition failed, falling back to redirect");
396
- await acquireTokenRedirect(scopes);
397
- throw new Error("[MSAL] Redirecting for token acquisition");
398
- } finally {
399
- pendingTokenRequests.delete(requestKey);
400
- }
401
- })();
402
- pendingTokenRequests.set(requestKey, tokenRequest);
403
- return tokenRequest;
404
- },
405
- [acquireTokenSilent, acquireTokenRedirect, defaultScopes, account]
406
- );
407
- const clearSession = (0, import_react2.useCallback)(async () => {
408
- instance.setActiveAccount(null);
409
- await instance.clearCache();
410
- }, [instance]);
411
- return {
412
- account,
413
- accounts,
414
- isAuthenticated,
415
- inProgress: inProgress !== import_msal_browser3.InteractionStatus.None,
416
- loginRedirect,
417
- logoutRedirect,
418
- acquireToken,
419
- acquireTokenSilent,
420
- acquireTokenRedirect,
421
- clearSession
422
- };
423
- }
424
-
425
- // src/components/MicrosoftSignInButton.tsx
426
- var import_react3 = require("react");
427
- var import_jsx_runtime3 = require("react/jsx-runtime");
428
- function MicrosoftSignInButton({
429
- text = "Sign in with Microsoft",
430
- variant = "dark",
431
- size = "medium",
432
- scopes,
433
- className = "",
434
- style,
435
- onSuccess,
436
- onError
437
- }) {
438
- const { loginRedirect, inProgress } = useMsalAuth();
439
- const [isLoading, setIsLoading] = (0, import_react3.useState)(false);
440
- const handleClick = async () => {
441
- setIsLoading(true);
442
- try {
443
- await loginRedirect(scopes);
444
- onSuccess?.();
445
- } catch (error) {
446
- onError?.(error);
447
- } finally {
448
- setTimeout(() => setIsLoading(false), 500);
449
- }
450
- };
451
- const sizeStyles = {
452
- small: {
453
- padding: "8px 16px",
454
- fontSize: "14px",
455
- height: "36px"
456
- },
457
- medium: {
458
- padding: "10px 20px",
459
- fontSize: "15px",
460
- height: "41px"
461
- },
462
- large: {
463
- padding: "12px 24px",
464
- fontSize: "16px",
465
- height: "48px"
466
- }
467
- };
468
- const variantStyles = {
469
- dark: {
470
- backgroundColor: "#2F2F2F",
471
- color: "#FFFFFF",
472
- border: "1px solid #8C8C8C"
473
- },
474
- light: {
475
- backgroundColor: "#FFFFFF",
476
- color: "#5E5E5E",
477
- border: "1px solid #8C8C8C"
478
- }
479
- };
480
- const isDisabled = inProgress || isLoading;
481
- const baseStyles = {
482
- display: "inline-flex",
483
- alignItems: "center",
484
- justifyContent: "center",
485
- gap: "12px",
486
- fontFamily: '"Segoe UI", Tahoma, Geneva, Verdana, sans-serif',
487
- fontWeight: 600,
488
- borderRadius: "2px",
489
- cursor: isDisabled ? "not-allowed" : "pointer",
490
- transition: "all 0.2s ease",
491
- opacity: isDisabled ? 0.6 : 1,
492
- ...variantStyles[variant],
493
- ...sizeStyles[size],
494
- ...style
495
- };
496
- return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(
497
- "button",
498
- {
499
- onClick: handleClick,
500
- disabled: isDisabled,
501
- className,
502
- style: baseStyles,
503
- "aria-label": text,
504
- children: [
505
- /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(MicrosoftLogo, {}),
506
- /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { children: text })
507
- ]
508
- }
509
- );
510
- }
511
- function MicrosoftLogo() {
512
- return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("svg", { width: "21", height: "21", viewBox: "0 0 21 21", fill: "none", xmlns: "http://www.w3.org/2000/svg", children: [
513
- /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("rect", { width: "10", height: "10", fill: "#F25022" }),
514
- /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("rect", { x: "11", width: "10", height: "10", fill: "#7FBA00" }),
515
- /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("rect", { y: "11", width: "10", height: "10", fill: "#00A4EF" }),
516
- /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("rect", { x: "11", y: "11", width: "10", height: "10", fill: "#FFB900" })
517
- ] });
518
- }
519
-
520
- // src/components/SignOutButton.tsx
521
- var import_jsx_runtime4 = require("react/jsx-runtime");
522
- function SignOutButton({
523
- text = "Sign out",
524
- variant = "dark",
525
- size = "medium",
526
- className = "",
527
- style,
528
- onSuccess,
529
- onError
530
- }) {
531
- const { logoutRedirect, inProgress } = useMsalAuth();
532
- const handleClick = async () => {
533
- try {
534
- await logoutRedirect();
535
- onSuccess?.();
536
- } catch (error) {
537
- onError?.(error);
538
- }
539
- };
540
- const sizeStyles = {
541
- small: {
542
- padding: "8px 16px",
543
- fontSize: "14px",
544
- height: "36px"
545
- },
546
- medium: {
547
- padding: "10px 20px",
548
- fontSize: "15px",
549
- height: "41px"
550
- },
551
- large: {
552
- padding: "12px 24px",
553
- fontSize: "16px",
554
- height: "48px"
555
- }
556
- };
557
- const variantStyles = {
558
- dark: {
559
- backgroundColor: "#2F2F2F",
560
- color: "#FFFFFF",
561
- border: "1px solid #8C8C8C"
562
- },
563
- light: {
564
- backgroundColor: "#FFFFFF",
565
- color: "#5E5E5E",
566
- border: "1px solid #8C8C8C"
567
- }
568
- };
569
- const baseStyles = {
570
- display: "inline-flex",
571
- alignItems: "center",
572
- justifyContent: "center",
573
- gap: "12px",
574
- fontFamily: '"Segoe UI", Tahoma, Geneva, Verdana, sans-serif',
575
- fontWeight: 600,
576
- borderRadius: "2px",
577
- cursor: inProgress ? "not-allowed" : "pointer",
578
- transition: "all 0.2s ease",
579
- opacity: inProgress ? 0.6 : 1,
580
- ...variantStyles[variant],
581
- ...sizeStyles[size],
582
- ...style
583
- };
584
- return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(
585
- "button",
586
- {
587
- onClick: handleClick,
588
- disabled: inProgress,
589
- className,
590
- style: baseStyles,
591
- "aria-label": text,
592
- children: [
593
- /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(MicrosoftLogo2, {}),
594
- /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("span", { children: text })
595
- ]
596
- }
597
- );
598
- }
599
- function MicrosoftLogo2() {
600
- return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("svg", { width: "21", height: "21", viewBox: "0 0 21 21", fill: "none", xmlns: "http://www.w3.org/2000/svg", children: [
601
- /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("rect", { width: "10", height: "10", fill: "#F25022" }),
602
- /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("rect", { x: "11", width: "10", height: "10", fill: "#7FBA00" }),
603
- /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("rect", { y: "11", width: "10", height: "10", fill: "#00A4EF" }),
604
- /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("rect", { x: "11", y: "11", width: "10", height: "10", fill: "#FFB900" })
605
- ] });
606
- }
607
-
608
- // src/components/UserAvatar.tsx
609
- var import_react6 = require("react");
610
-
611
- // src/hooks/useUserProfile.ts
612
- var import_react5 = require("react");
613
-
614
- // src/hooks/useGraphApi.ts
615
- var import_react4 = require("react");
616
- function useGraphApi() {
617
- const { acquireToken } = useMsalAuth();
618
- const request = (0, import_react4.useCallback)(
619
- async (endpoint, options = {}) => {
620
- const {
621
- scopes = ["User.Read"],
622
- version = "v1.0",
623
- debug = false,
624
- ...fetchOptions
625
- } = options;
626
- try {
627
- const token = await acquireToken(scopes);
628
- const baseUrl = `https://graph.microsoft.com/${version}`;
629
- const url = endpoint.startsWith("http") ? endpoint : `${baseUrl}${endpoint.startsWith("/") ? endpoint : `/${endpoint}`}`;
630
- if (debug) {
631
- console.log("[GraphAPI] Request:", { url, method: fetchOptions.method || "GET" });
632
- }
633
- const response = await fetch(url, {
634
- ...fetchOptions,
635
- headers: {
636
- "Authorization": `Bearer ${token}`,
637
- "Content-Type": "application/json",
638
- ...fetchOptions.headers
639
- }
640
- });
641
- if (!response.ok) {
642
- const errorText = await response.text();
643
- const errorMessage = `Graph API error (${response.status}): ${errorText}`;
644
- throw new Error(errorMessage);
645
- }
646
- if (response.status === 204 || response.headers.get("content-length") === "0") {
647
- return null;
648
- }
649
- const data = await response.json();
650
- if (debug) {
651
- console.log("[GraphAPI] Response:", data);
652
- }
653
- return data;
654
- } catch (error) {
655
- const sanitizedMessage = sanitizeError(error);
656
- console.error("[GraphAPI] Request failed:", sanitizedMessage);
657
- throw new Error(sanitizedMessage);
658
- }
659
- },
660
- [acquireToken]
661
- );
662
- const get = (0, import_react4.useCallback)(
663
- (endpoint, options = {}) => {
664
- return request(endpoint, { ...options, method: "GET" });
665
- },
666
- [request]
667
- );
668
- const post = (0, import_react4.useCallback)(
669
- (endpoint, body, options = {}) => {
670
- return request(endpoint, {
671
- ...options,
672
- method: "POST",
673
- body: body ? JSON.stringify(body) : void 0
674
- });
675
- },
676
- [request]
677
- );
678
- const put = (0, import_react4.useCallback)(
679
- (endpoint, body, options = {}) => {
680
- return request(endpoint, {
681
- ...options,
682
- method: "PUT",
683
- body: body ? JSON.stringify(body) : void 0
684
- });
685
- },
686
- [request]
687
- );
688
- const patch = (0, import_react4.useCallback)(
689
- (endpoint, body, options = {}) => {
690
- return request(endpoint, {
691
- ...options,
692
- method: "PATCH",
693
- body: body ? JSON.stringify(body) : void 0
694
- });
695
- },
696
- [request]
697
- );
698
- const deleteRequest = (0, import_react4.useCallback)(
699
- (endpoint, options = {}) => {
700
- return request(endpoint, { ...options, method: "DELETE" });
701
- },
702
- [request]
703
- );
704
- return {
705
- get,
706
- post,
707
- put,
708
- patch,
709
- delete: deleteRequest,
710
- request
711
- };
712
- }
713
-
714
- // src/hooks/useUserProfile.ts
715
- var profileCache = /* @__PURE__ */ new Map();
716
- var CACHE_DURATION = 5 * 60 * 1e3;
717
- var MAX_CACHE_SIZE = 100;
718
- function enforceCacheLimit() {
719
- if (profileCache.size > MAX_CACHE_SIZE) {
720
- const entries = Array.from(profileCache.entries());
721
- entries.sort((a, b) => a[1].timestamp - b[1].timestamp);
722
- const toRemove = entries.slice(0, profileCache.size - MAX_CACHE_SIZE);
723
- toRemove.forEach(([key]) => {
724
- const cached = profileCache.get(key);
725
- if (cached?.data.photo) {
726
- URL.revokeObjectURL(cached.data.photo);
727
- }
728
- profileCache.delete(key);
729
- });
730
- }
731
- }
732
- function useUserProfile() {
733
- const { isAuthenticated, account } = useMsalAuth();
734
- const graph = useGraphApi();
735
- const [profile, setProfile] = (0, import_react5.useState)(null);
736
- const [loading, setLoading] = (0, import_react5.useState)(false);
737
- const [error, setError] = (0, import_react5.useState)(null);
738
- const fetchProfile = (0, import_react5.useCallback)(async () => {
739
- if (!isAuthenticated || !account) {
740
- setProfile(null);
741
- return;
742
- }
743
- const cacheKey = account.homeAccountId;
744
- const cached = profileCache.get(cacheKey);
745
- if (cached && Date.now() - cached.timestamp < CACHE_DURATION) {
746
- setProfile(cached.data);
747
- return;
748
- }
749
- setLoading(true);
750
- setError(null);
751
- try {
752
- const userData = await graph.get("/me", {
753
- scopes: ["User.Read"]
754
- });
755
- let photoUrl;
756
- try {
757
- const photoBlob = await graph.get("/me/photo/$value", {
758
- scopes: ["User.Read"],
759
- headers: {
760
- "Content-Type": "image/jpeg"
761
- }
762
- });
763
- if (photoBlob) {
764
- photoUrl = URL.createObjectURL(photoBlob);
765
- }
766
- } catch (photoError) {
767
- console.debug("[UserProfile] Photo not available");
768
- }
769
- const profileData = {
770
- id: userData.id,
771
- displayName: userData.displayName,
772
- givenName: userData.givenName,
773
- surname: userData.surname,
774
- userPrincipalName: userData.userPrincipalName,
775
- mail: userData.mail,
776
- jobTitle: userData.jobTitle,
777
- officeLocation: userData.officeLocation,
778
- mobilePhone: userData.mobilePhone,
779
- businessPhones: userData.businessPhones,
780
- photo: photoUrl
781
- };
782
- profileCache.set(cacheKey, {
783
- data: profileData,
784
- timestamp: Date.now()
785
- });
786
- enforceCacheLimit();
787
- setProfile(profileData);
788
- } catch (err) {
789
- const error2 = err;
790
- const sanitizedMessage = sanitizeError(error2);
791
- const sanitizedError = new Error(sanitizedMessage);
792
- setError(sanitizedError);
793
- console.error("[UserProfile] Failed to fetch profile:", sanitizedMessage);
794
- } finally {
795
- setLoading(false);
796
- }
797
- }, [isAuthenticated, account, graph]);
798
- const clearCache = (0, import_react5.useCallback)(() => {
799
- if (account) {
800
- const cached = profileCache.get(account.homeAccountId);
801
- if (cached?.data.photo) {
802
- URL.revokeObjectURL(cached.data.photo);
803
- }
804
- profileCache.delete(account.homeAccountId);
805
- }
806
- if (profile?.photo) {
807
- URL.revokeObjectURL(profile.photo);
808
- }
809
- setProfile(null);
810
- }, [account, profile]);
811
- (0, import_react5.useEffect)(() => {
812
- fetchProfile();
813
- return () => {
814
- if (profile?.photo) {
815
- URL.revokeObjectURL(profile.photo);
816
- }
817
- };
818
- }, [fetchProfile]);
819
- (0, import_react5.useEffect)(() => {
820
- return () => {
821
- if (profile?.photo) {
822
- URL.revokeObjectURL(profile.photo);
823
- }
824
- };
825
- }, [profile?.photo]);
826
- return {
827
- profile,
828
- loading,
829
- error,
830
- refetch: fetchProfile,
831
- clearCache
832
- };
833
- }
834
-
835
- // src/components/UserAvatar.tsx
836
- var import_jsx_runtime5 = require("react/jsx-runtime");
837
- function UserAvatar({
838
- size = 40,
839
- className = "",
840
- style,
841
- showTooltip = true,
842
- fallbackImage
843
- }) {
844
- const { profile, loading } = useUserProfile();
845
- const [photoUrl, setPhotoUrl] = (0, import_react6.useState)(null);
846
- const [photoError, setPhotoError] = (0, import_react6.useState)(false);
847
- (0, import_react6.useEffect)(() => {
848
- if (profile?.photo) {
849
- setPhotoUrl(profile.photo);
850
- }
851
- }, [profile?.photo]);
852
- const getInitials = () => {
853
- if (!profile) return "?";
854
- const { givenName, surname, displayName: displayName2 } = profile;
855
- if (givenName && surname) {
856
- return `${givenName[0]}${surname[0]}`.toUpperCase();
857
- }
858
- if (displayName2) {
859
- const parts = displayName2.split(" ");
860
- if (parts.length >= 2) {
861
- return `${parts[0][0]}${parts[parts.length - 1][0]}`.toUpperCase();
862
- }
863
- return displayName2.substring(0, 2).toUpperCase();
864
- }
865
- return "?";
866
- };
867
- const baseStyles = {
868
- width: `${size}px`,
869
- height: `${size}px`,
870
- borderRadius: "50%",
871
- display: "inline-flex",
872
- alignItems: "center",
873
- justifyContent: "center",
874
- fontSize: `${size * 0.4}px`,
875
- fontWeight: 600,
876
- fontFamily: '"Segoe UI", Tahoma, Geneva, Verdana, sans-serif',
877
- backgroundColor: "#0078D4",
878
- color: "#FFFFFF",
879
- overflow: "hidden",
880
- userSelect: "none",
881
- ...style
882
- };
883
- const displayName = profile?.displayName || "User";
884
- if (loading) {
885
- return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
886
- "div",
887
- {
888
- className,
889
- style: { ...baseStyles, backgroundColor: "#E1E1E1" },
890
- "aria-label": "Loading user avatar",
891
- children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { style: { fontSize: `${size * 0.3}px` }, children: "..." })
892
- }
893
- );
894
- }
895
- if (photoUrl && !photoError) {
896
- return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
897
- "div",
898
- {
899
- className,
900
- style: baseStyles,
901
- title: showTooltip ? displayName : void 0,
902
- "aria-label": `${displayName} avatar`,
903
- children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
904
- "img",
905
- {
906
- src: photoUrl,
907
- alt: displayName,
908
- style: { width: "100%", height: "100%", objectFit: "cover" },
909
- onError: () => {
910
- setPhotoError(true);
911
- if (fallbackImage) {
912
- setPhotoUrl(fallbackImage);
913
- }
914
- }
915
- }
916
- )
917
- }
918
- );
919
- }
920
- return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
921
- "div",
922
- {
923
- className,
924
- style: baseStyles,
925
- title: showTooltip ? displayName : void 0,
926
- "aria-label": `${displayName} avatar`,
927
- children: getInitials()
928
- }
929
- );
930
- }
931
-
932
- // src/components/AuthStatus.tsx
933
- var import_jsx_runtime6 = require("react/jsx-runtime");
934
- function AuthStatus({
935
- className = "",
936
- style,
937
- showDetails = false,
938
- renderLoading,
939
- renderAuthenticated,
940
- renderUnauthenticated
941
- }) {
942
- const { isAuthenticated, inProgress, account } = useMsalAuth();
943
- const baseStyles = {
944
- display: "inline-flex",
945
- alignItems: "center",
946
- gap: "8px",
947
- padding: "8px 12px",
948
- borderRadius: "4px",
949
- fontFamily: '"Segoe UI", Tahoma, Geneva, Verdana, sans-serif',
950
- fontSize: "14px",
951
- fontWeight: 500,
952
- ...style
953
- };
954
- if (inProgress) {
955
- if (renderLoading) {
956
- return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(import_jsx_runtime6.Fragment, { children: renderLoading() });
957
- }
958
- return /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(
959
- "div",
960
- {
961
- className,
962
- style: { ...baseStyles, backgroundColor: "#FFF4CE", color: "#8A6D3B" },
963
- role: "status",
964
- "aria-live": "polite",
965
- children: [
966
- /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(StatusIndicator, { color: "#FFA500" }),
967
- /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("span", { children: "Loading..." })
968
- ]
969
- }
970
- );
971
- }
972
- if (isAuthenticated) {
973
- const username = account?.username || account?.name || "User";
974
- if (renderAuthenticated) {
975
- return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(import_jsx_runtime6.Fragment, { children: renderAuthenticated(username) });
976
- }
977
- return /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(
978
- "div",
979
- {
980
- className,
981
- style: { ...baseStyles, backgroundColor: "#D4EDDA", color: "#155724" },
982
- role: "status",
983
- "aria-live": "polite",
984
- children: [
985
- /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(StatusIndicator, { color: "#28A745" }),
986
- /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("span", { children: showDetails ? `Authenticated as ${username}` : "Authenticated" })
987
- ]
988
- }
989
- );
990
- }
991
- if (renderUnauthenticated) {
992
- return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(import_jsx_runtime6.Fragment, { children: renderUnauthenticated() });
993
- }
994
- return /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(
995
- "div",
996
- {
997
- className,
998
- style: { ...baseStyles, backgroundColor: "#F8D7DA", color: "#721C24" },
999
- role: "status",
1000
- "aria-live": "polite",
1001
- children: [
1002
- /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(StatusIndicator, { color: "#DC3545" }),
1003
- /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("span", { children: "Not authenticated" })
1004
- ]
1005
- }
1006
- );
1007
- }
1008
- function StatusIndicator({ color }) {
1009
- return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("svg", { width: "8", height: "8", viewBox: "0 0 8 8", fill: "none", xmlns: "http://www.w3.org/2000/svg", children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("circle", { cx: "4", cy: "4", r: "4", fill: color }) });
1010
- }
1011
-
1012
- // src/components/AuthGuard.tsx
1013
- var import_react7 = require("react");
1014
- var import_jsx_runtime7 = require("react/jsx-runtime");
1015
- function AuthGuard({
1016
- children,
1017
- loadingComponent,
1018
- fallbackComponent,
1019
- scopes,
1020
- onAuthRequired
1021
- }) {
1022
- const { isAuthenticated, inProgress, loginRedirect } = useMsalAuth();
1023
- (0, import_react7.useEffect)(() => {
1024
- if (!isAuthenticated && !inProgress) {
1025
- onAuthRequired?.();
1026
- const login = async () => {
1027
- try {
1028
- await loginRedirect(scopes);
1029
- } catch (error) {
1030
- console.error("[AuthGuard] Authentication failed:", error);
1031
- }
1032
- };
1033
- login();
1034
- }
1035
- }, [isAuthenticated, inProgress, scopes, loginRedirect, onAuthRequired]);
1036
- if (inProgress) {
1037
- return /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(import_jsx_runtime7.Fragment, { children: loadingComponent || /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("div", { children: "Authenticating..." }) });
1038
- }
1039
- if (!isAuthenticated) {
1040
- return /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(import_jsx_runtime7.Fragment, { children: fallbackComponent || /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("div", { children: "Redirecting to login..." }) });
1041
- }
1042
- return /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(import_jsx_runtime7.Fragment, { children });
1043
- }
1044
-
1045
- // src/components/ErrorBoundary.tsx
1046
- var import_react8 = require("react");
1047
- var import_jsx_runtime8 = require("react/jsx-runtime");
1048
- var ErrorBoundary = class extends import_react8.Component {
1049
- constructor(props) {
1050
- super(props);
1051
- this.reset = () => {
1052
- this.setState({
1053
- hasError: false,
1054
- error: null
1055
- });
1056
- };
1057
- this.state = {
1058
- hasError: false,
1059
- error: null
1060
- };
1061
- }
1062
- static getDerivedStateFromError(error) {
1063
- return {
1064
- hasError: true,
1065
- error
1066
- };
1067
- }
1068
- componentDidCatch(error, errorInfo) {
1069
- const { onError, debug } = this.props;
1070
- if (debug) {
1071
- console.error("[ErrorBoundary] Caught error:", error);
1072
- console.error("[ErrorBoundary] Error info:", errorInfo);
1073
- }
1074
- onError?.(error, errorInfo);
1075
- }
1076
- render() {
1077
- const { hasError, error } = this.state;
1078
- const { children, fallback } = this.props;
1079
- if (hasError && error) {
1080
- if (fallback) {
1081
- return fallback(error, this.reset);
1082
- }
1083
- return /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)(
1084
- "div",
1085
- {
1086
- style: {
1087
- padding: "20px",
1088
- margin: "20px",
1089
- border: "1px solid #DC3545",
1090
- borderRadius: "4px",
1091
- backgroundColor: "#F8D7DA",
1092
- color: "#721C24",
1093
- fontFamily: '"Segoe UI", Tahoma, Geneva, Verdana, sans-serif'
1094
- },
1095
- children: [
1096
- /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("h2", { style: { margin: "0 0 10px 0", fontSize: "18px" }, children: "Authentication Error" }),
1097
- /* @__PURE__ */ (0, import_jsx_runtime8.jsx)("p", { style: { margin: "0 0 10px 0" }, children: error.message }),
1098
- /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
1099
- "button",
1100
- {
1101
- onClick: this.reset,
1102
- style: {
1103
- padding: "8px 16px",
1104
- backgroundColor: "#DC3545",
1105
- color: "#FFFFFF",
1106
- border: "none",
1107
- borderRadius: "4px",
1108
- cursor: "pointer",
1109
- fontSize: "14px",
1110
- fontWeight: 600
1111
- },
1112
- children: "Try Again"
1113
- }
1114
- )
1115
- ]
1116
- }
1117
- );
1118
- }
1119
- return children;
1120
- }
1121
- };
1122
-
1123
- // src/hooks/useRoles.ts
1124
- var import_react9 = require("react");
1125
- var rolesCache = /* @__PURE__ */ new Map();
1126
- var CACHE_DURATION2 = 5 * 60 * 1e3;
1127
- var MAX_CACHE_SIZE2 = 100;
1128
- function clearRolesCache(accountId) {
1129
- if (accountId) {
1130
- rolesCache.delete(accountId);
1131
- } else {
1132
- rolesCache.clear();
1133
- }
1134
- }
1135
- function enforceCacheLimit2() {
1136
- if (rolesCache.size > MAX_CACHE_SIZE2) {
1137
- const entries = Array.from(rolesCache.entries());
1138
- entries.sort((a, b) => a[1].timestamp - b[1].timestamp);
1139
- const toRemove = entries.slice(0, rolesCache.size - MAX_CACHE_SIZE2);
1140
- toRemove.forEach(([key]) => rolesCache.delete(key));
1141
- }
1142
- }
1143
- function useRoles() {
1144
- const { isAuthenticated, account } = useMsalAuth();
1145
- const graph = useGraphApi();
1146
- const [roles, setRoles] = (0, import_react9.useState)([]);
1147
- const [groups, setGroups] = (0, import_react9.useState)([]);
1148
- const [loading, setLoading] = (0, import_react9.useState)(false);
1149
- const [error, setError] = (0, import_react9.useState)(null);
1150
- const fetchRolesAndGroups = (0, import_react9.useCallback)(async () => {
1151
- if (!isAuthenticated || !account) {
1152
- setRoles([]);
1153
- setGroups([]);
1154
- return;
1155
- }
1156
- const cacheKey = account.homeAccountId;
1157
- const cached = rolesCache.get(cacheKey);
1158
- if (cached && Date.now() - cached.timestamp < CACHE_DURATION2) {
1159
- setRoles(cached.roles);
1160
- setGroups(cached.groups);
1161
- return;
1162
- }
1163
- setLoading(true);
1164
- setError(null);
1165
- try {
1166
- const idTokenClaims = account.idTokenClaims;
1167
- const tokenRoles = idTokenClaims?.roles || [];
1168
- const groupsResponse = await graph.get("/me/memberOf", {
1169
- scopes: ["User.Read", "Directory.Read.All"]
1170
- });
1171
- const userGroups = groupsResponse.value.map((group) => group.id);
1172
- rolesCache.set(cacheKey, {
1173
- roles: tokenRoles,
1174
- groups: userGroups,
1175
- timestamp: Date.now()
1176
- });
1177
- enforceCacheLimit2();
1178
- setRoles(tokenRoles);
1179
- setGroups(userGroups);
1180
- } catch (err) {
1181
- const error2 = err;
1182
- const sanitizedMessage = sanitizeError(error2);
1183
- const sanitizedError = new Error(sanitizedMessage);
1184
- setError(sanitizedError);
1185
- console.error("[Roles] Failed to fetch roles/groups:", sanitizedMessage);
1186
- const idTokenClaims = account.idTokenClaims;
1187
- const tokenRoles = idTokenClaims?.roles || [];
1188
- setRoles(tokenRoles);
1189
- } finally {
1190
- setLoading(false);
1191
- }
1192
- }, [isAuthenticated, account, graph]);
1193
- const hasRole = (0, import_react9.useCallback)(
1194
- (role) => {
1195
- return roles.includes(role);
1196
- },
1197
- [roles]
1198
- );
1199
- const hasGroup = (0, import_react9.useCallback)(
1200
- (groupId) => {
1201
- return groups.includes(groupId);
1202
- },
1203
- [groups]
1204
- );
1205
- const hasAnyRole = (0, import_react9.useCallback)(
1206
- (checkRoles) => {
1207
- return checkRoles.some((role) => roles.includes(role));
1208
- },
1209
- [roles]
1210
- );
1211
- const hasAllRoles = (0, import_react9.useCallback)(
1212
- (checkRoles) => {
1213
- return checkRoles.every((role) => roles.includes(role));
1214
- },
1215
- [roles]
1216
- );
1217
- (0, import_react9.useEffect)(() => {
1218
- fetchRolesAndGroups();
1219
- return () => {
1220
- if (account) {
1221
- clearRolesCache(account.homeAccountId);
1222
- }
1223
- };
1224
- }, [fetchRolesAndGroups, account]);
1225
- return {
1226
- roles,
1227
- groups,
1228
- loading,
1229
- error,
1230
- hasRole,
1231
- hasGroup,
1232
- hasAnyRole,
1233
- hasAllRoles,
1234
- refetch: fetchRolesAndGroups
1235
- };
1236
- }
1237
-
1238
- // src/utils/withAuth.tsx
1239
- var import_jsx_runtime9 = require("react/jsx-runtime");
1240
- function withAuth(Component2, options = {}) {
1241
- const { displayName, ...guardProps } = options;
1242
- const WrappedComponent = (props) => {
1243
- return /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(AuthGuard, { ...guardProps, children: /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(Component2, { ...props }) });
1244
- };
1245
- WrappedComponent.displayName = displayName || `withAuth(${Component2.displayName || Component2.name || "Component"})`;
1246
- return WrappedComponent;
1247
- }
1248
-
1249
- // src/utils/tokenRetry.ts
1250
- async function retryWithBackoff(fn, config = {}) {
1251
- const {
1252
- maxRetries = 3,
1253
- initialDelay = 1e3,
1254
- maxDelay = 1e4,
1255
- backoffMultiplier = 2,
1256
- debug = false
1257
- } = config;
1258
- let lastError;
1259
- let delay = initialDelay;
1260
- for (let attempt = 0; attempt <= maxRetries; attempt++) {
1261
- try {
1262
- if (debug && attempt > 0) {
1263
- console.log(`[TokenRetry] Attempt ${attempt + 1}/${maxRetries + 1}`);
1264
- }
1265
- return await fn();
1266
- } catch (error) {
1267
- lastError = error;
1268
- if (attempt === maxRetries) {
1269
- if (debug) {
1270
- console.error("[TokenRetry] All retry attempts failed");
1271
- }
1272
- break;
1273
- }
1274
- if (!isRetryableError(error)) {
1275
- if (debug) {
1276
- console.log("[TokenRetry] Non-retryable error, aborting");
1277
- }
1278
- throw error;
1279
- }
1280
- if (debug) {
1281
- console.warn(`[TokenRetry] Attempt ${attempt + 1} failed, retrying in ${delay}ms...`);
1282
- }
1283
- await sleep(delay);
1284
- delay = Math.min(delay * backoffMultiplier, maxDelay);
1285
- }
1286
- }
1287
- throw lastError;
1288
- }
1289
- function isRetryableError(error) {
1290
- const message = error.message.toLowerCase();
1291
- if (message.includes("network") || message.includes("timeout") || message.includes("fetch") || message.includes("connection")) {
1292
- return true;
1293
- }
1294
- if (message.includes("500") || message.includes("502") || message.includes("503")) {
1295
- return true;
1296
- }
1297
- if (message.includes("429") || message.includes("rate limit")) {
1298
- return true;
1299
- }
1300
- if (message.includes("token") && message.includes("expired")) {
1301
- return true;
1302
- }
1303
- return false;
1304
- }
1305
- function sleep(ms) {
1306
- return new Promise((resolve) => setTimeout(resolve, ms));
1307
- }
1308
- function createRetryWrapper(fn, config = {}) {
1309
- return (...args) => {
1310
- return retryWithBackoff(() => fn(...args), config);
1311
- };
1312
- }
1313
-
1314
- // src/utils/debugLogger.ts
1315
- var DebugLogger = class {
1316
- constructor(config = {}) {
1317
- this.logHistory = [];
1318
- this.performanceTimings = /* @__PURE__ */ new Map();
1319
- this.config = {
1320
- enabled: config.enabled ?? false,
1321
- prefix: config.prefix ?? "[MSAL-Next]",
1322
- showTimestamp: config.showTimestamp ?? true,
1323
- level: config.level ?? "info",
1324
- enablePerformance: config.enablePerformance ?? false,
1325
- enableNetworkLogs: config.enableNetworkLogs ?? false,
1326
- maxHistorySize: config.maxHistorySize ?? 100
1327
- };
1328
- }
1329
- shouldLog(level) {
1330
- if (!this.config.enabled) return false;
1331
- const levels = ["error", "warn", "info", "debug"];
1332
- const currentLevelIndex = levels.indexOf(this.config.level);
1333
- const messageLevelIndex = levels.indexOf(level);
1334
- return messageLevelIndex <= currentLevelIndex;
1335
- }
1336
- formatMessage(level, message, data) {
1337
- const timestamp = this.config.showTimestamp ? `[${(/* @__PURE__ */ new Date()).toISOString()}]` : "";
1338
- const prefix = this.config.prefix;
1339
- const levelStr = `[${level.toUpperCase()}]`;
1340
- let formatted = `${timestamp} ${prefix} ${levelStr} ${message}`;
1341
- if (data !== void 0) {
1342
- formatted += "\n" + JSON.stringify(data, null, 2);
1343
- }
1344
- return formatted;
1345
- }
1346
- addToHistory(level, message, data) {
1347
- if (this.logHistory.length >= this.config.maxHistorySize) {
1348
- this.logHistory.shift();
1349
- }
1350
- this.logHistory.push({
1351
- timestamp: Date.now(),
1352
- level,
1353
- message,
1354
- data
1355
- });
1356
- }
1357
- error(message, data) {
1358
- if (this.shouldLog("error")) {
1359
- console.error(this.formatMessage("error", message, data));
1360
- this.addToHistory("error", message, data);
1361
- }
1362
- }
1363
- warn(message, data) {
1364
- if (this.shouldLog("warn")) {
1365
- console.warn(this.formatMessage("warn", message, data));
1366
- this.addToHistory("warn", message, data);
1367
- }
1368
- }
1369
- info(message, data) {
1370
- if (this.shouldLog("info")) {
1371
- console.info(this.formatMessage("info", message, data));
1372
- this.addToHistory("info", message, data);
1373
- }
1374
- }
1375
- debug(message, data) {
1376
- if (this.shouldLog("debug")) {
1377
- console.debug(this.formatMessage("debug", message, data));
1378
- this.addToHistory("debug", message, data);
1379
- }
1380
- }
1381
- group(label) {
1382
- if (this.config.enabled) {
1383
- console.group(`${this.config.prefix} ${label}`);
1384
- }
1385
- }
1386
- groupEnd() {
1387
- if (this.config.enabled) {
1388
- console.groupEnd();
1389
- }
1390
- }
1391
- /**
1392
- * Start performance timing for an operation
1393
- */
1394
- startTiming(operation) {
1395
- if (this.config.enablePerformance) {
1396
- this.performanceTimings.set(operation, {
1397
- operation,
1398
- startTime: performance.now()
1399
- });
1400
- this.debug(`\u23F1\uFE0F Started: ${operation}`);
1401
- }
1402
- }
1403
- /**
1404
- * End performance timing for an operation
1405
- */
1406
- endTiming(operation) {
1407
- if (this.config.enablePerformance) {
1408
- const timing = this.performanceTimings.get(operation);
1409
- if (timing) {
1410
- timing.endTime = performance.now();
1411
- timing.duration = timing.endTime - timing.startTime;
1412
- this.info(`\u23F1\uFE0F Completed: ${operation} (${timing.duration.toFixed(2)}ms)`);
1413
- return timing.duration;
1414
- }
1415
- }
1416
- return void 0;
1417
- }
1418
- /**
1419
- * Log network request
1420
- */
1421
- logRequest(method, url, options) {
1422
- if (this.config.enableNetworkLogs) {
1423
- this.debug(`\u{1F310} ${method} ${url}`, options);
1424
- }
1425
- }
1426
- /**
1427
- * Log network response
1428
- */
1429
- logResponse(method, url, status, data) {
1430
- if (this.config.enableNetworkLogs) {
1431
- const statusEmoji = status >= 200 && status < 300 ? "\u2705" : "\u274C";
1432
- this.debug(`${statusEmoji} ${method} ${url} - ${status}`, data);
1433
- }
1434
- }
1435
- /**
1436
- * Get log history
1437
- */
1438
- getHistory() {
1439
- return [...this.logHistory];
1440
- }
1441
- /**
1442
- * Get performance timings
1443
- */
1444
- getPerformanceTimings() {
1445
- return Array.from(this.performanceTimings.values());
1446
- }
1447
- /**
1448
- * Clear log history
1449
- */
1450
- clearHistory() {
1451
- this.logHistory = [];
1452
- }
1453
- /**
1454
- * Clear performance timings
1455
- */
1456
- clearTimings() {
1457
- this.performanceTimings.clear();
1458
- }
1459
- /**
1460
- * Export logs as JSON
1461
- */
1462
- exportLogs() {
1463
- return JSON.stringify({
1464
- config: this.config,
1465
- history: this.logHistory,
1466
- performanceTimings: Array.from(this.performanceTimings.values()),
1467
- exportedAt: (/* @__PURE__ */ new Date()).toISOString()
1468
- }, null, 2);
1469
- }
1470
- /**
1471
- * Download logs as a file
1472
- */
1473
- downloadLogs(filename = "msal-next-debug-logs.json") {
1474
- if (typeof window === "undefined") return;
1475
- const logs = this.exportLogs();
1476
- const blob = new Blob([logs], { type: "application/json" });
1477
- const url = URL.createObjectURL(blob);
1478
- const a = document.createElement("a");
1479
- a.href = url;
1480
- a.download = filename;
1481
- a.click();
1482
- URL.revokeObjectURL(url);
1483
- }
1484
- setEnabled(enabled) {
1485
- this.config.enabled = enabled;
1486
- }
1487
- setLevel(level) {
1488
- if (level) {
1489
- this.config.level = level;
1490
- }
1491
- }
1492
- };
1493
- var globalLogger = null;
1494
- function getDebugLogger(config) {
1495
- if (!globalLogger) {
1496
- globalLogger = new DebugLogger(config);
1497
- } else if (config) {
1498
- if (config.enabled !== void 0) {
1499
- globalLogger.setEnabled(config.enabled);
1500
- }
1501
- if (config.level) {
1502
- globalLogger.setLevel(config.level);
1503
- }
1504
- }
1505
- return globalLogger;
1506
- }
1507
- function createScopedLogger(scope, config) {
1508
- return new DebugLogger({
1509
- ...config,
1510
- prefix: `[MSAL-Next:${scope}]`
1511
- });
1512
- }
1513
-
1514
- // src/middleware/createAuthMiddleware.ts
1515
- var import_server = require("next/server");
1516
- function createAuthMiddleware(config = {}) {
1517
- const {
1518
- protectedRoutes = [],
1519
- publicOnlyRoutes = [],
1520
- loginPath = "/login",
1521
- redirectAfterLogin = "/",
1522
- sessionCookie = "msal.account",
1523
- isAuthenticated: customAuthCheck,
1524
- debug = false
1525
- } = config;
1526
- return async function authMiddleware(request) {
1527
- const { pathname } = request.nextUrl;
1528
- if (debug) {
1529
- console.log("[AuthMiddleware] Processing:", pathname);
1530
- }
1531
- let authenticated = false;
1532
- if (customAuthCheck) {
1533
- authenticated = await customAuthCheck(request);
1534
- } else {
1535
- const sessionData = request.cookies.get(sessionCookie);
1536
- authenticated = !!sessionData?.value;
1537
- }
1538
- if (debug) {
1539
- console.log("[AuthMiddleware] Authenticated:", authenticated);
1540
- }
1541
- const isProtectedRoute = protectedRoutes.some(
1542
- (route) => pathname.startsWith(route)
1543
- );
1544
- const isPublicOnlyRoute = publicOnlyRoutes.some(
1545
- (route) => pathname.startsWith(route)
1546
- );
1547
- if (isProtectedRoute && !authenticated) {
1548
- if (debug) {
1549
- console.log("[AuthMiddleware] Redirecting to login");
1550
- }
1551
- const url = request.nextUrl.clone();
1552
- url.pathname = loginPath;
1553
- url.searchParams.set("returnUrl", pathname);
1554
- return import_server.NextResponse.redirect(url);
1555
- }
1556
- if (isPublicOnlyRoute && authenticated) {
1557
- if (debug) {
1558
- console.log("[AuthMiddleware] Redirecting to home");
1559
- }
1560
- const returnUrl = request.nextUrl.searchParams.get("returnUrl");
1561
- const url = request.nextUrl.clone();
1562
- url.pathname = returnUrl || redirectAfterLogin;
1563
- url.searchParams.delete("returnUrl");
1564
- return import_server.NextResponse.redirect(url);
1565
- }
1566
- const response = import_server.NextResponse.next();
1567
- if (authenticated) {
1568
- response.headers.set("x-msal-authenticated", "true");
1569
- try {
1570
- const sessionData = request.cookies.get(sessionCookie);
1571
- if (sessionData?.value) {
1572
- const account = safeJsonParse(sessionData.value, isValidAccountData);
1573
- if (account?.username) {
1574
- response.headers.set("x-msal-username", account.username);
1575
- }
1576
- }
1577
- } catch (error) {
1578
- if (debug) {
1579
- console.warn("[AuthMiddleware] Failed to parse session data");
1580
- }
1581
- }
1582
- }
1583
- return response;
1584
- };
1585
- }
1586
-
1587
- // src/client.ts
1588
- var import_msal_react3 = require("@azure/msal-react");
1589
- // Annotate the CommonJS export names for ESM import in node:
1590
- 0 && (module.exports = {
1591
- AuthGuard,
1592
- AuthStatus,
1593
- ErrorBoundary,
1594
- MSALProvider,
1595
- MicrosoftSignInButton,
1596
- MsalAuthProvider,
1597
- SignOutButton,
1598
- UserAvatar,
1599
- createAuthMiddleware,
1600
- createMsalConfig,
1601
- createRetryWrapper,
1602
- createScopedLogger,
1603
- getDebugLogger,
1604
- getMsalInstance,
1605
- isValidAccountData,
1606
- isValidRedirectUri,
1607
- isValidScope,
1608
- retryWithBackoff,
1609
- safeJsonParse,
1610
- sanitizeError,
1611
- useAccount,
1612
- useGraphApi,
1613
- useIsAuthenticated,
1614
- useMsal,
1615
- useMsalAuth,
1616
- useRoles,
1617
- useUserProfile,
1618
- validateScopes,
1619
- withAuth
1620
- });
1
+ 'use strict';var msalReact=require('@azure/msal-react'),msalBrowser=require('@azure/msal-browser'),react=require('react'),jsxRuntime=require('react/jsx-runtime'),server=require('next/server');function q(r,e){try{let t=JSON.parse(r);return e(t)?t:(console.warn("[Validation] JSON validation failed"),null)}catch(t){return console.error("[Validation] JSON parse error:",t),null}}function _(r){return typeof r=="object"&&r!==null&&typeof r.homeAccountId=="string"&&r.homeAccountId.length>0&&typeof r.username=="string"&&r.username.length>0&&(r.name===void 0||typeof r.name=="string")}function v(r){return r instanceof Error?r.message.replace(/[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}/g,"[TOKEN_REDACTED]").replace(/[a-f0-9]{32,}/gi,"[SECRET_REDACTED]").replace(/Bearer\s+[^\s]+/gi,"Bearer [REDACTED]"):"An unexpected error occurred"}function G(r,e){try{let t=new URL(r);return e.some(o=>{let i=new URL(o);return t.origin===i.origin})}catch{return false}}function ne(r){return /^[a-zA-Z0-9._-]+$/.test(r)}function Ae(r){return Array.isArray(r)&&r.every(ne)}function H(r){if(r.msalConfig)return r.msalConfig;let{clientId:e,tenantId:t,authorityType:o="common",redirectUri:i,postLogoutRedirectUri:a,cacheLocation:p="sessionStorage",storeAuthStateInCookie:u=false,navigateToLoginRequestUrl:c=false,enableLogging:n=false,loggerCallback:h,allowedRedirectUris:g}=r;if(!e)throw new Error("@chemmangat/msal-next: clientId is required");let l=()=>{if(o==="tenant"){if(!t)throw new Error('@chemmangat/msal-next: tenantId is required when authorityType is "tenant"');return `https://login.microsoftonline.com/${t}`}return `https://login.microsoftonline.com/${o}`},s=typeof window<"u"?window.location.origin:"http://localhost:3000",m=i||s;if(g&&g.length>0){if(!G(m,g))throw new Error(`@chemmangat/msal-next: redirectUri "${m}" is not in the allowed list`);let d=a||m;if(!G(d,g))throw new Error(`@chemmangat/msal-next: postLogoutRedirectUri "${d}" is not in the allowed list`)}return {auth:{clientId:e,authority:l(),redirectUri:m,postLogoutRedirectUri:a||m,navigateToLoginRequestUrl:c},cache:{cacheLocation:p,storeAuthStateInCookie:u},system:{loggerOptions:{loggerCallback:h||((d,y,R)=>{if(!(R||!n))switch(d){case msalBrowser.LogLevel.Error:console.error("[MSAL]",y);break;case msalBrowser.LogLevel.Warning:console.warn("[MSAL]",y);break;case msalBrowser.LogLevel.Info:console.info("[MSAL]",y);break;case msalBrowser.LogLevel.Verbose:console.debug("[MSAL]",y);break}}),logLevel:n?msalBrowser.LogLevel.Verbose:msalBrowser.LogLevel.Error}}}}var se=null;function Pe(){return se}function V({children:r,loadingComponent:e,onInitialized:t,...o}){let[i,a]=react.useState(null),p=react.useRef(null);return react.useEffect(()=>{if(typeof window>"u"||p.current)return;(async()=>{try{let c=H(o),n=new msalBrowser.PublicClientApplication(c);await n.initialize();try{let l=await n.handleRedirectPromise();l&&(o.enableLogging&&console.log("[MSAL] Redirect authentication successful"),l.account&&n.setActiveAccount(l.account),window.location.hash&&window.history.replaceState(null,"",window.location.pathname+window.location.search));}catch(l){l?.errorCode==="no_token_request_cache_error"?o.enableLogging&&console.log("[MSAL] No pending redirect found (this is normal)"):l?.errorCode==="user_cancelled"?o.enableLogging&&console.log("[MSAL] User cancelled authentication"):console.error("[MSAL] Redirect handling error:",l),window.location.hash&&(window.location.hash.includes("code=")||window.location.hash.includes("error="))&&window.history.replaceState(null,"",window.location.pathname+window.location.search);}let h=n.getAllAccounts();h.length>0&&!n.getActiveAccount()&&n.setActiveAccount(h[0]);let g=o.enableLogging||!1;n.addEventCallback(l=>{if(l.eventType===msalBrowser.EventType.LOGIN_SUCCESS){let s=l.payload;s?.account&&n.setActiveAccount(s.account),g&&console.log("[MSAL] Login successful:",s.account?.username);}if(l.eventType===msalBrowser.EventType.LOGIN_FAILURE&&console.error("[MSAL] Login failed:",l.error),l.eventType===msalBrowser.EventType.LOGOUT_SUCCESS&&(n.setActiveAccount(null),g&&console.log("[MSAL] Logout successful")),l.eventType===msalBrowser.EventType.ACQUIRE_TOKEN_SUCCESS){let s=l.payload;s?.account&&!n.getActiveAccount()&&n.setActiveAccount(s.account);}l.eventType===msalBrowser.EventType.ACQUIRE_TOKEN_FAILURE&&g&&console.error("[MSAL] Token acquisition failed:",l.error);}),p.current=n,se=n,a(n),t&&t(n);}catch(c){throw console.error("[MSAL] Initialization failed:",c),c}})();},[]),typeof window>"u"?jsxRuntime.jsx(jsxRuntime.Fragment,{children:e||jsxRuntime.jsx("div",{children:"Loading authentication..."})}):i?jsxRuntime.jsx(msalReact.MsalProvider,{instance:i,children:r}):jsxRuntime.jsx(jsxRuntime.Fragment,{children:e||jsxRuntime.jsx("div",{children:"Loading authentication..."})})}function Se({children:r,...e}){return jsxRuntime.jsx(V,{...e,children:r})}var W=new Map;function A(r=["User.Read"]){let{instance:e,accounts:t,inProgress:o}=msalReact.useMsal(),i=msalReact.useAccount(t[0]||null),a=react.useMemo(()=>t.length>0,[t]),p=react.useCallback(async(l=r)=>{if(o!==msalBrowser.InteractionStatus.None){console.warn("[MSAL] Interaction already in progress");return}try{let s={scopes:l,prompt:"select_account"};await e.loginRedirect(s);}catch(s){if(s?.errorCode==="user_cancelled"){console.log("[MSAL] User cancelled login");return}throw console.error("[MSAL] Login redirect failed:",s),s}},[e,r,o]),u=react.useCallback(async()=>{try{await e.logoutRedirect({account:i||void 0});}catch(l){throw console.error("[MSAL] Logout redirect failed:",l),l}},[e,i]),c=react.useCallback(async(l=r)=>{if(!i)throw new Error("[MSAL] No active account. Please login first.");try{let s={scopes:l,account:i,forceRefresh:!1};return (await e.acquireTokenSilent(s)).accessToken}catch(s){throw console.error("[MSAL] Silent token acquisition failed:",s),s}},[e,i,r]),n=react.useCallback(async(l=r)=>{if(!i)throw new Error("[MSAL] No active account. Please login first.");try{let s={scopes:l,account:i};await e.acquireTokenRedirect(s);}catch(s){throw console.error("[MSAL] Token redirect acquisition failed:",s),s}},[e,i,r]),h=react.useCallback(async(l=r)=>{let s=`${i?.homeAccountId||"anonymous"}-${l.sort().join(",")}`,m=W.get(s);if(m)return m;let f=(async()=>{try{return await c(l)}catch{throw console.warn("[MSAL] Silent token acquisition failed, falling back to redirect"),await n(l),new Error("[MSAL] Redirecting for token acquisition")}finally{W.delete(s);}})();return W.set(s,f),f},[c,n,r,i]),g=react.useCallback(async()=>{e.setActiveAccount(null),await e.clearCache();},[e]);return {account:i,accounts:t,isAuthenticated:a,inProgress:o!==msalBrowser.InteractionStatus.None,loginRedirect:p,logoutRedirect:u,acquireToken:h,acquireTokenSilent:c,acquireTokenRedirect:n,clearSession:g}}function Ue({text:r="Sign in with Microsoft",variant:e="dark",size:t="medium",scopes:o,className:i="",style:a,onSuccess:p,onError:u}){let{loginRedirect:c,inProgress:n}=A(),[h,g]=react.useState(false),l=async()=>{g(true);try{await c(o),p?.();}catch(y){u?.(y);}finally{setTimeout(()=>g(false),500);}},s={small:{padding:"8px 16px",fontSize:"14px",height:"36px"},medium:{padding:"10px 20px",fontSize:"15px",height:"41px"},large:{padding:"12px 24px",fontSize:"16px",height:"48px"}},m={dark:{backgroundColor:"#2F2F2F",color:"#FFFFFF",border:"1px solid #8C8C8C"},light:{backgroundColor:"#FFFFFF",color:"#5E5E5E",border:"1px solid #8C8C8C"}},f=n||h,d={display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"12px",fontFamily:'"Segoe UI", Tahoma, Geneva, Verdana, sans-serif',fontWeight:600,borderRadius:"2px",cursor:f?"not-allowed":"pointer",transition:"all 0.2s ease",opacity:f?.6:1,...m[e],...s[t],...a};return jsxRuntime.jsxs("button",{onClick:l,disabled:f,className:i,style:d,"aria-label":r,children:[jsxRuntime.jsx(ke,{}),jsxRuntime.jsx("span",{children:r})]})}function ke(){return jsxRuntime.jsxs("svg",{width:"21",height:"21",viewBox:"0 0 21 21",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsxRuntime.jsx("rect",{width:"10",height:"10",fill:"#F25022"}),jsxRuntime.jsx("rect",{x:"11",width:"10",height:"10",fill:"#7FBA00"}),jsxRuntime.jsx("rect",{y:"11",width:"10",height:"10",fill:"#00A4EF"}),jsxRuntime.jsx("rect",{x:"11",y:"11",width:"10",height:"10",fill:"#FFB900"})]})}function Fe({text:r="Sign out",variant:e="dark",size:t="medium",className:o="",style:i,onSuccess:a,onError:p}){let{logoutRedirect:u,inProgress:c}=A(),n=async()=>{try{await u(),a?.();}catch(s){p?.(s);}},h={small:{padding:"8px 16px",fontSize:"14px",height:"36px"},medium:{padding:"10px 20px",fontSize:"15px",height:"41px"},large:{padding:"12px 24px",fontSize:"16px",height:"48px"}},l={display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"12px",fontFamily:'"Segoe UI", Tahoma, Geneva, Verdana, sans-serif',fontWeight:600,borderRadius:"2px",cursor:c?"not-allowed":"pointer",transition:"all 0.2s ease",opacity:c?.6:1,...{dark:{backgroundColor:"#2F2F2F",color:"#FFFFFF",border:"1px solid #8C8C8C"},light:{backgroundColor:"#FFFFFF",color:"#5E5E5E",border:"1px solid #8C8C8C"}}[e],...h[t],...i};return jsxRuntime.jsxs("button",{onClick:n,disabled:c,className:o,style:l,"aria-label":r,children:[jsxRuntime.jsx(Ne,{}),jsxRuntime.jsx("span",{children:r})]})}function Ne(){return jsxRuntime.jsxs("svg",{width:"21",height:"21",viewBox:"0 0 21 21",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[jsxRuntime.jsx("rect",{width:"10",height:"10",fill:"#F25022"}),jsxRuntime.jsx("rect",{x:"11",width:"10",height:"10",fill:"#7FBA00"}),jsxRuntime.jsx("rect",{y:"11",width:"10",height:"10",fill:"#00A4EF"}),jsxRuntime.jsx("rect",{x:"11",y:"11",width:"10",height:"10",fill:"#FFB900"})]})}function k(){let{acquireToken:r}=A(),e=react.useCallback(async(u,c={})=>{let{scopes:n=["User.Read"],version:h="v1.0",debug:g=false,...l}=c;try{let s=await r(n),m=`https://graph.microsoft.com/${h}`,f=u.startsWith("http")?u:`${m}${u.startsWith("/")?u:`/${u}`}`;g&&console.log("[GraphAPI] Request:",{url:f,method:l.method||"GET"});let d=await fetch(f,{...l,headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json",...l.headers}});if(!d.ok){let R=await d.text(),L=`Graph API error (${d.status}): ${R}`;throw new Error(L)}if(d.status===204||d.headers.get("content-length")==="0")return null;let y=await d.json();return g&&console.log("[GraphAPI] Response:",y),y}catch(s){let m=v(s);throw console.error("[GraphAPI] Request failed:",m),new Error(m)}},[r]),t=react.useCallback((u,c={})=>e(u,{...c,method:"GET"}),[e]),o=react.useCallback((u,c,n={})=>e(u,{...n,method:"POST",body:c?JSON.stringify(c):void 0}),[e]),i=react.useCallback((u,c,n={})=>e(u,{...n,method:"PUT",body:c?JSON.stringify(c):void 0}),[e]),a=react.useCallback((u,c,n={})=>e(u,{...n,method:"PATCH",body:c?JSON.stringify(c):void 0}),[e]),p=react.useCallback((u,c={})=>e(u,{...c,method:"DELETE"}),[e]);return {get:t,post:o,put:i,patch:a,delete:p,request:e}}var x=new Map,Ie=300*1e3,pe=100;function Oe(){if(x.size>pe){let r=Array.from(x.entries());r.sort((t,o)=>t[1].timestamp-o[1].timestamp),r.slice(0,x.size-pe).forEach(([t])=>{let o=x.get(t);o?.data.photo&&URL.revokeObjectURL(o.data.photo),x.delete(t);});}}function J(){let{isAuthenticated:r,account:e}=A(),t=k(),[o,i]=react.useState(null),[a,p]=react.useState(false),[u,c]=react.useState(null),n=react.useCallback(async()=>{if(!r||!e){i(null);return}let g=e.homeAccountId,l=x.get(g);if(l&&Date.now()-l.timestamp<Ie){i(l.data);return}p(true),c(null);try{let s=await t.get("/me",{scopes:["User.Read"]}),m;try{let d=await t.get("/me/photo/$value",{scopes:["User.Read"],headers:{"Content-Type":"image/jpeg"}});d&&(m=URL.createObjectURL(d));}catch{console.debug("[UserProfile] Photo not available");}let f={id:s.id,displayName:s.displayName,givenName:s.givenName,surname:s.surname,userPrincipalName:s.userPrincipalName,mail:s.mail,jobTitle:s.jobTitle,officeLocation:s.officeLocation,mobilePhone:s.mobilePhone,businessPhones:s.businessPhones,photo:m};x.set(g,{data:f,timestamp:Date.now()}),Oe(),i(f);}catch(s){let f=v(s),d=new Error(f);c(d),console.error("[UserProfile] Failed to fetch profile:",f);}finally{p(false);}},[r,e,t]),h=react.useCallback(()=>{if(e){let g=x.get(e.homeAccountId);g?.data.photo&&URL.revokeObjectURL(g.data.photo),x.delete(e.homeAccountId);}o?.photo&&URL.revokeObjectURL(o.photo),i(null);},[e,o]);return react.useEffect(()=>(n(),()=>{o?.photo&&URL.revokeObjectURL(o.photo);}),[n]),react.useEffect(()=>()=>{o?.photo&&URL.revokeObjectURL(o.photo);},[o?.photo]),{profile:o,loading:a,error:u,refetch:n,clearCache:h}}function Ge({size:r=40,className:e="",style:t,showTooltip:o=true,fallbackImage:i}){let{profile:a,loading:p}=J(),[u,c]=react.useState(null),[n,h]=react.useState(false);react.useEffect(()=>{a?.photo&&c(a.photo);},[a?.photo]);let g=()=>{if(!a)return "?";let{givenName:m,surname:f,displayName:d}=a;if(m&&f)return `${m[0]}${f[0]}`.toUpperCase();if(d){let y=d.split(" ");return y.length>=2?`${y[0][0]}${y[y.length-1][0]}`.toUpperCase():d.substring(0,2).toUpperCase()}return "?"},l={width:`${r}px`,height:`${r}px`,borderRadius:"50%",display:"inline-flex",alignItems:"center",justifyContent:"center",fontSize:`${r*.4}px`,fontWeight:600,fontFamily:'"Segoe UI", Tahoma, Geneva, Verdana, sans-serif',backgroundColor:"#0078D4",color:"#FFFFFF",overflow:"hidden",userSelect:"none",...t},s=a?.displayName||"User";return p?jsxRuntime.jsx("div",{className:e,style:{...l,backgroundColor:"#E1E1E1"},"aria-label":"Loading user avatar",children:jsxRuntime.jsx("span",{style:{fontSize:`${r*.3}px`},children:"..."})}):u&&!n?jsxRuntime.jsx("div",{className:e,style:l,title:o?s:void 0,"aria-label":`${s} avatar`,children:jsxRuntime.jsx("img",{src:u,alt:s,style:{width:"100%",height:"100%",objectFit:"cover"},onError:()=>{h(true),i&&c(i);}})}):jsxRuntime.jsx("div",{className:e,style:l,title:o?s:void 0,"aria-label":`${s} avatar`,children:g()})}function $e({className:r="",style:e,showDetails:t=false,renderLoading:o,renderAuthenticated:i,renderUnauthenticated:a}){let{isAuthenticated:p,inProgress:u,account:c}=A(),n={display:"inline-flex",alignItems:"center",gap:"8px",padding:"8px 12px",borderRadius:"4px",fontFamily:'"Segoe UI", Tahoma, Geneva, Verdana, sans-serif',fontSize:"14px",fontWeight:500,...e};if(u)return o?jsxRuntime.jsx(jsxRuntime.Fragment,{children:o()}):jsxRuntime.jsxs("div",{className:r,style:{...n,backgroundColor:"#FFF4CE",color:"#8A6D3B"},role:"status","aria-live":"polite",children:[jsxRuntime.jsx(K,{color:"#FFA500"}),jsxRuntime.jsx("span",{children:"Loading..."})]});if(p){let h=c?.username||c?.name||"User";return i?jsxRuntime.jsx(jsxRuntime.Fragment,{children:i(h)}):jsxRuntime.jsxs("div",{className:r,style:{...n,backgroundColor:"#D4EDDA",color:"#155724"},role:"status","aria-live":"polite",children:[jsxRuntime.jsx(K,{color:"#28A745"}),jsxRuntime.jsx("span",{children:t?`Authenticated as ${h}`:"Authenticated"})]})}return a?jsxRuntime.jsx(jsxRuntime.Fragment,{children:a()}):jsxRuntime.jsxs("div",{className:r,style:{...n,backgroundColor:"#F8D7DA",color:"#721C24"},role:"status","aria-live":"polite",children:[jsxRuntime.jsx(K,{color:"#DC3545"}),jsxRuntime.jsx("span",{children:"Not authenticated"})]})}function K({color:r}){return jsxRuntime.jsx("svg",{width:"8",height:"8",viewBox:"0 0 8 8",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:jsxRuntime.jsx("circle",{cx:"4",cy:"4",r:"4",fill:r})})}function Y({children:r,loadingComponent:e,fallbackComponent:t,scopes:o,onAuthRequired:i}){let{isAuthenticated:a,inProgress:p,loginRedirect:u}=A();return react.useEffect(()=>{!a&&!p&&(i?.(),(async()=>{try{await u(o);}catch(n){console.error("[AuthGuard] Authentication failed:",n);}})());},[a,p,o,u,i]),p?jsxRuntime.jsx(jsxRuntime.Fragment,{children:e||jsxRuntime.jsx("div",{children:"Authenticating..."})}):a?jsxRuntime.jsx(jsxRuntime.Fragment,{children:r}):jsxRuntime.jsx(jsxRuntime.Fragment,{children:t||jsxRuntime.jsx("div",{children:"Redirecting to login..."})})}var re=class extends react.Component{constructor(t){super(t);this.reset=()=>{this.setState({hasError:false,error:null});};this.state={hasError:false,error:null};}static getDerivedStateFromError(t){return {hasError:true,error:t}}componentDidCatch(t,o){let{onError:i,debug:a}=this.props;a&&(console.error("[ErrorBoundary] Caught error:",t),console.error("[ErrorBoundary] Error info:",o)),i?.(t,o);}render(){let{hasError:t,error:o}=this.state,{children:i,fallback:a}=this.props;return t&&o?a?a(o,this.reset):jsxRuntime.jsxs("div",{style:{padding:"20px",margin:"20px",border:"1px solid #DC3545",borderRadius:"4px",backgroundColor:"#F8D7DA",color:"#721C24",fontFamily:'"Segoe UI", Tahoma, Geneva, Verdana, sans-serif'},children:[jsxRuntime.jsx("h2",{style:{margin:"0 0 10px 0",fontSize:"18px"},children:"Authentication Error"}),jsxRuntime.jsx("p",{style:{margin:"0 0 10px 0"},children:o.message}),jsxRuntime.jsx("button",{onClick:this.reset,style:{padding:"8px 16px",backgroundColor:"#DC3545",color:"#FFFFFF",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"14px",fontWeight:600},children:"Try Again"})]}):i}};var w=new Map,He=300*1e3,fe=100;function Ve(r){r?w.delete(r):w.clear();}function We(){if(w.size>fe){let r=Array.from(w.entries());r.sort((t,o)=>t[1].timestamp-o[1].timestamp),r.slice(0,w.size-fe).forEach(([t])=>w.delete(t));}}function je(){let{isAuthenticated:r,account:e}=A(),t=k(),[o,i]=react.useState([]),[a,p]=react.useState([]),[u,c]=react.useState(false),[n,h]=react.useState(null),g=react.useCallback(async()=>{if(!r||!e){i([]),p([]);return}let d=e.homeAccountId,y=w.get(d);if(y&&Date.now()-y.timestamp<He){i(y.roles),p(y.groups);return}c(true),h(null);try{let L=e.idTokenClaims?.roles||[],D=(await t.get("/me/memberOf",{scopes:["User.Read","Directory.Read.All"]})).value.map(oe=>oe.id);w.set(d,{roles:L,groups:D,timestamp:Date.now()}),We(),i(L),p(D);}catch(R){let B=v(R),D=new Error(B);h(D),console.error("[Roles] Failed to fetch roles/groups:",B);let ye=e.idTokenClaims?.roles||[];i(ye);}finally{c(false);}},[r,e,t]),l=react.useCallback(d=>o.includes(d),[o]),s=react.useCallback(d=>a.includes(d),[a]),m=react.useCallback(d=>d.some(y=>o.includes(y)),[o]),f=react.useCallback(d=>d.every(y=>o.includes(y)),[o]);return react.useEffect(()=>(g(),()=>{e&&Ve(e.homeAccountId);}),[g,e]),{roles:o,groups:a,loading:u,error:n,hasRole:l,hasGroup:s,hasAnyRole:m,hasAllRoles:f,refetch:g}}function Je(r,e={}){let{displayName:t,...o}=e,i=a=>jsxRuntime.jsx(Y,{...o,children:jsxRuntime.jsx(r,{...a})});return i.displayName=t||`withAuth(${r.displayName||r.name||"Component"})`,i}async function me(r,e={}){let{maxRetries:t=3,initialDelay:o=1e3,maxDelay:i=1e4,backoffMultiplier:a=2,debug:p=false}=e,u,c=o;for(let n=0;n<=t;n++)try{return p&&n>0&&console.log(`[TokenRetry] Attempt ${n+1}/${t+1}`),await r()}catch(h){if(u=h,n===t){p&&console.error("[TokenRetry] All retry attempts failed");break}if(!Ke(h))throw p&&console.log("[TokenRetry] Non-retryable error, aborting"),h;p&&console.warn(`[TokenRetry] Attempt ${n+1} failed, retrying in ${c}ms...`),await Ze(c),c=Math.min(c*a,i);}throw u}function Ke(r){let e=r.message.toLowerCase();return !!(e.includes("network")||e.includes("timeout")||e.includes("fetch")||e.includes("connection")||e.includes("500")||e.includes("502")||e.includes("503")||e.includes("429")||e.includes("rate limit")||e.includes("token")&&e.includes("expired"))}function Ze(r){return new Promise(e=>setTimeout(e,r))}function Qe(r,e={}){return (...t)=>me(()=>r(...t),e)}var z=class{constructor(e={}){this.logHistory=[];this.performanceTimings=new Map;this.config={enabled:e.enabled??false,prefix:e.prefix??"[MSAL-Next]",showTimestamp:e.showTimestamp??true,level:e.level??"info",enablePerformance:e.enablePerformance??false,enableNetworkLogs:e.enableNetworkLogs??false,maxHistorySize:e.maxHistorySize??100};}shouldLog(e){if(!this.config.enabled)return false;let t=["error","warn","info","debug"],o=t.indexOf(this.config.level);return t.indexOf(e)<=o}formatMessage(e,t,o){let i=this.config.showTimestamp?`[${new Date().toISOString()}]`:"",a=this.config.prefix,p=`[${e.toUpperCase()}]`,u=`${i} ${a} ${p} ${t}`;return o!==void 0&&(u+=`
2
+ `+JSON.stringify(o,null,2)),u}addToHistory(e,t,o){this.logHistory.length>=this.config.maxHistorySize&&this.logHistory.shift(),this.logHistory.push({timestamp:Date.now(),level:e,message:t,data:o});}error(e,t){this.shouldLog("error")&&(console.error(this.formatMessage("error",e,t)),this.addToHistory("error",e,t));}warn(e,t){this.shouldLog("warn")&&(console.warn(this.formatMessage("warn",e,t)),this.addToHistory("warn",e,t));}info(e,t){this.shouldLog("info")&&(console.info(this.formatMessage("info",e,t)),this.addToHistory("info",e,t));}debug(e,t){this.shouldLog("debug")&&(console.debug(this.formatMessage("debug",e,t)),this.addToHistory("debug",e,t));}group(e){this.config.enabled&&console.group(`${this.config.prefix} ${e}`);}groupEnd(){this.config.enabled&&console.groupEnd();}startTiming(e){this.config.enablePerformance&&(this.performanceTimings.set(e,{operation:e,startTime:performance.now()}),this.debug(`\u23F1\uFE0F Started: ${e}`));}endTiming(e){if(this.config.enablePerformance){let t=this.performanceTimings.get(e);if(t)return t.endTime=performance.now(),t.duration=t.endTime-t.startTime,this.info(`\u23F1\uFE0F Completed: ${e} (${t.duration.toFixed(2)}ms)`),t.duration}}logRequest(e,t,o){this.config.enableNetworkLogs&&this.debug(`\u{1F310} ${e} ${t}`,o);}logResponse(e,t,o,i){if(this.config.enableNetworkLogs){let a=o>=200&&o<300?"\u2705":"\u274C";this.debug(`${a} ${e} ${t} - ${o}`,i);}}getHistory(){return [...this.logHistory]}getPerformanceTimings(){return Array.from(this.performanceTimings.values())}clearHistory(){this.logHistory=[];}clearTimings(){this.performanceTimings.clear();}exportLogs(){return JSON.stringify({config:this.config,history:this.logHistory,performanceTimings:Array.from(this.performanceTimings.values()),exportedAt:new Date().toISOString()},null,2)}downloadLogs(e="msal-next-debug-logs.json"){if(typeof window>"u")return;let t=this.exportLogs(),o=new Blob([t],{type:"application/json"}),i=URL.createObjectURL(o),a=document.createElement("a");a.href=i,a.download=e,a.click(),URL.revokeObjectURL(i);}setEnabled(e){this.config.enabled=e;}setLevel(e){e&&(this.config.level=e);}},O=null;function Xe(r){return O?r&&(r.enabled!==void 0&&O.setEnabled(r.enabled),r.level&&O.setLevel(r.level)):O=new z(r),O}function Ye(r,e){return new z({...e,prefix:`[MSAL-Next:${r}]`})}function er(r={}){let{protectedRoutes:e=[],publicOnlyRoutes:t=[],loginPath:o="/login",redirectAfterLogin:i="/",sessionCookie:a="msal.account",isAuthenticated:p,debug:u=false}=r;return async function(n){let{pathname:h}=n.nextUrl;u&&console.log("[AuthMiddleware] Processing:",h);let g=false;p?g=await p(n):g=!!n.cookies.get(a)?.value,u&&console.log("[AuthMiddleware] Authenticated:",g);let l=e.some(f=>h.startsWith(f)),s=t.some(f=>h.startsWith(f));if(l&&!g){u&&console.log("[AuthMiddleware] Redirecting to login");let f=n.nextUrl.clone();return f.pathname=o,f.searchParams.set("returnUrl",h),server.NextResponse.redirect(f)}if(s&&g){u&&console.log("[AuthMiddleware] Redirecting to home");let f=n.nextUrl.searchParams.get("returnUrl"),d=n.nextUrl.clone();return d.pathname=f||i,d.searchParams.delete("returnUrl"),server.NextResponse.redirect(d)}let m=server.NextResponse.next();if(g){m.headers.set("x-msal-authenticated","true");try{let f=n.cookies.get(a);if(f?.value){let d=q(f.value,_);d?.username&&m.headers.set("x-msal-username",d.username);}}catch{u&&console.warn("[AuthMiddleware] Failed to parse session data");}}return m}}Object.defineProperty(exports,"useAccount",{enumerable:true,get:function(){return msalReact.useAccount}});Object.defineProperty(exports,"useIsAuthenticated",{enumerable:true,get:function(){return msalReact.useIsAuthenticated}});Object.defineProperty(exports,"useMsal",{enumerable:true,get:function(){return msalReact.useMsal}});exports.AuthGuard=Y;exports.AuthStatus=$e;exports.ErrorBoundary=re;exports.MSALProvider=Se;exports.MicrosoftSignInButton=Ue;exports.MsalAuthProvider=V;exports.SignOutButton=Fe;exports.UserAvatar=Ge;exports.createAuthMiddleware=er;exports.createMsalConfig=H;exports.createRetryWrapper=Qe;exports.createScopedLogger=Ye;exports.getDebugLogger=Xe;exports.getMsalInstance=Pe;exports.isValidAccountData=_;exports.isValidRedirectUri=G;exports.isValidScope=ne;exports.retryWithBackoff=me;exports.safeJsonParse=q;exports.sanitizeError=v;exports.useGraphApi=k;exports.useMsalAuth=A;exports.useRoles=je;exports.useUserProfile=J;exports.validateScopes=Ae;exports.withAuth=Je;