Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

session.ts

80 lines2.7 KB

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);
27​
28/** Uses the selected environment's grant, including cached scopes during a refresh. */
29export function useEnvironmentScope(
30 environmentId: EnvironmentId | null,
31 scope: AuthEnvironmentScope,
32): boolean {
33 const result = useAtomValue(
34 environmentId === null
35 ? EMPTY_SESSION_STATE_ATOM
36 : environmentSession.sessionStateAtom(environmentId),
37 );
38 return sessionHasScope(result, scope);
40​
41/** Keeps background workers subscribed to each target's grant. */
42export function useEnvironmentsWithScope(
43 environments: ReadonlyArray<{ readonly environmentId: EnvironmentId }>,
44 scope: AuthEnvironmentScope,
45): ReadonlySet<EnvironmentId> {
46 const permittedEnvironments = useMemo(
47 () =>
48 Atom.make((get) => {
49 const permitted = new Set<EnvironmentId>();
50 for (const { environmentId } of environments) {
51 if (sessionHasScope(get(environmentSession.sessionStateAtom(environmentId)), scope)) {
52 permitted.add(environmentId);
53 }
54 }
55 return permitted;
56 }),
57 [environments, scope],
58 );
59 return useAtomValue(permittedEnvironments);
61​
62export function readEnvironmentScope(
63 environmentId: EnvironmentId,
64 scope: AuthEnvironmentScope,
65): boolean {
66 const result = appAtomRegistry.get(environmentSession.sessionStateAtom(environmentId));
67 return sessionHasScope(result, scope);
69​
70const EMPTY_PREPARED_CONNECTION_ATOM = Atom.make(Option.none()).pipe(
71 Atom.withLabel("mobile-prepared-connection:empty"),
72);
73​
74export function usePreparedConnection(environmentId: EnvironmentId | null) {
75 return useAtomValue(
76 environmentId === null
77 ? EMPTY_PREPARED_CONNECTION_ATOM
78 : environmentSession.preparedConnectionValueAtom(environmentId),
79 );