@civic/auth 0.0.1-beta.22 → 0.0.1-beta.23

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.
@@ -0,0 +1,703 @@
1
+ import {
2
+ BrowserAuthenticationInitiator,
3
+ BrowserAuthenticationService,
4
+ ConfidentialClientPKCEConsumer,
5
+ DEFAULT_AUTH_SERVER,
6
+ DEFAULT_SCOPES,
7
+ GenericUserSession,
8
+ IFRAME_ID,
9
+ LocalStorageAdapter,
10
+ PopupError,
11
+ TOKEN_EXCHANGE_TRIGGER_TEXT,
12
+ convertForwardedTokenFormat,
13
+ generateState,
14
+ getUser,
15
+ isWindowInIframe
16
+ } from "./chunk-4PLCDPEN.mjs";
17
+ import {
18
+ __async,
19
+ __spreadProps,
20
+ __spreadValues
21
+ } from "./chunk-RGHW4PYM.mjs";
22
+
23
+ // src/shared/hooks/useAuth.tsx
24
+ import { useContext } from "react";
25
+
26
+ // src/shared/AuthContext.tsx
27
+ import { createContext } from "react";
28
+ var AuthContext = createContext(null);
29
+
30
+ // src/shared/hooks/useAuth.tsx
31
+ var useAuth = () => {
32
+ const context = useContext(AuthContext);
33
+ if (!context) {
34
+ throw new Error("useAuth must be used within an AuthProvider");
35
+ }
36
+ return context;
37
+ };
38
+
39
+ // src/shared/hooks/useSession.tsx
40
+ import { useContext as useContext2 } from "react";
41
+
42
+ // src/shared/providers/SessionProvider.tsx
43
+ import { createContext as createContext2 } from "react";
44
+ import { jsx } from "react/jsx-runtime";
45
+ var defaultSession = {
46
+ authenticated: false,
47
+ idToken: void 0,
48
+ accessToken: void 0,
49
+ displayMode: "iframe"
50
+ };
51
+ var SessionContext = createContext2(defaultSession);
52
+ var SessionProvider = ({ children, session }) => /* @__PURE__ */ jsx(SessionContext.Provider, { value: __spreadValues(__spreadValues({}, defaultSession), session || {}), children });
53
+
54
+ // src/shared/hooks/useSession.tsx
55
+ var useSession = () => {
56
+ const context = useContext2(SessionContext);
57
+ if (!context) {
58
+ throw new Error("useSession must be used within an SessionProvider");
59
+ }
60
+ return context;
61
+ };
62
+
63
+ // src/shared/hooks/useToken.tsx
64
+ import { useContext as useContext3 } from "react";
65
+
66
+ // src/shared/providers/TokenProvider.tsx
67
+ import { createContext as createContext3, useMemo } from "react";
68
+ import { useMutation, useQueryClient } from "@tanstack/react-query";
69
+ import { parseJWT } from "oslo/jwt";
70
+ import { jsx as jsx2 } from "react/jsx-runtime";
71
+ var TokenContext = createContext3(void 0);
72
+ var TokenProvider = ({ children }) => {
73
+ const { isLoading, error: authError } = useAuth();
74
+ const session = useSession();
75
+ const queryClient = useQueryClient();
76
+ const refreshTokenMutation = useMutation({
77
+ mutationFn: () => __async(void 0, null, function* () {
78
+ throw new Error("Method not implemented.");
79
+ }),
80
+ onSuccess: () => {
81
+ queryClient.invalidateQueries({ queryKey: ["session"] });
82
+ }
83
+ });
84
+ const decodeTokens = useMemo(() => {
85
+ if (!(session == null ? void 0 : session.idToken)) return null;
86
+ const parsedJWT = parseJWT(session.idToken);
87
+ if (!parsedJWT) return null;
88
+ const { forwardedTokens } = parsedJWT.payload;
89
+ return forwardedTokens ? convertForwardedTokenFormat(forwardedTokens) : null;
90
+ }, [session == null ? void 0 : session.idToken]);
91
+ const value = useMemo(
92
+ () => ({
93
+ accessToken: session.accessToken || null,
94
+ idToken: session.idToken || null,
95
+ forwardedTokens: decodeTokens || {},
96
+ refreshToken: refreshTokenMutation.mutateAsync,
97
+ isLoading,
98
+ error: authError || refreshTokenMutation.error
99
+ }),
100
+ [
101
+ session.accessToken,
102
+ session.idToken,
103
+ decodeTokens,
104
+ refreshTokenMutation.mutateAsync,
105
+ refreshTokenMutation.error,
106
+ isLoading,
107
+ authError
108
+ ]
109
+ );
110
+ return /* @__PURE__ */ jsx2(TokenContext.Provider, { value, children });
111
+ };
112
+
113
+ // src/shared/hooks/useToken.tsx
114
+ var useToken = () => {
115
+ const context = useContext3(TokenContext);
116
+ if (!context) {
117
+ throw new Error("useToken must be used within a TokenProvider");
118
+ }
119
+ return context;
120
+ };
121
+
122
+ // src/shared/hooks/useConfig.tsx
123
+ import { useContext as useContext4 } from "react";
124
+
125
+ // src/config.ts
126
+ var authConfig = {
127
+ oauthServer: DEFAULT_AUTH_SERVER
128
+ };
129
+
130
+ // src/shared/providers/ConfigProvider.tsx
131
+ import { createContext as createContext4 } from "react";
132
+ import { jsx as jsx3 } from "react/jsx-runtime";
133
+ var defaultConfig = {
134
+ config: authConfig,
135
+ redirectUrl: "",
136
+ modalIframe: true,
137
+ serverTokenExchange: false
138
+ };
139
+ var ConfigContext = createContext4(defaultConfig);
140
+ var ConfigProvider = ({
141
+ children,
142
+ config,
143
+ redirectUrl,
144
+ modalIframe,
145
+ serverTokenExchange
146
+ }) => /* @__PURE__ */ jsx3(
147
+ ConfigContext.Provider,
148
+ {
149
+ value: {
150
+ config,
151
+ redirectUrl,
152
+ modalIframe: !!modalIframe,
153
+ serverTokenExchange
154
+ },
155
+ children
156
+ }
157
+ );
158
+
159
+ // src/shared/hooks/useConfig.tsx
160
+ var useConfig = () => {
161
+ const context = useContext4(ConfigContext);
162
+ if (!context) {
163
+ throw new Error("useConfig must be used within an ConfigProvider");
164
+ }
165
+ return context;
166
+ };
167
+
168
+ // src/shared/hooks/useIframe.tsx
169
+ import { useContext as useContext5 } from "react";
170
+
171
+ // src/shared/providers/IframeProvider.tsx
172
+ import {
173
+ createContext as createContext5
174
+ } from "react";
175
+ import { jsx as jsx4 } from "react/jsx-runtime";
176
+ var defaultIframe = {
177
+ iframeRef: null,
178
+ setAuthResponseUrl: () => {
179
+ }
180
+ };
181
+ var IframeContext = createContext5(defaultIframe);
182
+ var IframeProvider = ({
183
+ children,
184
+ iframeRef,
185
+ setAuthResponseUrl
186
+ }) => /* @__PURE__ */ jsx4(IframeContext.Provider, { value: { iframeRef, setAuthResponseUrl }, children });
187
+
188
+ // src/shared/hooks/useIframe.tsx
189
+ var useIframe = () => {
190
+ const context = useContext5(IframeContext);
191
+ if (!context) {
192
+ throw new Error("useIframe must be used within an IframeProvider");
193
+ }
194
+ return context;
195
+ };
196
+
197
+ // src/shared/components/CivicAuthIframeContainer.tsx
198
+ import { useCallback, useEffect, useRef, useState } from "react";
199
+
200
+ // src/shared/components/LoadingIcon.tsx
201
+ import { jsx as jsx5, jsxs } from "react/jsx-runtime";
202
+ var LoadingIcon = () => /* @__PURE__ */ jsxs("div", { role: "status", children: [
203
+ /* @__PURE__ */ jsxs(
204
+ "svg",
205
+ {
206
+ "aria-hidden": "true",
207
+ className: "cac-inline cac-h-8 cac-w-8 cac-animate-spin cac-fill-neutral-600 cac-text-neutral-200 dark:cac-fill-neutral-300 dark:cac-text-neutral-600",
208
+ viewBox: "0 0 100 101",
209
+ fill: "none",
210
+ xmlns: "http://www.w3.org/2000/svg",
211
+ children: [
212
+ /* @__PURE__ */ jsx5(
213
+ "path",
214
+ {
215
+ d: "M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z",
216
+ fill: "currentColor"
217
+ }
218
+ ),
219
+ /* @__PURE__ */ jsx5(
220
+ "path",
221
+ {
222
+ d: "M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z",
223
+ fill: "currentFill"
224
+ }
225
+ )
226
+ ]
227
+ }
228
+ ),
229
+ /* @__PURE__ */ jsx5("span", { className: "cac-sr-only", children: "Loading..." })
230
+ ] });
231
+
232
+ // src/shared/components/CloseIcon.tsx
233
+ import { jsx as jsx6, jsxs as jsxs2 } from "react/jsx-runtime";
234
+ var CloseIcon = () => /* @__PURE__ */ jsxs2(
235
+ "svg",
236
+ {
237
+ xmlns: "http://www.w3.org/2000/svg",
238
+ width: "24",
239
+ height: "24",
240
+ viewBox: "0 0 24 24",
241
+ fill: "none",
242
+ stroke: "currentColor",
243
+ strokeWidth: "2",
244
+ strokeLinecap: "round",
245
+ strokeLinejoin: "round",
246
+ className: "lucide lucide-x",
247
+ children: [
248
+ /* @__PURE__ */ jsx6("path", { d: "M18 6 6 18" }),
249
+ /* @__PURE__ */ jsx6("path", { d: "m6 6 12 12" })
250
+ ]
251
+ }
252
+ );
253
+
254
+ // src/shared/components/CivicAuthIframe.tsx
255
+ import { forwardRef } from "react";
256
+ import { jsx as jsx7 } from "react/jsx-runtime";
257
+ var CivicAuthIframe = forwardRef(
258
+ ({ onLoad }, ref) => {
259
+ return /* @__PURE__ */ jsx7(
260
+ "iframe",
261
+ {
262
+ id: IFRAME_ID,
263
+ ref,
264
+ className: "cac-h-[26rem] cac-w-full cac-border-none",
265
+ onLoad
266
+ }
267
+ );
268
+ }
269
+ );
270
+ CivicAuthIframe.displayName = "CivicAuthIframe";
271
+
272
+ // src/shared/components/CivicAuthIframeContainer.tsx
273
+ import { jsx as jsx8, jsxs as jsxs3 } from "react/jsx-runtime";
274
+ function NoChrome({
275
+ children
276
+ }) {
277
+ return /* @__PURE__ */ jsx8("div", { className: "cac-relative", children });
278
+ }
279
+ function IframeChrome({
280
+ children,
281
+ onClose
282
+ }) {
283
+ return /* @__PURE__ */ jsx8(
284
+ "div",
285
+ {
286
+ className: "cac-absolute cac-left-0 cac-top-0 cac-z-50 cac-flex cac-h-screen cac-w-screen cac-items-center cac-justify-center cac-bg-neutral-950 cac-bg-opacity-50",
287
+ onClick: onClose,
288
+ children: /* @__PURE__ */ jsxs3(
289
+ "div",
290
+ {
291
+ className: "cac-relative cac-rounded-3xl cac-bg-white cac-p-6 cac-shadow-lg",
292
+ onClick: (e) => e.stopPropagation(),
293
+ children: [
294
+ /* @__PURE__ */ jsx8(
295
+ "button",
296
+ {
297
+ className: "cac-absolute cac-right-4 cac-top-4 cac-flex cac-cursor-pointer cac-items-center cac-justify-center cac-border-none cac-bg-transparent cac-p-1 cac-text-neutral-400",
298
+ onClick: onClose,
299
+ children: /* @__PURE__ */ jsx8(CloseIcon, {})
300
+ }
301
+ ),
302
+ children
303
+ ]
304
+ }
305
+ )
306
+ }
307
+ );
308
+ }
309
+ var CivicAuthIframeContainer = ({
310
+ onClose,
311
+ closeOnRedirect = true
312
+ }) => {
313
+ var _a;
314
+ const [isLoading, setIsLoading] = useState(true);
315
+ const { isLoading: isAuthLoading } = useAuth();
316
+ const config = useConfig();
317
+ const { setAuthResponseUrl, iframeRef } = useIframe();
318
+ const processIframeUrl = useCallback(() => {
319
+ if (iframeRef && iframeRef.current && iframeRef.current.contentWindow) {
320
+ try {
321
+ const iframeUrl = iframeRef.current.contentWindow.location.href;
322
+ if (iframeUrl.startsWith(config.redirectUrl)) {
323
+ setIsLoading(true);
324
+ const iframeBody = iframeRef.current.contentWindow.document.body.innerHTML;
325
+ if (iframeBody.includes(TOKEN_EXCHANGE_TRIGGER_TEXT)) {
326
+ console.log(
327
+ `${TOKEN_EXCHANGE_TRIGGER_TEXT}, calling callback URL again...`
328
+ );
329
+ const params = new URL(iframeUrl).searchParams;
330
+ fetch(`${config.redirectUrl}?${params.toString()}`);
331
+ } else {
332
+ setAuthResponseUrl(iframeUrl);
333
+ }
334
+ if (closeOnRedirect) onClose == null ? void 0 : onClose();
335
+ return true;
336
+ }
337
+ } catch (e) {
338
+ console.log("Waiting for redirect...");
339
+ }
340
+ }
341
+ return false;
342
+ }, [
343
+ closeOnRedirect,
344
+ config.redirectUrl,
345
+ iframeRef,
346
+ onClose,
347
+ setAuthResponseUrl
348
+ ]);
349
+ const intervalId = useRef();
350
+ const handleEscape = useCallback(
351
+ (event) => {
352
+ if (event.key === "Escape") {
353
+ onClose == null ? void 0 : onClose();
354
+ }
355
+ },
356
+ [onClose]
357
+ );
358
+ useEffect(() => {
359
+ window.addEventListener("keydown", handleEscape);
360
+ return () => window.removeEventListener("keydown", handleEscape);
361
+ });
362
+ const handleIframeLoad = () => {
363
+ setIsLoading(false);
364
+ console.log("handleIframeLoad");
365
+ if (processIframeUrl() && intervalId.current) {
366
+ clearInterval(intervalId.current);
367
+ }
368
+ };
369
+ const showLoadingIcon = isLoading || isAuthLoading || !((_a = iframeRef == null ? void 0 : iframeRef.current) == null ? void 0 : _a.getAttribute("src"));
370
+ const WrapperComponent = config.modalIframe ? IframeChrome : NoChrome;
371
+ return /* @__PURE__ */ jsxs3(WrapperComponent, { onClose, children: [
372
+ showLoadingIcon && /* @__PURE__ */ jsx8("div", { className: "cac-absolute cac-inset-0 cac-flex cac-items-center cac-justify-center cac-rounded-3xl cac-bg-white", children: /* @__PURE__ */ jsx8(LoadingIcon, {}) }),
373
+ /* @__PURE__ */ jsx8(CivicAuthIframe, { ref: iframeRef, onLoad: handleIframeLoad })
374
+ ] });
375
+ };
376
+
377
+ // src/shared/UserProvider.tsx
378
+ import { createContext as createContext6 } from "react";
379
+ import { useQuery } from "@tanstack/react-query";
380
+ import { jsx as jsx9 } from "react/jsx-runtime";
381
+ var UserContext = createContext6(null);
382
+ var UserProvider = ({
383
+ children,
384
+ storage,
385
+ user: inputUser,
386
+ signOut: inputSignOut
387
+ }) => {
388
+ var _a;
389
+ const { isLoading: authLoading, error: authError } = useAuth();
390
+ const session = useSession();
391
+ const { accessToken, idToken } = useToken();
392
+ const { signIn, signOut } = useAuth();
393
+ const fetchUser = () => __async(void 0, null, function* () {
394
+ if (!accessToken) {
395
+ return null;
396
+ }
397
+ const userSession = new GenericUserSession(storage);
398
+ return userSession.get();
399
+ });
400
+ const {
401
+ data: user,
402
+ isLoading: userLoading,
403
+ error: userError
404
+ } = useQuery({
405
+ queryKey: ["user", session == null ? void 0 : session.idToken],
406
+ queryFn: fetchUser,
407
+ enabled: !!(session == null ? void 0 : session.idToken)
408
+ // Only run the query if we have an access token
409
+ });
410
+ const isLoading = authLoading || userLoading;
411
+ const error = authError || userError;
412
+ const userWithIdToken = user ? __spreadProps(__spreadValues({}, user), { idToken }) : null;
413
+ return /* @__PURE__ */ jsx9(
414
+ UserContext.Provider,
415
+ {
416
+ value: {
417
+ user: (_a = inputUser || userWithIdToken) != null ? _a : null,
418
+ isLoading,
419
+ error,
420
+ signIn,
421
+ signOut: inputSignOut || signOut
422
+ },
423
+ children
424
+ }
425
+ );
426
+ };
427
+
428
+ // src/shared/AuthProvider.tsx
429
+ import {
430
+ useCallback as useCallback2,
431
+ useEffect as useEffect2,
432
+ useMemo as useMemo2,
433
+ useRef as useRef2,
434
+ useState as useState2
435
+ } from "react";
436
+ import { useMutation as useMutation2, useQuery as useQuery2, useQueryClient as useQueryClient2 } from "@tanstack/react-query";
437
+ import { jsx as jsx10, jsxs as jsxs4 } from "react/jsx-runtime";
438
+ var globalThisObject;
439
+ if (typeof window !== "undefined") {
440
+ globalThisObject = window;
441
+ } else if (typeof global !== "undefined") {
442
+ globalThisObject = global;
443
+ } else {
444
+ globalThisObject = Function("return this")();
445
+ }
446
+ globalThisObject.globalThis = globalThisObject;
447
+ function BlockDisplay({ children }) {
448
+ return /* @__PURE__ */ jsx10("div", { className: "cac-relative cac-left-0 cac-top-0 cac-z-50 cac-flex cac-h-screen cac-w-screen cac-items-center cac-justify-center cac-bg-white", children: /* @__PURE__ */ jsx10("div", { className: "cac-absolute cac-inset-0 cac-flex cac-items-center cac-justify-center cac-bg-white", children }) });
449
+ }
450
+ var AuthProvider = ({
451
+ children,
452
+ clientId,
453
+ redirectUrl: inputRedirectUrl,
454
+ config = authConfig,
455
+ onSignIn,
456
+ onSignOut,
457
+ pkceConsumer,
458
+ nonce,
459
+ modalIframe = true,
460
+ sessionData: inputSessionData
461
+ }) => {
462
+ const [iframeUrl, setIframeUrl] = useState2(null);
463
+ const [currentUrl, setCurrentUrl] = useState2(null);
464
+ const [isInIframe, setIsInIframe] = useState2(false);
465
+ const [authResponseUrl, setAuthResponseUrl] = useState2(null);
466
+ const [tokenExchangeError, setTokenExchangeError] = useState2();
467
+ const [displayMode, setDisplayMode] = useState2("iframe");
468
+ const [browserAuthenticationInitiator, setBrowserAuthenticationInitiator] = useState2();
469
+ const [showIFrame, setShowIFrame] = useState2(false);
470
+ const [isRedirecting, setIsRedirecting] = useState2(false);
471
+ const queryClient = useQueryClient2();
472
+ const iframeRef = useRef2(null);
473
+ const serverTokenExchange = pkceConsumer instanceof ConfidentialClientPKCEConsumer;
474
+ useEffect2(() => {
475
+ if (typeof globalThis.window !== "undefined") {
476
+ setCurrentUrl(globalThis.window.location.href);
477
+ const isInIframeVal = isWindowInIframe(globalThis.window);
478
+ setIsInIframe(isInIframeVal);
479
+ }
480
+ }, []);
481
+ const redirectUrl = useMemo2(
482
+ () => (inputRedirectUrl || currentUrl || "").split("?")[0],
483
+ [currentUrl, inputRedirectUrl]
484
+ );
485
+ const [authService, setAuthService] = useState2();
486
+ useEffect2(() => {
487
+ if (!currentUrl) return;
488
+ BrowserAuthenticationService.build({
489
+ clientId,
490
+ redirectUrl,
491
+ oauthServer: config.oauthServer,
492
+ scopes: DEFAULT_SCOPES,
493
+ displayMode
494
+ }).then(setAuthService);
495
+ }, [currentUrl, clientId, redirectUrl, config, displayMode]);
496
+ const {
497
+ data: session,
498
+ isLoading,
499
+ error
500
+ } = useQuery2({
501
+ queryKey: [
502
+ "session",
503
+ authResponseUrl,
504
+ iframeUrl,
505
+ currentUrl,
506
+ isInIframe,
507
+ authService
508
+ ],
509
+ queryFn: () => __async(void 0, null, function* () {
510
+ if (!authService) {
511
+ return { authenticated: false };
512
+ }
513
+ if (inputSessionData) {
514
+ return inputSessionData;
515
+ }
516
+ const url = new URL(
517
+ authResponseUrl ? authResponseUrl : globalThis.window.location.href || ""
518
+ );
519
+ const existingSessionData = yield authService.validateExistingSession();
520
+ if (existingSessionData.authenticated) {
521
+ return existingSessionData;
522
+ }
523
+ const code = url.searchParams.get("code");
524
+ const state = url.searchParams.get("state");
525
+ if (!serverTokenExchange && code && state && !isInIframe) {
526
+ try {
527
+ console.log("AuthProvider useQuery code", {
528
+ isInIframe,
529
+ code,
530
+ state
531
+ });
532
+ yield authService.tokenExchange(code, state);
533
+ const clientStorage = new LocalStorageAdapter();
534
+ const user = yield getUser(clientStorage);
535
+ if (!user) {
536
+ throw new Error("Failed to get user info");
537
+ }
538
+ const userSession = new GenericUserSession(clientStorage);
539
+ userSession.set(user);
540
+ onSignIn == null ? void 0 : onSignIn();
541
+ return authService.getSessionData();
542
+ } catch (error2) {
543
+ setTokenExchangeError(error2);
544
+ onSignIn == null ? void 0 : onSignIn(
545
+ error2 instanceof Error ? error2 : new Error("Failed to sign in")
546
+ );
547
+ return { authenticated: false };
548
+ }
549
+ }
550
+ return existingSessionData;
551
+ })
552
+ });
553
+ const signOutMutation = useMutation2({
554
+ mutationFn: () => __async(void 0, null, function* () {
555
+ console.log("==== AA");
556
+ console.log("==== BB");
557
+ console.log("==== C");
558
+ console.log("==== D");
559
+ console.log("==== E");
560
+ console.log("==== F");
561
+ onSignOut == null ? void 0 : onSignOut();
562
+ }),
563
+ onSuccess: () => {
564
+ console.log("==== G");
565
+ }
566
+ });
567
+ const getAuthInitiator = useCallback2(
568
+ (overrideDisplayMode) => {
569
+ const useDisplayMode = overrideDisplayMode || displayMode;
570
+ if (!pkceConsumer) {
571
+ return null;
572
+ }
573
+ return browserAuthenticationInitiator || new BrowserAuthenticationInitiator({
574
+ pkceConsumer,
575
+ // generate and retrieve the challenge client-side
576
+ clientId,
577
+ redirectUrl,
578
+ state: generateState(useDisplayMode, serverTokenExchange),
579
+ scopes: DEFAULT_SCOPES,
580
+ displayMode: useDisplayMode,
581
+ oauthServer: config.oauthServer,
582
+ // the endpoints to use for the login (if not obtained from the auth server
583
+ endpointOverrides: config.endpoints,
584
+ nonce
585
+ });
586
+ },
587
+ [
588
+ serverTokenExchange,
589
+ displayMode,
590
+ browserAuthenticationInitiator,
591
+ clientId,
592
+ redirectUrl,
593
+ config.oauthServer,
594
+ config.endpoints,
595
+ pkceConsumer,
596
+ nonce
597
+ ]
598
+ );
599
+ const signIn = useCallback2(
600
+ (overrideDisplayMode = "iframe") => __async(void 0, null, function* () {
601
+ setDisplayMode(overrideDisplayMode);
602
+ const authInitiator = getAuthInitiator(overrideDisplayMode);
603
+ setBrowserAuthenticationInitiator(authInitiator);
604
+ if (overrideDisplayMode === "iframe") {
605
+ setShowIFrame(true);
606
+ } else if (overrideDisplayMode === "redirect") {
607
+ setIsRedirecting(true);
608
+ }
609
+ authInitiator == null ? void 0 : authInitiator.signIn(iframeRef.current).catch((error2) => {
610
+ console.log("signIn error", {
611
+ error: error2,
612
+ isPopupError: error2 instanceof PopupError
613
+ });
614
+ if (error2 instanceof PopupError) {
615
+ signIn("redirect");
616
+ }
617
+ });
618
+ }),
619
+ [getAuthInitiator]
620
+ );
621
+ useEffect2(() => {
622
+ return () => {
623
+ if (browserAuthenticationInitiator) {
624
+ browserAuthenticationInitiator.cleanup();
625
+ }
626
+ };
627
+ }, [browserAuthenticationInitiator]);
628
+ const isAuthenticated = useMemo2(
629
+ () => session ? session.authenticated : false,
630
+ [session]
631
+ );
632
+ useQuery2({
633
+ queryKey: ["autoSignIn", modalIframe, redirectUrl, isAuthenticated],
634
+ queryFn: () => __async(void 0, null, function* () {
635
+ if (!modalIframe && redirectUrl && !isAuthenticated && iframeRef.current) {
636
+ signIn("iframe");
637
+ }
638
+ return true;
639
+ }),
640
+ refetchOnWindowFocus: false
641
+ });
642
+ const value = useMemo2(
643
+ () => ({
644
+ isLoading,
645
+ error,
646
+ signOut: () => __async(void 0, null, function* () {
647
+ yield signOutMutation.mutateAsync();
648
+ }),
649
+ isAuthenticated,
650
+ signIn
651
+ }),
652
+ [isLoading, error, signOutMutation, isAuthenticated, signIn]
653
+ );
654
+ return /* @__PURE__ */ jsx10(AuthContext.Provider, { value, children: /* @__PURE__ */ jsx10(
655
+ ConfigProvider,
656
+ {
657
+ config,
658
+ redirectUrl,
659
+ modalIframe,
660
+ serverTokenExchange,
661
+ children: /* @__PURE__ */ jsx10(
662
+ IframeProvider,
663
+ {
664
+ setAuthResponseUrl,
665
+ iframeRef,
666
+ children: /* @__PURE__ */ jsx10(SessionProvider, { session, children: /* @__PURE__ */ jsxs4(TokenProvider, { children: [
667
+ modalIframe && !isInIframe && !(session == null ? void 0 : session.authenticated) && /* @__PURE__ */ jsx10(
668
+ "div",
669
+ {
670
+ style: showIFrame ? { display: "block" } : { display: "none" },
671
+ children: /* @__PURE__ */ jsx10(
672
+ CivicAuthIframeContainer,
673
+ {
674
+ onClose: () => setShowIFrame(false)
675
+ }
676
+ )
677
+ }
678
+ ),
679
+ modalIframe && (isInIframe || isRedirecting || isLoading && !serverTokenExchange) && /* @__PURE__ */ jsx10(BlockDisplay, { children: /* @__PURE__ */ jsx10(LoadingIcon, {}) }),
680
+ (tokenExchangeError || error) && /* @__PURE__ */ jsx10(BlockDisplay, { children: /* @__PURE__ */ jsxs4("div", { children: [
681
+ "Error: ",
682
+ (tokenExchangeError || error).message
683
+ ] }) }),
684
+ children
685
+ ] }) })
686
+ }
687
+ )
688
+ }
689
+ ) });
690
+ };
691
+
692
+ export {
693
+ useAuth,
694
+ useSession,
695
+ useToken,
696
+ UserContext,
697
+ UserProvider,
698
+ useConfig,
699
+ useIframe,
700
+ CivicAuthIframeContainer,
701
+ AuthProvider
702
+ };
703
+ //# sourceMappingURL=chunk-PKBT2ALA.mjs.map