@krak-stack/auth 0.1.71 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/README.md +4 -3
  2. package/dist/access.d.ts +4 -4
  3. package/dist/access.js +10 -4
  4. package/dist/admin/api.group.d.ts +17 -17
  5. package/dist/admin/api.group.js +2 -2
  6. package/dist/admin/schema.d.ts +18 -18
  7. package/dist/admin/schema.js +3 -3
  8. package/dist/api.d.ts +2093 -631
  9. package/dist/api.js +7 -7
  10. package/dist/auth/api.group.d.ts +793 -0
  11. package/dist/auth/api.group.js +241 -0
  12. package/dist/auth/schema.d.ts +800 -0
  13. package/dist/auth/schema.js +625 -0
  14. package/dist/components/admin-organization-form.d.ts +1 -1
  15. package/dist/components/admin-organization-form.js +16 -18
  16. package/dist/components/admin-organizations.js +52 -45
  17. package/dist/components/admin-users.js +115 -137
  18. package/dist/components/api-key-edit-form.d.ts +4 -3
  19. package/dist/components/api-key-edit-form.js +32 -27
  20. package/dist/components/api-key-permissions.d.ts +1 -1
  21. package/dist/components/api-key-rate-limit.d.ts +1 -1
  22. package/dist/components/api-key-referrers.d.ts +3 -2
  23. package/dist/components/api-key-referrers.js +2 -3
  24. package/dist/components/api-key.d.ts +0 -9
  25. package/dist/components/api-key.js +0 -39
  26. package/dist/components/auth-atoms.d.ts +178 -0
  27. package/dist/components/auth-atoms.js +46 -0
  28. package/dist/components/auth-client-api.d.ts +2474 -142
  29. package/dist/components/auth-client-api.js +14 -10
  30. package/dist/components/auth-forms.d.ts +1 -3
  31. package/dist/components/auth-forms.js +168 -195
  32. package/dist/components/auth-provider.d.ts +3 -7
  33. package/dist/components/auth-provider.js +56 -30
  34. package/dist/components/has-permission.js +1 -1
  35. package/dist/components/index.d.ts +19 -20
  36. package/dist/components/index.js +13 -13
  37. package/dist/components/member-required.d.ts +1 -3
  38. package/dist/components/member-required.js +102 -78
  39. package/dist/components/organization-switcher.d.ts +4 -6
  40. package/dist/components/organization-switcher.js +469 -323
  41. package/dist/components/project-access-matrix.d.ts +1 -1
  42. package/dist/components/project-access-matrix.js +9 -13
  43. package/dist/components/user-button.d.ts +5 -3
  44. package/dist/components/user-button.js +264 -314
  45. package/dist/components/utils.d.ts +3 -1
  46. package/dist/components/utils.js +4 -11
  47. package/dist/extra/api.group.d.ts +3 -3
  48. package/dist/extra/api.group.js +6 -6
  49. package/dist/extra/schema.js +1 -1
  50. package/dist/index.d.ts +11 -12
  51. package/dist/index.js +11 -12
  52. package/dist/query.d.ts +2 -2
  53. package/dist/roles.d.ts +5 -4
  54. package/dist/roles.js +11 -7
  55. package/dist/schema.d.ts +1 -1
  56. package/dist/schema.js +26 -19
  57. package/dist/server/actor.d.ts +20 -22
  58. package/dist/server/actor.js +14 -17
  59. package/dist/server/api.group.js +2 -2
  60. package/dist/server/index.d.ts +14 -14
  61. package/dist/server/index.js +8 -8
  62. package/dist/server/middleware.d.ts +1 -1
  63. package/dist/server/middleware.js +1 -1
  64. package/dist/server/schema.js +1 -1
  65. package/dist/service.d.ts +2043 -191
  66. package/dist/service.js +23 -16
  67. package/package.json +8 -7
  68. package/dist/better-auth/api.group.d.ts +0 -62
  69. package/dist/better-auth/api.group.js +0 -39
  70. package/dist/better-auth/schema.d.ts +0 -72
  71. package/dist/better-auth/schema.js +0 -110
  72. package/dist/components/auth-client.d.ts +0 -50
  73. package/dist/components/auth-client.js +0 -46
@@ -1,10 +1,11 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
- import { useAtomSuspense } from "@effect/atom-react";
2
+ import { useAtomRefresh, useAtomSuspense, useAtomValue, } from "@effect/atom-react";
3
3
  import { useRouterState } from "@tanstack/react-router";
4
+ import { AsyncResult } from "effect/unstable/reactivity";
4
5
  import { createContext, useCallback, useContext, useEffect, useEffectEvent, useMemo, useState, } from "react";
5
- import { createAuthUiClient } from "./auth-client";
6
- import { authClientApi } from "./auth-client-api";
7
- import { parseRoleList } from "../roles";
6
+ import { activeAuthOrganizationAtom, AUTH_CLIENT_CHANGE_EVENT, authSessionAtom, isAuthClientStorageEvent, } from "./auth-atoms.js";
7
+ import { authClientApi } from "./auth-client-api.js";
8
+ import { parseRoleList } from "../roles.js";
8
9
  const KrakstackAuthContext = createContext(null);
9
10
  const PROJECT_CONTEXT_COOKIE = "krakstack-auth.project_context";
10
11
  export const listenForSessionRevalidation = (target, revalidate) => {
@@ -17,10 +18,30 @@ export const listenForSessionRevalidation = (target, revalidate) => {
17
18
  target.removeEventListener("pageshow", onPageShow);
18
19
  };
19
20
  };
21
+ const listenForAuthChanges = (revalidate) => {
22
+ const onStorage = (event) => {
23
+ if (isAuthClientStorageEvent(event))
24
+ revalidate();
25
+ };
26
+ const onVisible = () => {
27
+ if (document.visibilityState === "visible")
28
+ revalidate();
29
+ };
30
+ window.addEventListener(AUTH_CLIENT_CHANGE_EVENT, revalidate);
31
+ window.addEventListener("storage", onStorage);
32
+ window.addEventListener("online", revalidate);
33
+ document.addEventListener("visibilitychange", onVisible);
34
+ return () => {
35
+ window.removeEventListener(AUTH_CLIENT_CHANGE_EVENT, revalidate);
36
+ window.removeEventListener("storage", onStorage);
37
+ window.removeEventListener("online", revalidate);
38
+ document.removeEventListener("visibilitychange", onVisible);
39
+ };
40
+ };
20
41
  const setProjectContextCookie = (projectId) => {
21
- if (typeof document === "undefined")
42
+ if (!globalThis.document)
22
43
  return;
23
- const secure = window.location.protocol === "https:" ? "; Secure" : "";
44
+ const secure = globalThis.window.location.protocol === "https:" ? "; Secure" : "";
24
45
  if (!projectId) {
25
46
  document.cookie = `${PROJECT_CONTEXT_COOKIE}=; Path=/; Max-Age=0; SameSite=Lax${secure}`;
26
47
  return;
@@ -32,7 +53,7 @@ const getSearchParam = (searchString, key) => {
32
53
  return null;
33
54
  return new URLSearchParams(searchString).get(key);
34
55
  };
35
- const getBrowserAuthHost = () => typeof window === "undefined" ? null : window.location.host;
56
+ const getBrowserAuthHost = () => globalThis.window?.location.host ?? null;
36
57
  const getRedirectHost = (searchString) => {
37
58
  if (!searchString)
38
59
  return null;
@@ -59,13 +80,17 @@ const useProjectConfig = (baseUrl, providedProjectId) => {
59
80
  const clientId = getSearchParam(searchString, "client_id");
60
81
  const host = getBrowserAuthHost();
61
82
  const rootHost = getRedirectHost(searchString);
83
+ const query = {};
84
+ if (projectId)
85
+ query.projectId = projectId;
86
+ if (clientId)
87
+ query.clientId = clientId;
88
+ if (host)
89
+ query.host = host;
90
+ if (rootHost)
91
+ query.rootHost = rootHost;
62
92
  const result = useAtomSuspense(authClientApi(baseUrl).query("authExtra", "getProjectPublicConfig", {
63
- query: {
64
- ...(projectId ? { projectId } : {}),
65
- ...(clientId ? { clientId } : {}),
66
- ...(host ? { host } : {}),
67
- ...(rootHost ? { rootHost } : {}),
68
- },
93
+ query,
69
94
  timeToLive: "5 minutes",
70
95
  reactivityKeys: [
71
96
  "project-public-config",
@@ -78,20 +103,21 @@ const useProjectConfig = (baseUrl, providedProjectId) => {
78
103
  }), { suspendOnWaiting: true });
79
104
  return result.value;
80
105
  };
81
- export function KrakstackAuthProvider({ children, locale = "en", baseUrl, projectId, authClient, access, accessLabels, }) {
106
+ export function KrakstackAuthProvider({ children, locale = "en", baseUrl, projectId, access, accessLabels, }) {
82
107
  const searchString = useRouterState({
83
108
  select: (state) => state.location.searchStr,
84
109
  });
85
110
  const resolvedProjectId = projectId ?? getSearchParam(searchString, "projectId");
86
- const resolvedAuthClient = useMemo(() => authClient ?? createAuthUiClient(baseUrl), [authClient, baseUrl]);
87
111
  const projectConfig = useProjectConfig(baseUrl, projectId);
88
112
  const [authRefreshVersion, setAuthRefreshVersion] = useState(0);
89
113
  const refreshAuth = useCallback(() => {
90
114
  setAuthRefreshVersion((current) => current + 1);
91
115
  }, []);
92
- const session = resolvedAuthClient.useSession();
116
+ const sessionAtom = authSessionAtom(baseUrl);
117
+ useAtomValue(sessionAtom);
118
+ const refreshSession = useAtomRefresh(sessionAtom);
93
119
  const revalidateSession = useEffectEvent(async () => {
94
- await session.refetch();
120
+ await refreshSession();
95
121
  refreshAuth();
96
122
  });
97
123
  useEffect(() => {
@@ -100,8 +126,10 @@ export function KrakstackAuthProvider({ children, locale = "en", baseUrl, projec
100
126
  useEffect(() => listenForSessionRevalidation(window, () => {
101
127
  void revalidateSession();
102
128
  }), []);
129
+ useEffect(() => listenForAuthChanges(() => {
130
+ void revalidateSession();
131
+ }), []);
103
132
  const value = useMemo(() => ({
104
- authClient: resolvedAuthClient,
105
133
  baseUrl,
106
134
  locale,
107
135
  projectId: resolvedProjectId,
@@ -111,7 +139,6 @@ export function KrakstackAuthProvider({ children, locale = "en", baseUrl, projec
111
139
  authRefreshVersion,
112
140
  refreshAuth,
113
141
  }), [
114
- resolvedAuthClient,
115
142
  baseUrl,
116
143
  locale,
117
144
  resolvedProjectId,
@@ -124,22 +151,18 @@ export function KrakstackAuthProvider({ children, locale = "en", baseUrl, projec
124
151
  return (_jsx(KrakstackAuthContext.Provider, { value: value, children: children }));
125
152
  }
126
153
  export const useKrakstackAuth = () => useContext(KrakstackAuthContext);
127
- export const useAuthClient = () => {
128
- const auth = useKrakstackAuth();
129
- if (!auth?.authClient) {
130
- throw new Error("KrakstackAuthProvider is required to use authClient.");
131
- }
132
- return auth.authClient;
133
- };
134
154
  export const useKrakstackAuthProjectConfig = () => useKrakstackAuth()?.projectConfig ?? null;
135
155
  export const usePermissions = () => {
136
156
  const auth = useKrakstackAuth();
137
157
  if (!auth) {
138
158
  throw new Error("KrakstackAuthProvider is required to use permissions.");
139
159
  }
140
- const session = auth.authClient.useSession();
141
- const activeOrganization = auth.authClient.useActiveOrganization();
142
- const memberRole = activeOrganization.data?.members.find((member) => member.userId === session.data?.user.id)?.role;
160
+ const sessionResult = useAtomValue(authSessionAtom(auth.baseUrl));
161
+ const session = AsyncResult.getOrElse(sessionResult, () => null);
162
+ const organizationId = session?.session.activeOrganizationId ?? null;
163
+ const activeOrganizationResult = useAtomValue(activeAuthOrganizationAtom(auth.baseUrl)(organizationId));
164
+ const activeOrganization = AsyncResult.getOrElse(activeOrganizationResult, () => null);
165
+ const memberRole = activeOrganization?.members.find((member) => member.userId === session?.user.id)?.role;
143
166
  const actions = new Set();
144
167
  if (auth.access) {
145
168
  for (const role of parseRoleList(memberRole)) {
@@ -148,7 +171,10 @@ export const usePermissions = () => {
148
171
  }
149
172
  }
150
173
  return {
151
- loading: session.isPending || activeOrganization.isPending,
174
+ loading: sessionResult._tag === "Initial" ||
175
+ sessionResult.waiting ||
176
+ activeOrganizationResult._tag === "Initial" ||
177
+ activeOrganizationResult.waiting,
152
178
  permissions: auth.access
153
179
  ? new Set(Array.from(actions, (action) => `${auth.access?.project}:${action}`))
154
180
  : new Set(),
@@ -1,4 +1,4 @@
1
1
  import { Fragment as _Fragment, jsx as _jsx } from "react/jsx-runtime";
2
- import { usePermissions } from "./auth-provider";
2
+ import { usePermissions } from "./auth-provider.js";
3
3
  export const useHasPermission = (permission) => usePermissions().can(permission);
4
4
  export const HasPermission = ({ children, permission, }) => (useHasPermission(permission) ? _jsx(_Fragment, { children: children }) : null);
@@ -1,20 +1,19 @@
1
- export { KrakstackAuthProvider, useAuthClient, useKrakstackAuth, useKrakstackAuthProjectConfig, usePermissions, } from "./auth-provider";
2
- export { createAuthUiClient } from "./auth-client";
3
- export { OrganizationSwitcher } from "./organization-switcher";
4
- export { MemberRequired } from "./member-required";
5
- export { HasPermission, useHasPermission } from "./has-permission";
6
- export { ProjectAccessMatrix } from "./project-access-matrix";
7
- export { ForgotPassword, ResetPassword, Signin, TwoFactor, VerifyEmail, } from "./auth-forms";
8
- export { UserButton } from "./user-button";
9
- export { AdminOrganizationsTable } from "./admin-organizations";
10
- export { AdminOrganizationForm } from "./admin-organization-form";
11
- export { AdminUsersTable, useAdminUsersTotal } from "./admin-users";
12
- export { assetUrl } from "./utils";
13
- export { ApiKeyPermissionGrant, CurrentActor, Forbidden, all, actorUserId, any, defineProjectAccess, defineProjectAccessLabels, permission, policy, withPolicy, } from "../access";
14
- export type { ApiKeyOwner, ApiKeyActor, Actor, Policy, ProjectAccessConfig, ProjectAccessCatalog, ProjectAccessLabelCatalog, ProjectAccessDefinition, ProjectAccessLabels, UserActor, } from "../access";
15
- export type { ProjectAccessMatrixAccess, ProjectAccessMatrixMessages, } from "./project-access-matrix";
16
- export type { KrakstackAuthContextValue, KrakstackAuthLocale, KrakstackAuthProviderProps, } from "./auth-provider";
17
- export type { OrganizationSwitcherDialog, OrganizationSwitcherFeatures, OrganizationSwitcherProps, } from "./organization-switcher";
18
- export type { UserButtonDialog, UserButtonProps } from "./user-button";
19
- export type { AuthUiClient } from "./auth-client";
20
- export type { MemberRequiredMessages, MemberRequiredProps, } from "./member-required";
1
+ export { KrakstackAuthProvider, useKrakstackAuth, useKrakstackAuthProjectConfig, usePermissions, } from "./auth-provider.js";
2
+ export { activeAuthOrganizationAtom, authOrganizationsAtom, authSessionAtom, } from "./auth-atoms.js";
3
+ export { OrganizationSwitcher } from "./organization-switcher.js";
4
+ export { MemberRequired } from "./member-required.js";
5
+ export { HasPermission, useHasPermission } from "./has-permission.js";
6
+ export { ProjectAccessMatrix } from "./project-access-matrix.js";
7
+ export { ForgotPassword, ResetPassword, Signin, TwoFactor, VerifyEmail, } from "./auth-forms.js";
8
+ export { UserButton } from "./user-button.js";
9
+ export { AdminOrganizationsTable } from "./admin-organizations.js";
10
+ export { AdminOrganizationForm } from "./admin-organization-form.js";
11
+ export { AdminUsersTable, useAdminUsersTotal } from "./admin-users.js";
12
+ export { assetUrl } from "./utils.js";
13
+ export { ApiKeyPermissionGrant, CurrentActor, Forbidden, all, actorUserId, any, defineProjectAccess, defineProjectAccessLabels, permission, policy, withPolicy, } from "../access.js";
14
+ export type { ApiKeyOwner, ApiKeyActor, Actor, Policy, ProjectAccessConfig, ProjectAccessCatalog, ProjectAccessLabelCatalog, ProjectAccessDefinition, ProjectAccessLabels, UserActor, } from "../access.js";
15
+ export type { ProjectAccessMatrixAccess, ProjectAccessMatrixMessages, } from "./project-access-matrix.js";
16
+ export type { KrakstackAuthContextValue, KrakstackAuthLocale, KrakstackAuthProviderProps, } from "./auth-provider.js";
17
+ export type { OrganizationSwitcherDialog, OrganizationSwitcherFeatures, OrganizationSwitcherProps, } from "./organization-switcher.js";
18
+ export type { UserButtonDialog, UserButtonProps } from "./user-button.js";
19
+ export type { MemberRequiredMessages, MemberRequiredProps, } from "./member-required.js";
@@ -1,13 +1,13 @@
1
- export { KrakstackAuthProvider, useAuthClient, useKrakstackAuth, useKrakstackAuthProjectConfig, usePermissions, } from "./auth-provider";
2
- export { createAuthUiClient } from "./auth-client";
3
- export { OrganizationSwitcher } from "./organization-switcher";
4
- export { MemberRequired } from "./member-required";
5
- export { HasPermission, useHasPermission } from "./has-permission";
6
- export { ProjectAccessMatrix } from "./project-access-matrix";
7
- export { ForgotPassword, ResetPassword, Signin, TwoFactor, VerifyEmail, } from "./auth-forms";
8
- export { UserButton } from "./user-button";
9
- export { AdminOrganizationsTable } from "./admin-organizations";
10
- export { AdminOrganizationForm } from "./admin-organization-form";
11
- export { AdminUsersTable, useAdminUsersTotal } from "./admin-users";
12
- export { assetUrl } from "./utils";
13
- export { ApiKeyPermissionGrant, CurrentActor, Forbidden, all, actorUserId, any, defineProjectAccess, defineProjectAccessLabels, permission, policy, withPolicy, } from "../access";
1
+ export { KrakstackAuthProvider, useKrakstackAuth, useKrakstackAuthProjectConfig, usePermissions, } from "./auth-provider.js";
2
+ export { activeAuthOrganizationAtom, authOrganizationsAtom, authSessionAtom, } from "./auth-atoms.js";
3
+ export { OrganizationSwitcher } from "./organization-switcher.js";
4
+ export { MemberRequired } from "./member-required.js";
5
+ export { HasPermission, useHasPermission } from "./has-permission.js";
6
+ export { ProjectAccessMatrix } from "./project-access-matrix.js";
7
+ export { ForgotPassword, ResetPassword, Signin, TwoFactor, VerifyEmail, } from "./auth-forms.js";
8
+ export { UserButton } from "./user-button.js";
9
+ export { AdminOrganizationsTable } from "./admin-organizations.js";
10
+ export { AdminOrganizationForm } from "./admin-organization-form.js";
11
+ export { AdminUsersTable, useAdminUsersTotal } from "./admin-users.js";
12
+ export { assetUrl } from "./utils.js";
13
+ export { ApiKeyPermissionGrant, CurrentActor, Forbidden, all, actorUserId, any, defineProjectAccess, defineProjectAccessLabels, permission, policy, withPolicy, } from "../access.js";
@@ -1,5 +1,4 @@
1
1
  import { type ReactNode } from "react";
2
- import type { AuthUiClient } from "./auth-client";
3
2
  declare const defaultMessages: {
4
3
  readonly en: {
5
4
  readonly member_required_title: "Organization access required";
@@ -35,11 +34,10 @@ declare const defaultMessages: {
35
34
  type MemberRequiredLabels = (typeof defaultMessages)["en"];
36
35
  export type MemberRequiredMessages = Partial<MemberRequiredLabels>;
37
36
  export type MemberRequiredProps = {
38
- authClient?: AuthUiClient | undefined;
39
37
  organizationId: string;
40
38
  contactEmail?: string | undefined;
41
39
  children?: ReactNode;
42
40
  messages?: MemberRequiredMessages | undefined;
43
41
  };
44
- export declare function MemberRequired({ authClient: providedAuthClient, organizationId, contactEmail, children, messages, }: MemberRequiredProps): import("react").JSX.Element;
42
+ export declare function MemberRequired({ organizationId, contactEmail, children, messages, }: MemberRequiredProps): import("react").JSX.Element;
45
43
  export {};
@@ -1,14 +1,17 @@
1
1
  import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { useAtomSuspense } from "@effect/atom-react";
3
- import { Effect } from "effect";
2
+ import { useAtomSet, useAtomSuspense } from "@effect/atom-react";
3
+ import { Effect, Schema } from "effect";
4
4
  import { Atom } from "effect/unstable/reactivity";
5
5
  import { Check, Loader2, Mail, ShieldAlert } from "lucide-react";
6
6
  import { useEffect, useState } from "react";
7
7
  import { Button } from "@/components/ui/button";
8
8
  import { CopyButton } from "@krak-stack/registry/copy-button";
9
9
  import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle, } from "@/components/ui/card";
10
- import { useKrakstackAuth } from "./auth-provider";
11
- import { isInvitationExpired, useInvitationExpirationClock, } from "./invitation-expiration";
10
+ import { authSessionAtom, notifyAuthChange } from "./auth-atoms.js";
11
+ import { authClientApi, authHttpClient } from "./auth-client-api.js";
12
+ import { useKrakstackAuth } from "./auth-provider.js";
13
+ import { AuthForbidden } from "../auth/schema.js";
14
+ import { isInvitationExpired, useInvitationExpirationClock, } from "./invitation-expiration.js";
12
15
  const defaultMessages = {
13
16
  en: {
14
17
  member_required_title: "Organization access required",
@@ -41,22 +44,6 @@ const defaultMessages = {
41
44
  member_required_copied_email: "E-mail copié",
42
45
  },
43
46
  };
44
- const isFullOrganization = (value) => {
45
- if (typeof value !== "object" || value === null)
46
- return false;
47
- if (!("id" in value) || typeof value.id !== "string")
48
- return false;
49
- if (!("name" in value) || typeof value.name !== "string")
50
- return false;
51
- if (!("slug" in value) || typeof value.slug !== "string")
52
- return false;
53
- if (!("displayName" in value) || typeof value.displayName !== "string") {
54
- return false;
55
- }
56
- if ("emails" in value && !Array.isArray(value.emails))
57
- return false;
58
- return true;
59
- };
60
47
  const interpolate = (value, params) => Object.entries(params ?? {}).reduce((current, [key, replacement]) => current.replace(`{${key}}`, replacement), value);
61
48
  const labels = (locale, overrides) => ({
62
49
  ...(locale === "fr" ? defaultMessages.fr : defaultMessages.en),
@@ -73,44 +60,81 @@ const organizationDisplayName = (invitation, organization, fallback) => organiza
73
60
  invitation?.organization?.name ??
74
61
  invitation?.organizationName ??
75
62
  fallback;
76
- const organizationProfileUrl = (baseUrl, organizationId, locale) => {
77
- const root = baseUrl?.trim() ||
78
- (typeof window === "undefined" ? "" : window.location.origin);
79
- const url = new URL("/api/auth/organization-profile", root);
80
- url.searchParams.set("organizationId", organizationId);
81
- if (locale)
82
- url.searchParams.set("locale", locale);
83
- return url;
84
- };
85
- const getOrganizationPublicProfile = async (baseUrl, organizationId, locale) => {
86
- const response = await fetch(organizationProfileUrl(baseUrl, organizationId, locale), {
87
- credentials: "include",
63
+ const acceptInvitationAtom = Atom.family((baseUrl) => Atom.fn(({ invitationId, organizationId, onFailure, onSuccess, }, get) => Effect.gen(function* () {
64
+ const client = yield* authHttpClient(baseUrl);
65
+ yield* client.auth.organizationAcceptInvitation({
66
+ payload: { invitationId },
88
67
  });
89
- if (!response.ok)
90
- return null;
91
- const body = await response.json();
92
- return isFullOrganization(body) ? body : null;
93
- };
94
- const accessAtom = Atom.family((authClient) => Atom.family((key) => {
95
- const { baseUrl, locale, organizationId } = JSON.parse(key);
96
- return Atom.keepAlive(Atom.make(Effect.tryPromise({
97
- try: async () => {
98
- const activeResult = await authClient.organization.setActive({
99
- organizationId,
68
+ yield* client.auth
69
+ .organizationSetActive({ payload: { organizationId } })
70
+ .pipe(Effect.catchCause(() => Effect.void));
71
+ get.refresh(authSessionAtom(baseUrl));
72
+ yield* get.result(authSessionAtom(baseUrl), {
73
+ suspendOnWaiting: true,
74
+ });
75
+ yield* Effect.sync(notifyAuthChange);
76
+ }).pipe(Effect.match({
77
+ onFailure,
78
+ onSuccess,
79
+ }))));
80
+ const organizationProfileAtom = Atom.family((baseUrl) => Atom.family((key) => {
81
+ const ProfileKey = Schema.fromJsonString(Schema.Struct({
82
+ locale: Schema.optional(Schema.Literals(["en", "fr"])),
83
+ organizationId: Schema.String,
84
+ }));
85
+ const { locale, organizationId } = Schema.decodeUnknownSync(ProfileKey)(key);
86
+ const query = locale ? { organizationId, locale } : { organizationId };
87
+ return authClientApi(baseUrl).query("authExtra", "getOrganizationPublicProfile", {
88
+ query,
89
+ timeToLive: "5 minutes",
90
+ serializationKey: `member-organization-profile:${key}`,
91
+ });
92
+ }));
93
+ const invitationsAtom = Atom.family((baseUrl) => Atom.family((accessKey) => authClientApi(baseUrl).query("auth", "organizationListUserInvitations", {
94
+ query: {},
95
+ serializationKey: `member-invitations:${accessKey}`,
96
+ })));
97
+ const accessAtom = Atom.family((baseUrl) => Atom.family((key) => {
98
+ const AccessKey = Schema.fromJsonString(Schema.Struct({
99
+ baseUrl: Schema.optional(Schema.String),
100
+ locale: Schema.optional(Schema.Literals(["en", "fr"])),
101
+ organizationId: Schema.String,
102
+ userId: Schema.optional(Schema.String),
103
+ }));
104
+ const { locale, organizationId } = Schema.decodeUnknownSync(AccessKey)(key);
105
+ return Atom.keepAlive(Atom.make((get) => Effect.gen(function* () {
106
+ const client = yield* authHttpClient(baseUrl);
107
+ const allowed = yield* client.auth
108
+ .organizationSetActive({ payload: { organizationId } })
109
+ .pipe(Effect.as(true), Effect.catch((error) => error instanceof AuthForbidden
110
+ ? Effect.succeed(false)
111
+ : Effect.fail(error)));
112
+ if (allowed) {
113
+ get.refresh(authSessionAtom(baseUrl));
114
+ yield* get.result(authSessionAtom(baseUrl), {
115
+ suspendOnWaiting: true,
100
116
  });
101
- if (!activeResult.error)
102
- return { allowed: true };
103
- const [organization, invitationsResult] = await Promise.all([
104
- getOrganizationPublicProfile(baseUrl, organizationId, locale).catch(() => null),
105
- authClient.organization.listUserInvitations({}),
106
- ]);
107
- return {
108
- allowed: false,
109
- organization,
110
- invitation: invitationsResult.data?.find((item) => invitationMatches(item, organizationId)) ?? null,
111
- };
112
- },
113
- catch: (error) => error,
117
+ return { allowed: true };
118
+ }
119
+ const profileKey = JSON.stringify({ locale, organizationId });
120
+ const { organization, invitations } = yield* Effect.all({
121
+ organization: get
122
+ .result(organizationProfileAtom(baseUrl)(profileKey), {
123
+ suspendOnWaiting: true,
124
+ })
125
+ .pipe(Effect.matchCause({
126
+ onFailure: () => null,
127
+ onSuccess: (value) => value,
128
+ })),
129
+ invitations: get.result(invitationsAtom(baseUrl)(key), {
130
+ suspendOnWaiting: true,
131
+ }),
132
+ }, { concurrency: "unbounded" });
133
+ return {
134
+ allowed: false,
135
+ organization,
136
+ invitation: invitations.find((item) => invitationMatches(item, organizationId)) ?? null,
137
+ };
114
138
  })));
115
139
  }));
116
140
  const accessAtomKey = ({ authRefreshVersion, baseUrl, locale, organizationId, userId, }) => JSON.stringify({
@@ -120,18 +144,16 @@ const accessAtomKey = ({ authRefreshVersion, baseUrl, locale, organizationId, us
120
144
  organizationId,
121
145
  userId,
122
146
  });
123
- export function MemberRequired({ authClient: providedAuthClient, organizationId, contactEmail, children, messages, }) {
147
+ export function MemberRequired({ organizationId, contactEmail, children, messages, }) {
124
148
  const auth = useKrakstackAuth();
125
- const authClient = providedAuthClient ?? auth?.authClient;
126
149
  const baseUrl = auth?.baseUrl;
127
150
  const authRefreshVersion = auth?.authRefreshVersion ?? 0;
128
151
  const locale = auth?.locale;
129
152
  const refreshAuth = auth?.refreshAuth;
130
- if (!authClient) {
131
- throw new Error("KrakstackAuthProvider is required to use authClient.");
132
- }
133
- const session = authClient.useSession();
134
- const userId = session.data?.user.id;
153
+ const session = useAtomSuspense(authSessionAtom(baseUrl), {
154
+ suspendOnWaiting: true,
155
+ }).value;
156
+ const userId = session?.user.id;
135
157
  const currentAccessKey = accessAtomKey({
136
158
  authRefreshVersion,
137
159
  baseUrl,
@@ -142,13 +164,14 @@ export function MemberRequired({ authClient: providedAuthClient, organizationId,
142
164
  const [allowedAccessKey, setAllowedAccessKey] = useState(null);
143
165
  if (allowedAccessKey === currentAccessKey)
144
166
  return _jsx(_Fragment, { children: children });
145
- return (_jsx(MemberRequiredGate, { accessKey: currentAccessKey, authClient: authClient, contactEmail: contactEmail, locale: locale, messages: messages, onAccessAllowed: () => setAllowedAccessKey(currentAccessKey), organizationId: organizationId, refreshAuth: refreshAuth, children: children }));
167
+ return (_jsx(MemberRequiredGate, { accessKey: currentAccessKey, baseUrl: baseUrl, contactEmail: contactEmail, locale: locale, messages: messages, onAccessAllowed: () => setAllowedAccessKey(currentAccessKey), organizationId: organizationId, refreshAuth: refreshAuth, children: children }));
146
168
  }
147
- function MemberRequiredGate({ accessKey, authClient, contactEmail, children, locale, messages, onAccessAllowed, organizationId, refreshAuth, }) {
169
+ function MemberRequiredGate({ accessKey, baseUrl, contactEmail, children, locale, messages, onAccessAllowed, organizationId, refreshAuth, }) {
148
170
  const m = labels(locale, messages);
149
- const accessResult = useAtomSuspense(accessAtom(authClient)(accessKey), {
171
+ const accessResult = useAtomSuspense(accessAtom(baseUrl)(accessKey), {
150
172
  suspendOnWaiting: true,
151
173
  });
174
+ const acceptInvitationMutation = useAtomSet(acceptInvitationAtom(baseUrl));
152
175
  const [accepting, setAccepting] = useState(false);
153
176
  const [error, setError] = useState(null);
154
177
  const access = accessResult.value;
@@ -166,25 +189,26 @@ function MemberRequiredGate({ accessKey, authClient, contactEmail, children, loc
166
189
  : false;
167
190
  const displayName = organizationDisplayName(invitation, organization, organizationId);
168
191
  const resolvedContactEmail = organizationContactEmail(organization, contactEmail);
169
- const acceptInvitation = async () => {
192
+ const acceptInvitation = () => {
170
193
  if (!invitation || isInvitationExpired(invitation))
171
194
  return;
172
195
  setAccepting(true);
173
196
  setError(null);
174
- const result = await authClient.organization.acceptInvitation({
197
+ acceptInvitationMutation({
175
198
  invitationId: invitation.id,
176
- });
177
- if (result.error) {
178
- setAccepting(false);
179
- setError(result.error.message ?? m.member_required_accept_error);
180
- return;
181
- }
182
- await authClient.organization.setActive({
183
199
  organizationId: invitation.organizationId,
200
+ onFailure: (cause) => {
201
+ setAccepting(false);
202
+ setError(cause instanceof Error && cause.message
203
+ ? cause.message
204
+ : m.member_required_accept_error);
205
+ },
206
+ onSuccess: () => {
207
+ refreshAuth?.();
208
+ onAccessAllowed();
209
+ setAccepting(false);
210
+ },
184
211
  });
185
- refreshAuth?.();
186
- onAccessAllowed();
187
- setAccepting(false);
188
212
  };
189
213
  return (_jsx("main", { className: "relative grid min-h-screen place-items-center px-6 py-10", children: _jsxs(Card, { className: "w-full max-w-md", children: [_jsxs(CardHeader, { children: [_jsx("div", { className: "bg-destructive/10 text-destructive mb-2 flex size-10 items-center justify-center rounded-md", children: _jsx(ShieldAlert, {}) }), _jsx(CardTitle, { children: m.member_required_title }), _jsx(CardDescription, { children: interpolate(m.member_required_org_description, {
190
214
  organization: displayName,
@@ -1,6 +1,5 @@
1
1
  import { type ComponentProps, type ReactNode } from "react";
2
2
  import { DropdownMenuContent } from "@/components/ui/dropdown-menu";
3
- import type { AuthUiClient } from "./auth-client";
4
3
  declare const messages: {
5
4
  readonly en: {
6
5
  readonly organization_back: "Back";
@@ -283,7 +282,6 @@ export type OrganizationSwitcherFeatures = {
283
282
  userInvitations?: boolean;
284
283
  };
285
284
  export type OrganizationSwitcherProps = {
286
- authClient?: AuthUiClient;
287
285
  baseUrl?: string | undefined;
288
286
  side?: ComponentProps<typeof DropdownMenuContent>["side"];
289
287
  className?: string;
@@ -304,10 +302,10 @@ type OrganizationSummary = {
304
302
  id: string;
305
303
  name: string;
306
304
  slug: string;
307
- metadata?: unknown;
308
- userId?: string | null;
309
- parentId?: string | null;
305
+ metadata?: unknown | undefined;
306
+ userId?: string | null | undefined;
307
+ parentId?: string | null | undefined;
310
308
  };
311
309
  export type OrganizationSwitcherDialog = "create" | "manage" | "members" | "apiKeys" | "invitations";
312
- export declare function OrganizationSwitcher({ authClient: providedAuthClient, baseUrl, side, className, defaultDialog, features, hideTrigger, menuActions, renderUnauthenticated, allowedOrganizationIds, messages, dialog: controlledDialog, onChange, onCreate, onDialogChange, apiKeyPermissions, }: OrganizationSwitcherProps): import("react").JSX.Element;
310
+ export declare function OrganizationSwitcher({ baseUrl: providedBaseUrl, side, className, defaultDialog, features, hideTrigger, menuActions, renderUnauthenticated, allowedOrganizationIds, messages, dialog: controlledDialog, onChange, onCreate, onDialogChange, apiKeyPermissions, }: OrganizationSwitcherProps): import("react").JSX.Element;
313
311
  export {};