@burdenoff/microfe-auth 2026.1101.1 → 2026.1101.3
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.
- package/README.md +21 -0
- package/dist/auth/hooks/useContextSwitcherData.js +5 -1
- package/dist/auth/hooks/useContextSwitcherData.js.map +1 -1
- package/dist/shell.d.ts +7 -0
- package/dist/shell.js +3 -0
- package/dist/store.d.ts +2 -0
- package/dist/store.js +1 -0
- package/package.json +11 -3
package/README.md
CHANGED
|
@@ -7,6 +7,27 @@ Part of the [Burdenoff](https://burdenoff.com) platform by
|
|
|
7
7
|
|
|
8
8
|
See `AGENTS.md` for development commands and architecture details.
|
|
9
9
|
|
|
10
|
+
## Shell imports
|
|
11
|
+
|
|
12
|
+
Hosts that only need auth state or context-switcher hooks can use the public
|
|
13
|
+
shell entries without statically importing auth routes and challenge UI:
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { useAuthStore } from '@burdenoff/microfe-auth/store';
|
|
17
|
+
import {
|
|
18
|
+
useContextSwitcherData,
|
|
19
|
+
useWorkspaceSyncEffect,
|
|
20
|
+
useProjectSyncEffect,
|
|
21
|
+
} from '@burdenoff/microfe-auth/shell';
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
These entries re-export the same canonical store and hooks as the root entry;
|
|
25
|
+
they do not create another store, change context loading, or defer logout
|
|
26
|
+
cleanup. The root entry and its existing exports remain supported. Both new
|
|
27
|
+
entries ship declarations, and the build checks their packed static graph.
|
|
28
|
+
Consumers must adopt a published package version containing these exports;
|
|
29
|
+
source-linked tests alone are not a published compatibility guarantee.
|
|
30
|
+
|
|
10
31
|
## Workspace and project selection
|
|
11
32
|
|
|
12
33
|
The shared context switcher issues a workspace token and reads `myProjects` to
|
|
@@ -367,7 +367,11 @@ function I(d) {
|
|
|
367
367
|
} },
|
|
368
368
|
authToken: c,
|
|
369
369
|
baseUrl: Y,
|
|
370
|
-
tenantId: i
|
|
370
|
+
tenantId: i,
|
|
371
|
+
workspaceId: n,
|
|
372
|
+
organizationId: t,
|
|
373
|
+
projectId: r ?? void 0,
|
|
374
|
+
workspaceToken: !1
|
|
371
375
|
});
|
|
372
376
|
if (p.errors?.length) {
|
|
373
377
|
let e = p.errors[0]?.message ?? "GraphQL error";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useContextSwitcherData.js","names":["selectWorkspaceWide","persistWorkspaceWideSelection","MY_ORGANIZATIONS_QUERY","WORKSPACES_BY_ORG_QUERY","MY_WORKSPACES_PAGE_QUERY","UNUSABLE_PROJECT_TOKEN_ERRORS","isUnusableProjectTokenError","code","WORKSPACES_PAGE_SIZE","WORKSPACES_MAX_PAGES","ISSUE_WORKSPACE_TOKEN_MUTATION","PROJECTS_QUERY","isTokenExpired","payload","token","bufferMs","getWorkspaceTokenPayload","isWorkspaceTokenValidForContext","expected","AuthError","message","isAuthGraphQLError","errors","resolveAccessToken","storeToken","useAuthStore","profileToken","getStoredAuthToken","readRemainingWorkspacePages","items","first","total","page","next","graphqlFetch","globalBaseUrl","pageItems","buildFallbackOrganizations","workspaces","workspace","organizationId","index","PROJECT_REFRESH_EVENTS","WORKSPACE_REFRESH_EVENTS","readEventWorkspaceId","value","useContextSwitcherData","disableBootstrap","options","disableWorkspaceSync","disableProjectSync","skipProjectFetch","activeOrganizationId","activeWorkspaceId","activeProjectId","activeTenantId","setActiveContext","useActiveContext","eventBus","useEventBus","organizations","state","currentOrganizationId","isLoadingOrganizations","currentWorkspaceId","workspaceToken","isLoadingWorkspaces","projects","currentProjectId","isLoadingProjects","row","organization","error","setError","useState","bootstrapFailureNonce","setBootstrapFailureNonce","bootstrapRetryAttemptRef","useRef","fetchOrganizationsPromiseRef","fetchWorkspacesPromisesRef","activeWorkspaceIdRef","activeOrganizationIdRef","resolvedBaseUrls","resolveGatewayBaseUrls","workspaceBaseUrl","lastAppliedOrgIdRef","lastAppliedWorkspaceIdRef","lastAppliedProjectIdRef","lastClearedTokenContextRef","store","project","isWorkspaceWideSelection","ctxKey","fetchOrganizations","useCallback","initialTargetOrgId","requestedWorkspaceId","workspaceFromUrl","getUrlParam","orgFromUrl","result","organizationsResult","workspacesResult","errorMessage","orgs","recovery","recoveryMessage","fallbackOrganizations","effectiveOrganizations","targetOrgId","listedWorkspaces","w","isCompleteListing","workspaceLink","decideWorkspaceDeepLink","linked","denial","decideOrganizationDeepLink","targetOrgIsAccessible","org","ws","wsResult","n","persistedWorkspace","nextActiveContext","err","useEffect","delayMs","timer","onOnline","fetchWorkspacesForOrg","profileId","resolveActiveProfileId","userId","requestKey","existingPromise","currentSelection","current","fetchPromise","issueWorkspaceToken","originalScope","workspaceWide","workspaceId","authToken","projectId","tokenResult","latest","resolvedWsId","fetchProjects","wsToken","wide","projs","selectOrganization","selectWorkspace","selected","accessToken","selectProject","clearWorkspaceWideSelection","selectWorkspaceWide$1","scope","selectWorkspaceWide","cancelled","makeCoalescedRefetch","running","queued","trigger","run","refreshProjects","refreshWorkspaces","orgId","unsubscribe","eventName","event","eventWorkspaceId","proj","useWorkspaceSyncEffect","hasMatchingWorkspaces","useProjectSyncEffect","syncInProgressRef","syncRevision","setSyncRevision","emptyProjectsResultRef","retryTimerRef","projectSyncFailuresRef","PROJECT_SYNC_FAILURE_COOLDOWN_MS","failureEntry","currentWorkspace","needsToken","scopeKey","hasProjectsForWorkspace","p","firstProject","contextStillCurrent","syncProjects","succeeded","projectsResult","scopeCurrent","revision","failures","pending","nextCount","existingTimer","backoffMs","timers"],"sources":["../../../src/auth/hooks/useContextSwitcherData.ts"],"sourcesContent":["import {\n isWorkspaceWideSelection,\n selectWorkspaceWide as persistWorkspaceWideSelection,\n clearWorkspaceWideSelection,\n} from \"@burdenoff/fe-libs/shared/providers/shell/WorkspaceWideSelection\";\nimport { resolveActiveProfileId } from \"@burdenoff/fe-libs/shared/providers/shell/ProfileStorageManager\";\nimport { getUrlParam } from \"@burdenoff/fe-libs/shared/providers/shell/ActiveContextStorage\";\nimport { useCallback, useState, useEffect, useRef } from \"react\";\nimport {\n graphqlFetch,\n getStoredAuthToken,\n} from \"@burdenoff/fe-libs/shared/graphql\";\nimport { useActiveContext } from \"@burdenoff/fe-libs/shared/providers/shell/ActiveContextProvider\";\nimport { useEventBus } from \"@burdenoff/fe-libs/shared/events\";\nimport { useAuthStore } from \"../store/authStore\";\nimport type { Organization, Workspace, Project } from \"../types\";\nimport { resolveGatewayBaseUrls } from \"../utils/gatewayBaseUrls\";\nimport {\n decideOrganizationDeepLink,\n decideWorkspaceDeepLink,\n isCompleteListing,\n} from \"./contextDeepLink\";\n\n// =============================================================================\n// Hook Options\n// =============================================================================\n\nexport interface UseContextSwitcherDataOptions {\n /**\n * Optional Global API Gateway base URL override.\n * If not provided, uses GATEWAYS config from fe-libs.\n */\n globalBaseUrl?: string;\n /**\n * Optional Workspaces API Gateway base URL override.\n * If not provided, uses GATEWAYS config from fe-libs.\n */\n workspaceBaseUrl?: string;\n /** Disable initial organization/workspace bootstrap fetches */\n disableBootstrap?: boolean;\n /** Disable the workspace sync effect */\n disableWorkspaceSync?: boolean;\n /** Disable the project sync effect */\n disableProjectSync?: boolean;\n /** Only hydrate the workspace token; do not eagerly fetch projects */\n skipProjectFetch?: boolean;\n}\n\n// =============================================================================\n// GraphQL Response Types\n// =============================================================================\n\ninterface MyOrganizationsResponse {\n myOrganizations: {\n total: number;\n items: Organization[];\n };\n}\n\ninterface WorkspacesByOrgResponse {\n workspaces: {\n total: number;\n items: Workspace[];\n };\n}\n\ntype GraphQLFetchResult<T> = Awaited<ReturnType<typeof graphqlFetch<T>>>;\n\ninterface IssueWorkspaceTokenResult {\n success: boolean;\n token: string | null;\n expiresAt: string | null;\n organizationId: string | null;\n workspaceId: string | null;\n projectId: string | null;\n scopes: string[] | null;\n error: {\n code: string;\n message: string;\n } | null;\n}\n\ninterface ProjectsResponse {\n projects: {\n total: number;\n items: Project[];\n };\n}\n\n// =============================================================================\n// GraphQL Query/Mutation Strings\n// =============================================================================\n\nconst MY_ORGANIZATIONS_QUERY = `\n query MyOrganizations {\n myOrganizations {\n total\n items {\n id\n name\n slug\n tenantId\n description\n logo\n website\n status\n type\n createdAt\n updatedAt\n }\n }\n }\n`;\n\n// Both queries below historically used `workspaces(filter: $filter)` with\n// a `WorkspaceFilterInput` to fetch workspaces for a specific organization.\n// That Query field was removed/renamed in the global subgraph; calling it\n// now throws GRAPHQL_VALIDATION_FAILED (\"Cannot query field 'workspaces'\n// on type 'Query'\") which crashes the context switcher and cascades into a\n// \"Verifying workspace access...\" stuck-spinner on every Platform module\n// route (/billing, /support, /notifications, /devportal).\n//\n// The supported field is `myWorkspaces(limit, offset)` on the global\n// subgraph — self-scoped, returns the caller's workspaces across all\n// orgs. It does NOT accept a filter, so we fetch up to 100 of \"my\"\n// workspaces and let the existing downstream auto-pick logic filter by\n// organizationId client-side. The recovery path at line ~624 already\n// uses this exact aliased pattern; we're just promoting it to the\n// primary path.\nconst WORKSPACES_BY_ORG_QUERY = `\n query WorkspacesByOrg {\n workspaces: myWorkspaces(limit: 100) {\n total\n items {\n id\n name\n slug\n tenantId\n organizationId\n type\n status\n region\n createdAt\n updatedAt\n }\n }\n }\n`;\n\n// A further page of `myWorkspaces`, read only when a deep-linked workspace is\n// not on the first page of a caller with more than 100 workspaces.\nconst MY_WORKSPACES_PAGE_QUERY = `\n query MyWorkspacesPage($limit: Int, $offset: Int) {\n workspaces: myWorkspaces(limit: $limit, offset: $offset) {\n total\n items {\n id\n name\n slug\n tenantId\n organizationId\n type\n status\n region\n createdAt\n updatedAt\n }\n }\n }\n`;\n\n/**\n * `issueWorkspaceToken` error codes that mean the requested project can never\n * be used by this caller (they are not a member, or it no longer exists). A\n * retry with the same project cannot succeed, so the project selection has to\n * be dropped instead.\n */\nconst UNUSABLE_PROJECT_TOKEN_ERRORS: ReadonlySet<string> = new Set([\n \"NOT_PROJECT_MEMBER\",\n \"PROJECT_NOT_FOUND\",\n]);\n\nfunction isUnusableProjectTokenError(code: string | null | undefined): boolean {\n return !!code && UNUSABLE_PROJECT_TOKEN_ERRORS.has(code);\n}\n\nconst WORKSPACES_PAGE_SIZE = 100;\n// Bounds the read for a deep link: 20 pages = 2,000 workspaces.\nconst WORKSPACES_MAX_PAGES = 20;\n\nconst ISSUE_WORKSPACE_TOKEN_MUTATION = `\n mutation IssueWorkspaceToken($input: IssueWorkspaceTokenInput!) {\n issueWorkspaceToken(input: $input) {\n success\n token\n expiresAt\n organizationId\n workspaceId\n projectId\n scopes\n error {\n code\n message\n }\n }\n }\n`;\n\n// The workspace gateway exposes `myProjects` (public RBAC, caller-scoped to\n// the active workspace via x-workspace-id) and the privileged\n// `projects(filter)` (list:project). The header has no `list:project`\n// permission seeded for the typical operator, so the privileged form\n// returns FORBIDDEN even though the caller is a member of the workspace.\n// `myProjects` is the right field for \"give me the projects I can see in\n// this workspace\" — workspace scope is already established by the\n// workspace token + x-workspace-id header that we pass with the request.\nconst PROJECTS_QUERY = `\n query MyProjectsForContext {\n projects: myProjects {\n total\n items {\n id\n name\n key\n workspaceId\n status\n archived\n createdAt\n updatedAt\n }\n }\n }\n`;\n\n// =============================================================================\n// Auth Helpers\n// =============================================================================\n\n/**\n * Check whether a JWT is expired (or within bufferMs of expiry).\n * Returns true if the token is expired, close to expiry, or malformed.\n */\nfunction isTokenExpired(token: string, bufferMs = 30_000): boolean {\n try {\n const payload = JSON.parse(atob(token.split(\".\")[1]));\n if (!payload.exp) return false;\n return payload.exp * 1000 < Date.now() + bufferMs;\n } catch {\n return true;\n }\n}\n\nfunction getWorkspaceTokenPayload(token: string): {\n workspaceId?: string;\n organizationId?: string;\n projectId?: string;\n exp?: number;\n} | null {\n try {\n const payload = JSON.parse(atob(token.split(\".\")[1]));\n return {\n workspaceId:\n typeof payload.workspaceId === \"string\"\n ? payload.workspaceId\n : undefined,\n organizationId:\n typeof payload.organizationId === \"string\"\n ? payload.organizationId\n : undefined,\n projectId:\n typeof payload.projectId === \"string\" ? payload.projectId : undefined,\n exp: typeof payload.exp === \"number\" ? payload.exp : undefined,\n };\n } catch {\n return null;\n }\n}\n\nfunction isWorkspaceTokenValidForContext(\n token: string | null | undefined,\n expected: {\n workspaceId?: string | null;\n organizationId?: string | null;\n projectId?: string | null;\n workspaceWide?: boolean;\n },\n): token is string {\n if (!token || isTokenExpired(token)) {\n return false;\n }\n\n const payload = getWorkspaceTokenPayload(token);\n if (!payload) {\n return false;\n }\n\n if (expected.workspaceId && payload.workspaceId !== expected.workspaceId) {\n return false;\n }\n\n if (\n expected.organizationId &&\n payload.organizationId !== expected.organizationId\n ) {\n return false;\n }\n\n if (expected.workspaceWide && payload.projectId) return false;\n\n if (expected.projectId && payload.projectId !== expected.projectId) {\n return false;\n }\n\n return true;\n}\n\n/**\n * Custom error class for auth-related failures (expired token, unauthorized, etc.).\n * Used to distinguish auth errors in outer catch blocks so they can be\n * suppressed from console.error — they are expected during token refresh cycles\n * and do not indicate application bugs.\n */\nclass AuthError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"AuthError\";\n }\n}\n\n/**\n * Detect whether a set of GraphQL errors are authentication-related.\n */\nfunction isAuthGraphQLError(\n errors: Array<{ message?: string; extensions?: { code?: string } }>,\n): boolean {\n return errors.some(\n (e) =>\n e.extensions?.code === \"UNAUTHENTICATED\" ||\n e.message?.toLowerCase().includes(\"unauthorized\") ||\n e.message?.toLowerCase().includes(\"not authenticated\"),\n );\n}\n\n/**\n * Resolve the best available access token:\n * 1. Try the zustand store token\n * 2. If expired, fall back to profile storage (may have been refreshed)\n * 3. Return null if no valid token is available\n */\nfunction resolveAccessToken(): string | null {\n const storeToken = useAuthStore.getState().accessToken;\n\n // If store token is valid (or has no exp claim), use it\n if (storeToken && !isTokenExpired(storeToken)) {\n return storeToken;\n }\n\n // Store token is expired or missing — try profile storage (may be fresher)\n const profileToken = getStoredAuthToken();\n if (profileToken && !isTokenExpired(profileToken)) {\n return profileToken;\n }\n\n // Both expired or missing — if store token exists at all, return it as a last\n // resort (the gateway will reject it and the useEffect will re-trigger after\n // token refresh). Returning null would silently swallow the first load.\n return storeToken;\n}\n\n/**\n * The rest of the caller's workspaces after `first` (a first page of\n * `myWorkspaces`), bounded by WORKSPACES_MAX_PAGES. A failed page ends the read\n * with what was gathered, marked complete only if every page was read.\n */\nasync function readRemainingWorkspacePages(\n first: WorkspacesByOrgResponse[\"workspaces\"],\n token: string,\n globalBaseUrl: string,\n): Promise<WorkspacesByOrgResponse[\"workspaces\"]> {\n const items = [...first.items];\n const total = first.total;\n for (\n let page = 1;\n page < WORKSPACES_MAX_PAGES && items.length < total;\n page += 1\n ) {\n const next = await graphqlFetch<WorkspacesByOrgResponse>({\n gateway: \"global\",\n query: MY_WORKSPACES_PAGE_QUERY,\n variables: { limit: WORKSPACES_PAGE_SIZE, offset: items.length },\n authToken: token,\n baseUrl: globalBaseUrl,\n });\n const pageItems = next.errors?.length\n ? []\n : (next.data?.workspaces?.items ?? []);\n if (pageItems.length === 0) {\n // Unreadable or short: report what we have as a partial listing so no\n // denial is concluded from it.\n return { total: Math.max(total, items.length + 1), items };\n }\n items.push(...pageItems);\n }\n return { total, items };\n}\n\nfunction buildFallbackOrganizations(workspaces: Workspace[]): Organization[] {\n const uniqueOrgIds = Array.from(\n new Set(\n workspaces.flatMap((workspace) =>\n workspace.organizationId ? [workspace.organizationId] : [],\n ),\n ),\n );\n\n return uniqueOrgIds.map((organizationId, index) => ({\n id: organizationId,\n name:\n workspaces.find(\n (workspace) => workspace.organizationId === organizationId,\n )?.name || `Organization ${index + 1}`,\n slug: organizationId,\n tenantId:\n workspaces.find(\n (workspace) => workspace.organizationId === organizationId,\n )?.tenantId || \"\",\n }));\n}\n\n// =============================================================================\n// Hook Implementation\n// =============================================================================\n\n/**\n * Hook for managing the context switcher data (organizations, workspaces, projects)\n *\n * Data flow:\n * 1. fetchOrganizations() - Get all orgs user has access to (Global Gateway)\n * 2. selectOrganization(org) - Set current org & fetch workspaces for that org\n * 3. selectWorkspace(ws) - Issue workspace token & fetch projects\n * 4. selectProject(proj) - Set current project\n *\n * All GraphQL calls go through graphqlFetch from fe-libs which automatically\n * resolves gateway URLs and injects auth + locale headers.\n *\n * @param options - Optional configuration (gateway base URL overrides)\n */\n// Domain events emitted by microfe-workspaces that should refresh the switcher's\n// cached lists. Module-scoped so they aren't reallocated on every effect run.\nconst PROJECT_REFRESH_EVENTS = new Set<string>([\n \"project.created\",\n \"project.updated\",\n \"project.deleted\",\n \"project.archived\",\n \"project.unarchived\",\n]);\nconst WORKSPACE_REFRESH_EVENTS = new Set<string>([\n \"workspace.created\",\n \"workspace.updated\",\n \"workspace.deleted\",\n \"workspace.archived\",\n \"workspace.reactivated\",\n]);\n\n// Safely read a string `workspaceId` off a cross-MFE event payload of unknown\n// shape, rather than trusting a bare cast (the payload is produced by another\n// MFE and could drift). Returns undefined when absent or not a string.\nfunction readEventWorkspaceId(payload: unknown): string | undefined {\n if (payload && typeof payload === \"object\" && \"workspaceId\" in payload) {\n const value = (payload as { workspaceId?: unknown }).workspaceId;\n return typeof value === \"string\" ? value : undefined;\n }\n return undefined;\n}\n\nexport function useContextSwitcherData(\n options?: UseContextSwitcherDataOptions,\n) {\n const disableBootstrap = options?.disableBootstrap ?? false;\n const disableWorkspaceSync = options?.disableWorkspaceSync ?? false;\n const disableProjectSync = options?.disableProjectSync ?? false;\n const skipProjectFetch = options?.skipProjectFetch ?? false;\n const {\n organizationId: activeOrganizationId,\n workspaceId: activeWorkspaceId,\n projectId: activeProjectId,\n tenantId: activeTenantId,\n setContext: setActiveContext,\n } = useActiveContext();\n\n const eventBus = useEventBus();\n\n // Use selectors for reactive state\n const organizations = useAuthStore((state) => state.organizations);\n const currentOrganizationId = useAuthStore(\n (state) => state.currentOrganizationId,\n );\n const isLoadingOrganizations = useAuthStore(\n (state) => state.isLoadingOrganizations,\n );\n\n const workspaces = useAuthStore((state) => state.workspaces);\n const currentWorkspaceId = useAuthStore((state) => state.currentWorkspaceId);\n const workspaceToken = useAuthStore((state) => state.workspaceToken);\n const isLoadingWorkspaces = useAuthStore(\n (state) => state.isLoadingWorkspaces,\n );\n\n const projects = useAuthStore((state) => state.projects);\n const currentProjectId = useAuthStore((state) => state.currentProjectId);\n const isLoadingProjects = useAuthStore((state) => state.isLoadingProjects);\n\n // Restored workspaces can already be present in the profile store, so the\n // first-workspace bootstrap branch is not sufficient to hydrate tenant.\n // Resolve it from the selected accessible rows, never from a placeholder,\n // URL tenant value or a workspace belonging to another organization.\n useEffect(() => {\n const workspace = workspaces.find(\n (row) =>\n row.id === activeWorkspaceId &&\n row.organizationId === activeOrganizationId,\n );\n const organization = organizations.find(\n (row) => row.id === activeOrganizationId,\n );\n if (\n !workspace ||\n !organization ||\n !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(\n workspace.tenantId,\n ) ||\n workspace.tenantId !== organization.tenantId ||\n activeTenantId === workspace.tenantId\n ) {\n return;\n }\n // Updating only tenant preserves the selected project, including an\n // explicit workspace-wide (null-project) selection.\n setActiveContext({ tenantId: workspace.tenantId });\n }, [\n activeOrganizationId,\n activeWorkspaceId,\n activeTenantId,\n organizations,\n workspaces,\n setActiveContext,\n ]);\n\n // Local error state\n const [error, setError] = useState<string | null>(null);\n\n // Bootstrap-retry signal: incremented on every TRANSIENT bootstrap failure\n // (orgs fetch, stale-context recovery, or the inner workspace bootstrap).\n // A monotonically increasing nonce — rather than the `error` string — keys\n // the retry effect, because two consecutive failures with the identical\n // message would not re-trigger a string-keyed effect and the retry chain\n // would silently stop after one attempt.\n const [bootstrapFailureNonce, setBootstrapFailureNonce] = useState(0);\n const bootstrapRetryAttemptRef = useRef(0);\n\n // Deduplication refs to prevent duplicate GraphQL calls\n const fetchOrganizationsPromiseRef = useRef<Promise<Organization[]> | null>(\n null,\n );\n const fetchWorkspacesPromisesRef = useRef<Map<string, Promise<Workspace[]>>>(\n new Map(),\n );\n\n // Stable refs for latest context values — avoids stale closures in callbacks\n // without adding them to useCallback dep arrays (which would recreate callbacks\n // on every context change and trigger spurious fetch re-runs).\n const activeWorkspaceIdRef = useRef(activeWorkspaceId);\n const activeOrganizationIdRef = useRef(activeOrganizationId);\n useEffect(() => {\n activeWorkspaceIdRef.current = activeWorkspaceId;\n activeOrganizationIdRef.current = activeOrganizationId;\n });\n\n const resolvedBaseUrls = resolveGatewayBaseUrls();\n const globalBaseUrl =\n options?.globalBaseUrl ?? resolvedBaseUrls.globalBaseUrl;\n const workspaceBaseUrl =\n options?.workspaceBaseUrl ?? resolvedBaseUrls.workspaceBaseUrl;\n\n // Refs to break feedback loops with the Header's \"store → URL\" sync effect.\n // Without these the pair can ping-pong: this effect writes (URL → store),\n // Header writes (store → URL), Zustand re-fires our subscribers, and React\n // hits \"Maximum update depth exceeded\" — especially when a downstream call\n // (workspace token issuance) returns 504 and leaves the two halves in\n // disagreement. The refs record the last value we pushed for each axis;\n // identical pushes are skipped so the loop has a hard floor.\n const lastAppliedOrgIdRef = useRef<string | null>(null);\n const lastAppliedWorkspaceIdRef = useRef<string | null>(null);\n const lastAppliedProjectIdRef = useRef<string | null>(null);\n const lastClearedTokenContextRef = useRef<string | null>(null);\n\n useEffect(() => {\n const store = useAuthStore.getState();\n\n if (\n activeOrganizationId &&\n activeOrganizationId !== store.currentOrganizationId &&\n activeOrganizationId !== lastAppliedOrgIdRef.current\n ) {\n lastAppliedOrgIdRef.current = activeOrganizationId;\n store.setCurrentOrganizationId(activeOrganizationId);\n if (\n store.workspaces.length > 0 &&\n !store.workspaces.some(\n (workspace) => workspace.organizationId === activeOrganizationId,\n )\n ) {\n store.setWorkspaces([]);\n }\n }\n\n if (\n activeWorkspaceId &&\n activeWorkspaceId !== store.currentWorkspaceId &&\n activeWorkspaceId !== lastAppliedWorkspaceIdRef.current\n ) {\n lastAppliedWorkspaceIdRef.current = activeWorkspaceId;\n store.setCurrentWorkspaceId(activeWorkspaceId);\n if (\n store.projects.length > 0 &&\n !store.projects.some(\n (project) => project.workspaceId === activeWorkspaceId,\n )\n ) {\n store.setProjects([]);\n store.setCurrentProjectId(null);\n }\n }\n\n if (\n isWorkspaceWideSelection({\n organizationId: activeOrganizationId,\n workspaceId: activeWorkspaceId,\n }) &&\n !activeProjectId &&\n store.currentProjectId\n ) {\n store.setCurrentProjectId(null);\n store.setWorkspaceToken(null);\n }\n\n if (\n activeProjectId &&\n activeProjectId !== store.currentProjectId &&\n activeProjectId !== lastAppliedProjectIdRef.current\n ) {\n lastAppliedProjectIdRef.current = activeProjectId;\n store.setCurrentProjectId(activeProjectId);\n }\n\n if (\n store.workspaceToken &&\n !isWorkspaceTokenValidForContext(store.workspaceToken, {\n workspaceId: activeWorkspaceId,\n organizationId: activeOrganizationId,\n projectId: activeProjectId,\n workspaceWide:\n !activeProjectId &&\n isWorkspaceWideSelection({\n organizationId: activeOrganizationId,\n workspaceId: activeWorkspaceId,\n }),\n })\n ) {\n // Clear-token-once-per-context guard: when the upstream gateway is\n // flaky (504s during workspace token issuance) the surrounding state\n // machine can oscillate between \"got token but invalid\" and \"clearing\n // token\". The downstream re-issue path then loops. Only clear once per\n // (org, ws, proj) tuple — a successful re-issue resets the ref via\n // setWorkspaceToken landing a new token for the same context.\n const ctxKey = `${activeOrganizationId ?? \"\"}|${activeWorkspaceId ?? \"\"}|${activeProjectId ?? \"\"}`;\n if (lastClearedTokenContextRef.current !== ctxKey) {\n lastClearedTokenContextRef.current = ctxKey;\n store.setWorkspaceToken(null);\n }\n }\n }, [activeOrganizationId, activeWorkspaceId, activeProjectId]);\n\n // ===========================================================================\n // Fetch Organizations (Global Gateway)\n // ===========================================================================\n\n const fetchOrganizations = useCallback(async (): Promise<Organization[]> => {\n // Deduplicate: if a fetch is already in progress, return the same promise\n if (fetchOrganizationsPromiseRef.current) {\n return fetchOrganizationsPromiseRef.current;\n }\n\n const store = useAuthStore.getState();\n const token = resolveAccessToken();\n\n if (!token) {\n // Not an error — user may not be authenticated yet (e.g., page load before login).\n // The useEffect in Header.tsx will re-trigger when accessToken becomes available.\n return [];\n }\n\n // NOTE: an EXPIRED token is deliberately NOT a bail-out. fe-libs\n // graphqlFetch now transparently refreshes on UNAUTHENTICATED and retries\n // the request once, and a definitive refresh failure triggers the shell's\n // forced logout (SESSION_EXPIRED_EVENT). The previous `isTokenExpired →\n // return []` short-circuit was the root cause of the persistently empty\n // context switcher: the expired token survives reloads in profile storage,\n // so every bootstrap silently produced [] — indistinguishable from \"you\n // have no organizations\" — until the user manually logged out.\n\n store.setLoadingOrganizations(true);\n setError(null);\n\n // Store the promise for deduplication before starting\n fetchOrganizationsPromiseRef.current = (async () => {\n try {\n const initialTargetOrgId =\n activeOrganizationIdRef.current ?? store.currentOrganizationId;\n // Deep links (contextDeepLink.ts): only ids that are in the URL right\n // now count as a link; restored ids fall back quietly as before.\n const requestedWorkspaceId = activeWorkspaceIdRef.current;\n const workspaceFromUrl =\n !!requestedWorkspaceId &&\n getUrlParam(\"workspace\") === requestedWorkspaceId;\n const orgFromUrl =\n !!initialTargetOrgId && getUrlParam(\"org\") === initialTargetOrgId;\n let result: GraphQLFetchResult<\n MyOrganizationsResponse & Partial<WorkspacesByOrgResponse>\n > =\n // The workspace list is read with the organizations whenever a\n // workspace is requested, because the workspace names its own\n // organization and may not be in the saved one.\n initialTargetOrgId || requestedWorkspaceId\n ? await (async () => {\n const [organizationsResult, workspacesResult] =\n await Promise.all([\n graphqlFetch<MyOrganizationsResponse>({\n gateway: \"global\",\n query: MY_ORGANIZATIONS_QUERY,\n authToken: token,\n baseUrl: globalBaseUrl,\n }),\n graphqlFetch<WorkspacesByOrgResponse>({\n gateway: \"global\",\n query: WORKSPACES_BY_ORG_QUERY,\n authToken: token,\n baseUrl: globalBaseUrl,\n }),\n ]);\n\n const data = organizationsResult.data?.myOrganizations\n ? {\n myOrganizations: organizationsResult.data.myOrganizations,\n ...(workspacesResult.data?.workspaces\n ? { workspaces: workspacesResult.data.workspaces }\n : {}),\n }\n : null;\n\n return {\n data,\n errors: [\n ...(organizationsResult.errors ?? []),\n ...(workspacesResult.errors ?? []),\n ],\n };\n })()\n : await graphqlFetch<MyOrganizationsResponse>({\n gateway: \"global\",\n query: MY_ORGANIZATIONS_QUERY,\n authToken: token,\n baseUrl: globalBaseUrl,\n });\n\n // Self-heal stale-URL case: if the workspace side of the bootstrap\n // fails because the URL points at an inaccessible org/workspace, retry\n // with the organization-only query so the operator sees their actual\n // orgs and the URL params get corrected on next render.\n if (\n initialTargetOrgId &&\n result.errors?.length &&\n result.errors.some(\n (e) =>\n e?.extensions?.code === \"FORBIDDEN\" ||\n /not a member of this organization/i.test(e?.message ?? \"\") ||\n // Public gateway often drops the underlying FORBIDDEN error\n // and replaces it with the schema-level non-null violation\n // (\"Cannot return null for non-nullable field Query.myOrganizations\").\n // That happens when ANY field in the query throws — workspaces\n // here — and data:null cascades up. Treat that pattern as a\n // signal to retry without the workspaces filter.\n /Cannot return null for non-nullable field Query\\.myOrganizations/i.test(\n e?.message ?? \"\",\n ),\n )\n ) {\n // Fetch myOrganizations + ALL workspaces (no filter) so the\n // downstream auto-pick logic still has a workspace list to seed\n // context from. If we only refetched myOrganizations, the page\n // would render but every workspace-scoped query would fail with\n // \"Select a workspace…\".\n result = await graphqlFetch<\n MyOrganizationsResponse & Partial<WorkspacesByOrgResponse>\n >({\n gateway: \"global\",\n query: `\n query ContextSwitcherRecover {\n myOrganizations {\n total\n items { id name slug tenantId description logo website status type createdAt updatedAt }\n }\n workspaces: myWorkspaces {\n total\n items { id name slug tenantId organizationId type status region createdAt updatedAt }\n }\n }\n `,\n authToken: token,\n baseUrl: globalBaseUrl,\n });\n }\n\n if (result.errors?.length) {\n const errorMessage = result.errors[0]?.message ?? \"GraphQL error\";\n if (isAuthGraphQLError(result.errors)) {\n // Auth errors are expected during token refresh cycles — throw AuthError\n // so the outer catch can suppress console.error.\n throw new AuthError(errorMessage);\n }\n if (store.workspaces.length === 0) {\n console.error(\"Failed to fetch organizations:\", result.errors);\n }\n throw new Error(errorMessage);\n }\n\n let orgs: Organization[] = result.data?.myOrganizations?.items ?? [];\n\n // Stale-context recovery: bootstrap query was filtered by\n // initialTargetOrgId, so when the URL/persisted org doesn't belong to\n // this user the response is empty. Re-fetch the unfiltered list of\n // *all* orgs the user can access so the guard below can pick a real\n // default. Skip the recovery when no target was set (already\n // unfiltered) or when workspaces are already in the store (the\n // existing fallback path covers that case).\n if (\n initialTargetOrgId &&\n orgs.length === 0 &&\n store.workspaces.length === 0\n ) {\n const recovery = await graphqlFetch<MyOrganizationsResponse>({\n gateway: \"global\",\n query: MY_ORGANIZATIONS_QUERY,\n authToken: token,\n baseUrl: globalBaseUrl,\n });\n if (!recovery.errors?.length) {\n orgs = recovery.data?.myOrganizations?.items ?? [];\n // discard the filtered workspaces payload — it was for the\n // ghost org and would only mislead the workspace selector below.\n result = {\n ...recovery,\n data: {\n myOrganizations: recovery.data?.myOrganizations ?? {\n items: [],\n total: 0,\n },\n },\n };\n } else {\n // The filtered bootstrap returned nothing AND the unfiltered\n // recovery failed — we genuinely do not know the user's org list.\n // Treat it as the failure it is (retryable via the bootstrap-retry\n // effect) instead of falling through to setOrganizations([]),\n // which presented a transient backend error as \"you have no\n // organizations\" until re-login.\n console.warn(\n \"[ContextSwitcher] Stale-context recovery failed:\",\n recovery.errors,\n );\n const recoveryMessage =\n recovery.errors?.[0]?.message ?? \"Failed to fetch organizations\";\n if (isAuthGraphQLError(recovery.errors ?? [])) {\n throw new AuthError(recoveryMessage);\n }\n throw new Error(recoveryMessage);\n }\n }\n\n const fallbackOrganizations =\n orgs.length === 0 && store.workspaces.length > 0\n ? buildFallbackOrganizations(store.workspaces)\n : [];\n const effectiveOrganizations =\n fallbackOrganizations.length > 0 ? fallbackOrganizations : orgs;\n\n store.setOrganizations(effectiveOrganizations);\n\n // Determine which organization to use for workspace fetching\n let targetOrgId = initialTargetOrgId;\n\n // The caller's workspaces across organizations, when this bootstrap\n // read them. A deep-linked workspace beyond the first page is looked\n // up in the remaining pages before anything is decided about it.\n let listedWorkspaces: WorkspacesByOrgResponse[\"workspaces\"] | null =\n result.data?.workspaces ?? null;\n if (\n workspaceFromUrl &&\n listedWorkspaces &&\n !listedWorkspaces.items.some((w) => w.id === requestedWorkspaceId) &&\n !isCompleteListing(listedWorkspaces)\n ) {\n listedWorkspaces = await readRemainingWorkspacePages(\n listedWorkspaces,\n token,\n globalBaseUrl,\n );\n }\n\n // A deep-linked workspace in another accessible organization switches\n // the organization to it, instead of being replaced by the saved\n // organization's first workspace (vc-fg-parity round 3). One the\n // caller cannot open is recorded so the shell can say so.\n const workspaceLink = decideWorkspaceDeepLink({\n requestedWorkspaceId,\n fromUrl: workspaceFromUrl,\n targetOrgId,\n organizations: orgs,\n workspaces: listedWorkspaces?.items ?? null,\n workspacesComplete: isCompleteListing(listedWorkspaces),\n });\n if (workspaceLink.kind === \"switch\") {\n const linked = workspaceLink.workspace;\n targetOrgId = linked.organizationId;\n setActiveContext({\n organizationId: linked.organizationId,\n workspaceId: linked.id,\n tenantId: linked.tenantId || null,\n projectId: getUrlParam(\"project\"),\n });\n store.setWorkspaces([]);\n store.setProjects([]);\n store.setCurrentProjectId(null);\n store.setWorkspaceToken(null);\n store.setCurrentWorkspaceId(linked.id);\n } else {\n const denial =\n workspaceLink.kind === \"denied\"\n ? workspaceLink.denial\n : decideOrganizationDeepLink({\n requestedOrgId: initialTargetOrgId,\n fromUrl: orgFromUrl,\n organizations: orgs,\n });\n if (denial) store.setContextLinkDenial(denial);\n }\n\n // Stale-context guard: if the persisted/URL org isn't in the user's\n // accessible orgs, fall back to the first available one and clear the\n // stale workspace/project so they get re-derived. Without this, URL\n // params like ?org=<ghost-id> from a prior session leak into the new\n // user's request headers and cause \"Authentication required\" /\n // \"not a member\" errors at every subgraph.\n //\n // Check against `orgs` (freshly returned from the API in this same\n // closure) rather than `effectiveOrganizations`, which can fall back\n // to ids derived from `store.workspaces` — that fallback path could\n // contain stale ghost orgIds and mask the guard.\n const targetOrgIsAccessible =\n targetOrgId && orgs.some((org) => org.id === targetOrgId);\n if (targetOrgId && !targetOrgIsAccessible && orgs.length > 0) {\n targetOrgId = orgs[0].id;\n setActiveContext({\n organizationId: targetOrgId,\n workspaceId: null,\n tenantId: null,\n projectId: null,\n });\n store.setWorkspaces([]);\n store.setProjects([]);\n store.setCurrentWorkspaceId(null);\n store.setCurrentProjectId(null);\n store.setWorkspaceToken(null);\n }\n\n if (targetOrgId && targetOrgId !== store.currentOrganizationId) {\n store.setCurrentOrganizationId(targetOrgId);\n }\n\n // Auto-select first organization if none is selected\n if (effectiveOrganizations.length > 0 && !targetOrgId) {\n store.setCurrentOrganizationId(effectiveOrganizations[0].id);\n targetOrgId = effectiveOrganizations[0].id;\n }\n\n // Fetch workspaces for the selected/auto-selected org if:\n // 1. We have a target org (either auto-selected or persisted from localStorage)\n // 2. AND workspaces array is empty (not persisted, or cleared)\n // This handles both initial login AND page refresh scenarios.\n // Read from useAuthStore.getState() rather than the captured `store`\n // snapshot so we see the post-guard cleared value when the org guard\n // above fired (the local `store.workspaces` ref is stale after\n // setWorkspaces([])).\n if (targetOrgId && useAuthStore.getState().workspaces.length === 0) {\n store.setLoadingWorkspaces(true);\n try {\n // myWorkspaces returns ALL workspaces the user is a member of\n // across every org. Filter to the target org client-side here.\n // The list read above covers every organization, so it serves the\n // target organization even when the guard or a deep link changed it.\n const bootstrappedWorkspaces = listedWorkspaces\n ? listedWorkspaces.items.filter(\n (w) => w.organizationId === targetOrgId,\n )\n : undefined;\n const ws = bootstrappedWorkspaces\n ? (bootstrappedWorkspaces as Workspace[])\n : await graphqlFetch<WorkspacesByOrgResponse>({\n gateway: \"global\",\n query: WORKSPACES_BY_ORG_QUERY,\n authToken: token,\n baseUrl: globalBaseUrl,\n }).then((wsResult) =>\n wsResult.errors?.length\n ? null\n : (wsResult.data?.workspaces?.items ?? []).filter(\n (w) => w.organizationId === targetOrgId,\n ),\n );\n\n if (!ws) {\n // Workspace bootstrap failed (errored result) while orgs\n // succeeded — retryable, otherwise the org renders with no\n // workspaces until manual interaction.\n setBootstrapFailureNonce((n) => n + 1);\n }\n if (ws) {\n store.setWorkspaces(ws);\n const persistedWorkspace = activeWorkspaceIdRef.current\n ? ws.find(\n (workspace) =>\n workspace.id === activeWorkspaceIdRef.current,\n )\n : null;\n\n if (persistedWorkspace) {\n store.setCurrentWorkspaceId(persistedWorkspace.id);\n } else if (ws.length > 0) {\n const nextActiveContext = {\n organizationId: targetOrgId,\n workspaceId: ws[0].id,\n tenantId: ws[0].tenantId,\n projectId: null,\n };\n\n if (activeWorkspaceIdRef.current) {\n // Stale-context guard: URL/persisted workspace ID is not in\n // the user's accessible workspaces for the active org. Fall\n // back to the first workspace and clear the stale URL param\n // so subsequent requests don't carry the ghost ID.\n store.setCurrentWorkspaceId(ws[0].id);\n store.setWorkspaceToken(null);\n setActiveContext(nextActiveContext);\n } else if (!store.currentWorkspaceId) {\n // Auto-select first workspace only if none is currently selected\n // (preserves selection from completeAuthFlow or persistence if applicable)\n store.setCurrentWorkspaceId(ws[0].id);\n setActiveContext(nextActiveContext);\n }\n }\n }\n } catch {\n // Non-critical for THIS call (user can still select a workspace\n // manually) but worth a bounded background retry.\n setBootstrapFailureNonce((n) => n + 1);\n } finally {\n store.setLoadingWorkspaces(false);\n }\n }\n\n // Full bootstrap succeeded — re-arm the retry budget for the next\n // genuine failure.\n bootstrapRetryAttemptRef.current = 0;\n return effectiveOrganizations;\n } catch (err) {\n // Auth errors are expected during token refresh / page load cycles.\n // Suppress from console.error — the useEffect will re-trigger when the\n // auth provider refreshes the token. (A DEFINITIVELY dead session\n // never reaches here as an AuthError loop: graphqlFetch dispatches\n // SESSION_EXPIRED_EVENT and the shell force-logs-out.)\n if (err instanceof AuthError) {\n return [];\n }\n const message =\n err instanceof Error ? err.message : \"Failed to fetch organizations\";\n if (store.workspaces.length === 0) {\n console.error(\"Failed to fetch organizations:\", err);\n }\n setError(message);\n setBootstrapFailureNonce((n) => n + 1);\n\n if (store.workspaces.length > 0) {\n const fallbackOrganizations = buildFallbackOrganizations(\n store.workspaces,\n );\n if (fallbackOrganizations.length > 0) {\n store.setOrganizations(fallbackOrganizations);\n if (!store.currentOrganizationId) {\n store.setCurrentOrganizationId(fallbackOrganizations[0].id);\n }\n return fallbackOrganizations;\n }\n }\n\n return [];\n } finally {\n store.setLoadingOrganizations(false);\n fetchOrganizationsPromiseRef.current = null;\n }\n })();\n\n return fetchOrganizationsPromiseRef.current;\n }, [globalBaseUrl, setActiveContext]);\n\n // ===========================================================================\n // Bootstrap retry (transient-failure self-heal)\n // ===========================================================================\n //\n // A transient backend failure during bootstrap (cold service, gateway blip,\n // Valkey/pg hiccup) used to leave the switcher empty for the whole session —\n // the shell's Header effect only re-fires on accessToken change, so nothing\n // ever retried. Retry with exponential backoff, bounded so a genuinely down\n // backend does not hammer: 1.5s, 3s, 6s, 12s, 12s (max 5 attempts, re-armed\n // by any subsequent successful bootstrap).\n useEffect(() => {\n if (disableBootstrap) return undefined;\n if (bootstrapFailureNonce === 0) return undefined;\n if (bootstrapRetryAttemptRef.current >= 5) return undefined;\n if (!resolveAccessToken()) return undefined;\n bootstrapRetryAttemptRef.current += 1;\n const delayMs = Math.min(\n 1500 * 2 ** (bootstrapRetryAttemptRef.current - 1),\n 12000,\n );\n const timer = window.setTimeout(() => {\n void fetchOrganizations();\n }, delayMs);\n return () => {\n window.clearTimeout(timer);\n };\n }, [disableBootstrap, bootstrapFailureNonce, fetchOrganizations]);\n\n // Connectivity recovery: if the browser reports we are back online and the\n // switcher is still empty, re-run the bootstrap immediately with a fresh\n // retry budget.\n useEffect(() => {\n if (disableBootstrap) return undefined;\n const onOnline = () => {\n if (\n useAuthStore.getState().organizations.length === 0 &&\n resolveAccessToken()\n ) {\n bootstrapRetryAttemptRef.current = 0;\n void fetchOrganizations();\n }\n };\n window.addEventListener(\"online\", onOnline);\n return () => {\n window.removeEventListener(\"online\", onOnline);\n };\n }, [disableBootstrap, fetchOrganizations]);\n\n // ===========================================================================\n // Fetch Workspaces for Organization (Global Gateway)\n // ===========================================================================\n\n const fetchWorkspacesForOrg = useCallback(\n async (organizationId: string): Promise<Workspace[]> => {\n const store = useAuthStore.getState();\n const token = resolveAccessToken();\n const profileId = resolveActiveProfileId();\n const userId = store.user?.id;\n // Account-scoped in-memory deduplication; this key is never persisted or logged.\n const requestKey = JSON.stringify([\n profileId,\n userId,\n token,\n organizationId,\n ]);\n const existingPromise =\n fetchWorkspacesPromisesRef.current.get(requestKey);\n if (existingPromise) return existingPromise;\n const currentSelection = () => {\n const current = useAuthStore.getState();\n return (\n resolveActiveProfileId() === profileId &&\n current.user?.id === userId &&\n resolveAccessToken() === token &&\n current.currentOrganizationId === organizationId\n );\n };\n\n // Only bail when there is NO token at all. An expired one is handled by\n // graphqlFetch's refresh-and-retry (or ends in the shell's forced\n // logout) — silently returning [] here masked expiry as an empty list.\n if (!token) {\n return [];\n }\n\n store.setLoadingWorkspaces(true);\n setError(null);\n\n // Store the promise for deduplication before starting\n const fetchPromise = (async () => {\n try {\n const result = await graphqlFetch<WorkspacesByOrgResponse>({\n gateway: \"global\",\n query: WORKSPACES_BY_ORG_QUERY,\n authToken: token,\n baseUrl: globalBaseUrl,\n });\n if (!currentSelection()) return [];\n // myWorkspaces returns workspaces across all the user's orgs;\n // filter to the requested org before handing to downstream.\n if (result.data?.workspaces?.items) {\n result.data.workspaces.items = result.data.workspaces.items.filter(\n (w) => w.organizationId === organizationId,\n );\n }\n\n if (result.errors?.length) {\n const errorMessage = result.errors[0]?.message ?? \"GraphQL error\";\n if (isAuthGraphQLError(result.errors)) {\n throw new AuthError(errorMessage);\n }\n console.error(\"Failed to fetch workspaces:\", result.errors);\n throw new Error(errorMessage);\n }\n\n // `myWorkspaces` returns every workspace the caller can see across\n // all of their orgs/tenants. The store key is per-org (selecting\n // org X then opening the dropdown should only show X's workspaces),\n // so we filter down to the requested org here. The dropdown filter\n // in ContextSwitcher.tsx is a defence-in-depth — without this\n // narrowing the store would briefly hold the caller's other-org\n // workspaces and the auto-pick logic (lines below) might select\n // one of them as the default.\n const allWs: Workspace[] = result.data?.workspaces?.items ?? [];\n const ws = allWs.filter((w) => w.organizationId === organizationId);\n store.setWorkspaces(ws);\n return ws;\n } catch (err) {\n if (!currentSelection() || err instanceof AuthError) {\n return [];\n }\n const message =\n err instanceof Error ? err.message : \"Failed to fetch workspaces\";\n console.error(\"Failed to fetch workspaces:\", err);\n setError(message);\n return [];\n } finally {\n if (currentSelection()) store.setLoadingWorkspaces(false);\n fetchWorkspacesPromisesRef.current.delete(requestKey);\n }\n })();\n\n fetchWorkspacesPromisesRef.current.set(requestKey, fetchPromise);\n return fetchPromise;\n },\n [globalBaseUrl],\n );\n\n // ===========================================================================\n // Issue Workspace Token (Workspace Gateway - wspace-auth-svc)\n // ===========================================================================\n\n const issueWorkspaceToken = useCallback(\n async (\n organizationId: string,\n workspaceId?: string,\n projectId?: string | null,\n // Target workspace's tenant. Sent as x-tenant-id so the token service can\n // resolve the tenant for a super_admin switching into a workspace not\n // mirrored into the wspace layer (whose access token carries no tenant\n // claim). Regular members resolve their tenant via membership regardless.\n tenantId?: string,\n ): Promise<{\n success: boolean;\n token?: string;\n resolvedWorkspaceId?: string;\n error?: string;\n }> => {\n const store = useAuthStore.getState();\n const originalScope = [\n store.currentOrganizationId,\n store.currentWorkspaceId,\n store.currentProjectId,\n ];\n const workspaceWide = isWorkspaceWideSelection({\n organizationId,\n workspaceId: workspaceId ?? null,\n });\n const authToken = resolveAccessToken();\n const profileId = resolveActiveProfileId();\n const userId = store.user?.id;\n\n // Expired tokens flow through: graphqlFetch refreshes and retries once.\n if (!authToken) {\n return { success: false, error: \"No valid access token available\" };\n }\n\n setError(null);\n\n try {\n const result = await graphqlFetch<{\n issueWorkspaceToken: IssueWorkspaceTokenResult;\n }>({\n gateway: \"workspace\",\n query: ISSUE_WORKSPACE_TOKEN_MUTATION,\n variables: {\n input: {\n organizationId,\n ...(workspaceId && { workspaceId }),\n ...(projectId && { projectId }),\n },\n },\n authToken,\n baseUrl: workspaceBaseUrl,\n tenantId,\n });\n\n if (result.errors?.length) {\n const errorMessage = result.errors[0]?.message ?? \"GraphQL error\";\n if (!isAuthGraphQLError(result.errors)) {\n console.error(\"Failed to issue workspace token:\", result.errors);\n }\n return { success: false, error: errorMessage };\n }\n\n const tokenResult = result.data?.issueWorkspaceToken;\n\n if (tokenResult?.success && tokenResult.token) {\n const latest = useAuthStore.getState();\n if (\n resolveActiveProfileId() !== profileId ||\n useAuthStore.getState().user?.id !== userId ||\n resolveAccessToken() !== authToken ||\n originalScope.some(\n (value, index) =>\n value !==\n [\n latest.currentOrganizationId,\n latest.currentWorkspaceId,\n latest.currentProjectId,\n ][index],\n ) ||\n isWorkspaceWideSelection({\n organizationId,\n workspaceId: workspaceId ?? null,\n }) !== workspaceWide ||\n !isWorkspaceTokenValidForContext(tokenResult.token, {\n organizationId,\n workspaceId,\n projectId,\n workspaceWide,\n })\n ) {\n return {\n success: false,\n error: \"Workspace context changed during token issuance\",\n };\n }\n const resolvedWsId = tokenResult.workspaceId || workspaceId;\n if (resolvedWsId) {\n store.setCurrentWorkspaceId(resolvedWsId);\n }\n store.setWorkspaceToken(tokenResult.token);\n return {\n success: true,\n token: tokenResult.token,\n resolvedWorkspaceId: resolvedWsId || undefined,\n };\n }\n\n return {\n success: false,\n error:\n tokenResult?.error?.message ?? \"Failed to issue workspace token\",\n };\n } catch (err) {\n const message =\n err instanceof Error\n ? err.message\n : \"Failed to issue workspace token\";\n console.error(\"Failed to issue workspace token:\", err);\n setError(message);\n return { success: false, error: message };\n }\n },\n [workspaceBaseUrl],\n );\n\n // ===========================================================================\n // Fetch Projects (Workspace Gateway - requires workspace token)\n // ===========================================================================\n\n const fetchProjects = useCallback(async (): Promise<Project[]> => {\n const store = useAuthStore.getState();\n const authToken = resolveAccessToken();\n const wsToken = store.workspaceToken;\n const workspaceId = store.currentWorkspaceId;\n const profileId = resolveActiveProfileId();\n const userId = store.user?.id;\n const organizationId = store.currentOrganizationId;\n const projectId = store.currentProjectId;\n const wide = isWorkspaceWideSelection({ organizationId, workspaceId });\n const currentSelection = () => {\n const current = useAuthStore.getState();\n return (\n resolveActiveProfileId() === profileId &&\n current.user?.id === userId &&\n resolveAccessToken() === authToken &&\n current.workspaceToken === wsToken &&\n current.currentOrganizationId === organizationId &&\n current.currentWorkspaceId === workspaceId &&\n current.currentProjectId === projectId &&\n isWorkspaceWideSelection({ organizationId, workspaceId }) === wide\n );\n };\n\n // Expired tokens flow through: graphqlFetch refreshes and retries once.\n if (!authToken) {\n return [];\n }\n\n if (!wsToken) {\n return [];\n }\n\n if (!workspaceId) {\n return [];\n }\n\n store.setLoadingProjects(true);\n setError(null);\n\n try {\n const result = await graphqlFetch<ProjectsResponse>({\n gateway: \"workspace\",\n query: PROJECTS_QUERY,\n authToken,\n workspaceToken: wsToken,\n baseUrl: workspaceBaseUrl,\n });\n\n if (!currentSelection()) return [];\n\n if (result.errors?.length) {\n const errorMessage = result.errors[0]?.message ?? \"GraphQL error\";\n if (isAuthGraphQLError(result.errors)) {\n throw new AuthError(errorMessage);\n }\n console.error(\"Failed to fetch projects:\", result.errors);\n throw new Error(errorMessage);\n }\n\n const projs: Project[] = result.data?.projects?.items ?? [];\n store.setProjects(projs);\n return projs;\n } catch (err) {\n if (err instanceof AuthError) {\n return [];\n }\n const message =\n err instanceof Error ? err.message : \"Failed to fetch projects\";\n console.error(\"Failed to fetch projects:\", err);\n setError(message);\n return [];\n } finally {\n store.setLoadingProjects(false);\n }\n }, [workspaceBaseUrl]);\n\n // ===========================================================================\n // High-Level Selection Actions\n // ===========================================================================\n\n const selectOrganization = useCallback(\n async (org: Organization): Promise<Workspace[]> => {\n const store = useAuthStore.getState();\n\n // A deliberate switch answers any \"link not available\" notice.\n store.setContextLinkDenial(null);\n store.setCurrentWorkspaceId(null);\n store.setWorkspaceToken(null);\n store.setProjects([]);\n store.setCurrentProjectId(null);\n store.setCurrentOrganizationId(org.id);\n\n const ws = await fetchWorkspacesForOrg(org.id);\n return ws;\n },\n [fetchWorkspacesForOrg],\n );\n\n const selectWorkspace = useCallback(\n async (\n workspace: Workspace,\n ): Promise<{\n success: boolean;\n projects?: Project[];\n error?: string;\n }> => {\n const store = useAuthStore.getState();\n\n // A deliberate switch answers any \"link not available\" notice.\n store.setContextLinkDenial(null);\n store.setCurrentProjectId(null);\n store.setProjects([]);\n\n if (!workspace.organizationId) {\n console.error(\"Workspace missing organizationId:\", workspace);\n return {\n success: false,\n error: \"Workspace is missing organizationId\",\n };\n }\n\n const tokenResult = await issueWorkspaceToken(\n workspace.organizationId,\n workspace.id,\n undefined,\n workspace.tenantId,\n );\n\n if (!tokenResult.success) {\n return { success: false, error: tokenResult.error };\n }\n\n const selected = useAuthStore.getState();\n const profileId = resolveActiveProfileId();\n const userId = selected.user?.id;\n const accessToken = resolveAccessToken();\n const workspaceToken = selected.workspaceToken;\n const projectId = selected.currentProjectId;\n const wide = isWorkspaceWideSelection({\n organizationId: workspace.organizationId,\n workspaceId: workspace.id,\n });\n const currentSelection = () => {\n const current = useAuthStore.getState();\n return (\n resolveActiveProfileId() === profileId &&\n current.user?.id === userId &&\n resolveAccessToken() === accessToken &&\n current.workspaceToken === workspaceToken &&\n current.currentOrganizationId === workspace.organizationId &&\n current.currentWorkspaceId === workspace.id &&\n current.currentProjectId === projectId &&\n isWorkspaceWideSelection({\n organizationId: workspace.organizationId,\n workspaceId: workspace.id,\n }) === wide\n );\n };\n const projs = await fetchProjects();\n if (!currentSelection())\n return { success: false, error: \"Context changed during selection\" };\n\n if (\n projs.length > 0 &&\n !isWorkspaceWideSelection({\n organizationId: workspace.organizationId,\n workspaceId: workspace.id,\n })\n ) {\n store.setCurrentProjectId(projs[0]!.id);\n }\n\n return { success: true, projects: projs };\n },\n [issueWorkspaceToken, fetchProjects],\n );\n\n const selectProject = useCallback((project: Project): void => {\n const store = useAuthStore.getState();\n clearWorkspaceWideSelection({\n organizationId: store.currentOrganizationId,\n workspaceId: store.currentWorkspaceId,\n });\n store.setCurrentProjectId(project.id);\n if (\n store.workspaceToken &&\n !isWorkspaceTokenValidForContext(store.workspaceToken, {\n workspaceId: store.currentWorkspaceId,\n organizationId: store.currentOrganizationId,\n projectId: project.id,\n })\n ) {\n store.setWorkspaceToken(null);\n }\n }, []);\n\n const selectWorkspaceWide = useCallback((): void => {\n const store = useAuthStore.getState();\n const scope = {\n organizationId: activeOrganizationIdRef.current,\n workspaceId: activeWorkspaceIdRef.current,\n };\n if (\n !scope.organizationId ||\n !scope.workspaceId ||\n store.currentOrganizationId !== scope.organizationId ||\n store.currentWorkspaceId !== scope.workspaceId\n ) {\n throw new Error(\"Current workspace context required\");\n }\n if (!persistWorkspaceWideSelection(scope))\n throw new Error(\"Workspace-wide preference could not be saved\");\n store.setCurrentProjectId(null);\n store.setWorkspaceToken(null);\n setActiveContext({ projectId: null });\n }, [setActiveContext]);\n\n // ===========================================================================\n // Cross-MFE refresh: keep the switcher lists current when another MFE mutates\n // org/workspace/project entities. microfe-workspaces emits these domain events\n // on the shared event bus (e.g. on project rename); without this the switcher\n // keeps showing the stale cached name until a full page reload.\n // ===========================================================================\n\n useEffect(() => {\n let cancelled = false;\n\n // Coalesce a refetch into a single in-flight run with one trailing re-run,\n // so a burst of events collapses to one request (+ one trailing) instead of\n // fanning out or being swallowed by a downstream per-key dedupe. The flag is\n // cleared on cleanup so nothing fires after the subscription is torn down.\n const makeCoalescedRefetch = (run: () => Promise<unknown>) => {\n let running = false;\n let queued = false;\n const trigger = () => {\n if (cancelled) return;\n if (running) {\n queued = true;\n return;\n }\n running = true;\n void run().finally(() => {\n running = false;\n if (!cancelled && queued) {\n queued = false;\n trigger();\n }\n });\n };\n return trigger;\n };\n\n const refreshProjects = makeCoalescedRefetch(() => fetchProjects());\n const refreshWorkspaces = makeCoalescedRefetch(() => {\n const orgId = useAuthStore.getState().currentOrganizationId;\n return orgId ? fetchWorkspacesForOrg(orgId) : Promise.resolve();\n });\n\n // Custom domain events (not in BurdenoffEventName) flow through `onAny`.\n const unsubscribe = eventBus.onAny((event) => {\n // Custom event names aren't in the BurdenoffEventName union; compare as string.\n const eventName: string = event.name;\n\n if (PROJECT_REFRESH_EVENTS.has(eventName)) {\n if (disableProjectSync || skipProjectFetch) return;\n const eventWorkspaceId = readEventWorkspaceId(event.payload);\n const { currentWorkspaceId } = useAuthStore.getState();\n // Only refetch when the event targets the workspace currently in\n // context (events without a workspace id are treated as relevant).\n if (\n eventWorkspaceId &&\n currentWorkspaceId &&\n eventWorkspaceId !== currentWorkspaceId\n ) {\n return;\n }\n // Refetch only — a deleted project simply drops out of the list, and\n // `currentProject` resolves to undefined for it. Clearing the selection\n // here would race ActiveContext / the project sync effect (the real\n // source of truth), so we leave selection reconciliation to them.\n refreshProjects();\n return;\n }\n\n if (WORKSPACE_REFRESH_EVENTS.has(eventName)) {\n if (disableWorkspaceSync) return;\n refreshWorkspaces();\n }\n });\n\n return () => {\n cancelled = true;\n unsubscribe();\n };\n }, [\n eventBus,\n fetchProjects,\n fetchWorkspacesForOrg,\n disableWorkspaceSync,\n disableProjectSync,\n skipProjectFetch,\n ]);\n\n // ===========================================================================\n // Get Current Items\n // ===========================================================================\n\n const currentOrganization = organizations.find(\n (org) => org.id === currentOrganizationId,\n );\n const currentWorkspace = workspaces.find(\n (ws) => ws.id === currentWorkspaceId,\n );\n const currentProject = projects.find((proj) => proj.id === currentProjectId);\n\n // ===========================================================================\n // Return Hook API\n // ===========================================================================\n\n return {\n organizations,\n workspaces,\n projects,\n\n currentOrganizationId,\n currentWorkspaceId,\n currentProjectId,\n\n currentOrganization,\n currentWorkspace,\n currentProject,\n\n workspaceToken,\n\n isLoadingOrganizations,\n isLoadingWorkspaces,\n isLoadingProjects,\n isLoading:\n isLoadingOrganizations || isLoadingWorkspaces || isLoadingProjects,\n\n error,\n\n fetchOrganizations,\n fetchWorkspacesForOrg,\n issueWorkspaceToken,\n fetchProjects,\n\n selectOrganization,\n selectWorkspace,\n selectProject,\n selectWorkspaceWide,\n };\n}\n\n/**\n * Hook to reactively ensure workspaces are synced with the current organization.\n *\n * This handles edge cases where the organization changes but workspaces\n * from a different org are still in the store (e.g., stale data, race conditions).\n *\n * Usage:\n * ```tsx\n * import { useWorkspaceSyncEffect } from '@burdenoff/microfe-auth';\n *\n * function MyComponent() {\n * useWorkspaceSyncEffect(); // Ensures workspaces stay in sync\n * // ...\n * }\n * ```\n */\nexport function useWorkspaceSyncEffect(\n options?: UseContextSwitcherDataOptions,\n) {\n const currentOrganizationId = useAuthStore(\n (state) => state.currentOrganizationId,\n );\n const workspaces = useAuthStore((state) => state.workspaces);\n const accessToken = useAuthStore((state) => state.accessToken);\n const isLoadingWorkspaces = useAuthStore(\n (state) => state.isLoadingWorkspaces,\n );\n const resolvedBaseUrls = resolveGatewayBaseUrls();\n const globalBaseUrl =\n options?.globalBaseUrl ?? resolvedBaseUrls.globalBaseUrl;\n const disableWorkspaceSync = options?.disableWorkspaceSync ?? false;\n\n useEffect(() => {\n if (disableWorkspaceSync) return;\n // Skip if no org selected, no token, or already loading\n if (!currentOrganizationId || !accessToken || isLoadingWorkspaces) return;\n\n // Check if any workspace matches the current org\n const hasMatchingWorkspaces = workspaces.some(\n (ws) => ws.organizationId === currentOrganizationId,\n );\n\n // If workspaces exist but none match current org, we need to refetch\n // This can happen in edge cases with stale data or race conditions\n if (workspaces.length > 0 && !hasMatchingWorkspaces) {\n const store = useAuthStore.getState();\n store.setLoadingWorkspaces(true);\n\n // Inline fetch to avoid circular dependency with useContextSwitcherData\n graphqlFetch<WorkspacesByOrgResponse>({\n gateway: \"global\",\n query: WORKSPACES_BY_ORG_QUERY,\n authToken: accessToken,\n baseUrl: globalBaseUrl,\n })\n .then((result) => {\n // myWorkspaces returns ALL my workspaces; filter to current org\n // client-side (the old server-side filter no longer exists).\n if (result.data?.workspaces?.items) {\n result.data.workspaces.items = result.data.workspaces.items.filter(\n (w) => w.organizationId === currentOrganizationId,\n );\n }\n if (!result.errors?.length) {\n const allWs: Workspace[] = result.data?.workspaces?.items ?? [];\n // Same per-org narrowing as fetchWorkspacesForOrg — see the\n // comment there for why we don't just dump the full caller-\n // visible list into the store.\n const ws = allWs.filter(\n (w) => w.organizationId === currentOrganizationId,\n );\n store.setWorkspaces(ws);\n }\n })\n .catch(() => {\n // Silent fail - user can manually refresh or select org again\n })\n .finally(() => {\n store.setLoadingWorkspaces(false);\n });\n }\n }, [\n currentOrganizationId,\n workspaces,\n accessToken,\n isLoadingWorkspaces,\n globalBaseUrl,\n disableWorkspaceSync,\n ]);\n}\n\n/**\n * Hook to reactively ensure projects are loaded when a workspace is selected.\n *\n * This handles the case where a workspace is auto-selected (from URL/localStorage)\n * but projects haven't been fetched yet. It will:\n * 1. Issue a workspace token if not present\n * 2. Fetch projects for the selected workspace\n *\n * Usage:\n * ```tsx\n * import { useProjectSyncEffect } from '@burdenoff/microfe-auth';\n *\n * function MyComponent() {\n * useProjectSyncEffect(); // Ensures projects are loaded for selected workspace\n * // ...\n * }\n * ```\n */\nexport function useProjectSyncEffect(options?: UseContextSwitcherDataOptions) {\n const currentWorkspaceId = useAuthStore((state) => state.currentWorkspaceId);\n const currentOrganizationId = useAuthStore(\n (state) => state.currentOrganizationId,\n );\n const workspaces = useAuthStore((state) => state.workspaces);\n const projects = useAuthStore((state) => state.projects);\n const currentProjectId = useAuthStore((state) => state.currentProjectId);\n const workspaceToken = useAuthStore((state) => state.workspaceToken);\n const accessToken = useAuthStore((state) => state.accessToken);\n const { setContext: setActiveContext } = useActiveContext();\n const resolvedBaseUrls = resolveGatewayBaseUrls();\n const workspaceBaseUrl =\n options?.workspaceBaseUrl ?? resolvedBaseUrls.workspaceBaseUrl;\n const disableProjectSync = options?.disableProjectSync ?? false;\n const skipProjectFetch = options?.skipProjectFetch ?? false;\n\n // Use refs to prevent the infinite loop caused by including loading/failure\n // state in the dependency array. Without these, the cycle is:\n // setLoadingProjects(true) -> dep change -> effect re-runs (guarded) ->\n // async completes -> setLoadingProjects(false) -> dep change ->\n // effect re-runs -> starts again -> INFINITE LOOP\n const syncInProgressRef = useRef(false);\n const [syncRevision, setSyncRevision] = useState(0);\n const emptyProjectsResultRef = useRef<{\n scopeKey: string;\n projects: Project[];\n } | null>(null);\n // Pending retry timer per workspace, so transient failures (e.g. RBAC lag\n // right after workspace creation) get an automatic second chance even if no\n // dependency change re-triggers the effect.\n const retryTimerRef = useRef<Map<string, ReturnType<typeof setTimeout>>>(\n new Map(),\n );\n // Per-workspace failure tracker — caps retry attempts when project bootstrap\n // (token issue or list) fails. An empty authorized project list is a valid\n // workspace-only context, not a provisioning failure.\n //\n // We track both count AND lastFailureAt so we can honour a \"cool-down\" window:\n // after PROJECT_SYNC_FAILURE_COOLDOWN_MS has elapsed since the last failure,\n // the counter is treated as cleared so transient backend hiccups (e.g. RBAC\n // role propagation lag right after signup) don't permanently lock a workspace\n // out of the context dropdown — the original cause of marqueue §729.\n const projectSyncFailuresRef = useRef<\n Map<string, { count: number; lastFailureAt: number }>\n >(new Map());\n const PROJECT_SYNC_MAX_FAILURES = 8;\n const PROJECT_SYNC_FAILURE_COOLDOWN_MS = 30_000;\n useEffect(() => {\n if (disableProjectSync) return;\n // Skip if no workspace selected or no access token\n if (!currentWorkspaceId || !accessToken) return;\n\n // Skip if a sync is already in progress (ref-based guard avoids dep loop)\n if (syncInProgressRef.current) return;\n\n // Stop retrying once this workspace has failed too many times in a row.\n // Counter is reset on success, on workspace switch (different key), by\n // an explicit user retry path (e.g. selectWorkspace), or after the\n // cool-down window has elapsed since the last failure (so transient\n // backend issues don't permanently wedge the dropdown).\n const failureEntry = projectSyncFailuresRef.current.get(currentWorkspaceId);\n if (\n failureEntry &&\n failureEntry.count >= PROJECT_SYNC_MAX_FAILURES &&\n Date.now() - failureEntry.lastFailureAt < PROJECT_SYNC_FAILURE_COOLDOWN_MS\n ) {\n return;\n }\n if (\n failureEntry &&\n Date.now() - failureEntry.lastFailureAt >=\n PROJECT_SYNC_FAILURE_COOLDOWN_MS\n ) {\n // Cool-down elapsed — clear the counter so we get a fresh budget.\n projectSyncFailuresRef.current.delete(currentWorkspaceId);\n }\n\n // Resolve organizationId: prefer the workspace object (if loaded), fall\n // back to the persisted currentOrganizationId. The workspaces array is\n // NOT persisted by zustand, so on page reload it is empty until\n // fetchOrganizations() completes. Using the persisted org ID lets us\n // issue the workspace token immediately instead of waiting.\n const currentWorkspace = workspaces.find(\n (ws) => ws.id === currentWorkspaceId,\n );\n\n // Guard: transient (newOrg, oldWs) divergence during org switches — token issuance always fails.\n if (\n currentWorkspace &&\n currentOrganizationId &&\n currentWorkspace.organizationId !== currentOrganizationId\n ) {\n return;\n }\n\n const organizationId =\n currentWorkspace?.organizationId ?? currentOrganizationId;\n if (!organizationId) return;\n\n const store = useAuthStore.getState();\n if (\n currentProjectId &&\n getUrlParam(\"project\") === currentProjectId &&\n getUrlParam(\"workspace\") === currentWorkspaceId &&\n getUrlParam(\"org\") === organizationId\n ) {\n clearWorkspaceWideSelection({\n organizationId,\n workspaceId: currentWorkspaceId,\n });\n }\n const profileId = resolveActiveProfileId();\n const userId = store.user?.id;\n const workspaceWide = isWorkspaceWideSelection({\n organizationId,\n workspaceId: currentWorkspaceId,\n });\n if (workspaceWide && store.currentProjectId) {\n store.setCurrentProjectId(null);\n store.setWorkspaceToken(null);\n return;\n }\n\n // If we don't have a workspace token or it's expired, issue one first\n const needsToken =\n !workspaceToken ||\n isTokenExpired(workspaceToken) ||\n !isWorkspaceTokenValidForContext(workspaceToken, {\n workspaceId: currentWorkspaceId,\n organizationId: currentOrganizationId,\n projectId: currentProjectId,\n workspaceWide,\n });\n\n // Skip if projects are already loaded for this workspace AND token is valid\n const scopeKey = JSON.stringify([\n profileId,\n userId,\n accessToken,\n organizationId,\n currentWorkspaceId,\n ]);\n const hasProjectsForWorkspace =\n projects.some((p) => p.workspaceId === currentWorkspaceId) ||\n (emptyProjectsResultRef.current?.scopeKey === scopeKey &&\n emptyProjectsResultRef.current.projects === projects);\n if (hasProjectsForWorkspace && !needsToken) {\n if (!store.currentProjectId && !workspaceWide) {\n const firstProject = projects.find(\n (project) => project.workspaceId === currentWorkspaceId,\n );\n if (firstProject) {\n store.setCurrentProjectId(firstProject.id);\n }\n }\n return;\n }\n\n const contextStillCurrent = () => {\n const latest = useAuthStore.getState();\n return (\n latest.accessToken === accessToken &&\n latest.user?.id === userId &&\n resolveActiveProfileId() === profileId &&\n latest.currentOrganizationId === organizationId &&\n latest.currentWorkspaceId === currentWorkspaceId &&\n latest.currentProjectId === currentProjectId &&\n isWorkspaceWideSelection({\n organizationId,\n workspaceId: currentWorkspaceId,\n }) === workspaceWide\n );\n };\n\n const syncProjects = async () => {\n syncInProgressRef.current = true;\n store.setLoadingProjects(true);\n let succeeded = false;\n\n try {\n let wsToken = workspaceToken;\n\n // Issue workspace token if needed\n if (needsToken) {\n const tokenResult = await graphqlFetch<{\n issueWorkspaceToken: IssueWorkspaceTokenResult;\n }>({\n gateway: \"workspace\",\n query: ISSUE_WORKSPACE_TOKEN_MUTATION,\n variables: {\n input: {\n organizationId,\n workspaceId: currentWorkspaceId,\n ...(currentProjectId ? { projectId: currentProjectId } : {}),\n },\n },\n authToken: accessToken,\n baseUrl: workspaceBaseUrl,\n // See issueWorkspaceToken: send the current workspace's tenant so a\n // super_admin (no tenant claim) can resolve it for an unmirrored ws.\n tenantId: workspaces.find((ws) => ws.id === currentWorkspaceId)\n ?.tenantId,\n });\n\n if (\n tokenResult.data?.issueWorkspaceToken?.success &&\n tokenResult.data.issueWorkspaceToken.token\n ) {\n wsToken = tokenResult.data.issueWorkspaceToken.token;\n if (\n !contextStillCurrent() ||\n !isWorkspaceTokenValidForContext(wsToken, {\n workspaceId: currentWorkspaceId,\n organizationId,\n projectId: currentProjectId,\n workspaceWide,\n })\n )\n return;\n store.setWorkspaceToken(wsToken);\n } else {\n // A restored project the caller is no longer a member of (or that\n // was deleted) can never yield a token, and without a token the\n // project list below is never re-read to discard it. Drop the\n // project everywhere it is held so the next run issues a\n // workspace-scoped token; leaving it in place locks the user out\n // of every workspace-token page (BOFF-10431).\n if (\n currentProjectId &&\n contextStillCurrent() &&\n isUnusableProjectTokenError(\n tokenResult.data?.issueWorkspaceToken?.error?.code,\n )\n ) {\n store.setCurrentProjectId(null);\n store.setWorkspaceToken(null);\n setActiveContext({ projectId: null });\n }\n return;\n }\n }\n\n // Fetch projects (skip if already loaded or token-only sync requested)\n if (wsToken && !hasProjectsForWorkspace && !skipProjectFetch) {\n const projectsResult = await graphqlFetch<ProjectsResponse>({\n gateway: \"workspace\",\n query: PROJECTS_QUERY,\n authToken: accessToken,\n workspaceToken: wsToken,\n baseUrl: workspaceBaseUrl,\n });\n\n if (!contextStillCurrent() || projectsResult.errors?.length) {\n return;\n }\n\n const projs: Project[] = projectsResult.data?.projects?.items ?? [];\n // myProjects lists accessible projects. An empty result does not\n // authorize creating one. Remember this result to avoid a render/\n // fetch loop; changing account or clearing the list invalidates it.\n emptyProjectsResultRef.current =\n projs.length === 0 ? { scopeKey, projects: projs } : null;\n store.setProjects(projs);\n\n // A restored/deep-linked project may have been removed or revoked.\n // Discard its token so the next sync establishes the current scope.\n if (\n currentProjectId &&\n !projs.some((project) => project.id === currentProjectId)\n ) {\n store.setCurrentProjectId(null);\n store.setWorkspaceToken(null);\n }\n\n // Auto-select first project if none selected and projects exist\n if (\n projs.length > 0 &&\n !useAuthStore.getState().currentProjectId &&\n !isWorkspaceWideSelection({\n organizationId,\n workspaceId: currentWorkspaceId,\n })\n ) {\n store.setCurrentProjectId(projs[0].id);\n }\n }\n\n succeeded = true;\n } catch {\n // A later auth/context update should be able to retry.\n } finally {\n store.setLoadingProjects(false);\n syncInProgressRef.current = false;\n const scopeCurrent = contextStillCurrent();\n if (!scopeCurrent) setSyncRevision((revision) => revision + 1);\n const failures = projectSyncFailuresRef.current;\n if (scopeCurrent && succeeded) {\n failures.delete(currentWorkspaceId);\n const pending = retryTimerRef.current.get(currentWorkspaceId);\n if (pending) {\n clearTimeout(pending);\n retryTimerRef.current.delete(currentWorkspaceId);\n }\n } else if (scopeCurrent) {\n const existing = failures.get(currentWorkspaceId);\n const nextCount = (existing?.count ?? 0) + 1;\n failures.set(currentWorkspaceId, {\n count: nextCount,\n lastFailureAt: Date.now(),\n });\n // Schedule a backoff retry for transient backend lag (e.g. RBAC\n // role propagation right after signup → first projects() call hits\n // permission-denied). Without this, the effect would only re-run on\n // dep change and the user would be stuck staring at an empty\n // project dropdown until something else triggered a re-render.\n if (nextCount < PROJECT_SYNC_MAX_FAILURES) {\n const existingTimer = retryTimerRef.current.get(currentWorkspaceId);\n if (existingTimer) clearTimeout(existingTimer);\n const backoffMs = Math.min(1000 * 2 ** (nextCount - 1), 8000);\n const timer = setTimeout(() => {\n retryTimerRef.current.delete(currentWorkspaceId);\n // Only re-run if the workspace context is still the same and\n // a project hasn't been loaded for it in the meantime.\n const latest = useAuthStore.getState();\n if (\n contextStillCurrent() &&\n latest.currentWorkspaceId === currentWorkspaceId &&\n !latest.projects.some(\n (p) => p.workspaceId === currentWorkspaceId,\n ) &&\n !syncInProgressRef.current\n ) {\n // Bump a render by clearing then resetting workspaceToken\n // when valid, OR by re-issuing projects fetch directly. The\n // simplest robust trigger is to clear the in-progress guard\n // and call syncProjects() again with current closure values.\n void syncProjects();\n }\n }, backoffMs);\n retryTimerRef.current.set(currentWorkspaceId, timer);\n }\n }\n }\n };\n\n syncProjects();\n }, [\n syncRevision,\n currentWorkspaceId,\n currentOrganizationId,\n workspaces,\n projects,\n currentProjectId,\n workspaceToken,\n accessToken,\n workspaceBaseUrl,\n disableProjectSync,\n skipProjectFetch,\n setActiveContext,\n ]);\n\n // Cleanup any pending retry timers on unmount so we don't leak stray\n // setTimeout callbacks running against stale closures.\n useEffect(() => {\n const timers = retryTimerRef.current;\n return () => {\n timers.forEach((timer) => clearTimeout(timer));\n timers.clear();\n };\n }, []);\n}\n// hmr-bust-1778064429\n"],"mappings":";;;;;;;;;;;AA6FA,IAAME,IAAyB,2RAoCzBC,IAA0B,oSAsB1BC,IAA2B,oVA0B3BC,oBAAqD,IAAI,IAAI,CACjE,sBACA,mBACF,CAAC;AAED,SAASC,EAA4B,GAA0C;CAC7E,O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B;MACzC,IAAMC,IAAgBnB,EAAc,QAAQ,IAAIvH,CAAkB;MAClE,AAAI0I,KAAe,aAAaA,CAAa;MAC7C,IAAMC,IAAY,KAAK,IAAI,MAAO,MAAMF,IAAY,IAAI,GAAI,GACtDxE,IAAQ,iBAAiB;OAC7B,EAAc,QAAQ,OAAOjE,CAAkB;OAG/C,IAAMmF,IAAS1H,EAAa,SAAS;OACrC,AACEwK,EAAoB,KACpB9C,EAAO,uBAAuBnF,KAC9B,CAACmF,EAAO,SAAS,MACd,MAAM4C,EAAE,gBAAgB/H,CAC3B,KACA,CAACmH,EAAkB,WAMnBe,EAAkB;MAEtB,GAAGS,CAAS;MACZ,EAAc,QAAQ,IAAI3I,GAAoBiE,CAAK;KACrD;IACF;GACF;EACF;EAEA,EAAa;CACf,GAAG;EACDmD;EACApH;EACAF;EACAxB;EACA6B;EACAC;EACAH;EACA2F;EACAvE;EACAnC;EACAC;EACAK;CACF,CAAC,GAIDuE,QAAgB;EACd,IAAM6E,IAASrB,EAAc;EAC7B,aAAa;GAEX,AADAqB,EAAO,SAAS,MAAU,aAAa3E,CAAK,CAAC,GAC7C2E,EAAO,MAAM;EACf;CACF,GAAG,CAAC,CAAC;AACP"}
|
|
1
|
+
{"version":3,"file":"useContextSwitcherData.js","names":["selectWorkspaceWide","persistWorkspaceWideSelection","MY_ORGANIZATIONS_QUERY","WORKSPACES_BY_ORG_QUERY","MY_WORKSPACES_PAGE_QUERY","UNUSABLE_PROJECT_TOKEN_ERRORS","isUnusableProjectTokenError","code","WORKSPACES_PAGE_SIZE","WORKSPACES_MAX_PAGES","ISSUE_WORKSPACE_TOKEN_MUTATION","PROJECTS_QUERY","isTokenExpired","payload","token","bufferMs","getWorkspaceTokenPayload","isWorkspaceTokenValidForContext","expected","AuthError","message","isAuthGraphQLError","errors","resolveAccessToken","storeToken","useAuthStore","profileToken","getStoredAuthToken","readRemainingWorkspacePages","items","first","total","page","next","graphqlFetch","globalBaseUrl","pageItems","buildFallbackOrganizations","workspaces","workspace","organizationId","index","PROJECT_REFRESH_EVENTS","WORKSPACE_REFRESH_EVENTS","readEventWorkspaceId","value","useContextSwitcherData","disableBootstrap","options","disableWorkspaceSync","disableProjectSync","skipProjectFetch","activeOrganizationId","activeWorkspaceId","activeProjectId","activeTenantId","setActiveContext","useActiveContext","eventBus","useEventBus","organizations","state","currentOrganizationId","isLoadingOrganizations","currentWorkspaceId","workspaceToken","isLoadingWorkspaces","projects","currentProjectId","isLoadingProjects","row","organization","error","setError","useState","bootstrapFailureNonce","setBootstrapFailureNonce","bootstrapRetryAttemptRef","useRef","fetchOrganizationsPromiseRef","fetchWorkspacesPromisesRef","activeWorkspaceIdRef","activeOrganizationIdRef","resolvedBaseUrls","resolveGatewayBaseUrls","workspaceBaseUrl","lastAppliedOrgIdRef","lastAppliedWorkspaceIdRef","lastAppliedProjectIdRef","lastClearedTokenContextRef","store","project","isWorkspaceWideSelection","ctxKey","fetchOrganizations","useCallback","initialTargetOrgId","requestedWorkspaceId","workspaceFromUrl","getUrlParam","orgFromUrl","result","organizationsResult","workspacesResult","errorMessage","orgs","recovery","recoveryMessage","fallbackOrganizations","effectiveOrganizations","targetOrgId","listedWorkspaces","w","isCompleteListing","workspaceLink","decideWorkspaceDeepLink","linked","denial","decideOrganizationDeepLink","targetOrgIsAccessible","org","ws","wsResult","n","persistedWorkspace","nextActiveContext","err","useEffect","delayMs","timer","onOnline","fetchWorkspacesForOrg","profileId","resolveActiveProfileId","userId","requestKey","existingPromise","currentSelection","current","fetchPromise","issueWorkspaceToken","originalScope","workspaceWide","workspaceId","authToken","projectId","tokenResult","latest","resolvedWsId","fetchProjects","wsToken","wide","projs","selectOrganization","selectWorkspace","selected","accessToken","selectProject","clearWorkspaceWideSelection","selectWorkspaceWide$1","scope","selectWorkspaceWide","cancelled","makeCoalescedRefetch","running","queued","trigger","run","refreshProjects","refreshWorkspaces","orgId","unsubscribe","eventName","event","eventWorkspaceId","proj","useWorkspaceSyncEffect","hasMatchingWorkspaces","useProjectSyncEffect","syncInProgressRef","syncRevision","setSyncRevision","emptyProjectsResultRef","retryTimerRef","projectSyncFailuresRef","PROJECT_SYNC_FAILURE_COOLDOWN_MS","failureEntry","currentWorkspace","needsToken","scopeKey","hasProjectsForWorkspace","p","firstProject","contextStillCurrent","syncProjects","succeeded","projectsResult","scopeCurrent","revision","failures","pending","nextCount","existingTimer","backoffMs","timers"],"sources":["../../../src/auth/hooks/useContextSwitcherData.ts"],"sourcesContent":["import {\n isWorkspaceWideSelection,\n selectWorkspaceWide as persistWorkspaceWideSelection,\n clearWorkspaceWideSelection,\n} from \"@burdenoff/fe-libs/shared/providers/shell/WorkspaceWideSelection\";\nimport { resolveActiveProfileId } from \"@burdenoff/fe-libs/shared/providers/shell/ProfileStorageManager\";\nimport { getUrlParam } from \"@burdenoff/fe-libs/shared/providers/shell/ActiveContextStorage\";\nimport { useCallback, useState, useEffect, useRef } from \"react\";\nimport {\n graphqlFetch,\n getStoredAuthToken,\n} from \"@burdenoff/fe-libs/shared/graphql\";\nimport { useActiveContext } from \"@burdenoff/fe-libs/shared/providers/shell/ActiveContextProvider\";\nimport { useEventBus } from \"@burdenoff/fe-libs/shared/events\";\nimport { useAuthStore } from \"../store/authStore\";\nimport type { Organization, Workspace, Project } from \"../types\";\nimport { resolveGatewayBaseUrls } from \"../utils/gatewayBaseUrls\";\nimport {\n decideOrganizationDeepLink,\n decideWorkspaceDeepLink,\n isCompleteListing,\n} from \"./contextDeepLink\";\n\n// =============================================================================\n// Hook Options\n// =============================================================================\n\nexport interface UseContextSwitcherDataOptions {\n /**\n * Optional Global API Gateway base URL override.\n * If not provided, uses GATEWAYS config from fe-libs.\n */\n globalBaseUrl?: string;\n /**\n * Optional Workspaces API Gateway base URL override.\n * If not provided, uses GATEWAYS config from fe-libs.\n */\n workspaceBaseUrl?: string;\n /** Disable initial organization/workspace bootstrap fetches */\n disableBootstrap?: boolean;\n /** Disable the workspace sync effect */\n disableWorkspaceSync?: boolean;\n /** Disable the project sync effect */\n disableProjectSync?: boolean;\n /** Only hydrate the workspace token; do not eagerly fetch projects */\n skipProjectFetch?: boolean;\n}\n\n// =============================================================================\n// GraphQL Response Types\n// =============================================================================\n\ninterface MyOrganizationsResponse {\n myOrganizations: {\n total: number;\n items: Organization[];\n };\n}\n\ninterface WorkspacesByOrgResponse {\n workspaces: {\n total: number;\n items: Workspace[];\n };\n}\n\ntype GraphQLFetchResult<T> = Awaited<ReturnType<typeof graphqlFetch<T>>>;\n\ninterface IssueWorkspaceTokenResult {\n success: boolean;\n token: string | null;\n expiresAt: string | null;\n organizationId: string | null;\n workspaceId: string | null;\n projectId: string | null;\n scopes: string[] | null;\n error: {\n code: string;\n message: string;\n } | null;\n}\n\ninterface ProjectsResponse {\n projects: {\n total: number;\n items: Project[];\n };\n}\n\n// =============================================================================\n// GraphQL Query/Mutation Strings\n// =============================================================================\n\nconst MY_ORGANIZATIONS_QUERY = `\n query MyOrganizations {\n myOrganizations {\n total\n items {\n id\n name\n slug\n tenantId\n description\n logo\n website\n status\n type\n createdAt\n updatedAt\n }\n }\n }\n`;\n\n// Both queries below historically used `workspaces(filter: $filter)` with\n// a `WorkspaceFilterInput` to fetch workspaces for a specific organization.\n// That Query field was removed/renamed in the global subgraph; calling it\n// now throws GRAPHQL_VALIDATION_FAILED (\"Cannot query field 'workspaces'\n// on type 'Query'\") which crashes the context switcher and cascades into a\n// \"Verifying workspace access...\" stuck-spinner on every Platform module\n// route (/billing, /support, /notifications, /devportal).\n//\n// The supported field is `myWorkspaces(limit, offset)` on the global\n// subgraph — self-scoped, returns the caller's workspaces across all\n// orgs. It does NOT accept a filter, so we fetch up to 100 of \"my\"\n// workspaces and let the existing downstream auto-pick logic filter by\n// organizationId client-side. The recovery path at line ~624 already\n// uses this exact aliased pattern; we're just promoting it to the\n// primary path.\nconst WORKSPACES_BY_ORG_QUERY = `\n query WorkspacesByOrg {\n workspaces: myWorkspaces(limit: 100) {\n total\n items {\n id\n name\n slug\n tenantId\n organizationId\n type\n status\n region\n createdAt\n updatedAt\n }\n }\n }\n`;\n\n// A further page of `myWorkspaces`, read only when a deep-linked workspace is\n// not on the first page of a caller with more than 100 workspaces.\nconst MY_WORKSPACES_PAGE_QUERY = `\n query MyWorkspacesPage($limit: Int, $offset: Int) {\n workspaces: myWorkspaces(limit: $limit, offset: $offset) {\n total\n items {\n id\n name\n slug\n tenantId\n organizationId\n type\n status\n region\n createdAt\n updatedAt\n }\n }\n }\n`;\n\n/**\n * `issueWorkspaceToken` error codes that mean the requested project can never\n * be used by this caller (they are not a member, or it no longer exists). A\n * retry with the same project cannot succeed, so the project selection has to\n * be dropped instead.\n */\nconst UNUSABLE_PROJECT_TOKEN_ERRORS: ReadonlySet<string> = new Set([\n \"NOT_PROJECT_MEMBER\",\n \"PROJECT_NOT_FOUND\",\n]);\n\nfunction isUnusableProjectTokenError(code: string | null | undefined): boolean {\n return !!code && UNUSABLE_PROJECT_TOKEN_ERRORS.has(code);\n}\n\nconst WORKSPACES_PAGE_SIZE = 100;\n// Bounds the read for a deep link: 20 pages = 2,000 workspaces.\nconst WORKSPACES_MAX_PAGES = 20;\n\nconst ISSUE_WORKSPACE_TOKEN_MUTATION = `\n mutation IssueWorkspaceToken($input: IssueWorkspaceTokenInput!) {\n issueWorkspaceToken(input: $input) {\n success\n token\n expiresAt\n organizationId\n workspaceId\n projectId\n scopes\n error {\n code\n message\n }\n }\n }\n`;\n\n// The workspace gateway exposes `myProjects` (public RBAC, caller-scoped to\n// the active workspace via x-workspace-id) and the privileged\n// `projects(filter)` (list:project). The header has no `list:project`\n// permission seeded for the typical operator, so the privileged form\n// returns FORBIDDEN even though the caller is a member of the workspace.\n// `myProjects` is the right field for \"give me the projects I can see in\n// this workspace\" — workspace scope is already established by the\n// workspace token + x-workspace-id header that we pass with the request.\nconst PROJECTS_QUERY = `\n query MyProjectsForContext {\n projects: myProjects {\n total\n items {\n id\n name\n key\n workspaceId\n status\n archived\n createdAt\n updatedAt\n }\n }\n }\n`;\n\n// =============================================================================\n// Auth Helpers\n// =============================================================================\n\n/**\n * Check whether a JWT is expired (or within bufferMs of expiry).\n * Returns true if the token is expired, close to expiry, or malformed.\n */\nfunction isTokenExpired(token: string, bufferMs = 30_000): boolean {\n try {\n const payload = JSON.parse(atob(token.split(\".\")[1]));\n if (!payload.exp) return false;\n return payload.exp * 1000 < Date.now() + bufferMs;\n } catch {\n return true;\n }\n}\n\nfunction getWorkspaceTokenPayload(token: string): {\n workspaceId?: string;\n organizationId?: string;\n projectId?: string;\n exp?: number;\n} | null {\n try {\n const payload = JSON.parse(atob(token.split(\".\")[1]));\n return {\n workspaceId:\n typeof payload.workspaceId === \"string\"\n ? payload.workspaceId\n : undefined,\n organizationId:\n typeof payload.organizationId === \"string\"\n ? payload.organizationId\n : undefined,\n projectId:\n typeof payload.projectId === \"string\" ? payload.projectId : undefined,\n exp: typeof payload.exp === \"number\" ? payload.exp : undefined,\n };\n } catch {\n return null;\n }\n}\n\nfunction isWorkspaceTokenValidForContext(\n token: string | null | undefined,\n expected: {\n workspaceId?: string | null;\n organizationId?: string | null;\n projectId?: string | null;\n workspaceWide?: boolean;\n },\n): token is string {\n if (!token || isTokenExpired(token)) {\n return false;\n }\n\n const payload = getWorkspaceTokenPayload(token);\n if (!payload) {\n return false;\n }\n\n if (expected.workspaceId && payload.workspaceId !== expected.workspaceId) {\n return false;\n }\n\n if (\n expected.organizationId &&\n payload.organizationId !== expected.organizationId\n ) {\n return false;\n }\n\n if (expected.workspaceWide && payload.projectId) return false;\n\n if (expected.projectId && payload.projectId !== expected.projectId) {\n return false;\n }\n\n return true;\n}\n\n/**\n * Custom error class for auth-related failures (expired token, unauthorized, etc.).\n * Used to distinguish auth errors in outer catch blocks so they can be\n * suppressed from console.error — they are expected during token refresh cycles\n * and do not indicate application bugs.\n */\nclass AuthError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"AuthError\";\n }\n}\n\n/**\n * Detect whether a set of GraphQL errors are authentication-related.\n */\nfunction isAuthGraphQLError(\n errors: Array<{ message?: string; extensions?: { code?: string } }>,\n): boolean {\n return errors.some(\n (e) =>\n e.extensions?.code === \"UNAUTHENTICATED\" ||\n e.message?.toLowerCase().includes(\"unauthorized\") ||\n e.message?.toLowerCase().includes(\"not authenticated\"),\n );\n}\n\n/**\n * Resolve the best available access token:\n * 1. Try the zustand store token\n * 2. If expired, fall back to profile storage (may have been refreshed)\n * 3. Return null if no valid token is available\n */\nfunction resolveAccessToken(): string | null {\n const storeToken = useAuthStore.getState().accessToken;\n\n // If store token is valid (or has no exp claim), use it\n if (storeToken && !isTokenExpired(storeToken)) {\n return storeToken;\n }\n\n // Store token is expired or missing — try profile storage (may be fresher)\n const profileToken = getStoredAuthToken();\n if (profileToken && !isTokenExpired(profileToken)) {\n return profileToken;\n }\n\n // Both expired or missing — if store token exists at all, return it as a last\n // resort (the gateway will reject it and the useEffect will re-trigger after\n // token refresh). Returning null would silently swallow the first load.\n return storeToken;\n}\n\n/**\n * The rest of the caller's workspaces after `first` (a first page of\n * `myWorkspaces`), bounded by WORKSPACES_MAX_PAGES. A failed page ends the read\n * with what was gathered, marked complete only if every page was read.\n */\nasync function readRemainingWorkspacePages(\n first: WorkspacesByOrgResponse[\"workspaces\"],\n token: string,\n globalBaseUrl: string,\n): Promise<WorkspacesByOrgResponse[\"workspaces\"]> {\n const items = [...first.items];\n const total = first.total;\n for (\n let page = 1;\n page < WORKSPACES_MAX_PAGES && items.length < total;\n page += 1\n ) {\n const next = await graphqlFetch<WorkspacesByOrgResponse>({\n gateway: \"global\",\n query: MY_WORKSPACES_PAGE_QUERY,\n variables: { limit: WORKSPACES_PAGE_SIZE, offset: items.length },\n authToken: token,\n baseUrl: globalBaseUrl,\n });\n const pageItems = next.errors?.length\n ? []\n : (next.data?.workspaces?.items ?? []);\n if (pageItems.length === 0) {\n // Unreadable or short: report what we have as a partial listing so no\n // denial is concluded from it.\n return { total: Math.max(total, items.length + 1), items };\n }\n items.push(...pageItems);\n }\n return { total, items };\n}\n\nfunction buildFallbackOrganizations(workspaces: Workspace[]): Organization[] {\n const uniqueOrgIds = Array.from(\n new Set(\n workspaces.flatMap((workspace) =>\n workspace.organizationId ? [workspace.organizationId] : [],\n ),\n ),\n );\n\n return uniqueOrgIds.map((organizationId, index) => ({\n id: organizationId,\n name:\n workspaces.find(\n (workspace) => workspace.organizationId === organizationId,\n )?.name || `Organization ${index + 1}`,\n slug: organizationId,\n tenantId:\n workspaces.find(\n (workspace) => workspace.organizationId === organizationId,\n )?.tenantId || \"\",\n }));\n}\n\n// =============================================================================\n// Hook Implementation\n// =============================================================================\n\n/**\n * Hook for managing the context switcher data (organizations, workspaces, projects)\n *\n * Data flow:\n * 1. fetchOrganizations() - Get all orgs user has access to (Global Gateway)\n * 2. selectOrganization(org) - Set current org & fetch workspaces for that org\n * 3. selectWorkspace(ws) - Issue workspace token & fetch projects\n * 4. selectProject(proj) - Set current project\n *\n * All GraphQL calls go through graphqlFetch from fe-libs which automatically\n * resolves gateway URLs and injects auth + locale headers.\n *\n * @param options - Optional configuration (gateway base URL overrides)\n */\n// Domain events emitted by microfe-workspaces that should refresh the switcher's\n// cached lists. Module-scoped so they aren't reallocated on every effect run.\nconst PROJECT_REFRESH_EVENTS = new Set<string>([\n \"project.created\",\n \"project.updated\",\n \"project.deleted\",\n \"project.archived\",\n \"project.unarchived\",\n]);\nconst WORKSPACE_REFRESH_EVENTS = new Set<string>([\n \"workspace.created\",\n \"workspace.updated\",\n \"workspace.deleted\",\n \"workspace.archived\",\n \"workspace.reactivated\",\n]);\n\n// Safely read a string `workspaceId` off a cross-MFE event payload of unknown\n// shape, rather than trusting a bare cast (the payload is produced by another\n// MFE and could drift). Returns undefined when absent or not a string.\nfunction readEventWorkspaceId(payload: unknown): string | undefined {\n if (payload && typeof payload === \"object\" && \"workspaceId\" in payload) {\n const value = (payload as { workspaceId?: unknown }).workspaceId;\n return typeof value === \"string\" ? value : undefined;\n }\n return undefined;\n}\n\nexport function useContextSwitcherData(\n options?: UseContextSwitcherDataOptions,\n) {\n const disableBootstrap = options?.disableBootstrap ?? false;\n const disableWorkspaceSync = options?.disableWorkspaceSync ?? false;\n const disableProjectSync = options?.disableProjectSync ?? false;\n const skipProjectFetch = options?.skipProjectFetch ?? false;\n const {\n organizationId: activeOrganizationId,\n workspaceId: activeWorkspaceId,\n projectId: activeProjectId,\n tenantId: activeTenantId,\n setContext: setActiveContext,\n } = useActiveContext();\n\n const eventBus = useEventBus();\n\n // Use selectors for reactive state\n const organizations = useAuthStore((state) => state.organizations);\n const currentOrganizationId = useAuthStore(\n (state) => state.currentOrganizationId,\n );\n const isLoadingOrganizations = useAuthStore(\n (state) => state.isLoadingOrganizations,\n );\n\n const workspaces = useAuthStore((state) => state.workspaces);\n const currentWorkspaceId = useAuthStore((state) => state.currentWorkspaceId);\n const workspaceToken = useAuthStore((state) => state.workspaceToken);\n const isLoadingWorkspaces = useAuthStore(\n (state) => state.isLoadingWorkspaces,\n );\n\n const projects = useAuthStore((state) => state.projects);\n const currentProjectId = useAuthStore((state) => state.currentProjectId);\n const isLoadingProjects = useAuthStore((state) => state.isLoadingProjects);\n\n // Restored workspaces can already be present in the profile store, so the\n // first-workspace bootstrap branch is not sufficient to hydrate tenant.\n // Resolve it from the selected accessible rows, never from a placeholder,\n // URL tenant value or a workspace belonging to another organization.\n useEffect(() => {\n const workspace = workspaces.find(\n (row) =>\n row.id === activeWorkspaceId &&\n row.organizationId === activeOrganizationId,\n );\n const organization = organizations.find(\n (row) => row.id === activeOrganizationId,\n );\n if (\n !workspace ||\n !organization ||\n !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(\n workspace.tenantId,\n ) ||\n workspace.tenantId !== organization.tenantId ||\n activeTenantId === workspace.tenantId\n ) {\n return;\n }\n // Updating only tenant preserves the selected project, including an\n // explicit workspace-wide (null-project) selection.\n setActiveContext({ tenantId: workspace.tenantId });\n }, [\n activeOrganizationId,\n activeWorkspaceId,\n activeTenantId,\n organizations,\n workspaces,\n setActiveContext,\n ]);\n\n // Local error state\n const [error, setError] = useState<string | null>(null);\n\n // Bootstrap-retry signal: incremented on every TRANSIENT bootstrap failure\n // (orgs fetch, stale-context recovery, or the inner workspace bootstrap).\n // A monotonically increasing nonce — rather than the `error` string — keys\n // the retry effect, because two consecutive failures with the identical\n // message would not re-trigger a string-keyed effect and the retry chain\n // would silently stop after one attempt.\n const [bootstrapFailureNonce, setBootstrapFailureNonce] = useState(0);\n const bootstrapRetryAttemptRef = useRef(0);\n\n // Deduplication refs to prevent duplicate GraphQL calls\n const fetchOrganizationsPromiseRef = useRef<Promise<Organization[]> | null>(\n null,\n );\n const fetchWorkspacesPromisesRef = useRef<Map<string, Promise<Workspace[]>>>(\n new Map(),\n );\n\n // Stable refs for latest context values — avoids stale closures in callbacks\n // without adding them to useCallback dep arrays (which would recreate callbacks\n // on every context change and trigger spurious fetch re-runs).\n const activeWorkspaceIdRef = useRef(activeWorkspaceId);\n const activeOrganizationIdRef = useRef(activeOrganizationId);\n useEffect(() => {\n activeWorkspaceIdRef.current = activeWorkspaceId;\n activeOrganizationIdRef.current = activeOrganizationId;\n });\n\n const resolvedBaseUrls = resolveGatewayBaseUrls();\n const globalBaseUrl =\n options?.globalBaseUrl ?? resolvedBaseUrls.globalBaseUrl;\n const workspaceBaseUrl =\n options?.workspaceBaseUrl ?? resolvedBaseUrls.workspaceBaseUrl;\n\n // Refs to break feedback loops with the Header's \"store → URL\" sync effect.\n // Without these the pair can ping-pong: this effect writes (URL → store),\n // Header writes (store → URL), Zustand re-fires our subscribers, and React\n // hits \"Maximum update depth exceeded\" — especially when a downstream call\n // (workspace token issuance) returns 504 and leaves the two halves in\n // disagreement. The refs record the last value we pushed for each axis;\n // identical pushes are skipped so the loop has a hard floor.\n const lastAppliedOrgIdRef = useRef<string | null>(null);\n const lastAppliedWorkspaceIdRef = useRef<string | null>(null);\n const lastAppliedProjectIdRef = useRef<string | null>(null);\n const lastClearedTokenContextRef = useRef<string | null>(null);\n\n useEffect(() => {\n const store = useAuthStore.getState();\n\n if (\n activeOrganizationId &&\n activeOrganizationId !== store.currentOrganizationId &&\n activeOrganizationId !== lastAppliedOrgIdRef.current\n ) {\n lastAppliedOrgIdRef.current = activeOrganizationId;\n store.setCurrentOrganizationId(activeOrganizationId);\n if (\n store.workspaces.length > 0 &&\n !store.workspaces.some(\n (workspace) => workspace.organizationId === activeOrganizationId,\n )\n ) {\n store.setWorkspaces([]);\n }\n }\n\n if (\n activeWorkspaceId &&\n activeWorkspaceId !== store.currentWorkspaceId &&\n activeWorkspaceId !== lastAppliedWorkspaceIdRef.current\n ) {\n lastAppliedWorkspaceIdRef.current = activeWorkspaceId;\n store.setCurrentWorkspaceId(activeWorkspaceId);\n if (\n store.projects.length > 0 &&\n !store.projects.some(\n (project) => project.workspaceId === activeWorkspaceId,\n )\n ) {\n store.setProjects([]);\n store.setCurrentProjectId(null);\n }\n }\n\n if (\n isWorkspaceWideSelection({\n organizationId: activeOrganizationId,\n workspaceId: activeWorkspaceId,\n }) &&\n !activeProjectId &&\n store.currentProjectId\n ) {\n store.setCurrentProjectId(null);\n store.setWorkspaceToken(null);\n }\n\n if (\n activeProjectId &&\n activeProjectId !== store.currentProjectId &&\n activeProjectId !== lastAppliedProjectIdRef.current\n ) {\n lastAppliedProjectIdRef.current = activeProjectId;\n store.setCurrentProjectId(activeProjectId);\n }\n\n if (\n store.workspaceToken &&\n !isWorkspaceTokenValidForContext(store.workspaceToken, {\n workspaceId: activeWorkspaceId,\n organizationId: activeOrganizationId,\n projectId: activeProjectId,\n workspaceWide:\n !activeProjectId &&\n isWorkspaceWideSelection({\n organizationId: activeOrganizationId,\n workspaceId: activeWorkspaceId,\n }),\n })\n ) {\n // Clear-token-once-per-context guard: when the upstream gateway is\n // flaky (504s during workspace token issuance) the surrounding state\n // machine can oscillate between \"got token but invalid\" and \"clearing\n // token\". The downstream re-issue path then loops. Only clear once per\n // (org, ws, proj) tuple — a successful re-issue resets the ref via\n // setWorkspaceToken landing a new token for the same context.\n const ctxKey = `${activeOrganizationId ?? \"\"}|${activeWorkspaceId ?? \"\"}|${activeProjectId ?? \"\"}`;\n if (lastClearedTokenContextRef.current !== ctxKey) {\n lastClearedTokenContextRef.current = ctxKey;\n store.setWorkspaceToken(null);\n }\n }\n }, [activeOrganizationId, activeWorkspaceId, activeProjectId]);\n\n // ===========================================================================\n // Fetch Organizations (Global Gateway)\n // ===========================================================================\n\n const fetchOrganizations = useCallback(async (): Promise<Organization[]> => {\n // Deduplicate: if a fetch is already in progress, return the same promise\n if (fetchOrganizationsPromiseRef.current) {\n return fetchOrganizationsPromiseRef.current;\n }\n\n const store = useAuthStore.getState();\n const token = resolveAccessToken();\n\n if (!token) {\n // Not an error — user may not be authenticated yet (e.g., page load before login).\n // The useEffect in Header.tsx will re-trigger when accessToken becomes available.\n return [];\n }\n\n // NOTE: an EXPIRED token is deliberately NOT a bail-out. fe-libs\n // graphqlFetch now transparently refreshes on UNAUTHENTICATED and retries\n // the request once, and a definitive refresh failure triggers the shell's\n // forced logout (SESSION_EXPIRED_EVENT). The previous `isTokenExpired →\n // return []` short-circuit was the root cause of the persistently empty\n // context switcher: the expired token survives reloads in profile storage,\n // so every bootstrap silently produced [] — indistinguishable from \"you\n // have no organizations\" — until the user manually logged out.\n\n store.setLoadingOrganizations(true);\n setError(null);\n\n // Store the promise for deduplication before starting\n fetchOrganizationsPromiseRef.current = (async () => {\n try {\n const initialTargetOrgId =\n activeOrganizationIdRef.current ?? store.currentOrganizationId;\n // Deep links (contextDeepLink.ts): only ids that are in the URL right\n // now count as a link; restored ids fall back quietly as before.\n const requestedWorkspaceId = activeWorkspaceIdRef.current;\n const workspaceFromUrl =\n !!requestedWorkspaceId &&\n getUrlParam(\"workspace\") === requestedWorkspaceId;\n const orgFromUrl =\n !!initialTargetOrgId && getUrlParam(\"org\") === initialTargetOrgId;\n let result: GraphQLFetchResult<\n MyOrganizationsResponse & Partial<WorkspacesByOrgResponse>\n > =\n // The workspace list is read with the organizations whenever a\n // workspace is requested, because the workspace names its own\n // organization and may not be in the saved one.\n initialTargetOrgId || requestedWorkspaceId\n ? await (async () => {\n const [organizationsResult, workspacesResult] =\n await Promise.all([\n graphqlFetch<MyOrganizationsResponse>({\n gateway: \"global\",\n query: MY_ORGANIZATIONS_QUERY,\n authToken: token,\n baseUrl: globalBaseUrl,\n }),\n graphqlFetch<WorkspacesByOrgResponse>({\n gateway: \"global\",\n query: WORKSPACES_BY_ORG_QUERY,\n authToken: token,\n baseUrl: globalBaseUrl,\n }),\n ]);\n\n const data = organizationsResult.data?.myOrganizations\n ? {\n myOrganizations: organizationsResult.data.myOrganizations,\n ...(workspacesResult.data?.workspaces\n ? { workspaces: workspacesResult.data.workspaces }\n : {}),\n }\n : null;\n\n return {\n data,\n errors: [\n ...(organizationsResult.errors ?? []),\n ...(workspacesResult.errors ?? []),\n ],\n };\n })()\n : await graphqlFetch<MyOrganizationsResponse>({\n gateway: \"global\",\n query: MY_ORGANIZATIONS_QUERY,\n authToken: token,\n baseUrl: globalBaseUrl,\n });\n\n // Self-heal stale-URL case: if the workspace side of the bootstrap\n // fails because the URL points at an inaccessible org/workspace, retry\n // with the organization-only query so the operator sees their actual\n // orgs and the URL params get corrected on next render.\n if (\n initialTargetOrgId &&\n result.errors?.length &&\n result.errors.some(\n (e) =>\n e?.extensions?.code === \"FORBIDDEN\" ||\n /not a member of this organization/i.test(e?.message ?? \"\") ||\n // Public gateway often drops the underlying FORBIDDEN error\n // and replaces it with the schema-level non-null violation\n // (\"Cannot return null for non-nullable field Query.myOrganizations\").\n // That happens when ANY field in the query throws — workspaces\n // here — and data:null cascades up. Treat that pattern as a\n // signal to retry without the workspaces filter.\n /Cannot return null for non-nullable field Query\\.myOrganizations/i.test(\n e?.message ?? \"\",\n ),\n )\n ) {\n // Fetch myOrganizations + ALL workspaces (no filter) so the\n // downstream auto-pick logic still has a workspace list to seed\n // context from. If we only refetched myOrganizations, the page\n // would render but every workspace-scoped query would fail with\n // \"Select a workspace…\".\n result = await graphqlFetch<\n MyOrganizationsResponse & Partial<WorkspacesByOrgResponse>\n >({\n gateway: \"global\",\n query: `\n query ContextSwitcherRecover {\n myOrganizations {\n total\n items { id name slug tenantId description logo website status type createdAt updatedAt }\n }\n workspaces: myWorkspaces {\n total\n items { id name slug tenantId organizationId type status region createdAt updatedAt }\n }\n }\n `,\n authToken: token,\n baseUrl: globalBaseUrl,\n });\n }\n\n if (result.errors?.length) {\n const errorMessage = result.errors[0]?.message ?? \"GraphQL error\";\n if (isAuthGraphQLError(result.errors)) {\n // Auth errors are expected during token refresh cycles — throw AuthError\n // so the outer catch can suppress console.error.\n throw new AuthError(errorMessage);\n }\n if (store.workspaces.length === 0) {\n console.error(\"Failed to fetch organizations:\", result.errors);\n }\n throw new Error(errorMessage);\n }\n\n let orgs: Organization[] = result.data?.myOrganizations?.items ?? [];\n\n // Stale-context recovery: bootstrap query was filtered by\n // initialTargetOrgId, so when the URL/persisted org doesn't belong to\n // this user the response is empty. Re-fetch the unfiltered list of\n // *all* orgs the user can access so the guard below can pick a real\n // default. Skip the recovery when no target was set (already\n // unfiltered) or when workspaces are already in the store (the\n // existing fallback path covers that case).\n if (\n initialTargetOrgId &&\n orgs.length === 0 &&\n store.workspaces.length === 0\n ) {\n const recovery = await graphqlFetch<MyOrganizationsResponse>({\n gateway: \"global\",\n query: MY_ORGANIZATIONS_QUERY,\n authToken: token,\n baseUrl: globalBaseUrl,\n });\n if (!recovery.errors?.length) {\n orgs = recovery.data?.myOrganizations?.items ?? [];\n // discard the filtered workspaces payload — it was for the\n // ghost org and would only mislead the workspace selector below.\n result = {\n ...recovery,\n data: {\n myOrganizations: recovery.data?.myOrganizations ?? {\n items: [],\n total: 0,\n },\n },\n };\n } else {\n // The filtered bootstrap returned nothing AND the unfiltered\n // recovery failed — we genuinely do not know the user's org list.\n // Treat it as the failure it is (retryable via the bootstrap-retry\n // effect) instead of falling through to setOrganizations([]),\n // which presented a transient backend error as \"you have no\n // organizations\" until re-login.\n console.warn(\n \"[ContextSwitcher] Stale-context recovery failed:\",\n recovery.errors,\n );\n const recoveryMessage =\n recovery.errors?.[0]?.message ?? \"Failed to fetch organizations\";\n if (isAuthGraphQLError(recovery.errors ?? [])) {\n throw new AuthError(recoveryMessage);\n }\n throw new Error(recoveryMessage);\n }\n }\n\n const fallbackOrganizations =\n orgs.length === 0 && store.workspaces.length > 0\n ? buildFallbackOrganizations(store.workspaces)\n : [];\n const effectiveOrganizations =\n fallbackOrganizations.length > 0 ? fallbackOrganizations : orgs;\n\n store.setOrganizations(effectiveOrganizations);\n\n // Determine which organization to use for workspace fetching\n let targetOrgId = initialTargetOrgId;\n\n // The caller's workspaces across organizations, when this bootstrap\n // read them. A deep-linked workspace beyond the first page is looked\n // up in the remaining pages before anything is decided about it.\n let listedWorkspaces: WorkspacesByOrgResponse[\"workspaces\"] | null =\n result.data?.workspaces ?? null;\n if (\n workspaceFromUrl &&\n listedWorkspaces &&\n !listedWorkspaces.items.some((w) => w.id === requestedWorkspaceId) &&\n !isCompleteListing(listedWorkspaces)\n ) {\n listedWorkspaces = await readRemainingWorkspacePages(\n listedWorkspaces,\n token,\n globalBaseUrl,\n );\n }\n\n // A deep-linked workspace in another accessible organization switches\n // the organization to it, instead of being replaced by the saved\n // organization's first workspace (vc-fg-parity round 3). One the\n // caller cannot open is recorded so the shell can say so.\n const workspaceLink = decideWorkspaceDeepLink({\n requestedWorkspaceId,\n fromUrl: workspaceFromUrl,\n targetOrgId,\n organizations: orgs,\n workspaces: listedWorkspaces?.items ?? null,\n workspacesComplete: isCompleteListing(listedWorkspaces),\n });\n if (workspaceLink.kind === \"switch\") {\n const linked = workspaceLink.workspace;\n targetOrgId = linked.organizationId;\n setActiveContext({\n organizationId: linked.organizationId,\n workspaceId: linked.id,\n tenantId: linked.tenantId || null,\n projectId: getUrlParam(\"project\"),\n });\n store.setWorkspaces([]);\n store.setProjects([]);\n store.setCurrentProjectId(null);\n store.setWorkspaceToken(null);\n store.setCurrentWorkspaceId(linked.id);\n } else {\n const denial =\n workspaceLink.kind === \"denied\"\n ? workspaceLink.denial\n : decideOrganizationDeepLink({\n requestedOrgId: initialTargetOrgId,\n fromUrl: orgFromUrl,\n organizations: orgs,\n });\n if (denial) store.setContextLinkDenial(denial);\n }\n\n // Stale-context guard: if the persisted/URL org isn't in the user's\n // accessible orgs, fall back to the first available one and clear the\n // stale workspace/project so they get re-derived. Without this, URL\n // params like ?org=<ghost-id> from a prior session leak into the new\n // user's request headers and cause \"Authentication required\" /\n // \"not a member\" errors at every subgraph.\n //\n // Check against `orgs` (freshly returned from the API in this same\n // closure) rather than `effectiveOrganizations`, which can fall back\n // to ids derived from `store.workspaces` — that fallback path could\n // contain stale ghost orgIds and mask the guard.\n const targetOrgIsAccessible =\n targetOrgId && orgs.some((org) => org.id === targetOrgId);\n if (targetOrgId && !targetOrgIsAccessible && orgs.length > 0) {\n targetOrgId = orgs[0].id;\n setActiveContext({\n organizationId: targetOrgId,\n workspaceId: null,\n tenantId: null,\n projectId: null,\n });\n store.setWorkspaces([]);\n store.setProjects([]);\n store.setCurrentWorkspaceId(null);\n store.setCurrentProjectId(null);\n store.setWorkspaceToken(null);\n }\n\n if (targetOrgId && targetOrgId !== store.currentOrganizationId) {\n store.setCurrentOrganizationId(targetOrgId);\n }\n\n // Auto-select first organization if none is selected\n if (effectiveOrganizations.length > 0 && !targetOrgId) {\n store.setCurrentOrganizationId(effectiveOrganizations[0].id);\n targetOrgId = effectiveOrganizations[0].id;\n }\n\n // Fetch workspaces for the selected/auto-selected org if:\n // 1. We have a target org (either auto-selected or persisted from localStorage)\n // 2. AND workspaces array is empty (not persisted, or cleared)\n // This handles both initial login AND page refresh scenarios.\n // Read from useAuthStore.getState() rather than the captured `store`\n // snapshot so we see the post-guard cleared value when the org guard\n // above fired (the local `store.workspaces` ref is stale after\n // setWorkspaces([])).\n if (targetOrgId && useAuthStore.getState().workspaces.length === 0) {\n store.setLoadingWorkspaces(true);\n try {\n // myWorkspaces returns ALL workspaces the user is a member of\n // across every org. Filter to the target org client-side here.\n // The list read above covers every organization, so it serves the\n // target organization even when the guard or a deep link changed it.\n const bootstrappedWorkspaces = listedWorkspaces\n ? listedWorkspaces.items.filter(\n (w) => w.organizationId === targetOrgId,\n )\n : undefined;\n const ws = bootstrappedWorkspaces\n ? (bootstrappedWorkspaces as Workspace[])\n : await graphqlFetch<WorkspacesByOrgResponse>({\n gateway: \"global\",\n query: WORKSPACES_BY_ORG_QUERY,\n authToken: token,\n baseUrl: globalBaseUrl,\n }).then((wsResult) =>\n wsResult.errors?.length\n ? null\n : (wsResult.data?.workspaces?.items ?? []).filter(\n (w) => w.organizationId === targetOrgId,\n ),\n );\n\n if (!ws) {\n // Workspace bootstrap failed (errored result) while orgs\n // succeeded — retryable, otherwise the org renders with no\n // workspaces until manual interaction.\n setBootstrapFailureNonce((n) => n + 1);\n }\n if (ws) {\n store.setWorkspaces(ws);\n const persistedWorkspace = activeWorkspaceIdRef.current\n ? ws.find(\n (workspace) =>\n workspace.id === activeWorkspaceIdRef.current,\n )\n : null;\n\n if (persistedWorkspace) {\n store.setCurrentWorkspaceId(persistedWorkspace.id);\n } else if (ws.length > 0) {\n const nextActiveContext = {\n organizationId: targetOrgId,\n workspaceId: ws[0].id,\n tenantId: ws[0].tenantId,\n projectId: null,\n };\n\n if (activeWorkspaceIdRef.current) {\n // Stale-context guard: URL/persisted workspace ID is not in\n // the user's accessible workspaces for the active org. Fall\n // back to the first workspace and clear the stale URL param\n // so subsequent requests don't carry the ghost ID.\n store.setCurrentWorkspaceId(ws[0].id);\n store.setWorkspaceToken(null);\n setActiveContext(nextActiveContext);\n } else if (!store.currentWorkspaceId) {\n // Auto-select first workspace only if none is currently selected\n // (preserves selection from completeAuthFlow or persistence if applicable)\n store.setCurrentWorkspaceId(ws[0].id);\n setActiveContext(nextActiveContext);\n }\n }\n }\n } catch {\n // Non-critical for THIS call (user can still select a workspace\n // manually) but worth a bounded background retry.\n setBootstrapFailureNonce((n) => n + 1);\n } finally {\n store.setLoadingWorkspaces(false);\n }\n }\n\n // Full bootstrap succeeded — re-arm the retry budget for the next\n // genuine failure.\n bootstrapRetryAttemptRef.current = 0;\n return effectiveOrganizations;\n } catch (err) {\n // Auth errors are expected during token refresh / page load cycles.\n // Suppress from console.error — the useEffect will re-trigger when the\n // auth provider refreshes the token. (A DEFINITIVELY dead session\n // never reaches here as an AuthError loop: graphqlFetch dispatches\n // SESSION_EXPIRED_EVENT and the shell force-logs-out.)\n if (err instanceof AuthError) {\n return [];\n }\n const message =\n err instanceof Error ? err.message : \"Failed to fetch organizations\";\n if (store.workspaces.length === 0) {\n console.error(\"Failed to fetch organizations:\", err);\n }\n setError(message);\n setBootstrapFailureNonce((n) => n + 1);\n\n if (store.workspaces.length > 0) {\n const fallbackOrganizations = buildFallbackOrganizations(\n store.workspaces,\n );\n if (fallbackOrganizations.length > 0) {\n store.setOrganizations(fallbackOrganizations);\n if (!store.currentOrganizationId) {\n store.setCurrentOrganizationId(fallbackOrganizations[0].id);\n }\n return fallbackOrganizations;\n }\n }\n\n return [];\n } finally {\n store.setLoadingOrganizations(false);\n fetchOrganizationsPromiseRef.current = null;\n }\n })();\n\n return fetchOrganizationsPromiseRef.current;\n }, [globalBaseUrl, setActiveContext]);\n\n // ===========================================================================\n // Bootstrap retry (transient-failure self-heal)\n // ===========================================================================\n //\n // A transient backend failure during bootstrap (cold service, gateway blip,\n // Valkey/pg hiccup) used to leave the switcher empty for the whole session —\n // the shell's Header effect only re-fires on accessToken change, so nothing\n // ever retried. Retry with exponential backoff, bounded so a genuinely down\n // backend does not hammer: 1.5s, 3s, 6s, 12s, 12s (max 5 attempts, re-armed\n // by any subsequent successful bootstrap).\n useEffect(() => {\n if (disableBootstrap) return undefined;\n if (bootstrapFailureNonce === 0) return undefined;\n if (bootstrapRetryAttemptRef.current >= 5) return undefined;\n if (!resolveAccessToken()) return undefined;\n bootstrapRetryAttemptRef.current += 1;\n const delayMs = Math.min(\n 1500 * 2 ** (bootstrapRetryAttemptRef.current - 1),\n 12000,\n );\n const timer = window.setTimeout(() => {\n void fetchOrganizations();\n }, delayMs);\n return () => {\n window.clearTimeout(timer);\n };\n }, [disableBootstrap, bootstrapFailureNonce, fetchOrganizations]);\n\n // Connectivity recovery: if the browser reports we are back online and the\n // switcher is still empty, re-run the bootstrap immediately with a fresh\n // retry budget.\n useEffect(() => {\n if (disableBootstrap) return undefined;\n const onOnline = () => {\n if (\n useAuthStore.getState().organizations.length === 0 &&\n resolveAccessToken()\n ) {\n bootstrapRetryAttemptRef.current = 0;\n void fetchOrganizations();\n }\n };\n window.addEventListener(\"online\", onOnline);\n return () => {\n window.removeEventListener(\"online\", onOnline);\n };\n }, [disableBootstrap, fetchOrganizations]);\n\n // ===========================================================================\n // Fetch Workspaces for Organization (Global Gateway)\n // ===========================================================================\n\n const fetchWorkspacesForOrg = useCallback(\n async (organizationId: string): Promise<Workspace[]> => {\n const store = useAuthStore.getState();\n const token = resolveAccessToken();\n const profileId = resolveActiveProfileId();\n const userId = store.user?.id;\n // Account-scoped in-memory deduplication; this key is never persisted or logged.\n const requestKey = JSON.stringify([\n profileId,\n userId,\n token,\n organizationId,\n ]);\n const existingPromise =\n fetchWorkspacesPromisesRef.current.get(requestKey);\n if (existingPromise) return existingPromise;\n const currentSelection = () => {\n const current = useAuthStore.getState();\n return (\n resolveActiveProfileId() === profileId &&\n current.user?.id === userId &&\n resolveAccessToken() === token &&\n current.currentOrganizationId === organizationId\n );\n };\n\n // Only bail when there is NO token at all. An expired one is handled by\n // graphqlFetch's refresh-and-retry (or ends in the shell's forced\n // logout) — silently returning [] here masked expiry as an empty list.\n if (!token) {\n return [];\n }\n\n store.setLoadingWorkspaces(true);\n setError(null);\n\n // Store the promise for deduplication before starting\n const fetchPromise = (async () => {\n try {\n const result = await graphqlFetch<WorkspacesByOrgResponse>({\n gateway: \"global\",\n query: WORKSPACES_BY_ORG_QUERY,\n authToken: token,\n baseUrl: globalBaseUrl,\n });\n if (!currentSelection()) return [];\n // myWorkspaces returns workspaces across all the user's orgs;\n // filter to the requested org before handing to downstream.\n if (result.data?.workspaces?.items) {\n result.data.workspaces.items = result.data.workspaces.items.filter(\n (w) => w.organizationId === organizationId,\n );\n }\n\n if (result.errors?.length) {\n const errorMessage = result.errors[0]?.message ?? \"GraphQL error\";\n if (isAuthGraphQLError(result.errors)) {\n throw new AuthError(errorMessage);\n }\n console.error(\"Failed to fetch workspaces:\", result.errors);\n throw new Error(errorMessage);\n }\n\n // `myWorkspaces` returns every workspace the caller can see across\n // all of their orgs/tenants. The store key is per-org (selecting\n // org X then opening the dropdown should only show X's workspaces),\n // so we filter down to the requested org here. The dropdown filter\n // in ContextSwitcher.tsx is a defence-in-depth — without this\n // narrowing the store would briefly hold the caller's other-org\n // workspaces and the auto-pick logic (lines below) might select\n // one of them as the default.\n const allWs: Workspace[] = result.data?.workspaces?.items ?? [];\n const ws = allWs.filter((w) => w.organizationId === organizationId);\n store.setWorkspaces(ws);\n return ws;\n } catch (err) {\n if (!currentSelection() || err instanceof AuthError) {\n return [];\n }\n const message =\n err instanceof Error ? err.message : \"Failed to fetch workspaces\";\n console.error(\"Failed to fetch workspaces:\", err);\n setError(message);\n return [];\n } finally {\n if (currentSelection()) store.setLoadingWorkspaces(false);\n fetchWorkspacesPromisesRef.current.delete(requestKey);\n }\n })();\n\n fetchWorkspacesPromisesRef.current.set(requestKey, fetchPromise);\n return fetchPromise;\n },\n [globalBaseUrl],\n );\n\n // ===========================================================================\n // Issue Workspace Token (Workspace Gateway - wspace-auth-svc)\n // ===========================================================================\n\n const issueWorkspaceToken = useCallback(\n async (\n organizationId: string,\n workspaceId?: string,\n projectId?: string | null,\n // Target workspace's tenant. Sent as x-tenant-id so the token service can\n // resolve the tenant for a super_admin switching into a workspace not\n // mirrored into the wspace layer (whose access token carries no tenant\n // claim). Regular members resolve their tenant via membership regardless.\n tenantId?: string,\n ): Promise<{\n success: boolean;\n token?: string;\n resolvedWorkspaceId?: string;\n error?: string;\n }> => {\n const store = useAuthStore.getState();\n const originalScope = [\n store.currentOrganizationId,\n store.currentWorkspaceId,\n store.currentProjectId,\n ];\n const workspaceWide = isWorkspaceWideSelection({\n organizationId,\n workspaceId: workspaceId ?? null,\n });\n const authToken = resolveAccessToken();\n const profileId = resolveActiveProfileId();\n const userId = store.user?.id;\n\n // Expired tokens flow through: graphqlFetch refreshes and retries once.\n if (!authToken) {\n return { success: false, error: \"No valid access token available\" };\n }\n\n setError(null);\n\n try {\n const result = await graphqlFetch<{\n issueWorkspaceToken: IssueWorkspaceTokenResult;\n }>({\n gateway: \"workspace\",\n query: ISSUE_WORKSPACE_TOKEN_MUTATION,\n variables: {\n input: {\n organizationId,\n ...(workspaceId && { workspaceId }),\n ...(projectId && { projectId }),\n },\n },\n authToken,\n baseUrl: workspaceBaseUrl,\n tenantId,\n // This is a bootstrap for the requested context, not an operation in\n // the previously active workspace. The gateway/token owner still\n // validates the actor's actual target membership and organization.\n workspaceId,\n organizationId,\n projectId: projectId ?? undefined,\n workspaceToken: false,\n });\n\n if (result.errors?.length) {\n const errorMessage = result.errors[0]?.message ?? \"GraphQL error\";\n if (!isAuthGraphQLError(result.errors)) {\n console.error(\"Failed to issue workspace token:\", result.errors);\n }\n return { success: false, error: errorMessage };\n }\n\n const tokenResult = result.data?.issueWorkspaceToken;\n\n if (tokenResult?.success && tokenResult.token) {\n const latest = useAuthStore.getState();\n if (\n resolveActiveProfileId() !== profileId ||\n useAuthStore.getState().user?.id !== userId ||\n resolveAccessToken() !== authToken ||\n originalScope.some(\n (value, index) =>\n value !==\n [\n latest.currentOrganizationId,\n latest.currentWorkspaceId,\n latest.currentProjectId,\n ][index],\n ) ||\n isWorkspaceWideSelection({\n organizationId,\n workspaceId: workspaceId ?? null,\n }) !== workspaceWide ||\n !isWorkspaceTokenValidForContext(tokenResult.token, {\n organizationId,\n workspaceId,\n projectId,\n workspaceWide,\n })\n ) {\n return {\n success: false,\n error: \"Workspace context changed during token issuance\",\n };\n }\n const resolvedWsId = tokenResult.workspaceId || workspaceId;\n if (resolvedWsId) {\n store.setCurrentWorkspaceId(resolvedWsId);\n }\n store.setWorkspaceToken(tokenResult.token);\n return {\n success: true,\n token: tokenResult.token,\n resolvedWorkspaceId: resolvedWsId || undefined,\n };\n }\n\n return {\n success: false,\n error:\n tokenResult?.error?.message ?? \"Failed to issue workspace token\",\n };\n } catch (err) {\n const message =\n err instanceof Error\n ? err.message\n : \"Failed to issue workspace token\";\n console.error(\"Failed to issue workspace token:\", err);\n setError(message);\n return { success: false, error: message };\n }\n },\n [workspaceBaseUrl],\n );\n\n // ===========================================================================\n // Fetch Projects (Workspace Gateway - requires workspace token)\n // ===========================================================================\n\n const fetchProjects = useCallback(async (): Promise<Project[]> => {\n const store = useAuthStore.getState();\n const authToken = resolveAccessToken();\n const wsToken = store.workspaceToken;\n const workspaceId = store.currentWorkspaceId;\n const profileId = resolveActiveProfileId();\n const userId = store.user?.id;\n const organizationId = store.currentOrganizationId;\n const projectId = store.currentProjectId;\n const wide = isWorkspaceWideSelection({ organizationId, workspaceId });\n const currentSelection = () => {\n const current = useAuthStore.getState();\n return (\n resolveActiveProfileId() === profileId &&\n current.user?.id === userId &&\n resolveAccessToken() === authToken &&\n current.workspaceToken === wsToken &&\n current.currentOrganizationId === organizationId &&\n current.currentWorkspaceId === workspaceId &&\n current.currentProjectId === projectId &&\n isWorkspaceWideSelection({ organizationId, workspaceId }) === wide\n );\n };\n\n // Expired tokens flow through: graphqlFetch refreshes and retries once.\n if (!authToken) {\n return [];\n }\n\n if (!wsToken) {\n return [];\n }\n\n if (!workspaceId) {\n return [];\n }\n\n store.setLoadingProjects(true);\n setError(null);\n\n try {\n const result = await graphqlFetch<ProjectsResponse>({\n gateway: \"workspace\",\n query: PROJECTS_QUERY,\n authToken,\n workspaceToken: wsToken,\n baseUrl: workspaceBaseUrl,\n });\n\n if (!currentSelection()) return [];\n\n if (result.errors?.length) {\n const errorMessage = result.errors[0]?.message ?? \"GraphQL error\";\n if (isAuthGraphQLError(result.errors)) {\n throw new AuthError(errorMessage);\n }\n console.error(\"Failed to fetch projects:\", result.errors);\n throw new Error(errorMessage);\n }\n\n const projs: Project[] = result.data?.projects?.items ?? [];\n store.setProjects(projs);\n return projs;\n } catch (err) {\n if (err instanceof AuthError) {\n return [];\n }\n const message =\n err instanceof Error ? err.message : \"Failed to fetch projects\";\n console.error(\"Failed to fetch projects:\", err);\n setError(message);\n return [];\n } finally {\n store.setLoadingProjects(false);\n }\n }, [workspaceBaseUrl]);\n\n // ===========================================================================\n // High-Level Selection Actions\n // ===========================================================================\n\n const selectOrganization = useCallback(\n async (org: Organization): Promise<Workspace[]> => {\n const store = useAuthStore.getState();\n\n // A deliberate switch answers any \"link not available\" notice.\n store.setContextLinkDenial(null);\n store.setCurrentWorkspaceId(null);\n store.setWorkspaceToken(null);\n store.setProjects([]);\n store.setCurrentProjectId(null);\n store.setCurrentOrganizationId(org.id);\n\n const ws = await fetchWorkspacesForOrg(org.id);\n return ws;\n },\n [fetchWorkspacesForOrg],\n );\n\n const selectWorkspace = useCallback(\n async (\n workspace: Workspace,\n ): Promise<{\n success: boolean;\n projects?: Project[];\n error?: string;\n }> => {\n const store = useAuthStore.getState();\n\n // A deliberate switch answers any \"link not available\" notice.\n store.setContextLinkDenial(null);\n store.setCurrentProjectId(null);\n store.setProjects([]);\n\n if (!workspace.organizationId) {\n console.error(\"Workspace missing organizationId:\", workspace);\n return {\n success: false,\n error: \"Workspace is missing organizationId\",\n };\n }\n\n const tokenResult = await issueWorkspaceToken(\n workspace.organizationId,\n workspace.id,\n undefined,\n workspace.tenantId,\n );\n\n if (!tokenResult.success) {\n return { success: false, error: tokenResult.error };\n }\n\n const selected = useAuthStore.getState();\n const profileId = resolveActiveProfileId();\n const userId = selected.user?.id;\n const accessToken = resolveAccessToken();\n const workspaceToken = selected.workspaceToken;\n const projectId = selected.currentProjectId;\n const wide = isWorkspaceWideSelection({\n organizationId: workspace.organizationId,\n workspaceId: workspace.id,\n });\n const currentSelection = () => {\n const current = useAuthStore.getState();\n return (\n resolveActiveProfileId() === profileId &&\n current.user?.id === userId &&\n resolveAccessToken() === accessToken &&\n current.workspaceToken === workspaceToken &&\n current.currentOrganizationId === workspace.organizationId &&\n current.currentWorkspaceId === workspace.id &&\n current.currentProjectId === projectId &&\n isWorkspaceWideSelection({\n organizationId: workspace.organizationId,\n workspaceId: workspace.id,\n }) === wide\n );\n };\n const projs = await fetchProjects();\n if (!currentSelection())\n return { success: false, error: \"Context changed during selection\" };\n\n if (\n projs.length > 0 &&\n !isWorkspaceWideSelection({\n organizationId: workspace.organizationId,\n workspaceId: workspace.id,\n })\n ) {\n store.setCurrentProjectId(projs[0]!.id);\n }\n\n return { success: true, projects: projs };\n },\n [issueWorkspaceToken, fetchProjects],\n );\n\n const selectProject = useCallback((project: Project): void => {\n const store = useAuthStore.getState();\n clearWorkspaceWideSelection({\n organizationId: store.currentOrganizationId,\n workspaceId: store.currentWorkspaceId,\n });\n store.setCurrentProjectId(project.id);\n if (\n store.workspaceToken &&\n !isWorkspaceTokenValidForContext(store.workspaceToken, {\n workspaceId: store.currentWorkspaceId,\n organizationId: store.currentOrganizationId,\n projectId: project.id,\n })\n ) {\n store.setWorkspaceToken(null);\n }\n }, []);\n\n const selectWorkspaceWide = useCallback((): void => {\n const store = useAuthStore.getState();\n const scope = {\n organizationId: activeOrganizationIdRef.current,\n workspaceId: activeWorkspaceIdRef.current,\n };\n if (\n !scope.organizationId ||\n !scope.workspaceId ||\n store.currentOrganizationId !== scope.organizationId ||\n store.currentWorkspaceId !== scope.workspaceId\n ) {\n throw new Error(\"Current workspace context required\");\n }\n if (!persistWorkspaceWideSelection(scope))\n throw new Error(\"Workspace-wide preference could not be saved\");\n store.setCurrentProjectId(null);\n store.setWorkspaceToken(null);\n setActiveContext({ projectId: null });\n }, [setActiveContext]);\n\n // ===========================================================================\n // Cross-MFE refresh: keep the switcher lists current when another MFE mutates\n // org/workspace/project entities. microfe-workspaces emits these domain events\n // on the shared event bus (e.g. on project rename); without this the switcher\n // keeps showing the stale cached name until a full page reload.\n // ===========================================================================\n\n useEffect(() => {\n let cancelled = false;\n\n // Coalesce a refetch into a single in-flight run with one trailing re-run,\n // so a burst of events collapses to one request (+ one trailing) instead of\n // fanning out or being swallowed by a downstream per-key dedupe. The flag is\n // cleared on cleanup so nothing fires after the subscription is torn down.\n const makeCoalescedRefetch = (run: () => Promise<unknown>) => {\n let running = false;\n let queued = false;\n const trigger = () => {\n if (cancelled) return;\n if (running) {\n queued = true;\n return;\n }\n running = true;\n void run().finally(() => {\n running = false;\n if (!cancelled && queued) {\n queued = false;\n trigger();\n }\n });\n };\n return trigger;\n };\n\n const refreshProjects = makeCoalescedRefetch(() => fetchProjects());\n const refreshWorkspaces = makeCoalescedRefetch(() => {\n const orgId = useAuthStore.getState().currentOrganizationId;\n return orgId ? fetchWorkspacesForOrg(orgId) : Promise.resolve();\n });\n\n // Custom domain events (not in BurdenoffEventName) flow through `onAny`.\n const unsubscribe = eventBus.onAny((event) => {\n // Custom event names aren't in the BurdenoffEventName union; compare as string.\n const eventName: string = event.name;\n\n if (PROJECT_REFRESH_EVENTS.has(eventName)) {\n if (disableProjectSync || skipProjectFetch) return;\n const eventWorkspaceId = readEventWorkspaceId(event.payload);\n const { currentWorkspaceId } = useAuthStore.getState();\n // Only refetch when the event targets the workspace currently in\n // context (events without a workspace id are treated as relevant).\n if (\n eventWorkspaceId &&\n currentWorkspaceId &&\n eventWorkspaceId !== currentWorkspaceId\n ) {\n return;\n }\n // Refetch only — a deleted project simply drops out of the list, and\n // `currentProject` resolves to undefined for it. Clearing the selection\n // here would race ActiveContext / the project sync effect (the real\n // source of truth), so we leave selection reconciliation to them.\n refreshProjects();\n return;\n }\n\n if (WORKSPACE_REFRESH_EVENTS.has(eventName)) {\n if (disableWorkspaceSync) return;\n refreshWorkspaces();\n }\n });\n\n return () => {\n cancelled = true;\n unsubscribe();\n };\n }, [\n eventBus,\n fetchProjects,\n fetchWorkspacesForOrg,\n disableWorkspaceSync,\n disableProjectSync,\n skipProjectFetch,\n ]);\n\n // ===========================================================================\n // Get Current Items\n // ===========================================================================\n\n const currentOrganization = organizations.find(\n (org) => org.id === currentOrganizationId,\n );\n const currentWorkspace = workspaces.find(\n (ws) => ws.id === currentWorkspaceId,\n );\n const currentProject = projects.find((proj) => proj.id === currentProjectId);\n\n // ===========================================================================\n // Return Hook API\n // ===========================================================================\n\n return {\n organizations,\n workspaces,\n projects,\n\n currentOrganizationId,\n currentWorkspaceId,\n currentProjectId,\n\n currentOrganization,\n currentWorkspace,\n currentProject,\n\n workspaceToken,\n\n isLoadingOrganizations,\n isLoadingWorkspaces,\n isLoadingProjects,\n isLoading:\n isLoadingOrganizations || isLoadingWorkspaces || isLoadingProjects,\n\n error,\n\n fetchOrganizations,\n fetchWorkspacesForOrg,\n issueWorkspaceToken,\n fetchProjects,\n\n selectOrganization,\n selectWorkspace,\n selectProject,\n selectWorkspaceWide,\n };\n}\n\n/**\n * Hook to reactively ensure workspaces are synced with the current organization.\n *\n * This handles edge cases where the organization changes but workspaces\n * from a different org are still in the store (e.g., stale data, race conditions).\n *\n * Usage:\n * ```tsx\n * import { useWorkspaceSyncEffect } from '@burdenoff/microfe-auth';\n *\n * function MyComponent() {\n * useWorkspaceSyncEffect(); // Ensures workspaces stay in sync\n * // ...\n * }\n * ```\n */\nexport function useWorkspaceSyncEffect(\n options?: UseContextSwitcherDataOptions,\n) {\n const currentOrganizationId = useAuthStore(\n (state) => state.currentOrganizationId,\n );\n const workspaces = useAuthStore((state) => state.workspaces);\n const accessToken = useAuthStore((state) => state.accessToken);\n const isLoadingWorkspaces = useAuthStore(\n (state) => state.isLoadingWorkspaces,\n );\n const resolvedBaseUrls = resolveGatewayBaseUrls();\n const globalBaseUrl =\n options?.globalBaseUrl ?? resolvedBaseUrls.globalBaseUrl;\n const disableWorkspaceSync = options?.disableWorkspaceSync ?? false;\n\n useEffect(() => {\n if (disableWorkspaceSync) return;\n // Skip if no org selected, no token, or already loading\n if (!currentOrganizationId || !accessToken || isLoadingWorkspaces) return;\n\n // Check if any workspace matches the current org\n const hasMatchingWorkspaces = workspaces.some(\n (ws) => ws.organizationId === currentOrganizationId,\n );\n\n // If workspaces exist but none match current org, we need to refetch\n // This can happen in edge cases with stale data or race conditions\n if (workspaces.length > 0 && !hasMatchingWorkspaces) {\n const store = useAuthStore.getState();\n store.setLoadingWorkspaces(true);\n\n // Inline fetch to avoid circular dependency with useContextSwitcherData\n graphqlFetch<WorkspacesByOrgResponse>({\n gateway: \"global\",\n query: WORKSPACES_BY_ORG_QUERY,\n authToken: accessToken,\n baseUrl: globalBaseUrl,\n })\n .then((result) => {\n // myWorkspaces returns ALL my workspaces; filter to current org\n // client-side (the old server-side filter no longer exists).\n if (result.data?.workspaces?.items) {\n result.data.workspaces.items = result.data.workspaces.items.filter(\n (w) => w.organizationId === currentOrganizationId,\n );\n }\n if (!result.errors?.length) {\n const allWs: Workspace[] = result.data?.workspaces?.items ?? [];\n // Same per-org narrowing as fetchWorkspacesForOrg — see the\n // comment there for why we don't just dump the full caller-\n // visible list into the store.\n const ws = allWs.filter(\n (w) => w.organizationId === currentOrganizationId,\n );\n store.setWorkspaces(ws);\n }\n })\n .catch(() => {\n // Silent fail - user can manually refresh or select org again\n })\n .finally(() => {\n store.setLoadingWorkspaces(false);\n });\n }\n }, [\n currentOrganizationId,\n workspaces,\n accessToken,\n isLoadingWorkspaces,\n globalBaseUrl,\n disableWorkspaceSync,\n ]);\n}\n\n/**\n * Hook to reactively ensure projects are loaded when a workspace is selected.\n *\n * This handles the case where a workspace is auto-selected (from URL/localStorage)\n * but projects haven't been fetched yet. It will:\n * 1. Issue a workspace token if not present\n * 2. Fetch projects for the selected workspace\n *\n * Usage:\n * ```tsx\n * import { useProjectSyncEffect } from '@burdenoff/microfe-auth';\n *\n * function MyComponent() {\n * useProjectSyncEffect(); // Ensures projects are loaded for selected workspace\n * // ...\n * }\n * ```\n */\nexport function useProjectSyncEffect(options?: UseContextSwitcherDataOptions) {\n const currentWorkspaceId = useAuthStore((state) => state.currentWorkspaceId);\n const currentOrganizationId = useAuthStore(\n (state) => state.currentOrganizationId,\n );\n const workspaces = useAuthStore((state) => state.workspaces);\n const projects = useAuthStore((state) => state.projects);\n const currentProjectId = useAuthStore((state) => state.currentProjectId);\n const workspaceToken = useAuthStore((state) => state.workspaceToken);\n const accessToken = useAuthStore((state) => state.accessToken);\n const { setContext: setActiveContext } = useActiveContext();\n const resolvedBaseUrls = resolveGatewayBaseUrls();\n const workspaceBaseUrl =\n options?.workspaceBaseUrl ?? resolvedBaseUrls.workspaceBaseUrl;\n const disableProjectSync = options?.disableProjectSync ?? false;\n const skipProjectFetch = options?.skipProjectFetch ?? false;\n\n // Use refs to prevent the infinite loop caused by including loading/failure\n // state in the dependency array. Without these, the cycle is:\n // setLoadingProjects(true) -> dep change -> effect re-runs (guarded) ->\n // async completes -> setLoadingProjects(false) -> dep change ->\n // effect re-runs -> starts again -> INFINITE LOOP\n const syncInProgressRef = useRef(false);\n const [syncRevision, setSyncRevision] = useState(0);\n const emptyProjectsResultRef = useRef<{\n scopeKey: string;\n projects: Project[];\n } | null>(null);\n // Pending retry timer per workspace, so transient failures (e.g. RBAC lag\n // right after workspace creation) get an automatic second chance even if no\n // dependency change re-triggers the effect.\n const retryTimerRef = useRef<Map<string, ReturnType<typeof setTimeout>>>(\n new Map(),\n );\n // Per-workspace failure tracker — caps retry attempts when project bootstrap\n // (token issue or list) fails. An empty authorized project list is a valid\n // workspace-only context, not a provisioning failure.\n //\n // We track both count AND lastFailureAt so we can honour a \"cool-down\" window:\n // after PROJECT_SYNC_FAILURE_COOLDOWN_MS has elapsed since the last failure,\n // the counter is treated as cleared so transient backend hiccups (e.g. RBAC\n // role propagation lag right after signup) don't permanently lock a workspace\n // out of the context dropdown — the original cause of marqueue §729.\n const projectSyncFailuresRef = useRef<\n Map<string, { count: number; lastFailureAt: number }>\n >(new Map());\n const PROJECT_SYNC_MAX_FAILURES = 8;\n const PROJECT_SYNC_FAILURE_COOLDOWN_MS = 30_000;\n useEffect(() => {\n if (disableProjectSync) return;\n // Skip if no workspace selected or no access token\n if (!currentWorkspaceId || !accessToken) return;\n\n // Skip if a sync is already in progress (ref-based guard avoids dep loop)\n if (syncInProgressRef.current) return;\n\n // Stop retrying once this workspace has failed too many times in a row.\n // Counter is reset on success, on workspace switch (different key), by\n // an explicit user retry path (e.g. selectWorkspace), or after the\n // cool-down window has elapsed since the last failure (so transient\n // backend issues don't permanently wedge the dropdown).\n const failureEntry = projectSyncFailuresRef.current.get(currentWorkspaceId);\n if (\n failureEntry &&\n failureEntry.count >= PROJECT_SYNC_MAX_FAILURES &&\n Date.now() - failureEntry.lastFailureAt < PROJECT_SYNC_FAILURE_COOLDOWN_MS\n ) {\n return;\n }\n if (\n failureEntry &&\n Date.now() - failureEntry.lastFailureAt >=\n PROJECT_SYNC_FAILURE_COOLDOWN_MS\n ) {\n // Cool-down elapsed — clear the counter so we get a fresh budget.\n projectSyncFailuresRef.current.delete(currentWorkspaceId);\n }\n\n // Resolve organizationId: prefer the workspace object (if loaded), fall\n // back to the persisted currentOrganizationId. The workspaces array is\n // NOT persisted by zustand, so on page reload it is empty until\n // fetchOrganizations() completes. Using the persisted org ID lets us\n // issue the workspace token immediately instead of waiting.\n const currentWorkspace = workspaces.find(\n (ws) => ws.id === currentWorkspaceId,\n );\n\n // Guard: transient (newOrg, oldWs) divergence during org switches — token issuance always fails.\n if (\n currentWorkspace &&\n currentOrganizationId &&\n currentWorkspace.organizationId !== currentOrganizationId\n ) {\n return;\n }\n\n const organizationId =\n currentWorkspace?.organizationId ?? currentOrganizationId;\n if (!organizationId) return;\n\n const store = useAuthStore.getState();\n if (\n currentProjectId &&\n getUrlParam(\"project\") === currentProjectId &&\n getUrlParam(\"workspace\") === currentWorkspaceId &&\n getUrlParam(\"org\") === organizationId\n ) {\n clearWorkspaceWideSelection({\n organizationId,\n workspaceId: currentWorkspaceId,\n });\n }\n const profileId = resolveActiveProfileId();\n const userId = store.user?.id;\n const workspaceWide = isWorkspaceWideSelection({\n organizationId,\n workspaceId: currentWorkspaceId,\n });\n if (workspaceWide && store.currentProjectId) {\n store.setCurrentProjectId(null);\n store.setWorkspaceToken(null);\n return;\n }\n\n // If we don't have a workspace token or it's expired, issue one first\n const needsToken =\n !workspaceToken ||\n isTokenExpired(workspaceToken) ||\n !isWorkspaceTokenValidForContext(workspaceToken, {\n workspaceId: currentWorkspaceId,\n organizationId: currentOrganizationId,\n projectId: currentProjectId,\n workspaceWide,\n });\n\n // Skip if projects are already loaded for this workspace AND token is valid\n const scopeKey = JSON.stringify([\n profileId,\n userId,\n accessToken,\n organizationId,\n currentWorkspaceId,\n ]);\n const hasProjectsForWorkspace =\n projects.some((p) => p.workspaceId === currentWorkspaceId) ||\n (emptyProjectsResultRef.current?.scopeKey === scopeKey &&\n emptyProjectsResultRef.current.projects === projects);\n if (hasProjectsForWorkspace && !needsToken) {\n if (!store.currentProjectId && !workspaceWide) {\n const firstProject = projects.find(\n (project) => project.workspaceId === currentWorkspaceId,\n );\n if (firstProject) {\n store.setCurrentProjectId(firstProject.id);\n }\n }\n return;\n }\n\n const contextStillCurrent = () => {\n const latest = useAuthStore.getState();\n return (\n latest.accessToken === accessToken &&\n latest.user?.id === userId &&\n resolveActiveProfileId() === profileId &&\n latest.currentOrganizationId === organizationId &&\n latest.currentWorkspaceId === currentWorkspaceId &&\n latest.currentProjectId === currentProjectId &&\n isWorkspaceWideSelection({\n organizationId,\n workspaceId: currentWorkspaceId,\n }) === workspaceWide\n );\n };\n\n const syncProjects = async () => {\n syncInProgressRef.current = true;\n store.setLoadingProjects(true);\n let succeeded = false;\n\n try {\n let wsToken = workspaceToken;\n\n // Issue workspace token if needed\n if (needsToken) {\n const tokenResult = await graphqlFetch<{\n issueWorkspaceToken: IssueWorkspaceTokenResult;\n }>({\n gateway: \"workspace\",\n query: ISSUE_WORKSPACE_TOKEN_MUTATION,\n variables: {\n input: {\n organizationId,\n workspaceId: currentWorkspaceId,\n ...(currentProjectId ? { projectId: currentProjectId } : {}),\n },\n },\n authToken: accessToken,\n baseUrl: workspaceBaseUrl,\n // See issueWorkspaceToken: send the current workspace's tenant so a\n // super_admin (no tenant claim) can resolve it for an unmirrored ws.\n tenantId: workspaces.find((ws) => ws.id === currentWorkspaceId)\n ?.tenantId,\n });\n\n if (\n tokenResult.data?.issueWorkspaceToken?.success &&\n tokenResult.data.issueWorkspaceToken.token\n ) {\n wsToken = tokenResult.data.issueWorkspaceToken.token;\n if (\n !contextStillCurrent() ||\n !isWorkspaceTokenValidForContext(wsToken, {\n workspaceId: currentWorkspaceId,\n organizationId,\n projectId: currentProjectId,\n workspaceWide,\n })\n )\n return;\n store.setWorkspaceToken(wsToken);\n } else {\n // A restored project the caller is no longer a member of (or that\n // was deleted) can never yield a token, and without a token the\n // project list below is never re-read to discard it. Drop the\n // project everywhere it is held so the next run issues a\n // workspace-scoped token; leaving it in place locks the user out\n // of every workspace-token page (BOFF-10431).\n if (\n currentProjectId &&\n contextStillCurrent() &&\n isUnusableProjectTokenError(\n tokenResult.data?.issueWorkspaceToken?.error?.code,\n )\n ) {\n store.setCurrentProjectId(null);\n store.setWorkspaceToken(null);\n setActiveContext({ projectId: null });\n }\n return;\n }\n }\n\n // Fetch projects (skip if already loaded or token-only sync requested)\n if (wsToken && !hasProjectsForWorkspace && !skipProjectFetch) {\n const projectsResult = await graphqlFetch<ProjectsResponse>({\n gateway: \"workspace\",\n query: PROJECTS_QUERY,\n authToken: accessToken,\n workspaceToken: wsToken,\n baseUrl: workspaceBaseUrl,\n });\n\n if (!contextStillCurrent() || projectsResult.errors?.length) {\n return;\n }\n\n const projs: Project[] = projectsResult.data?.projects?.items ?? [];\n // myProjects lists accessible projects. An empty result does not\n // authorize creating one. Remember this result to avoid a render/\n // fetch loop; changing account or clearing the list invalidates it.\n emptyProjectsResultRef.current =\n projs.length === 0 ? { scopeKey, projects: projs } : null;\n store.setProjects(projs);\n\n // A restored/deep-linked project may have been removed or revoked.\n // Discard its token so the next sync establishes the current scope.\n if (\n currentProjectId &&\n !projs.some((project) => project.id === currentProjectId)\n ) {\n store.setCurrentProjectId(null);\n store.setWorkspaceToken(null);\n }\n\n // Auto-select first project if none selected and projects exist\n if (\n projs.length > 0 &&\n !useAuthStore.getState().currentProjectId &&\n !isWorkspaceWideSelection({\n organizationId,\n workspaceId: currentWorkspaceId,\n })\n ) {\n store.setCurrentProjectId(projs[0].id);\n }\n }\n\n succeeded = true;\n } catch {\n // A later auth/context update should be able to retry.\n } finally {\n store.setLoadingProjects(false);\n syncInProgressRef.current = false;\n const scopeCurrent = contextStillCurrent();\n if (!scopeCurrent) setSyncRevision((revision) => revision + 1);\n const failures = projectSyncFailuresRef.current;\n if (scopeCurrent && succeeded) {\n failures.delete(currentWorkspaceId);\n const pending = retryTimerRef.current.get(currentWorkspaceId);\n if (pending) {\n clearTimeout(pending);\n retryTimerRef.current.delete(currentWorkspaceId);\n }\n } else if (scopeCurrent) {\n const existing = failures.get(currentWorkspaceId);\n const nextCount = (existing?.count ?? 0) + 1;\n failures.set(currentWorkspaceId, {\n count: nextCount,\n lastFailureAt: Date.now(),\n });\n // Schedule a backoff retry for transient backend lag (e.g. RBAC\n // role propagation right after signup → first projects() call hits\n // permission-denied). Without this, the effect would only re-run on\n // dep change and the user would be stuck staring at an empty\n // project dropdown until something else triggered a re-render.\n if (nextCount < PROJECT_SYNC_MAX_FAILURES) {\n const existingTimer = retryTimerRef.current.get(currentWorkspaceId);\n if (existingTimer) clearTimeout(existingTimer);\n const backoffMs = Math.min(1000 * 2 ** (nextCount - 1), 8000);\n const timer = setTimeout(() => {\n retryTimerRef.current.delete(currentWorkspaceId);\n // Only re-run if the workspace context is still the same and\n // a project hasn't been loaded for it in the meantime.\n const latest = useAuthStore.getState();\n if (\n contextStillCurrent() &&\n latest.currentWorkspaceId === currentWorkspaceId &&\n !latest.projects.some(\n (p) => p.workspaceId === currentWorkspaceId,\n ) &&\n !syncInProgressRef.current\n ) {\n // Bump a render by clearing then resetting workspaceToken\n // when valid, OR by re-issuing projects fetch directly. The\n // simplest robust trigger is to clear the in-progress guard\n // and call syncProjects() again with current closure values.\n void syncProjects();\n }\n }, backoffMs);\n retryTimerRef.current.set(currentWorkspaceId, timer);\n }\n }\n }\n };\n\n syncProjects();\n }, [\n syncRevision,\n currentWorkspaceId,\n currentOrganizationId,\n workspaces,\n projects,\n currentProjectId,\n workspaceToken,\n accessToken,\n workspaceBaseUrl,\n disableProjectSync,\n skipProjectFetch,\n setActiveContext,\n ]);\n\n // Cleanup any pending retry timers on unmount so we don't leak stray\n // setTimeout callbacks running against stale closures.\n useEffect(() => {\n const timers = retryTimerRef.current;\n return () => {\n timers.forEach((timer) => clearTimeout(timer));\n timers.clear();\n };\n }, []);\n}\n// hmr-bust-1778064429\n"],"mappings":";;;;;;;;;;;AA6FA,IAAME,IAAyB,2RAoCzBC,IAA0B,oSAsB1BC,IAA2B,oVA0B3BC,oBAAqD,IAAI,IAAI,CACjE,sBACA,mBACF,CAAC;AAED,SAASC,EAA4B,GAA0C;CAC7E,OAAO,CAAC,CAACC,KAAQF,EAA8B,IAAIE,CAAI;AACzD;AAEA,IAAMC,IAAuB,KAEvBC,IAAuB,IAEvBC,KAAiC,6SA0BjCC,KAAiB;AA0BvB,SAASC,EAAe,GAAe,IAAW,KAAiB;CACjE,IAAI;EACF,IAAMC,IAAU,KAAK,MAAM,KAAKC,EAAM,MAAM,GAAG,CAAC,CAAC,EAAE,CAAC;EAEpD,OADKD,EAAQ,MACNA,EAAQ,MAAM,MAAO,KAAK,IAAI,IAAIE,IADhB;CAE3B,QAAQ;EACN,OAAO;CACT;AACF;AAEA,SAASC,EAAyB,GAKzB;CACP,IAAI;EACF,IAAMH,IAAU,KAAK,MAAM,KAAKC,EAAM,MAAM,GAAG,CAAC,CAAC,EAAE,CAAC;EACpD,OAAO;GACL,aACE,OAAOD,EAAQ,eAAgB,WAC3BA,EAAQ,cACR,KAAA;GACN,gBACE,OAAOA,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H;EACAF;EACAxB;EACA6B;EACAC;EACAH;EACA2F;EACAvE;EACAnC;EACAC;EACAK;CACF,CAAC,GAIDuE,QAAgB;EACd,IAAM6E,IAASrB,EAAc;EAC7B,aAAa;GAEX,AADAqB,EAAO,SAAS,MAAU,aAAa3E,CAAK,CAAC,GAC7C2E,EAAO,MAAM;EACf;CACF,GAAG,CAAC,CAAC;AACP"}
|
package/dist/shell.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shell integration without importing auth routes/pages. Re-export the same
|
|
3
|
+
* modules as the root entry: no second store and no asynchronous logout cleanup.
|
|
4
|
+
*/
|
|
5
|
+
export { useAuthStore } from './auth/store/authStore';
|
|
6
|
+
export { useContextSwitcherData, useWorkspaceSyncEffect, useProjectSyncEffect, } from './auth/hooks/useContextSwitcherData';
|
|
7
|
+
export type { UseContextSwitcherDataOptions } from './auth/hooks/useContextSwitcherData';
|
package/dist/shell.js
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { useAuthStore as e } from "./auth/store/authStore.js";
|
|
2
|
+
import { useContextSwitcherData as t, useProjectSyncEffect as n, useWorkspaceSyncEffect as r } from "./auth/hooks/useContextSwitcherData.js";
|
|
3
|
+
export { e as useAuthStore, t as useContextSwitcherData, n as useProjectSyncEffect, r as useWorkspaceSyncEffect };
|
package/dist/store.d.ts
ADDED
package/dist/store.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { useAuthStore } from "./auth/store/authStore.js";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@burdenoff/microfe-auth",
|
|
3
|
-
"version": "2026.1101.
|
|
3
|
+
"version": "2026.1101.3",
|
|
4
4
|
"description": "Auth microfrontend for Burdenoff products",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"imports": {
|
|
@@ -11,6 +11,14 @@
|
|
|
11
11
|
".": {
|
|
12
12
|
"types": "./dist/index.d.ts",
|
|
13
13
|
"import": "./dist/index.js"
|
|
14
|
+
},
|
|
15
|
+
"./store": {
|
|
16
|
+
"types": "./dist/store.d.ts",
|
|
17
|
+
"import": "./dist/store.js"
|
|
18
|
+
},
|
|
19
|
+
"./shell": {
|
|
20
|
+
"types": "./dist/shell.d.ts",
|
|
21
|
+
"import": "./dist/shell.js"
|
|
14
22
|
}
|
|
15
23
|
},
|
|
16
24
|
"main": "./dist/index.js",
|
|
@@ -22,7 +30,7 @@
|
|
|
22
30
|
],
|
|
23
31
|
"scripts": {
|
|
24
32
|
"dev": "vite",
|
|
25
|
-
"build": "tsc && bash scripts/build-limits.sh --gate vite build && bun scripts/verify-dts.ts && bun scripts/verify-css.ts && bun scripts/verify-packed-imports.ts",
|
|
33
|
+
"build": "tsc && bash scripts/build-limits.sh --gate vite build && bun scripts/verify-dts.ts && bun scripts/verify-css.ts && bun scripts/verify-packed-imports.ts && bun scripts/verify-shell-exports.ts",
|
|
26
34
|
"build:fast": "MFE_DTS=0 bash scripts/build-limits.sh --gate vite build",
|
|
27
35
|
"verify:dts": "bun scripts/verify-dts.ts",
|
|
28
36
|
"verify:css": "bun scripts/verify-css.ts",
|
|
@@ -47,7 +55,7 @@
|
|
|
47
55
|
"switch:check": "bun scripts/deps-mode.ts check",
|
|
48
56
|
"prepare": "lefthook install || true",
|
|
49
57
|
"format:check": "prettier --check \"src/**/*.{ts,tsx}\"",
|
|
50
|
-
"test:tooling": "bun test scripts/codegen.test.ts scripts/packaged-imports.test.ts"
|
|
58
|
+
"test:tooling": "bun test scripts/codegen.test.ts scripts/packaged-imports.test.ts scripts/shell-exports.test.ts"
|
|
51
59
|
},
|
|
52
60
|
"dependencies": {
|
|
53
61
|
"@apollo/client": "^4.0.9",
|