|
1 | | -import { ClerkProvider, useAuth } from "@clerk/expo"; |
| 1 | +import { ClerkProvider, getClerkInstance } from "@clerk/expo"; |
2 | 2 | import { tokenCache } from "@clerk/expo/token-cache"; |
3 | | -import { ManagedRelay, setManagedRelaySession } from "@t3tools/client-runtime/relay"; |
4 | | -import { |
5 | | - reportAtomCommandResult, |
6 | | - settleAsyncResult, |
7 | | - settlePromise, |
8 | | - squashAtomCommandFailure, |
9 | | -} from "@t3tools/client-runtime/state/runtime"; |
10 | | -import * as Effect from "effect/Effect"; |
11 | | -import { type ReactNode, useEffect, useRef } from "react"; |
12 | | - |
13 | | -import { runtime } from "../../lib/runtime"; |
14 | | -import { appAtomRegistry } from "../../state/atom-registry"; |
15 | | -import { useAtomCommand } from "../../state/use-atom-command"; |
16 | | -import { |
17 | | - getComposerCloudAccountId, |
18 | | - restoreCloudComposerDrafts, |
19 | | -} from "../../state/use-composer-drafts"; |
20 | | -import { |
21 | | - releaseAgentAwarenessRelayTokenProvider, |
22 | | - setAgentAwarenessRelayTokenProvider, |
23 | | - unregisterAgentAwarenessDeviceForCurrentUser, |
24 | | -} from "../agent-awareness/remoteRegistration"; |
25 | | -import { clearConnectOnboardingRequest, requestConnectOnboarding } from "./connectOnboarding"; |
26 | | -import { resolveCloudPublicConfig, resolveRelayClerkTokenOptions } from "./publicConfig"; |
27 | | -import { removeCloudEnvironments } from "./cloud-drafts"; |
28 | | - |
29 | | -function resetManagedRelayTokenCache() { |
30 | | - return settleAsyncResult(() => |
31 | | - runtime.runPromiseExit( |
32 | | - ManagedRelay.ManagedRelayClient.pipe(Effect.flatMap((client) => client.resetTokenCache)), |
33 | | - ), |
34 | | - ); |
35 | | -} |
36 | | - |
37 | | -export function deactivateCloudRelayAccount(): void { |
38 | | - setAgentAwarenessRelayTokenProvider(null); |
39 | | - setManagedRelaySession(appAtomRegistry, null); |
40 | | -} |
41 | | - |
42 | | -export function activateCloudRelayAccount( |
43 | | - accountId: string, |
44 | | - tokenProvider: () => Promise<string | null>, |
45 | | -): void { |
46 | | - setAgentAwarenessRelayTokenProvider(tokenProvider, accountId); |
47 | | - setManagedRelaySession(appAtomRegistry, { |
48 | | - accountId, |
49 | | - readClerkToken: tokenProvider, |
50 | | - }); |
51 | | -} |
52 | | - |
53 | | -function CloudAuthBridge(props: { readonly children: ReactNode }) { |
54 | | - const { getToken, isLoaded, isSignedIn, userId } = useAuth({ treatPendingAsSignedOut: false }); |
55 | | - const removeRelayEnvironments = useAtomCommand(removeCloudEnvironments, { |
56 | | - reportFailure: false, |
57 | | - reportDefect: false, |
58 | | - }); |
59 | | - const previousTokenProviderRef = useRef<{ |
60 | | - readonly userId: string; |
61 | | - readonly provider: () => Promise<string | null>; |
62 | | - } | null>(null); |
63 | | - const observedAccountRef = useRef<string | null | undefined>(undefined); |
64 | | - const accountTransitionRef = useRef<Promise<void> | null>(null); |
65 | | - |
66 | | - useEffect(() => { |
67 | | - let cancelled = false; |
68 | | - if (!isLoaded) { |
69 | | - return; |
70 | | - } |
71 | | - |
72 | | - const previousObservedAccount = observedAccountRef.current; |
73 | | - const nextAccount = isSignedIn && userId ? userId : null; |
74 | | - observedAccountRef.current = nextAccount; |
75 | | - |
76 | | - // Request after activateSession cleanup to avoid listing the previous account; sign-out drops pending requests. |
77 | | - const isAccountTransition = |
78 | | - previousObservedAccount !== undefined && previousObservedAccount !== nextAccount; |
79 | | - if (isAccountTransition && nextAccount === null) { |
80 | | - clearConnectOnboardingRequest(); |
81 | | - } |
82 | | - |
83 | | - const cleanUpAccount = async ( |
84 | | - previous: { |
85 | | - readonly userId: string; |
86 | | - readonly provider: () => Promise<string | null>; |
87 | | - } | null, |
88 | | - accountId: string | null, |
89 | | - ) => { |
90 | | - const removal = await removeRelayEnvironments(accountId); |
91 | | - if (removal._tag !== "Success") throw squashAtomCommandFailure(removal); |
92 | | - const cleanup = [ |
93 | | - resetManagedRelayTokenCache(), |
94 | | - ...(previous |
95 | | - ? [ |
96 | | - settleAsyncResult(() => |
97 | | - runtime.runPromiseExit( |
98 | | - unregisterAgentAwarenessDeviceForCurrentUser(previous.provider), |
99 | | - ), |
100 | | - ), |
101 | | - ] |
102 | | - : []), |
103 | | - ]; |
104 | | - const results = await Promise.all(cleanup); |
105 | | - for (const result of results) { |
106 | | - reportAtomCommandResult(result, { label: "cloud account cleanup" }); |
107 | | - } |
108 | | - }; |
109 | | - const queueAccountCleanup = (previous: typeof previousTokenProviderRef.current) => { |
110 | | - const previousTransition = accountTransitionRef.current ?? Promise.resolve(); |
111 | | - accountTransitionRef.current = previousTransition |
112 | | - .catch(() => {}) |
113 | | - .then(() => cleanUpAccount(previous, previousObservedAccount ?? null)); |
114 | | - return accountTransitionRef.current; |
115 | | - }; |
116 | | - |
117 | | - if (!isSignedIn || !userId) { |
118 | | - const previous = previousTokenProviderRef.current; |
119 | | - previousTokenProviderRef.current = null; |
120 | | - deactivateCloudRelayAccount(); |
121 | | - if (previousObservedAccount !== null) { |
122 | | - void settlePromise(() => queueAccountCleanup(previous)).then((result) => { |
123 | | - reportAtomCommandResult(result, { label: "cloud account cleanup" }); |
124 | | - }); |
125 | | - } |
126 | | - return; |
127 | | - } |
128 | | - |
129 | | - const previous = previousTokenProviderRef.current; |
130 | | - const tokenProvider = () => getToken(resolveRelayClerkTokenOptions()); |
131 | | - const activateSession = () => { |
132 | | - if (cancelled) { |
133 | | - return; |
134 | | - } |
135 | | - previousTokenProviderRef.current = { userId, provider: tokenProvider }; |
136 | | - activateCloudRelayAccount(userId, tokenProvider); |
137 | | - if (isAccountTransition) { |
138 | | - requestConnectOnboarding(userId); |
139 | | - } |
140 | | - }; |
141 | | - const activateAfterTransition = (transition: Promise<void>) => { |
142 | | - const activation = (async () => { |
143 | | - await transition; |
144 | | - if (cancelled) return; |
145 | | - const storedAccount = await getComposerCloudAccountId(); |
146 | | - if (storedAccount !== null && storedAccount !== userId) { |
147 | | - await cleanUpAccount(null, storedAccount); |
148 | | - } |
149 | | - if (cancelled) return; |
150 | | - await restoreCloudComposerDrafts(userId); |
151 | | - activateSession(); |
152 | | - })(); |
153 | | - accountTransitionRef.current = activation; |
154 | | - void settlePromise(() => activation).then((result) => { |
155 | | - reportAtomCommandResult(result, { label: "cloud account activation" }); |
156 | | - }); |
157 | | - }; |
158 | | - if ( |
159 | | - previousObservedAccount !== undefined && |
160 | | - previousObservedAccount !== null && |
161 | | - previousObservedAccount !== userId |
162 | | - ) { |
163 | | - previousTokenProviderRef.current = null; |
164 | | - deactivateCloudRelayAccount(); |
165 | | - activateAfterTransition(queueAccountCleanup(previous)); |
166 | | - } else { |
167 | | - activateAfterTransition((accountTransitionRef.current ?? Promise.resolve()).catch(() => {})); |
168 | | - } |
169 | | - |
170 | | - return () => { |
171 | | - cancelled = true; |
172 | | - }; |
173 | | - }, [getToken, isLoaded, isSignedIn, removeRelayEnvironments, userId]); |
174 | | - |
175 | | - useEffect( |
176 | | - () => () => { |
177 | | - previousTokenProviderRef.current = null; |
178 | | - // Unmounting does not imply sign-out; preserve registration and lock-screen activities. |
179 | | - releaseAgentAwarenessRelayTokenProvider(); |
180 | | - setManagedRelaySession(appAtomRegistry, null); |
181 | | - }, |
182 | | - [], |
183 | | - ); |
184 | | - |
185 | | - return props.children; |
| 3 | +import type { ReactNode } from "react"; |
| 4 | + |
| 5 | +import { cloudAccountService, deactivateCloudRelayAccount } from "./cloudAccountService"; |
| 6 | +import { resolveCloudPublicConfig } from "./publicConfig"; |
| 7 | + |
| 8 | +const cloudConfig = resolveCloudPublicConfig(); |
| 9 | +// Build-time constant: null when this build has no cloud config. |
| 10 | +const publishableKey = cloudConfig.relay.url ? cloudConfig.clerk.publishableKey : null; |
| 11 | + |
| 12 | +if (publishableKey) { |
| 13 | + // The same native singleton ClerkProvider renders with, so the service |
| 14 | + // observes it for the app's lifetime without a React subscription. |
| 15 | + cloudAccountService.attach(getClerkInstance({ publishableKey })); |
| 16 | +} else { |
| 17 | + // Without cloud config no account can ever activate, so drop anything a |
| 18 | + // previous build with cloud enabled left registered. |
| 19 | + deactivateCloudRelayAccount(); |
186 | 20 | } |
187 | 21 |
|
188 | 22 | export function CloudAuthProvider(props: { readonly children: ReactNode }) { |
189 | | - const config = resolveCloudPublicConfig(); |
190 | | - const publishableKey = config.clerk.publishableKey; |
191 | | - const relayUrl = config.relay.url; |
192 | | - |
193 | | - useEffect(() => { |
194 | | - if (!publishableKey || !relayUrl) { |
195 | | - deactivateCloudRelayAccount(); |
196 | | - } |
197 | | - }, [publishableKey, relayUrl]); |
198 | | - |
199 | | - if (!publishableKey || !relayUrl) { |
| 23 | + if (!publishableKey) { |
200 | 24 | return props.children; |
201 | 25 | } |
202 | 26 |
|
203 | 27 | return ( |
204 | 28 | <ClerkProvider publishableKey={publishableKey} tokenCache={tokenCache}> |
205 | | - <CloudAuthBridge>{props.children}</CloudAuthBridge> |
| 29 | + {props.children} |
206 | 30 | </ClerkProvider> |
207 | 31 | ); |
208 | 32 | } |
0 commit comments