1import { managedRelaySessionAtom, setManagedRelaySession } from "@t3tools/client-runtime/relay";
2import * as Effect from "effect/Effect";
3import { afterEach, describe, expect, it, vi } from "vite-plus/test";
4
5import { appAtomRegistry } from "../rpc/atomRegistry";
6import {
7 activateManagedRelayAuthentication,
8 deactivateManagedRelayAuthentication,
9} from "./managedAuth";
10
11vi.mock("@clerk/react", () => ({
12 useAuth: vi.fn(),
13}));
14
15vi.mock("../lib/runtime", () => ({
16 runtime: {
17 runPromiseExit: vi.fn(),
18 },
19}));
20
21vi.mock("../connection/catalog", () => ({
22 environmentCatalog: {
23 removeRelayEnvironments: {},
24 },
25}));
26
27afterEach(() => {
28 deactivateManagedRelayAuthentication();
29});
30
31describe("managed relay authentication", () => {
32 it("clears all token access synchronously before account cleanup can fail", async () => {
33 activateManagedRelayAuthentication("account-1", async () => "account-1-token");
34 expect(appAtomRegistry.get(managedRelaySessionAtom)?.accountId).toBe("account-1");
35 const token = await Effect.fromNullishOr(appAtomRegistry.get(managedRelaySessionAtom)).pipe(
36 Effect.flatMap((session) => session.readClerkToken()),
37 Effect.runPromise,
38 );
39 expect(token).toBe("account-1-token");
40
41 deactivateManagedRelayAuthentication();
42 const cleanup = Promise.reject(new Error("Persistence removal failed.")).catch(() => undefined);
43
44 expect(appAtomRegistry.get(managedRelaySessionAtom)).toBeNull();
45 await cleanup;
46 });
47
48 it("replaces an existing account session atomically", () => {
49 setManagedRelaySession(appAtomRegistry, {
50 accountId: "account-1",
51 readClerkToken: async () => "account-1-token",
52 });
53
54 activateManagedRelayAuthentication("account-2", async () => "account-2-token");
55
56 expect(appAtomRegistry.get(managedRelaySessionAtom)?.accountId).toBe("account-2");
57 });
58});