Open History to see the last commit
1import { useClerk } from "@clerk/react";
2import {
3 createCloudAccountService,
4 ManagedRelay,
5 setManagedRelaySession,
6} from "@t3tools/client-runtime/relay";
7import {
8 reportAtomCommandResult,
9 runAtomCommand,
10 settleAsyncResult,
11} from "@t3tools/client-runtime/state/runtime";
12import * as Effect from "effect/Effect";
13import { useEffect, type ReactNode } from "react";
14
15import { trackMountedClerk } from "../components/clerk/clerkLoadFailure";
16import { environmentCatalog } from "../connection/catalog";
17import { runtime } from "../lib/runtime";
18import { appAtomRegistry } from "../rpc/atomRegistry";
19import { resolveRelayClerkTokenOptions } from "./publicConfig";
20
21export function deactivateManagedRelayAuthentication(): void {
22 setManagedRelaySession(appAtomRegistry, null);
23}
24
25export function activateManagedRelayAuthentication(
26 accountId: string,
27 readClerkToken: () => Promise<string | null>,
28): void {
29 setManagedRelaySession(appAtomRegistry, {
30 accountId,
31 readClerkToken,
32 });
33}
34
35type ClerkInstance = ReturnType<typeof useClerk>;
36
37function clerkTokenReader(clerk: ClerkInstance): () => Promise<string | null> {
38 return async () =>
39 clerk.session ? await clerk.session.getToken(resolveRelayClerkTokenOptions()) : null;
40}
41
42const managedRelayAccountService = createCloudAccountService<ClerkInstance>({
43 deactivate: deactivateManagedRelayAuthentication,
44 detach: deactivateManagedRelayAuthentication,
45 cleanUp: async () => {
46 const results = await Promise.all([
47 runAtomCommand(appAtomRegistry, environmentCatalog.removeRelayEnvironments, undefined, {
48 reportFailure: false,
49 reportDefect: false,
50 }),
51 settleAsyncResult(() =>
52 runtime.runPromiseExit(
53 ManagedRelay.ManagedRelayClient.pipe(Effect.flatMap((client) => client.resetTokenCache)),
54 ),
55 ),
56 ]);
57 for (const result of results) {
58 reportAtomCommandResult(result, { label: "cloud account cleanup" });
59 }
60 },
61 activate: ({ source, accountId }) =>
62 activateManagedRelayAuthentication(accountId, clerkTokenReader(source)),
63});
64
65export function ManagedRelayAuthProvider({ children }: { readonly children: ReactNode }) {
66 // ClerkProvider creates the Clerk instance and owns its lifetime, so the
67 // account service observes it for as long as this provider is mounted.
68 const clerk = useClerk();
69 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- attaches the Clerk instance to the managed relay account service for the provider's lifetime
70 useEffect(() => managedRelayAccountService.attach(clerk), [clerk]);
71 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- exposes the mounted Clerk instance's load status for the provider's lifetime
72 useEffect(() => trackMountedClerk(clerk), [clerk]);
73 return children;
74}