Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import { createEnvironmentSessionAtoms } from "@t3tools/client-runtime/state/session";
3import {
4 type AuthEnvironmentScope,
5 type AuthSessionState,
6 type EnvironmentId,
7 sessionGrantsScope,
8} from "@t3tools/contracts";
9import * as Option from "effect/Option";
10import { AsyncResult, Atom } from "effect/reactivity";
11import { useMemo } from "react";
12
13import { connectionAtomRuntime } from "../connection/runtime";
14import { appAtomRegistry } from "./atom-registry";
15
16export const environmentSession = createEnvironmentSessionAtoms(connectionAtomRuntime);
17
18const EMPTY_SESSION_STATE_ATOM = Atom.make(AsyncResult.initial<AuthSessionState>());
19
20function sessionHasScope(
21 result: AsyncResult.AsyncResult<AuthSessionState, unknown>,
22 scope: AuthEnvironmentScope,
23): boolean {
24 const session = Option.getOrNull(AsyncResult.value(result));
25 return result._tag !== "Failure" && session !== null && sessionGrantsScope(session, scope);
26}
27
28export function useEnvironmentScope(
29 environmentId: EnvironmentId | null,
30 scope: AuthEnvironmentScope,
31): boolean {
32 const result = useAtomValue(
33 environmentId === null
34 ? EMPTY_SESSION_STATE_ATOM
35 : environmentSession.sessionStateAtom(environmentId),
36 );
37 return sessionHasScope(result, scope);
38}
39
40export function useEnvironmentsWithScope(
41 environments: ReadonlyArray<{ readonly environmentId: EnvironmentId }>,
42 scope: AuthEnvironmentScope,
43): ReadonlySet<EnvironmentId> {
44 const permittedEnvironments = useMemo(
45 () =>
46 Atom.make((get) => {
47 const permitted = new Set<EnvironmentId>();
48 for (const { environmentId } of environments) {
49 if (sessionHasScope(get(environmentSession.sessionStateAtom(environmentId)), scope)) {
50 permitted.add(environmentId);
51 }
52 }
53 return permitted;
54 }),
55 [environments, scope],
56 );
57 return useAtomValue(permittedEnvironments);
58}
59
60export function readEnvironmentScope(
61 environmentId: EnvironmentId,
62 scope: AuthEnvironmentScope,
63): boolean {
64 const result = appAtomRegistry.get(environmentSession.sessionStateAtom(environmentId));
65 return sessionHasScope(result, scope);
66}
67
68const EMPTY_PREPARED_CONNECTION_ATOM = Atom.make(Option.none()).pipe(
69 Atom.withLabel("mobile-prepared-connection:empty"),
70);
71
72export function usePreparedConnection(environmentId: EnvironmentId | null) {
73 return useAtomValue(
74 environmentId === null
75 ? EMPTY_PREPARED_CONNECTION_ATOM
76 : environmentSession.preparedConnectionValueAtom(environmentId),
77 );
78}