@nibssplc/cams-sdk-react 0.0.1-beta.75 → 0.0.1-beta.77

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.cjs.js CHANGED
@@ -256,322 +256,18 @@ function useCAMSAuth(options) {
256
256
  };
257
257
  }
258
258
 
259
- function useCAMSMSALAuth(options) {
260
- var _this = this;
261
- var storageKey = options.storageKey || "CAMS-MSAL-AUTH-SDK";
262
- var _a = msalReact.useMsal(), instance = _a.instance, inProgress = _a.inProgress, accounts = _a.accounts;
263
- var account = msalReact.useAccount(accounts[0] || {});
264
- var _b = React.useState(null), error = _b[0], setError = _b[1];
265
- var _c = React.useState(""), idToken = _c[0], setIdToken = _c[1];
266
- var _d = React.useState(""), accessToken = _d[0], setAccessToken = _d[1];
267
- var _e = React.useState(null), mfaAuthenticator = _e[0], setMfaAuthenticator = _e[1];
268
- var _f = React.useState(false), requiresMFA = _f[0], setRequiresMFA = _f[1];
269
- var isLoading = inProgress !== msalBrowser.InteractionStatus.None;
270
- var isAuthenticated = !!account && !!accessToken && !requiresMFA;
271
- var scopes = options.scopes || ["openid", "profile", "email"];
272
- var isTokenValid = function (token) {
273
- try {
274
- var payload = JSON.parse(atob(token.split(".")[1]));
275
- return payload.exp * 1000 > Date.now();
276
- }
277
- catch (_a) {
278
- return false;
279
- }
280
- };
281
- React.useEffect(function () {
282
- if (typeof window !== "undefined" && !accessToken) {
283
- var stored = localStorage.getItem(storageKey);
284
- if (stored) {
285
- try {
286
- var _a = JSON.parse(stored), accessToken_1 = _a.accessToken, idToken_1 = _a.idToken, storedRequiresMFA = _a.requiresMFA, storedIsAuthenticated = _a.isAuthenticated;
287
- if (accessToken_1 && isTokenValid(accessToken_1)) {
288
- setAccessToken(accessToken_1);
289
- setIdToken(idToken_1);
290
- // Restore MFA state
291
- if (storedRequiresMFA && !storedIsAuthenticated) {
292
- var mfaConfig = {
293
- accessToken: accessToken_1,
294
- idToken: idToken_1,
295
- appCode: options.appCode,
296
- provider: "MSAL",
297
- apiEndpoint: options.MFAEndpoint,
298
- };
299
- var authenticator = new camsSdk.CAMSMFAAuthenticator(mfaConfig);
300
- setMfaAuthenticator(authenticator);
301
- setRequiresMFA(true);
302
- }
303
- camsSdk.Logger.debug("App Code", { ">>>": options.appCode });
304
- }
305
- else {
306
- localStorage.removeItem(storageKey);
307
- }
308
- }
309
- catch (_b) { }
310
- }
311
- else if (account) {
312
- // Storage cleared but MSAL account exists - clear MSAL state
313
- instance.logoutRedirect().catch(function () { });
314
- }
315
- }
316
- }, [accessToken, account, instance, options.storageKey]);
317
- // useEffect(() => {
318
- // const handleRedirect = async () => {
319
- // try {
320
- // const response = await instance.handleRedirectPromise();
321
- // if (response) {
322
- // const account = response.account;
323
- // instance.setActiveA ccount(account);
324
- // const tokenResponse = await instance.acq uireTokenSilent({
325
- // scopes,
326
- // account,
327
- // });
328
- // setToken(tokenResponse.accessToken);
329
- // setAccessToken(tokenResponse.accessToken);
330
- // setIdToken(tokenResponse.idTo ken);
331
- // options.onAuthSuccess?.(tokenR esponse.accessToken);
332
- // if (
333
- // typeof window !== "undefined" &&
334
- // process.env.NODE_ENV !== "test"
335
- // ) {
336
- // window.location.href = options.mfaUrl!;
337
- // }
338
- // }
339
- // } catch (err) {
340
- // console.error("Redirect handling failed:", err);
341
- // }
342
- // };
343
- // handleRedirect();
344
- // }, []);
345
- var login = React.useCallback(function () { return __awaiter(_this, void 0, void 0, function () {
346
- var response, mfaConfig, authenticator, err_1, camsError_1, camsError;
347
- var _a, _b, _c, _d;
348
- return __generator(this, function (_e) {
349
- switch (_e.label) {
350
- case 0:
351
- setError(null);
352
- _e.label = 1;
353
- case 1:
354
- _e.trys.push([1, 3, , 4]);
355
- return [4 /*yield*/, instance.loginPopup({
356
- scopes: scopes,
357
- prompt: options.prompt || "login",
358
- })];
359
- case 2:
360
- response = _e.sent();
361
- console.log("Login Token response:", {
362
- accessToken: response.accessToken,
363
- idToken: response.idToken,
364
- });
365
- setAccessToken(response.accessToken);
366
- setIdToken(response.idToken);
367
- mfaConfig = {
368
- accessToken: response.accessToken,
369
- idToken: response.idToken,
370
- appCode: options.appCode,
371
- provider: "MSAL",
372
- apiEndpoint: options.MFAEndpoint,
373
- };
374
- authenticator = new camsSdk.CAMSMFAAuthenticator(mfaConfig);
375
- setMfaAuthenticator(authenticator);
376
- setRequiresMFA(true);
377
- // Don't persist as authenticated until MFA is complete
378
- if (typeof window !== "undefined") {
379
- localStorage.setItem(storageKey, JSON.stringify({
380
- isAuthenticated: false,
381
- requiresMFA: true,
382
- accessToken: response.accessToken,
383
- idToken: response.idToken,
384
- }));
385
- }
386
- (_a = options.onAuthSuccess) === null || _a === void 0 ? void 0 : _a.call(options, response.accessToken);
387
- return [3 /*break*/, 4];
388
- case 3:
389
- err_1 = _e.sent();
390
- // Handle user cancellation gracefully
391
- if (err_1.errorCode === "user_cancelled") {
392
- camsSdk.Logger.error("User cancelled login");
393
- setError(null); // Don't treat cancellation as an error
394
- return [2 /*return*/];
395
- }
396
- // If popup is blocked
397
- if (err_1.errorCode === "popup_window_error" ||
398
- ((_b = err_1.message) === null || _b === void 0 ? void 0 : _b.includes("popup"))) {
399
- camsError_1 = new camsSdk.CAMSError(camsSdk.CAMSErrorType.POPUP_BLOCKED, "Popup blocked by browser. Please allow popups and try again.");
400
- setError(camsError_1);
401
- (_c = options.onAuthError) === null || _c === void 0 ? void 0 : _c.call(options, camsError_1);
402
- return [2 /*return*/];
403
- }
404
- camsError = new camsSdk.CAMSError(camsSdk.CAMSErrorType.API_VALIDATION_ERROR, "Login failed: " + err_1.message || err_1);
405
- setError(camsError);
406
- (_d = options.onAuthError) === null || _d === void 0 ? void 0 : _d.call(options, camsError);
407
- return [3 /*break*/, 4];
408
- case 4: return [2 /*return*/];
409
- }
410
- });
411
- }); }, [instance, scopes, options]);
412
- var completeMFA = React.useCallback(function (code, type) { return __awaiter(_this, void 0, void 0, function () {
413
- var mfaResponse, error_1;
414
- return __generator(this, function (_a) {
415
- switch (_a.label) {
416
- case 0:
417
- if (!mfaAuthenticator) {
418
- throw new camsSdk.CAMSError(camsSdk.CAMSErrorType.API_VALIDATION_ERROR, "MFA Authenticator not initialized");
419
- }
420
- _a.label = 1;
421
- case 1:
422
- _a.trys.push([1, 3, , 4]);
423
- return [4 /*yield*/, mfaAuthenticator.verifyOTP(code, type)];
424
- case 2:
425
- mfaResponse = _a.sent();
426
- if (mfaResponse.isAuthenticated) {
427
- // Update storage with complete authentication BEFORE setting state
428
- if (typeof window !== "undefined") {
429
- localStorage.setItem(storageKey, JSON.stringify({
430
- isAuthenticated: true,
431
- requiresMFA: false,
432
- accessToken: accessToken,
433
- idToken: idToken,
434
- userProfile: mfaResponse,
435
- }));
436
- camsSdk.Logger.info("MFA completed successfully, storage updated", {
437
- accessToken: accessToken,
438
- idToken: idToken,
439
- isAuthenticated: isAuthenticated,
440
- requiresMFA: requiresMFA,
441
- });
442
- }
443
- // Set requiresMFA to false after storage update
444
- setRequiresMFA(false);
445
- camsSdk.Logger.debug("MFA completed successfully, requiresMFA set to false");
446
- }
447
- return [2 /*return*/, mfaResponse];
448
- case 3:
449
- error_1 = _a.sent();
450
- setError(error_1);
451
- throw error_1;
452
- case 4: return [2 /*return*/];
453
- }
454
- });
455
- }); }, [mfaAuthenticator, accessToken, idToken, storageKey, requiresMFA]);
456
- var sendEmailOTP = React.useCallback(function () { return __awaiter(_this, void 0, void 0, function () {
457
- return __generator(this, function (_a) {
458
- switch (_a.label) {
459
- case 0:
460
- if (!mfaAuthenticator) {
461
- return [2 /*return*/, false];
462
- }
463
- return [4 /*yield*/, mfaAuthenticator.sendEmailOTP()];
464
- case 1: return [2 /*return*/, _a.sent()];
465
- }
466
- });
467
- }); }, [mfaAuthenticator]);
468
- var logout = React.useCallback(function () { return __awaiter(_this, void 0, void 0, function () {
469
- var err_2, camsError;
470
- return __generator(this, function (_a) {
471
- switch (_a.label) {
472
- case 0:
473
- _a.trys.push([0, 2, , 3]);
474
- camsSdk.Logger.info("Logging User Out");
475
- return [4 /*yield*/, instance.logoutRedirect()];
476
- case 1:
477
- _a.sent();
478
- setAccessToken("");
479
- setIdToken("");
480
- setError(null);
481
- setMfaAuthenticator(null);
482
- setRequiresMFA(false);
483
- if (typeof window !== "undefined") {
484
- localStorage.removeItem(storageKey);
485
- }
486
- return [3 /*break*/, 3];
487
- case 2:
488
- err_2 = _a.sent();
489
- camsError = new camsSdk.CAMSError(camsSdk.CAMSErrorType.API_VALIDATION_ERROR, "Logout failed: " + err_2);
490
- setError(camsError);
491
- return [3 /*break*/, 3];
492
- case 3: return [2 /*return*/];
493
- }
494
- });
495
- }); }, [instance, storageKey]);
496
- return {
497
- login: login,
498
- logout: logout,
499
- storageKey: storageKey,
500
- isAuthenticated: isAuthenticated,
501
- isLoading: isLoading,
502
- error: error,
503
- idToken: idToken,
504
- accessToken: accessToken,
505
- appCode: options.appCode,
506
- mfaAuthenticator: mfaAuthenticator,
507
- requiresMFA: requiresMFA,
508
- completeMFA: completeMFA,
509
- sendEmailOTP: sendEmailOTP,
510
- };
511
- }
259
+ var jsxRuntime = {exports: {}};
260
+
261
+ var reactJsxRuntime_production = {};
512
262
 
513
263
  /**
514
- * Hook for handling authentication in popup windows
515
- * This should be used by the popup app to complete authentication
516
- */
517
- function useCAMSPopupAuth(options) {
518
- if (options === void 0) { options = {}; }
519
- var _a = options.storageKey, storageKey = _a === void 0 ? "CAMS-SDK" : _a, targetOrigin = options.targetOrigin, onAuthComplete = options.onAuthComplete, onAuthError = options.onAuthError;
520
- React.useEffect(function () {
521
- if (typeof window === "undefined" || !camsSdk.isPopupWindow())
522
- return;
523
- // Initialize popup auth handler
524
- camsSdk.initializePopupAuth(targetOrigin);
525
- // Set up global handlers for the popup app
526
- var globalHandlers = window.__CAMS_POPUP_AUTH__;
527
- if (globalHandlers) {
528
- var originalCompleteAuth_1 = globalHandlers.completeAuth;
529
- var originalErrorAuth_1 = globalHandlers.errorAuth;
530
- globalHandlers.completeAuth = function (profile) {
531
- onAuthComplete === null || onAuthComplete === void 0 ? void 0 : onAuthComplete(profile);
532
- originalCompleteAuth_1(profile);
533
- };
534
- globalHandlers.errorAuth = function (error) {
535
- onAuthError === null || onAuthError === void 0 ? void 0 : onAuthError(error);
536
- originalErrorAuth_1(error);
537
- };
538
- }
539
- }, [targetOrigin, onAuthComplete, onAuthError]);
540
- var completeAuth = React.useCallback(function (profile) {
541
- if (!camsSdk.isPopupWindow()) {
542
- console.warn("completeAuth called outside of popup window");
543
- return;
544
- }
545
- var sessionManager = new camsSdk.CAMSSessionManager(localStorage, storageKey);
546
- sessionManager.completePopupAuth(profile, targetOrigin);
547
- }, [storageKey, targetOrigin]);
548
- var errorAuth = React.useCallback(function (error) {
549
- if (!camsSdk.isPopupWindow()) {
550
- console.warn("errorAuth called outside of popup window");
551
- return;
552
- }
553
- var sessionManager = new camsSdk.CAMSSessionManager(localStorage, storageKey);
554
- sessionManager.errorPopupAuth(error, targetOrigin);
555
- }, [storageKey, targetOrigin]);
556
- return {
557
- completeAuth: completeAuth,
558
- errorAuth: errorAuth,
559
- isPopup: camsSdk.isPopupWindow(),
560
- };
561
- }
562
-
563
- var jsxRuntime = {exports: {}};
564
-
565
- var reactJsxRuntime_production = {};
566
-
567
- /**
568
- * @license React
569
- * react-jsx-runtime.production.js
570
- *
571
- * Copyright (c) Meta Platforms, Inc. and affiliates.
572
- *
573
- * This source code is licensed under the MIT license found in the
574
- * LICENSE file in the root directory of this source tree.
264
+ * @license React
265
+ * react-jsx-runtime.production.js
266
+ *
267
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
268
+ *
269
+ * This source code is licensed under the MIT license found in the
270
+ * LICENSE file in the root directory of this source tree.
575
271
  */
576
272
 
577
273
  var hasRequiredReactJsxRuntime_production;
@@ -971,17 +667,464 @@ function requireReactJsxRuntime_development () {
971
667
  return reactJsxRuntime_development;
972
668
  }
973
669
 
974
- if (process.env.NODE_ENV === 'production') {
975
- jsxRuntime.exports = requireReactJsxRuntime_production();
976
- } else {
977
- jsxRuntime.exports = requireReactJsxRuntime_development();
670
+ if (process.env.NODE_ENV === 'production') {
671
+ jsxRuntime.exports = requireReactJsxRuntime_production();
672
+ } else {
673
+ jsxRuntime.exports = requireReactJsxRuntime_development();
674
+ }
675
+
676
+ var jsxRuntimeExports = jsxRuntime.exports;
677
+
678
+ var CAMSContext$1 = React.createContext(null);
679
+ function useCAMSContext$1() {
680
+ var context = React.useContext(CAMSContext$1);
681
+ if (!context) {
682
+ throw new Error("useCAMSContext must be used within a UnifiedCAMSProvider");
683
+ }
684
+ return context;
685
+ }
686
+
687
+ var ClientOnly = function (_a) {
688
+ var children = _a.children, _b = _a.fallback, fallback = _b === void 0 ? null : _b;
689
+ var _c = React.useState(false), hasMounted = _c[0], setHasMounted = _c[1];
690
+ React.useEffect(function () {
691
+ setHasMounted(true);
692
+ }, []);
693
+ if (!hasMounted) {
694
+ return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, { children: fallback });
695
+ }
696
+ return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, { children: children });
697
+ };
698
+
699
+ var GuidSchema = z.z.uuid("appCode must be a valid GUID");
700
+ var setCookie$1 = function (name, value, days) {
701
+ if (days === void 0) { days = 1; }
702
+ var expires = new Date(Date.now() + days * 24 * 60 * 60 * 1000).toUTCString();
703
+ document.cookie = "".concat(name, "=").concat(encodeURIComponent(value), "; expires=").concat(expires, "; path=/; samesite=Lax");
704
+ };
705
+ var getCookie$1 = function (name) {
706
+ var _a;
707
+ return ((_a = document.cookie
708
+ .split("; ")
709
+ .find(function (row) { return row.startsWith(name + "="); })) === null || _a === void 0 ? void 0 : _a.split("=")[1])
710
+ ? decodeURIComponent(document.cookie
711
+ .split("; ")
712
+ .find(function (row) { return row.startsWith(name + "="); })
713
+ .split("=")[1])
714
+ : null;
715
+ };
716
+ var deleteCookie$1 = function (name) {
717
+ document.cookie = name + "=; Max-Age=-99999999; path=/";
718
+ };
719
+ function CAMSProviderCore(props) {
720
+ var _this = this;
721
+ var children = props.children, mode = props.mode, appCode = props.appCode;
722
+ // Always call both hooks to satisfy Rules of Hooks
723
+ var regularAuth = useCAMSAuth(mode === "REGULAR"
724
+ ? __assign(__assign({}, props), { appCode: appCode })
725
+ : { appCode: "" });
726
+ var msalAuth = useCAMSMSALAuth(mode === "MSAL"
727
+ ? __assign(__assign({}, props), { appCode: appCode })
728
+ : { appCode: "" });
729
+ var auth = mode === "REGULAR" ? regularAuth : msalAuth;
730
+ var profileStorageKey = "".concat(auth.storageKey, "-PROFILE");
731
+ var getInitialProfile = function () {
732
+ if (typeof window === "undefined")
733
+ return null;
734
+ try {
735
+ var storedProfile = getCookie$1(profileStorageKey);
736
+ return storedProfile ? JSON.parse(storedProfile) : null;
737
+ }
738
+ catch (_a) {
739
+ return null;
740
+ }
741
+ };
742
+ var _a = React.useState(getInitialProfile), userProfile = _a[0], setUserProfile = _a[1];
743
+ React.useEffect(function () {
744
+ if (typeof window !== "undefined") {
745
+ var storedProfile = getCookie$1(profileStorageKey);
746
+ if (storedProfile) {
747
+ try {
748
+ setUserProfile(JSON.parse(storedProfile));
749
+ }
750
+ catch (_a) { }
751
+ }
752
+ }
753
+ }, [profileStorageKey]);
754
+ React.useEffect(function () {
755
+ if (typeof window !== "undefined") {
756
+ if (userProfile) {
757
+ setCookie$1(profileStorageKey, JSON.stringify(userProfile), 1);
758
+ }
759
+ else {
760
+ deleteCookie$1(profileStorageKey);
761
+ }
762
+ }
763
+ }, [userProfile, profileStorageKey]);
764
+ var enhancedLogout = function () { return __awaiter(_this, void 0, void 0, function () {
765
+ return __generator(this, function (_a) {
766
+ switch (_a.label) {
767
+ case 0: return [4 /*yield*/, auth.logout()];
768
+ case 1:
769
+ _a.sent();
770
+ setUserProfile(null);
771
+ if (typeof window !== "undefined") {
772
+ deleteCookie$1(profileStorageKey);
773
+ }
774
+ return [2 /*return*/];
775
+ }
776
+ });
777
+ }); };
778
+ // Handle MFA completion for MSAL mode
779
+ React.useEffect(function () {
780
+ if (mode === "MSAL" &&
781
+ "requiresMFA" in auth &&
782
+ !auth.requiresMFA &&
783
+ auth.isAuthenticated) {
784
+ // MFA completed, extract profile from localStorage
785
+ var storedData = localStorage.getItem(auth.storageKey);
786
+ console.log("MFA Complete - Checking for profile:", storedData);
787
+ if (storedData) {
788
+ try {
789
+ var parsed = JSON.parse(storedData);
790
+ console.log("Parsed storage data:", parsed);
791
+ if (parsed.userProfile) {
792
+ console.log("Setting user profile:", parsed.userProfile);
793
+ setUserProfile(parsed.userProfile);
794
+ }
795
+ }
796
+ catch (e) {
797
+ console.error("Error parsing stored data:", e);
798
+ }
799
+ }
800
+ }
801
+ }, [
802
+ mode,
803
+ "requiresMFA" in auth ? auth.requiresMFA : false,
804
+ auth.isAuthenticated,
805
+ auth.storageKey,
806
+ userProfile,
807
+ ]);
808
+ var value = React.useMemo(function () {
809
+ return (__assign(__assign({}, auth), { logout: enhancedLogout, userProfile: userProfile, setUserProfile: setUserProfile, authMode: mode }));
810
+ }, [auth, userProfile, mode]);
811
+ return jsxRuntimeExports.jsx(CAMSContext$1.Provider, { value: value, children: children });
812
+ }
813
+ function UnifiedCAMSProvider(props) {
814
+ // Validate appCode is a valid GUID
815
+ var appCodeValidation = GuidSchema.safeParse(props.appCode);
816
+ if (!appCodeValidation.success) {
817
+ throw new Error("Invalid appCode: ".concat(appCodeValidation.error.issues[0].message));
818
+ }
819
+ if (props.mode === "MSAL") {
820
+ var msalConfig = props.msalConfig, msalInstance = props.msalInstance;
821
+ var instance = msalInstance || new msalBrowser.PublicClientApplication(msalConfig);
822
+ return (jsxRuntimeExports.jsx(msalReact.MsalProvider, { instance: instance, children: jsxRuntimeExports.jsx(CAMSProviderCore, __assign({}, props)) }));
823
+ }
824
+ return (jsxRuntimeExports.jsx(ClientOnly, { fallback: jsxRuntimeExports.jsx("div", { children: "Loading..." }), children: jsxRuntimeExports.jsx(CAMSProviderCore, __assign({}, props)) }));
825
+ }
826
+ // Backward compatibility exports
827
+ var CAMSProvider = function (props) { return (jsxRuntimeExports.jsx(UnifiedCAMSProvider, __assign({}, props, { mode: "REGULAR" }))); };
828
+
829
+ function useCAMSMSALAuth(options) {
830
+ var _this = this;
831
+ var storageKey = options.storageKey || "CAMS-MSAL-AUTH-SDK";
832
+ var _a = msalReact.useMsal(), instance = _a.instance, inProgress = _a.inProgress, accounts = _a.accounts;
833
+ var account = msalReact.useAccount(accounts[0] || {});
834
+ var _b = React.useState(null), error = _b[0], setError = _b[1];
835
+ var _c = React.useState(""), idToken = _c[0], setIdToken = _c[1];
836
+ var _d = React.useState(""), accessToken = _d[0], setAccessToken = _d[1];
837
+ var _e = React.useState(null), mfaAuthenticator = _e[0], setMfaAuthenticator = _e[1];
838
+ var _f = React.useState(false), requiresMFA = _f[0], setRequiresMFA = _f[1];
839
+ var isLoading = inProgress !== msalBrowser.InteractionStatus.None;
840
+ var isAuthenticated = !!account && !!accessToken && !requiresMFA;
841
+ var scopes = options.scopes || ["openid", "profile", "email"];
842
+ var isTokenValid = function (token) {
843
+ try {
844
+ var payload = JSON.parse(atob(token.split(".")[1]));
845
+ return payload.exp * 1000 > Date.now();
846
+ }
847
+ catch (_a) {
848
+ return false;
849
+ }
850
+ };
851
+ React.useEffect(function () {
852
+ if (typeof window !== "undefined" && !accessToken) {
853
+ var stored = localStorage.getItem(storageKey);
854
+ if (stored) {
855
+ try {
856
+ var _a = JSON.parse(stored), accessToken_1 = _a.accessToken, idToken_1 = _a.idToken, storedRequiresMFA = _a.requiresMFA, storedIsAuthenticated = _a.isAuthenticated;
857
+ if (accessToken_1 && isTokenValid(accessToken_1)) {
858
+ setAccessToken(accessToken_1);
859
+ setIdToken(idToken_1);
860
+ // Restore MFA state
861
+ if (storedRequiresMFA && !storedIsAuthenticated) {
862
+ var mfaConfig = {
863
+ accessToken: accessToken_1,
864
+ idToken: idToken_1,
865
+ appCode: options.appCode,
866
+ provider: "MSAL",
867
+ apiEndpoint: options.MFAEndpoint,
868
+ };
869
+ var authenticator = new camsSdk.CAMSMFAAuthenticator(mfaConfig);
870
+ setMfaAuthenticator(authenticator);
871
+ setRequiresMFA(true);
872
+ }
873
+ camsSdk.Logger.debug("App Code", { ">>>": options.appCode });
874
+ }
875
+ else {
876
+ localStorage.removeItem(storageKey);
877
+ }
878
+ }
879
+ catch (_b) { }
880
+ }
881
+ else if (account) {
882
+ // Storage cleared but MSAL account exists - clear MSAL state
883
+ instance.logoutRedirect().catch(function () { });
884
+ }
885
+ }
886
+ }, [accessToken, account, instance, options.storageKey]);
887
+ // useEffect(() => {
888
+ // const handleRedirect = async () => {
889
+ // try {
890
+ // const response = await instance.handleRedirectPromise();
891
+ // if (response) {
892
+ // const account = response.account;
893
+ // instance.setActiveA ccount(account);
894
+ // const tokenResponse = await instance.acq uireTokenSilent({
895
+ // scopes,
896
+ // account,
897
+ // });
898
+ // setToken(tokenResponse.accessToken);
899
+ // setAccessToken(tokenResponse.accessToken);
900
+ // setIdToken(tokenResponse.idTo ken);
901
+ // options.onAuthSuccess?.(tokenR esponse.accessToken);
902
+ // if (
903
+ // typeof window !== "undefined" &&
904
+ // process.env.NODE_ENV !== "test"
905
+ // ) {
906
+ // window.location.href = options.mfaUrl!;
907
+ // }
908
+ // }
909
+ // } catch (err) {
910
+ // console.error("Redirect handling failed:", err);
911
+ // }
912
+ // };
913
+ // handleRedirect();
914
+ // }, []);
915
+ var login = React.useCallback(function () { return __awaiter(_this, void 0, void 0, function () {
916
+ var response, mfaConfig, authenticator, err_1, camsError_1, camsError;
917
+ var _a, _b, _c, _d;
918
+ return __generator(this, function (_e) {
919
+ switch (_e.label) {
920
+ case 0:
921
+ setError(null);
922
+ _e.label = 1;
923
+ case 1:
924
+ _e.trys.push([1, 3, , 4]);
925
+ return [4 /*yield*/, instance.loginPopup({
926
+ scopes: scopes,
927
+ prompt: options.prompt || "login",
928
+ })];
929
+ case 2:
930
+ response = _e.sent();
931
+ console.log("Login Token response:", {
932
+ accessToken: response.accessToken,
933
+ idToken: response.idToken,
934
+ });
935
+ setAccessToken(response.accessToken);
936
+ setIdToken(response.idToken);
937
+ mfaConfig = {
938
+ accessToken: response.accessToken,
939
+ idToken: response.idToken,
940
+ appCode: options.appCode,
941
+ provider: "MSAL",
942
+ apiEndpoint: options.MFAEndpoint,
943
+ };
944
+ authenticator = new camsSdk.CAMSMFAAuthenticator(mfaConfig);
945
+ setMfaAuthenticator(authenticator);
946
+ setRequiresMFA(true);
947
+ // Don't persist as authenticated until MFA is complete
948
+ if (typeof window !== "undefined") {
949
+ localStorage.setItem(storageKey, JSON.stringify({
950
+ isAuthenticated: false,
951
+ requiresMFA: true,
952
+ accessToken: response.accessToken,
953
+ idToken: response.idToken,
954
+ }));
955
+ }
956
+ (_a = options.onAuthSuccess) === null || _a === void 0 ? void 0 : _a.call(options, response.accessToken);
957
+ return [3 /*break*/, 4];
958
+ case 3:
959
+ err_1 = _e.sent();
960
+ // Handle user cancellation gracefully
961
+ if (err_1.errorCode === "user_cancelled") {
962
+ camsSdk.Logger.error("User cancelled login");
963
+ setError(null); // Don't treat cancellation as an error
964
+ return [2 /*return*/];
965
+ }
966
+ // If popup is blocked
967
+ if (err_1.errorCode === "popup_window_error" ||
968
+ ((_b = err_1.message) === null || _b === void 0 ? void 0 : _b.includes("popup"))) {
969
+ camsError_1 = new camsSdk.CAMSError(camsSdk.CAMSErrorType.POPUP_BLOCKED, "Popup blocked by browser. Please allow popups and try again.");
970
+ setError(camsError_1);
971
+ (_c = options.onAuthError) === null || _c === void 0 ? void 0 : _c.call(options, camsError_1);
972
+ return [2 /*return*/];
973
+ }
974
+ camsError = new camsSdk.CAMSError(camsSdk.CAMSErrorType.API_VALIDATION_ERROR, "Login failed: " + err_1.message || err_1);
975
+ setError(camsError);
976
+ (_d = options.onAuthError) === null || _d === void 0 ? void 0 : _d.call(options, camsError);
977
+ return [3 /*break*/, 4];
978
+ case 4: return [2 /*return*/];
979
+ }
980
+ });
981
+ }); }, [instance, scopes, options]);
982
+ var completeMFA = React.useCallback(function (data) { return __awaiter(_this, void 0, void 0, function () {
983
+ return __generator(this, function (_a) {
984
+ if (!mfaAuthenticator) {
985
+ throw new camsSdk.CAMSError(camsSdk.CAMSErrorType.API_VALIDATION_ERROR, "MFA Authenticator not initialized");
986
+ }
987
+ camsSdk.Logger.info("Completed MFA.. Setting State");
988
+ try {
989
+ // Update storage with complete authentication BEFORE setting state
990
+ if (typeof window !== "undefined") {
991
+ localStorage.setItem(storageKey, JSON.stringify({
992
+ isAuthenticated: true,
993
+ requiresMFA: false,
994
+ accessToken: accessToken,
995
+ idToken: idToken,
996
+ }));
997
+ setCookie$1("CAMS-MSAL-AUTH-SDK-PROFILE", JSON.stringify({ type: "AUTH_SUCCESS", userProfile: __assign({}, data) }), 1);
998
+ setRequiresMFA(false);
999
+ // Set requiresMFA to false after storage update
1000
+ camsSdk.Logger.debug("MFA completed successfully, storage updated", {
1001
+ accessToken: accessToken,
1002
+ idToken: idToken,
1003
+ isAuthenticated: true,
1004
+ requiresMFA: false,
1005
+ });
1006
+ }
1007
+ camsSdk.Logger.debug("MFA completed successfully, requiresMFA set to false");
1008
+ return [2 /*return*/, data];
1009
+ }
1010
+ catch (error) {
1011
+ setError(error);
1012
+ throw error;
1013
+ }
1014
+ return [2 /*return*/];
1015
+ });
1016
+ }); }, [mfaAuthenticator, accessToken, idToken, storageKey]);
1017
+ var sendEmailOTP = React.useCallback(function () { return __awaiter(_this, void 0, void 0, function () {
1018
+ return __generator(this, function (_a) {
1019
+ switch (_a.label) {
1020
+ case 0:
1021
+ if (!mfaAuthenticator) {
1022
+ return [2 /*return*/, false];
1023
+ }
1024
+ return [4 /*yield*/, mfaAuthenticator.sendEmailOTP()];
1025
+ case 1: return [2 /*return*/, _a.sent()];
1026
+ }
1027
+ });
1028
+ }); }, [mfaAuthenticator]);
1029
+ var logout = React.useCallback(function () { return __awaiter(_this, void 0, void 0, function () {
1030
+ var err_2, camsError;
1031
+ return __generator(this, function (_a) {
1032
+ switch (_a.label) {
1033
+ case 0:
1034
+ _a.trys.push([0, 2, , 3]);
1035
+ camsSdk.Logger.info("Logging User Out");
1036
+ return [4 /*yield*/, instance.logoutRedirect()];
1037
+ case 1:
1038
+ _a.sent();
1039
+ setAccessToken("");
1040
+ setIdToken("");
1041
+ setError(null);
1042
+ setMfaAuthenticator(null);
1043
+ setRequiresMFA(false);
1044
+ if (typeof window !== "undefined") {
1045
+ localStorage.removeItem(storageKey);
1046
+ }
1047
+ return [3 /*break*/, 3];
1048
+ case 2:
1049
+ err_2 = _a.sent();
1050
+ camsError = new camsSdk.CAMSError(camsSdk.CAMSErrorType.API_VALIDATION_ERROR, "Logout failed: " + err_2);
1051
+ setError(camsError);
1052
+ return [3 /*break*/, 3];
1053
+ case 3: return [2 /*return*/];
1054
+ }
1055
+ });
1056
+ }); }, [instance, storageKey]);
1057
+ return {
1058
+ login: login,
1059
+ logout: logout,
1060
+ storageKey: storageKey,
1061
+ isAuthenticated: isAuthenticated,
1062
+ isLoading: isLoading,
1063
+ error: error,
1064
+ idToken: idToken,
1065
+ accessToken: accessToken,
1066
+ appCode: options.appCode,
1067
+ mfaAuthenticator: mfaAuthenticator,
1068
+ requiresMFA: requiresMFA,
1069
+ completeMFA: completeMFA,
1070
+ sendEmailOTP: sendEmailOTP,
1071
+ setRequiresMFA: setRequiresMFA,
1072
+ };
1073
+ }
1074
+
1075
+ /**
1076
+ * Hook for handling authentication in popup windows
1077
+ * This should be used by the popup app to complete authentication
1078
+ */
1079
+ function useCAMSPopupAuth(options) {
1080
+ if (options === void 0) { options = {}; }
1081
+ var _a = options.storageKey, storageKey = _a === void 0 ? "CAMS-SDK" : _a, targetOrigin = options.targetOrigin, onAuthComplete = options.onAuthComplete, onAuthError = options.onAuthError;
1082
+ React.useEffect(function () {
1083
+ if (typeof window === "undefined" || !camsSdk.isPopupWindow())
1084
+ return;
1085
+ // Initialize popup auth handler
1086
+ camsSdk.initializePopupAuth(targetOrigin);
1087
+ // Set up global handlers for the popup app
1088
+ var globalHandlers = window.__CAMS_POPUP_AUTH__;
1089
+ if (globalHandlers) {
1090
+ var originalCompleteAuth_1 = globalHandlers.completeAuth;
1091
+ var originalErrorAuth_1 = globalHandlers.errorAuth;
1092
+ globalHandlers.completeAuth = function (profile) {
1093
+ onAuthComplete === null || onAuthComplete === void 0 ? void 0 : onAuthComplete(profile);
1094
+ originalCompleteAuth_1(profile);
1095
+ };
1096
+ globalHandlers.errorAuth = function (error) {
1097
+ onAuthError === null || onAuthError === void 0 ? void 0 : onAuthError(error);
1098
+ originalErrorAuth_1(error);
1099
+ };
1100
+ }
1101
+ }, [targetOrigin, onAuthComplete, onAuthError]);
1102
+ var completeAuth = React.useCallback(function (profile) {
1103
+ if (!camsSdk.isPopupWindow()) {
1104
+ console.warn("completeAuth called outside of popup window");
1105
+ return;
1106
+ }
1107
+ var sessionManager = new camsSdk.CAMSSessionManager(localStorage, storageKey);
1108
+ sessionManager.completePopupAuth(profile, targetOrigin);
1109
+ }, [storageKey, targetOrigin]);
1110
+ var errorAuth = React.useCallback(function (error) {
1111
+ if (!camsSdk.isPopupWindow()) {
1112
+ console.warn("errorAuth called outside of popup window");
1113
+ return;
1114
+ }
1115
+ var sessionManager = new camsSdk.CAMSSessionManager(localStorage, storageKey);
1116
+ sessionManager.errorPopupAuth(error, targetOrigin);
1117
+ }, [storageKey, targetOrigin]);
1118
+ return {
1119
+ completeAuth: completeAuth,
1120
+ errorAuth: errorAuth,
1121
+ isPopup: camsSdk.isPopupWindow(),
1122
+ };
978
1123
  }
979
1124
 
980
- var jsxRuntimeExports = jsxRuntime.exports;
981
-
982
- var CAMSContext$1 = React.createContext(null);
983
- function useCAMSContext$1() {
984
- var context = React.useContext(CAMSContext$1);
1125
+ var CAMSContext = React.createContext(null);
1126
+ function useCAMSContext() {
1127
+ var context = React.useContext(CAMSContext);
985
1128
  if (!context) {
986
1129
  throw new Error('useCAMSContext must be used within a CAMSProvider');
987
1130
  }
@@ -990,7 +1133,7 @@ function useCAMSContext$1() {
990
1133
 
991
1134
  function ProtectedRoute(_a) {
992
1135
  var children = _a.children, fallback = _a.fallback, redirectTo = _a.redirectTo;
993
- var _b = useCAMSContext$1(), isAuthenticated = _b.isAuthenticated, isLoading = _b.isLoading;
1136
+ var _b = useCAMSContext(), isAuthenticated = _b.isAuthenticated, isLoading = _b.isLoading;
994
1137
  if (isLoading) {
995
1138
  return fallback || jsxRuntimeExports.jsx("div", { children: "Loading..." });
996
1139
  }
@@ -1005,11 +1148,11 @@ function ProtectedRoute(_a) {
1005
1148
  }
1006
1149
 
1007
1150
  var CAMSMSALContext = React.createContext(null);
1008
- var setCookie$1 = function (name, value, days) {
1151
+ var setCookie = function (name, value, days) {
1009
1152
  var expires = new Date(Date.now() + days * 864e5).toUTCString();
1010
1153
  document.cookie = "".concat(name, "=").concat(encodeURIComponent(value), "; expires=").concat(expires, "; path=/; samesite=Lax");
1011
1154
  };
1012
- var getCookie$1 = function (name) {
1155
+ var getCookie = function (name) {
1013
1156
  var _a;
1014
1157
  return ((_a = document.cookie
1015
1158
  .split("; ")
@@ -1020,7 +1163,7 @@ var getCookie$1 = function (name) {
1020
1163
  .split("=")[1])
1021
1164
  : null;
1022
1165
  };
1023
- var deleteCookie$1 = function (name) {
1166
+ var deleteCookie = function (name) {
1024
1167
  document.cookie = name + "=; Max-Age=-99999999; path=/";
1025
1168
  };
1026
1169
  var isTokenValid = function (token) {
@@ -1042,7 +1185,7 @@ function CAMSMSALProviderInner(_a) {
1042
1185
  return null;
1043
1186
  }
1044
1187
  try {
1045
- var storedProfile = getCookie$1(profileStorageKey);
1188
+ var storedProfile = getCookie(profileStorageKey);
1046
1189
  return storedProfile ? JSON.parse(storedProfile) : null;
1047
1190
  }
1048
1191
  catch (_a) {
@@ -1054,7 +1197,7 @@ function CAMSMSALProviderInner(_a) {
1054
1197
  React.useEffect(function () {
1055
1198
  if (typeof window !== "undefined") {
1056
1199
  // const storedProfile = localStorage.get Item(profileStorageKey);
1057
- var storedProfile = getCookie$1(profileStorageKey);
1200
+ var storedProfile = getCookie(profileStorageKey);
1058
1201
  if (storedProfile) {
1059
1202
  try {
1060
1203
  setUserProfile(JSON.parse(storedProfile));
@@ -1079,10 +1222,10 @@ function CAMSMSALProviderInner(_a) {
1079
1222
  React.useEffect(function () {
1080
1223
  if (typeof window !== "undefined") {
1081
1224
  if (userProfile) {
1082
- setCookie$1(profileStorageKey, JSON.stringify(userProfile), 1); // Store for 1 day
1225
+ setCookie(profileStorageKey, JSON.stringify(userProfile), 1); // Store for 1 day
1083
1226
  }
1084
1227
  else {
1085
- deleteCookie$1(profileStorageKey);
1228
+ deleteCookie(profileStorageKey);
1086
1229
  }
1087
1230
  }
1088
1231
  }, [userProfile, profileStorageKey]);
@@ -1095,7 +1238,7 @@ function CAMSMSALProviderInner(_a) {
1095
1238
  _a.sent();
1096
1239
  setUserProfile(null);
1097
1240
  if (typeof window !== "undefined") {
1098
- deleteCookie$1(profileStorageKey);
1241
+ deleteCookie(profileStorageKey);
1099
1242
  }
1100
1243
  return [2 /*return*/];
1101
1244
  }
@@ -1117,156 +1260,6 @@ function useCAMSMSALContext() {
1117
1260
  return context;
1118
1261
  }
1119
1262
 
1120
- var ClientOnly = function (_a) {
1121
- var children = _a.children, _b = _a.fallback, fallback = _b === void 0 ? null : _b;
1122
- var _c = React.useState(false), hasMounted = _c[0], setHasMounted = _c[1];
1123
- React.useEffect(function () {
1124
- setHasMounted(true);
1125
- }, []);
1126
- if (!hasMounted) {
1127
- return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, { children: fallback });
1128
- }
1129
- return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, { children: children });
1130
- };
1131
-
1132
- var CAMSContext = React.createContext(null);
1133
- function useCAMSContext() {
1134
- var context = React.useContext(CAMSContext);
1135
- if (!context) {
1136
- throw new Error("useCAMSContext must be used within a UnifiedCAMSProvider");
1137
- }
1138
- return context;
1139
- }
1140
-
1141
- var GuidSchema = z.z.uuid("appCode must be a valid GUID");
1142
- var setCookie = function (name, value, days) {
1143
- var expires = new Date(Date.now() + days * 24 * 60 * 60 * 1000).toUTCString();
1144
- document.cookie = "".concat(name, "=").concat(encodeURIComponent(value), "; expires=").concat(expires, "; path=/; samesite=Lax");
1145
- };
1146
- var getCookie = function (name) {
1147
- var _a;
1148
- return ((_a = document.cookie
1149
- .split("; ")
1150
- .find(function (row) { return row.startsWith(name + "="); })) === null || _a === void 0 ? void 0 : _a.split("=")[1])
1151
- ? decodeURIComponent(document.cookie
1152
- .split("; ")
1153
- .find(function (row) { return row.startsWith(name + "="); })
1154
- .split("=")[1])
1155
- : null;
1156
- };
1157
- var deleteCookie = function (name) {
1158
- document.cookie = name + "=; Max-Age=-99999999; path=/";
1159
- };
1160
- function CAMSProviderCore(props) {
1161
- var _this = this;
1162
- var children = props.children, mode = props.mode, appCode = props.appCode;
1163
- // Always call both hooks to satisfy Rules of Hooks
1164
- var regularAuth = useCAMSAuth(mode === "REGULAR"
1165
- ? __assign(__assign({}, props), { appCode: appCode })
1166
- : { appCode: "" });
1167
- var msalAuth = useCAMSMSALAuth(mode === "MSAL"
1168
- ? __assign(__assign({}, props), { appCode: appCode })
1169
- : { appCode: "" });
1170
- var auth = mode === "REGULAR" ? regularAuth : msalAuth;
1171
- var profileStorageKey = "".concat(auth.storageKey, "-PROFILE");
1172
- var getInitialProfile = function () {
1173
- if (typeof window === "undefined")
1174
- return null;
1175
- try {
1176
- var storedProfile = getCookie(profileStorageKey);
1177
- return storedProfile ? JSON.parse(storedProfile) : null;
1178
- }
1179
- catch (_a) {
1180
- return null;
1181
- }
1182
- };
1183
- var _a = React.useState(getInitialProfile), userProfile = _a[0], setUserProfile = _a[1];
1184
- React.useEffect(function () {
1185
- if (typeof window !== "undefined") {
1186
- var storedProfile = getCookie(profileStorageKey);
1187
- if (storedProfile) {
1188
- try {
1189
- setUserProfile(JSON.parse(storedProfile));
1190
- }
1191
- catch (_a) { }
1192
- }
1193
- }
1194
- }, [profileStorageKey]);
1195
- React.useEffect(function () {
1196
- if (typeof window !== "undefined") {
1197
- if (userProfile) {
1198
- setCookie(profileStorageKey, JSON.stringify(userProfile), 1);
1199
- }
1200
- else {
1201
- deleteCookie(profileStorageKey);
1202
- }
1203
- }
1204
- }, [userProfile, profileStorageKey]);
1205
- var enhancedLogout = function () { return __awaiter(_this, void 0, void 0, function () {
1206
- return __generator(this, function (_a) {
1207
- switch (_a.label) {
1208
- case 0: return [4 /*yield*/, auth.logout()];
1209
- case 1:
1210
- _a.sent();
1211
- setUserProfile(null);
1212
- if (typeof window !== "undefined") {
1213
- deleteCookie(profileStorageKey);
1214
- }
1215
- return [2 /*return*/];
1216
- }
1217
- });
1218
- }); };
1219
- // Handle MFA completion for MSAL mode
1220
- React.useEffect(function () {
1221
- if (mode === "MSAL" &&
1222
- "requiresMFA" in auth &&
1223
- !auth.requiresMFA &&
1224
- auth.isAuthenticated) {
1225
- // MFA completed, extract profile from localStorage
1226
- var storedData = localStorage.getItem(auth.storageKey);
1227
- console.log("MFA Complete - Checking for profile:", storedData);
1228
- if (storedData) {
1229
- try {
1230
- var parsed = JSON.parse(storedData);
1231
- console.log("Parsed storage data:", parsed);
1232
- if (parsed.userProfile) {
1233
- console.log("Setting user profile:", parsed.userProfile);
1234
- setUserProfile(parsed.userProfile);
1235
- }
1236
- }
1237
- catch (e) {
1238
- console.error("Error parsing stored data:", e);
1239
- }
1240
- }
1241
- }
1242
- }, [
1243
- mode,
1244
- "requiresMFA" in auth ? auth.requiresMFA : false,
1245
- auth.isAuthenticated,
1246
- auth.storageKey,
1247
- userProfile,
1248
- ]);
1249
- var value = React.useMemo(function () {
1250
- return (__assign(__assign({}, auth), { logout: enhancedLogout, userProfile: userProfile, setUserProfile: setUserProfile, authMode: mode }));
1251
- }, [auth, userProfile, mode]);
1252
- return jsxRuntimeExports.jsx(CAMSContext.Provider, { value: value, children: children });
1253
- }
1254
- function UnifiedCAMSProvider(props) {
1255
- // Validate appCode is a valid GUID
1256
- var appCodeValidation = GuidSchema.safeParse(props.appCode);
1257
- if (!appCodeValidation.success) {
1258
- throw new Error("Invalid appCode: ".concat(appCodeValidation.error.issues[0].message));
1259
- }
1260
- if (props.mode === "MSAL") {
1261
- var msalConfig = props.msalConfig, msalInstance = props.msalInstance;
1262
- var instance = msalInstance || new msalBrowser.PublicClientApplication(msalConfig);
1263
- return (jsxRuntimeExports.jsx(msalReact.MsalProvider, { instance: instance, children: jsxRuntimeExports.jsx(CAMSProviderCore, __assign({}, props)) }));
1264
- }
1265
- return (jsxRuntimeExports.jsx(ClientOnly, { fallback: jsxRuntimeExports.jsx("div", { children: "Loading..." }), children: jsxRuntimeExports.jsx(CAMSProviderCore, __assign({}, props)) }));
1266
- }
1267
- // Backward compatibility exports
1268
- var CAMSProvider = function (props) { return (jsxRuntimeExports.jsx(UnifiedCAMSProvider, __assign({}, props, { mode: "REGULAR" }))); };
1269
-
1270
1263
  /** A special constant with type `never` */
1271
1264
  function $constructor(name, initializer, params) {
1272
1265
  function init(inst, def) {
@@ -1766,8 +1759,8 @@ var MFAOptions = function (_a) {
1766
1759
  var _d = React.useState(false), otpVisible = _d[0], setOtpVisible = _d[1];
1767
1760
  var _e = React.useState(false), showSuccessAnimation = _e[0], setShowSuccessAnimation = _e[1];
1768
1761
  var _f = React.useState(null), authType = _f[0], setAuthType = _f[1];
1769
- var _g = React.useState(""), lastOTPCode = _g[0], setLastOTPCode = _g[1];
1770
- var context = useCAMSContext();
1762
+ var _g = React.useState(""); _g[0]; var setLastOTPCode = _g[1];
1763
+ var context = useCAMSContext$1();
1771
1764
  var _h = context.authMode === "MSAL" && "sendEmailOTP" in context
1772
1765
  ? context
1773
1766
  : { sendEmailOTP: null, completeMFA: null, logout: function () { return __awaiter(void 0, void 0, void 0, function () { return __generator(this, function (_a) {
@@ -1783,10 +1776,12 @@ var MFAOptions = function (_a) {
1783
1776
  authenticationType: authType,
1784
1777
  MFAEndpoint: MFAEndpoint,
1785
1778
  onAuthComplete: function (state, data) {
1779
+ console.log("Completed Auth. Handling MFA", state);
1786
1780
  if (state) {
1787
1781
  // Call completeMFA to update context state
1788
- if (completeMFA && authType && lastOTPCode) {
1789
- completeMFA(lastOTPCode, authType).catch(function (error) {
1782
+ if (completeMFA && data) {
1783
+ console.log("IN Complete MFA Block. Handling MFA", data);
1784
+ completeMFA(data).catch(function (error) {
1790
1785
  console.error("Failed to complete MFA:", error);
1791
1786
  });
1792
1787
  }
@@ -1802,7 +1797,7 @@ var MFAOptions = function (_a) {
1802
1797
  onAuthFailed === null || onAuthFailed === void 0 ? void 0 : onAuthFailed();
1803
1798
  onComplete === null || onComplete === void 0 ? void 0 : onComplete(false);
1804
1799
  });
1805
- }, 1000);
1800
+ }, 3000);
1806
1801
  }
1807
1802
  }
1808
1803
  },
@@ -1874,7 +1869,7 @@ var AuthLogo = "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2
1874
1869
  var MicrosoftLogo = "data:image/svg+xml,%3Csvg%20width%3D%2225%22%20height%3D%2225%22%20viewBox%3D%220%200%2025%2025%22%20fill%3D%22none%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cg%20id%3D%22microsoft_svgrepo.com%22%3E%3Cpath%20id%3D%22Vector%22%20d%3D%22M20.75%2013.25H13.25V20.75H20.75V13.25Z%22%20fill%3D%22%23FEBA08%22%2F%3E%3Cpath%20id%3D%22Vector_2%22%20d%3D%22M11.75%2013.25H4.25V20.75H11.75V13.25Z%22%20fill%3D%22%2305A6F0%22%2F%3E%3Cpath%20id%3D%22Vector_3%22%20d%3D%22M20.75%204.25H13.25V11.75H20.75V4.25Z%22%20fill%3D%22%2380BC06%22%2F%3E%3Cpath%20id%3D%22Vector_4%22%20d%3D%22M11.75%204.25H4.25V11.75H11.75V4.25Z%22%20fill%3D%22%23F25325%22%2F%3E%3C%2Fg%3E%3C%2Fsvg%3E";
1875
1870
 
1876
1871
  var DefaultLoginPage = function () {
1877
- var context = useCAMSContext();
1872
+ var context = useCAMSContext$1();
1878
1873
  var login = context.login, isLoading = context.isLoading, authMode = context.authMode;
1879
1874
  var handleLogin = function () {
1880
1875
  if (authMode === "MSAL") {
@@ -1902,41 +1897,49 @@ var DefaultLoginPage = function () {
1902
1897
  className: "w-full flex items-center justify-center cursor-pointer bg-[#506f4a] hover:bg-[#506f4a] rounded-lg border border-transparent px-5 py-8 text-base font-medium transition-colors duration-250", onClick: handleLogin, disabled: isLoading, children: [jsxRuntimeExports.jsx("img", { src: MicrosoftLogo, alt: "Microsoft Logo", width: 35, height: 35 }), jsxRuntimeExports.jsx("span", { children: isLoading ? 'Logging in...' : "Sign in with Microsoft" })] }) }), jsxRuntimeExports.jsxs(CardFooter, { className: "flex items-center justify-center mt-6 space-x-2 text-gray-400 text-sm", children: [jsxRuntimeExports.jsx(lucideReact.ShieldCheck, { className: "w-4 h-4 text-[#506f4a] pulse-glow" }), jsxRuntimeExports.jsx("span", { children: "Powered By NIBSS" })] })] }) }) }, "landing") }));
1903
1898
  };
1904
1899
 
1900
+ var ErrorFallback = function (_a) {
1901
+ var message = _a.message;
1902
+ return (jsxRuntimeExports.jsx("div", { className: "flex items-center justify-center min-h-screen bg-gray-50", children: jsxRuntimeExports.jsxs("div", { className: "bg-white p-6 rounded-lg shadow-lg border border-red-200 max-w-md", children: [jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3 mb-2", children: [jsxRuntimeExports.jsx("svg", { className: "w-6 h-6 text-red-500", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: jsxRuntimeExports.jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" }) }), jsxRuntimeExports.jsx("h2", { className: "text-lg font-semibold text-gray-900", children: "Configuration Error" })] }), jsxRuntimeExports.jsx("p", { className: "text-red-600", children: message })] }) }));
1903
+ };
1904
+
1905
1905
  var MFAEndpointUrlSchema = z.url("MFAEndpoint must be a valid URL");
1906
1906
  var MFAGate = function (_a) {
1907
- var children = _a.children, fallback = _a.fallback, LoginComponent = _a.loginComponent, MFAEndpoint = _a.MFAEndpoint;
1908
- var context = useCAMSContext();
1909
- var urlValidation = MFAEndpointUrlSchema.safeParse(MFAEndpoint);
1910
- if (!urlValidation.success) {
1911
- throw new Error("Invalid MFAEndpoint: ".concat(urlValidation.error.issues[0].message));
1912
- }
1907
+ var children = _a.children, _b = _a.fallback, fallback = _b === void 0 ? jsxRuntimeExports.jsx(LoadingSpinner, {}) : _b, _c = _a.loginComponent, LoginComponent = _c === void 0 ? DefaultLoginPage : _c, MFAEndpoint = _a.MFAEndpoint;
1908
+ var context = useCAMSContext$1();
1909
+ var validatedMFAEndpoint = React.useMemo(function () {
1910
+ var parsed = MFAEndpointUrlSchema.safeParse(MFAEndpoint);
1911
+ if (!parsed.success) {
1912
+ camsSdk.Logger.error("Invalid MFAEndpoint", parsed.error);
1913
+ return null;
1914
+ }
1915
+ return parsed.data;
1916
+ }, [MFAEndpoint]);
1917
+ var handleComplete = React.useCallback(function (success) {
1918
+ if (!success)
1919
+ camsSdk.Logger.error("MFA authentication failed");
1920
+ }, []);
1921
+ var handleAuthFailed = React.useCallback(function () { return __awaiter(void 0, void 0, void 0, function () {
1922
+ return __generator(this, function (_a) {
1923
+ switch (_a.label) {
1924
+ case 0: return [4 /*yield*/, context.logout()];
1925
+ case 1:
1926
+ _a.sent();
1927
+ return [2 /*return*/];
1928
+ }
1929
+ });
1930
+ }); }, [context.logout]);
1913
1931
  camsSdk.Logger.debug("MFA Endpoint >>>", { MFAEndpoint: MFAEndpoint });
1914
- // Only apply MFA gate for MSAL mode
1915
- if (context.authMode !== "MSAL") {
1932
+ if (!validatedMFAEndpoint)
1933
+ return jsxRuntimeExports.jsx(ErrorFallback, { message: "Invalid MFA configuration." });
1934
+ if (context.authMode !== "MSAL")
1916
1935
  return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, { children: children });
1936
+ if (context.isLoading)
1937
+ return fallback;
1938
+ if (context.requiresMFA) {
1939
+ return (jsxRuntimeExports.jsx(MFAOptions, { MFAEndpoint: validatedMFAEndpoint, onComplete: handleComplete, onAuthFailed: handleAuthFailed }));
1917
1940
  }
1918
- var requiresMFA = context.requiresMFA, isAuthenticated = context.isAuthenticated, isLoading = context.isLoading;
1919
- if (isLoading) {
1920
- return fallback || jsxRuntimeExports.jsx("div", { className: "flex h-dvh items-center justify-center", children: "Loading..." });
1921
- }
1922
- if (requiresMFA) {
1923
- return (jsxRuntimeExports.jsx(MFAOptions, { MFAEndpoint: MFAEndpoint, onComplete: function (success) {
1924
- if (!success) {
1925
- console.error("MFA authentication failed");
1926
- }
1927
- }, onAuthFailed: function () { return __awaiter(void 0, void 0, void 0, function () {
1928
- return __generator(this, function (_a) {
1929
- switch (_a.label) {
1930
- case 0: return [4 /*yield*/, context.logout()];
1931
- case 1:
1932
- _a.sent();
1933
- return [2 /*return*/];
1934
- }
1935
- });
1936
- }); } }));
1937
- }
1938
- if (!isAuthenticated) {
1939
- return LoginComponent ? jsxRuntimeExports.jsx(LoginComponent, {}) : jsxRuntimeExports.jsx(DefaultLoginPage, {});
1941
+ if (!context.isAuthenticated) {
1942
+ return jsxRuntimeExports.jsx(LoginComponent, {});
1940
1943
  }
1941
1944
  return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, { children: children });
1942
1945
  };
@@ -1949,8 +1952,9 @@ exports.MFAGate = MFAGate;
1949
1952
  exports.MFAOptions = MFAOptions;
1950
1953
  exports.ProtectedRoute = ProtectedRoute;
1951
1954
  exports.UnifiedCAMSProvider = UnifiedCAMSProvider;
1955
+ exports.setCookie = setCookie$1;
1952
1956
  exports.useCAMSAuth = useCAMSAuth;
1953
- exports.useCAMSContext = useCAMSContext;
1957
+ exports.useCAMSContext = useCAMSContext$1;
1954
1958
  exports.useCAMSMSALAuth = useCAMSMSALAuth;
1955
1959
  exports.useCAMSMSALContext = useCAMSMSALContext;
1956
1960
  exports.useCAMSPopupAuth = useCAMSPopupAuth;