@burdenoff/microfe-auth 2026.1005.1 → 2026.1013.1

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 CHANGED
@@ -7,6 +7,20 @@ 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
+ ## Workspace and project selection
11
+
12
+ The shared context switcher issues a workspace token and reads `myProjects` to
13
+ show projects accessible to the current actor. An empty list is a valid
14
+ workspace-only context: learners and other workspace members do not need
15
+ `create:project` permission to open a product. Switching or restoring context
16
+ never creates a project. Default project provisioning belongs to workspace
17
+ creation; deliberate project creation remains a separate authorized action.
18
+
19
+ An empty successful response is retained for the current account and workspace
20
+ to avoid repeated fetches. Changing accounts or resetting the project list
21
+ causes a fresh read. Existing projects may still be selected automatically
22
+ unless the user explicitly chose workspace-wide scope.
23
+
10
24
  ## License
11
25
 
12
26
  Proprietary — Copyright Burdenoff Consultancy Services Pvt. Ltd.
@@ -8,19 +8,8 @@ import { clearWorkspaceWideSelection as u, isWorkspaceWideSelection as d, select
8
8
  import { getUrlParam as p } from "@burdenoff/fe-libs/shared/providers/shell/ActiveContextStorage";
9
9
  import { useActiveContext as m } from "@burdenoff/fe-libs/shared/providers/shell/ActiveContextProvider";
10
10
  //#region src/auth/hooks/useContextSwitcherData.ts
11
- var h = "\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", g = "\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 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", v = "\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", y = "\n mutation CreateDefaultProject($input: CreateProjectInput!) {\n createProject(input: $input) {\n id\n name\n key\n workspaceId\n status\n archived\n createdAt\n updatedAt\n }\n }\n";
12
- async function b({ authToken: e, workspaceBaseUrl: t, workspaceToken: n }) {
13
- let r = await l({
14
- gateway: "workspace",
15
- query: y,
16
- variables: { input: { name: "Default Project" } },
17
- authToken: e,
18
- workspaceToken: n,
19
- baseUrl: t
20
- });
21
- return r.errors?.length ? (console.warn("Failed to create default project:", r.errors), null) : r.data?.createProject ?? null;
22
- }
23
- function x(e, t = 3e4) {
11
+ var h = "\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", g = "\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 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", v = "\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";
12
+ function y(e, t = 3e4) {
24
13
  try {
25
14
  let n = JSON.parse(atob(e.split(".")[1]));
26
15
  return n.exp ? n.exp * 1e3 < Date.now() + t : !1;
@@ -28,7 +17,7 @@ function x(e, t = 3e4) {
28
17
  return !0;
29
18
  }
30
19
  }
31
- function S(e) {
20
+ function b(e) {
32
21
  try {
33
22
  let t = JSON.parse(atob(e.split(".")[1]));
34
23
  return {
@@ -41,26 +30,26 @@ function S(e) {
41
30
  return null;
42
31
  }
43
32
  }
44
- function C(e, t) {
45
- if (!e || x(e)) return !1;
46
- let n = S(e);
33
+ function x(e, t) {
34
+ if (!e || y(e)) return !1;
35
+ let n = b(e);
47
36
  return !(!n || t.workspaceId && n.workspaceId !== t.workspaceId || t.organizationId && n.organizationId !== t.organizationId || t.workspaceWide && n.projectId || t.projectId && n.projectId !== t.projectId);
48
37
  }
49
- var w = class extends Error {
38
+ var S = class extends Error {
50
39
  constructor(e) {
51
40
  super(e), this.name = "AuthError";
52
41
  }
53
42
  };
54
- function T(e) {
43
+ function C(e) {
55
44
  return e.some((e) => e.extensions?.code === "UNAUTHENTICATED" || e.message?.toLowerCase().includes("unauthorized") || e.message?.toLowerCase().includes("not authenticated"));
56
45
  }
57
- function E() {
46
+ function w() {
58
47
  let t = e.getState().accessToken;
59
- if (t && !x(t)) return t;
48
+ if (t && !y(t)) return t;
60
49
  let n = c();
61
- return n && !x(n) ? n : t;
50
+ return n && !y(n) ? n : t;
62
51
  }
63
- function D(e) {
52
+ function T(e) {
64
53
  return Array.from(new Set(e.flatMap((e) => e.organizationId ? [e.organizationId] : []))).map((t, n) => ({
65
54
  id: t,
66
55
  name: e.find((e) => e.organizationId === t)?.name || `Organization ${n + 1}`,
@@ -68,56 +57,56 @@ function D(e) {
68
57
  tenantId: e.find((e) => e.organizationId === t)?.tenantId || ""
69
58
  }));
70
59
  }
71
- var O = new Set([
60
+ var E = new Set([
72
61
  "project.created",
73
62
  "project.updated",
74
63
  "project.deleted",
75
64
  "project.archived",
76
65
  "project.unarchived"
77
- ]), ee = new Set([
66
+ ]), D = new Set([
78
67
  "workspace.created",
79
68
  "workspace.updated",
80
69
  "workspace.deleted",
81
70
  "workspace.archived",
82
71
  "workspace.reactivated"
83
72
  ]);
84
- function k(e) {
73
+ function ee(e) {
85
74
  if (e && typeof e == "object" && "workspaceId" in e) {
86
75
  let t = e.workspaceId;
87
76
  return typeof t == "string" ? t : void 0;
88
77
  }
89
78
  }
90
- function A(c) {
91
- let { organizationId: p, workspaceId: y, projectId: x, setContext: S } = m(), A = s(), j = e((e) => e.organizations), M = e((e) => e.currentOrganizationId), N = e((e) => e.isLoadingOrganizations), P = e((e) => e.workspaces), F = e((e) => e.currentWorkspaceId), I = e((e) => e.workspaceToken), L = e((e) => e.isLoadingWorkspaces), te = e((e) => e.projects), R = e((e) => e.currentProjectId), z = e((e) => e.isLoadingProjects), [ne, B] = a(null), [V, H] = a(0), U = i(0), W = i(null), G = i(/* @__PURE__ */ new Map()), K = i(y), q = i(p);
79
+ function O(c) {
80
+ let { organizationId: p, workspaceId: y, projectId: b, setContext: O } = m(), k = s(), A = e((e) => e.organizations), j = e((e) => e.currentOrganizationId), M = e((e) => e.isLoadingOrganizations), N = e((e) => e.workspaces), P = e((e) => e.currentWorkspaceId), F = e((e) => e.workspaceToken), I = e((e) => e.isLoadingWorkspaces), L = e((e) => e.projects), R = e((e) => e.currentProjectId), z = e((e) => e.isLoadingProjects), [te, B] = a(null), [V, H] = a(0), U = i(0), W = i(null), G = i(/* @__PURE__ */ new Map()), K = i(y), q = i(p);
92
81
  r(() => {
93
82
  K.current = y, q.current = p;
94
83
  });
95
- let re = t(), J = c?.globalBaseUrl ?? re.globalBaseUrl, Y = c?.workspaceBaseUrl ?? re.workspaceBaseUrl, ie = i(null), ae = i(null), oe = i(null), se = i(null);
84
+ let ne = t(), J = c?.globalBaseUrl ?? ne.globalBaseUrl, Y = c?.workspaceBaseUrl ?? ne.workspaceBaseUrl, re = i(null), ie = i(null), ae = i(null), oe = i(null);
96
85
  r(() => {
97
86
  let t = e.getState();
98
- if (p && p !== t.currentOrganizationId && p !== ie.current && (ie.current = p, t.setCurrentOrganizationId(p), t.workspaces.length > 0 && !t.workspaces.some((e) => e.organizationId === p) && t.setWorkspaces([])), y && y !== t.currentWorkspaceId && y !== ae.current && (ae.current = y, t.setCurrentWorkspaceId(y), t.projects.length > 0 && !t.projects.some((e) => e.workspaceId === y) && (t.setProjects([]), t.setCurrentProjectId(null))), d({
87
+ if (p && p !== t.currentOrganizationId && p !== re.current && (re.current = p, t.setCurrentOrganizationId(p), t.workspaces.length > 0 && !t.workspaces.some((e) => e.organizationId === p) && t.setWorkspaces([])), y && y !== t.currentWorkspaceId && y !== ie.current && (ie.current = y, t.setCurrentWorkspaceId(y), t.projects.length > 0 && !t.projects.some((e) => e.workspaceId === y) && (t.setProjects([]), t.setCurrentProjectId(null))), d({
99
88
  organizationId: p,
100
89
  workspaceId: y
101
- }) && !x && t.currentProjectId && (t.setCurrentProjectId(null), t.setWorkspaceToken(null)), x && x !== t.currentProjectId && x !== oe.current && (oe.current = x, t.setCurrentProjectId(x)), t.workspaceToken && !C(t.workspaceToken, {
90
+ }) && !b && t.currentProjectId && (t.setCurrentProjectId(null), t.setWorkspaceToken(null)), b && b !== t.currentProjectId && b !== ae.current && (ae.current = b, t.setCurrentProjectId(b)), t.workspaceToken && !x(t.workspaceToken, {
102
91
  workspaceId: y,
103
92
  organizationId: p,
104
- projectId: x,
105
- workspaceWide: !x && d({
93
+ projectId: b,
94
+ workspaceWide: !b && d({
106
95
  organizationId: p,
107
96
  workspaceId: y
108
97
  })
109
98
  })) {
110
- let e = `${p ?? ""}|${y ?? ""}|${x ?? ""}`;
111
- se.current !== e && (se.current = e, t.setWorkspaceToken(null));
99
+ let e = `${p ?? ""}|${y ?? ""}|${b ?? ""}`;
100
+ oe.current !== e && (oe.current = e, t.setWorkspaceToken(null));
112
101
  }
113
102
  }, [
114
103
  p,
115
104
  y,
116
- x
105
+ b
117
106
  ]);
118
107
  let X = n(async () => {
119
108
  if (W.current) return W.current;
120
- let t = e.getState(), n = E();
109
+ let t = e.getState(), n = w();
121
110
  return n ? (t.setLoadingOrganizations(!0), B(null), W.current = (async () => {
122
111
  try {
123
112
  let r = q.current ?? t.currentOrganizationId, i = r ? await (async () => {
@@ -152,7 +141,7 @@ function A(c) {
152
141
  baseUrl: J
153
142
  })), i.errors?.length) {
154
143
  let e = i.errors[0]?.message ?? "GraphQL error";
155
- throw T(i.errors) ? new w(e) : (t.workspaces.length === 0 && console.error("Failed to fetch organizations:", i.errors), Error(e));
144
+ throw C(i.errors) ? new S(e) : (t.workspaces.length === 0 && console.error("Failed to fetch organizations:", i.errors), Error(e));
156
145
  }
157
146
  let a = i.data?.myOrganizations?.items ?? [];
158
147
  if (r && a.length === 0 && t.workspaces.length === 0) {
@@ -172,13 +161,13 @@ function A(c) {
172
161
  else {
173
162
  console.warn("[ContextSwitcher] Stale-context recovery failed:", e.errors);
174
163
  let t = e.errors?.[0]?.message ?? "Failed to fetch organizations";
175
- throw T(e.errors ?? []) ? new w(t) : Error(t);
164
+ throw C(e.errors ?? []) ? new S(t) : Error(t);
176
165
  }
177
166
  }
178
- let o = a.length === 0 && t.workspaces.length > 0 ? D(t.workspaces) : [], s = o.length > 0 ? o : a;
167
+ let o = a.length === 0 && t.workspaces.length > 0 ? T(t.workspaces) : [], s = o.length > 0 ? o : a;
179
168
  t.setOrganizations(s);
180
169
  let c = r, u = c && a.some((e) => e.id === c);
181
- if (c && !u && a.length > 0 && (c = a[0].id, S({
170
+ if (c && !u && a.length > 0 && (c = a[0].id, O({
182
171
  organizationId: c,
183
172
  workspaceId: null,
184
173
  tenantId: null,
@@ -203,7 +192,7 @@ function A(c) {
203
192
  tenantId: e[0].tenantId,
204
193
  projectId: null
205
194
  };
206
- K.current ? (t.setCurrentWorkspaceId(e[0].id), t.setWorkspaceToken(null), S(n)) : t.currentWorkspaceId || (t.setCurrentWorkspaceId(e[0].id), S(n));
195
+ K.current ? (t.setCurrentWorkspaceId(e[0].id), t.setWorkspaceToken(null), O(n)) : t.currentWorkspaceId || (t.setCurrentWorkspaceId(e[0].id), O(n));
207
196
  }
208
197
  }
209
198
  } catch {
@@ -214,10 +203,10 @@ function A(c) {
214
203
  }
215
204
  return U.current = 0, s;
216
205
  } catch (e) {
217
- if (e instanceof w) return [];
206
+ if (e instanceof S) return [];
218
207
  let n = e instanceof Error ? e.message : "Failed to fetch organizations";
219
208
  if (t.workspaces.length === 0 && console.error("Failed to fetch organizations:", e), B(n), H((e) => e + 1), t.workspaces.length > 0) {
220
- let e = D(t.workspaces);
209
+ let e = T(t.workspaces);
221
210
  if (e.length > 0) return t.setOrganizations(e), t.currentOrganizationId || t.setCurrentOrganizationId(e[0].id), e;
222
211
  }
223
212
  return [];
@@ -225,9 +214,9 @@ function A(c) {
225
214
  t.setLoadingOrganizations(!1), W.current = null;
226
215
  }
227
216
  })(), W.current) : [];
228
- }, [J, S]);
217
+ }, [J, O]);
229
218
  r(() => {
230
- if (V === 0 || U.current >= 5 || !E()) return;
219
+ if (V === 0 || U.current >= 5 || !w()) return;
231
220
  U.current += 1;
232
221
  let e = Math.min(1500 * 2 ** (U.current - 1), 12e3), t = window.setTimeout(() => {
233
222
  X();
@@ -237,14 +226,14 @@ function A(c) {
237
226
  };
238
227
  }, [V, X]), r(() => {
239
228
  let t = () => {
240
- e.getState().organizations.length === 0 && E() && (U.current = 0, X());
229
+ e.getState().organizations.length === 0 && w() && (U.current = 0, X());
241
230
  };
242
231
  return window.addEventListener("online", t), () => {
243
232
  window.removeEventListener("online", t);
244
233
  };
245
234
  }, [X]);
246
235
  let Z = n(async (t) => {
247
- let n = e.getState(), r = E(), i = o(), a = n.user?.id, s = JSON.stringify([
236
+ let n = e.getState(), r = w(), i = o(), a = n.user?.id, s = JSON.stringify([
248
237
  i,
249
238
  a,
250
239
  r,
@@ -253,7 +242,7 @@ function A(c) {
253
242
  if (c) return c;
254
243
  let u = () => {
255
244
  let n = e.getState();
256
- return o() === i && n.user?.id === a && E() === r && n.currentOrganizationId === t;
245
+ return o() === i && n.user?.id === a && w() === r && n.currentOrganizationId === t;
257
246
  };
258
247
  if (!r) return [];
259
248
  n.setLoadingWorkspaces(!0), B(null);
@@ -268,12 +257,12 @@ function A(c) {
268
257
  if (!u()) return [];
269
258
  if (e.data?.workspaces?.items && (e.data.workspaces.items = e.data.workspaces.items.filter((e) => e.organizationId === t)), e.errors?.length) {
270
259
  let t = e.errors[0]?.message ?? "GraphQL error";
271
- throw T(e.errors) ? new w(t) : (console.error("Failed to fetch workspaces:", e.errors), Error(t));
260
+ throw C(e.errors) ? new S(t) : (console.error("Failed to fetch workspaces:", e.errors), Error(t));
272
261
  }
273
262
  let i = (e.data?.workspaces?.items ?? []).filter((e) => e.organizationId === t);
274
263
  return n.setWorkspaces(i), i;
275
264
  } catch (e) {
276
- if (!u() || e instanceof w) return [];
265
+ if (!u() || e instanceof S) return [];
277
266
  let t = e instanceof Error ? e.message : "Failed to fetch workspaces";
278
267
  return console.error("Failed to fetch workspaces:", e), B(t), [];
279
268
  } finally {
@@ -289,7 +278,7 @@ function A(c) {
289
278
  ], c = d({
290
279
  organizationId: t,
291
280
  workspaceId: n ?? null
292
- }), u = E(), f = o(), p = a.user?.id;
281
+ }), u = w(), f = o(), p = a.user?.id;
293
282
  if (!u) return {
294
283
  success: !1,
295
284
  error: "No valid access token available"
@@ -310,7 +299,7 @@ function A(c) {
310
299
  });
311
300
  if (m.errors?.length) {
312
301
  let e = m.errors[0]?.message ?? "GraphQL error";
313
- return T(m.errors) || console.error("Failed to issue workspace token:", m.errors), {
302
+ return C(m.errors) || console.error("Failed to issue workspace token:", m.errors), {
314
303
  success: !1,
315
304
  error: e
316
305
  };
@@ -318,14 +307,14 @@ function A(c) {
318
307
  let h = m.data?.issueWorkspaceToken;
319
308
  if (h?.success && h.token) {
320
309
  let i = e.getState();
321
- if (o() !== f || e.getState().user?.id !== p || E() !== u || s.some((e, t) => e !== [
310
+ if (o() !== f || e.getState().user?.id !== p || w() !== u || s.some((e, t) => e !== [
322
311
  i.currentOrganizationId,
323
312
  i.currentWorkspaceId,
324
313
  i.currentProjectId
325
314
  ][t]) || d({
326
315
  organizationId: t,
327
316
  workspaceId: n ?? null
328
- }) !== c || !C(h.token, {
317
+ }) !== c || !x(h.token, {
329
318
  organizationId: t,
330
319
  workspaceId: n,
331
320
  projectId: r,
@@ -353,12 +342,12 @@ function A(c) {
353
342
  };
354
343
  }
355
344
  }, [Y]), $ = n(async () => {
356
- let t = e.getState(), n = E(), r = t.workspaceToken, i = t.currentWorkspaceId, a = o(), s = t.user?.id, c = t.currentOrganizationId, u = t.currentProjectId, f = d({
345
+ let t = e.getState(), n = w(), r = t.workspaceToken, i = t.currentWorkspaceId, a = o(), s = t.user?.id, c = t.currentOrganizationId, u = t.currentProjectId, f = d({
357
346
  organizationId: c,
358
347
  workspaceId: i
359
348
  }), p = () => {
360
349
  let t = e.getState();
361
- return o() === a && t.user?.id === s && E() === n && t.workspaceToken === r && t.currentOrganizationId === c && t.currentWorkspaceId === i && t.currentProjectId === u && d({
350
+ return o() === a && t.user?.id === s && w() === n && t.workspaceToken === r && t.currentOrganizationId === c && t.currentWorkspaceId === i && t.currentProjectId === u && d({
362
351
  organizationId: c,
363
352
  workspaceId: i
364
353
  }) === f;
@@ -376,21 +365,21 @@ function A(c) {
376
365
  if (!p()) return [];
377
366
  if (e.errors?.length) {
378
367
  let t = e.errors[0]?.message ?? "GraphQL error";
379
- throw T(e.errors) ? new w(t) : (console.error("Failed to fetch projects:", e.errors), Error(t));
368
+ throw C(e.errors) ? new S(t) : (console.error("Failed to fetch projects:", e.errors), Error(t));
380
369
  }
381
370
  let i = e.data?.projects?.items ?? [];
382
371
  return t.setProjects(i), i;
383
372
  } catch (e) {
384
- if (e instanceof w) return [];
373
+ if (e instanceof S) return [];
385
374
  let t = e instanceof Error ? e.message : "Failed to fetch projects";
386
375
  return console.error("Failed to fetch projects:", e), B(t), [];
387
376
  } finally {
388
377
  t.setLoadingProjects(!1);
389
378
  }
390
- }, [Y]), ce = n(async (t) => {
379
+ }, [Y]), se = n(async (t) => {
391
380
  let n = e.getState();
392
381
  return n.setCurrentWorkspaceId(null), n.setWorkspaceToken(null), n.setProjects([]), n.setCurrentProjectId(null), n.setCurrentOrganizationId(t.id), await Z(t.id);
393
- }, [Z]), le = n(async (t) => {
382
+ }, [Z]), ce = n(async (t) => {
394
383
  let n = e.getState();
395
384
  if (n.setCurrentProjectId(null), n.setProjects([]), !t.organizationId) return console.error("Workspace missing organizationId:", t), {
396
385
  success: !1,
@@ -401,68 +390,45 @@ function A(c) {
401
390
  success: !1,
402
391
  error: r.error
403
392
  };
404
- let i = e.getState(), a = o(), s = i.user?.id, c = E(), l = i.workspaceToken, u = i.currentProjectId, f = d({
393
+ let i = e.getState(), a = o(), s = i.user?.id, c = w(), l = i.workspaceToken, u = i.currentProjectId, f = d({
405
394
  organizationId: t.organizationId,
406
395
  workspaceId: t.id
407
396
  }), p = () => {
408
397
  let n = e.getState();
409
- return o() === a && n.user?.id === s && E() === c && n.workspaceToken === l && n.currentOrganizationId === t.organizationId && n.currentWorkspaceId === t.id && n.currentProjectId === u && d({
398
+ return o() === a && n.user?.id === s && w() === c && n.workspaceToken === l && n.currentOrganizationId === t.organizationId && n.currentWorkspaceId === t.id && n.currentProjectId === u && d({
410
399
  organizationId: t.organizationId,
411
400
  workspaceId: t.id
412
401
  }) === f;
413
402
  }, m = await $();
414
- if (!p()) return {
415
- success: !1,
416
- error: "Context changed during selection"
417
- };
418
- if (m.length === 0 && !d({
419
- organizationId: t.organizationId,
420
- workspaceId: t.id
421
- })) {
422
- let t = E(), r = e.getState().workspaceToken;
423
- if (t && r) {
424
- let e = await b({
425
- authToken: t,
426
- workspaceBaseUrl: Y,
427
- workspaceToken: r
428
- });
429
- if (!p()) return {
430
- success: !1,
431
- error: "Context changed during selection"
432
- };
433
- e && (m = [e], n.setProjects(m));
434
- }
435
- }
436
- return m.length > 0 && !d({
403
+ return p() ? (m.length > 0 && !d({
437
404
  organizationId: t.organizationId,
438
405
  workspaceId: t.id
439
406
  }) && n.setCurrentProjectId(m[0].id), {
440
407
  success: !0,
441
408
  projects: m
409
+ }) : {
410
+ success: !1,
411
+ error: "Context changed during selection"
442
412
  };
443
- }, [
444
- Q,
445
- $,
446
- Y
447
- ]), ue = n((t) => {
413
+ }, [Q, $]), le = n((t) => {
448
414
  let n = e.getState();
449
415
  u({
450
416
  organizationId: n.currentOrganizationId,
451
417
  workspaceId: n.currentWorkspaceId
452
- }), n.setCurrentProjectId(t.id), n.workspaceToken && !C(n.workspaceToken, {
418
+ }), n.setCurrentProjectId(t.id), n.workspaceToken && !x(n.workspaceToken, {
453
419
  workspaceId: n.currentWorkspaceId,
454
420
  organizationId: n.currentOrganizationId,
455
421
  projectId: t.id
456
422
  }) && n.setWorkspaceToken(null);
457
- }, []), de = n(() => {
423
+ }, []), ue = n(() => {
458
424
  let t = e.getState(), n = {
459
425
  organizationId: q.current,
460
426
  workspaceId: K.current
461
427
  };
462
428
  if (!n.organizationId || !n.workspaceId || t.currentOrganizationId !== n.organizationId || t.currentWorkspaceId !== n.workspaceId) throw Error("Current workspace context required");
463
429
  if (!f(n)) throw Error("Workspace-wide preference could not be saved");
464
- t.setCurrentProjectId(null), t.setWorkspaceToken(null), S({ projectId: null });
465
- }, [S]);
430
+ t.setCurrentProjectId(null), t.setWorkspaceToken(null), O({ projectId: null });
431
+ }, [O]);
466
432
  return r(() => {
467
433
  let t = !1, n = (e) => {
468
434
  let n = !1, r = !1, i = () => {
@@ -480,50 +446,50 @@ function A(c) {
480
446
  }, r = n(() => $()), i = n(() => {
481
447
  let t = e.getState().currentOrganizationId;
482
448
  return t ? Z(t) : Promise.resolve();
483
- }), a = A.onAny((t) => {
449
+ }), a = k.onAny((t) => {
484
450
  let n = t.name;
485
- if (O.has(n)) {
486
- let n = k(t.payload), { currentWorkspaceId: i } = e.getState();
451
+ if (E.has(n)) {
452
+ let n = ee(t.payload), { currentWorkspaceId: i } = e.getState();
487
453
  if (n && i && n !== i) return;
488
454
  r();
489
455
  return;
490
456
  }
491
- ee.has(n) && i();
457
+ D.has(n) && i();
492
458
  });
493
459
  return () => {
494
460
  t = !0, a();
495
461
  };
496
462
  }, [
497
- A,
463
+ k,
498
464
  $,
499
465
  Z
500
466
  ]), {
501
- organizations: j,
502
- workspaces: P,
503
- projects: te,
504
- currentOrganizationId: M,
505
- currentWorkspaceId: F,
467
+ organizations: A,
468
+ workspaces: N,
469
+ projects: L,
470
+ currentOrganizationId: j,
471
+ currentWorkspaceId: P,
506
472
  currentProjectId: R,
507
- currentOrganization: j.find((e) => e.id === M),
508
- currentWorkspace: P.find((e) => e.id === F),
509
- currentProject: te.find((e) => e.id === R),
510
- workspaceToken: I,
511
- isLoadingOrganizations: N,
512
- isLoadingWorkspaces: L,
473
+ currentOrganization: A.find((e) => e.id === j),
474
+ currentWorkspace: N.find((e) => e.id === P),
475
+ currentProject: L.find((e) => e.id === R),
476
+ workspaceToken: F,
477
+ isLoadingOrganizations: M,
478
+ isLoadingWorkspaces: I,
513
479
  isLoadingProjects: z,
514
- isLoading: N || L || z,
515
- error: ne,
480
+ isLoading: M || I || z,
481
+ error: te,
516
482
  fetchOrganizations: X,
517
483
  fetchWorkspacesForOrg: Z,
518
484
  issueWorkspaceToken: Q,
519
485
  fetchProjects: $,
520
- selectOrganization: ce,
521
- selectWorkspace: le,
522
- selectProject: ue,
523
- selectWorkspaceWide: de
486
+ selectOrganization: se,
487
+ selectWorkspace: ce,
488
+ selectProject: le,
489
+ selectWorkspaceWide: ue
524
490
  };
525
491
  }
526
- function j(n) {
492
+ function k(n) {
527
493
  let i = e((e) => e.currentOrganizationId), a = e((e) => e.workspaces), o = e((e) => e.accessToken), s = e((e) => e.isLoadingWorkspaces), c = t(), u = n?.globalBaseUrl ?? c.globalBaseUrl, d = n?.disableWorkspaceSync ?? !1;
528
494
  r(() => {
529
495
  if (d || !i || !o || s) return;
@@ -553,13 +519,13 @@ function j(n) {
553
519
  d
554
520
  ]);
555
521
  }
556
- function M(n) {
557
- let s = e((e) => e.currentWorkspaceId), c = e((e) => e.currentOrganizationId), f = e((e) => e.workspaces), m = e((e) => e.projects), h = e((e) => e.currentProjectId), g = e((e) => e.workspaceToken), y = e((e) => e.accessToken), S = t(), w = n?.workspaceBaseUrl ?? S.workspaceBaseUrl, T = n?.disableProjectSync ?? !1, E = n?.skipProjectFetch ?? !1, D = i(!1), [O, ee] = a(0), k = i(null), A = i(/* @__PURE__ */ new Map()), j = i(/* @__PURE__ */ new Map()), M = 3e4;
522
+ function A(n) {
523
+ let s = e((e) => e.currentWorkspaceId), c = e((e) => e.currentOrganizationId), f = e((e) => e.workspaces), m = e((e) => e.projects), h = e((e) => e.currentProjectId), g = e((e) => e.workspaceToken), b = e((e) => e.accessToken), S = t(), C = n?.workspaceBaseUrl ?? S.workspaceBaseUrl, w = n?.disableProjectSync ?? !1, T = n?.skipProjectFetch ?? !1, E = i(!1), [D, ee] = a(0), O = i(null), k = i(/* @__PURE__ */ new Map()), A = i(/* @__PURE__ */ new Map()), j = 3e4;
558
524
  r(() => {
559
- if (T || !s || !y || D.current) return;
560
- let t = j.current.get(s);
561
- if (t && t.count >= 8 && Date.now() - t.lastFailureAt < M) return;
562
- t && Date.now() - t.lastFailureAt >= M && j.current.delete(s);
525
+ if (w || !s || !b || E.current) return;
526
+ let t = A.current.get(s);
527
+ if (t && t.count >= 8 && Date.now() - t.lastFailureAt < j) return;
528
+ t && Date.now() - t.lastFailureAt >= j && A.current.delete(s);
563
529
  let n = f.find((e) => e.id === s);
564
530
  if (n && c && n.organizationId !== c) return;
565
531
  let r = n?.organizationId ?? c;
@@ -569,40 +535,46 @@ function M(n) {
569
535
  organizationId: r,
570
536
  workspaceId: s
571
537
  });
572
- let a = o(), S = i.user?.id, O = d({
538
+ let a = o(), S = i.user?.id, D = d({
573
539
  organizationId: r,
574
540
  workspaceId: s
575
541
  });
576
- if (O && i.currentProjectId) {
542
+ if (D && i.currentProjectId) {
577
543
  i.setCurrentProjectId(null), i.setWorkspaceToken(null);
578
544
  return;
579
545
  }
580
- let N = !g || x(g) || !C(g, {
546
+ let M = !g || y(g) || !x(g, {
581
547
  workspaceId: s,
582
548
  organizationId: c,
583
549
  projectId: h,
584
- workspaceWide: O
585
- }), P = JSON.stringify([r, s]), F = m.some((e) => e.workspaceId === s) || O && k.current === P;
586
- if (F && !N) {
587
- if (!i.currentProjectId && !O) {
550
+ workspaceWide: D
551
+ }), N = JSON.stringify([
552
+ a,
553
+ S,
554
+ b,
555
+ r,
556
+ s
557
+ ]), P = m.some((e) => e.workspaceId === s) || O.current?.scopeKey === N && O.current.projects === m;
558
+ if (P && !M) {
559
+ if (!i.currentProjectId && !D) {
588
560
  let e = m.find((e) => e.workspaceId === s);
589
561
  e && i.setCurrentProjectId(e.id);
590
562
  }
591
563
  return;
592
564
  }
593
- let I = () => {
565
+ let F = () => {
594
566
  let t = e.getState();
595
- return t.accessToken === y && t.user?.id === S && o() === a && t.currentOrganizationId === r && t.currentWorkspaceId === s && t.currentProjectId === h && d({
567
+ return t.accessToken === b && t.user?.id === S && o() === a && t.currentOrganizationId === r && t.currentWorkspaceId === s && t.currentProjectId === h && d({
596
568
  organizationId: r,
597
569
  workspaceId: s
598
- }) === O;
599
- }, L = async () => {
600
- D.current = !0, i.setLoadingProjects(!0);
570
+ }) === D;
571
+ }, I = async () => {
572
+ E.current = !0, i.setLoadingProjects(!0);
601
573
  let t = !1;
602
574
  try {
603
- let e = g;
604
- if (N) {
605
- let t = await l({
575
+ let n = g;
576
+ if (M) {
577
+ let e = await l({
606
578
  gateway: "workspace",
607
579
  query: _,
608
580
  variables: { input: {
@@ -610,94 +582,87 @@ function M(n) {
610
582
  workspaceId: s,
611
583
  ...h ? { projectId: h } : {}
612
584
  } },
613
- authToken: y,
614
- baseUrl: w,
585
+ authToken: b,
586
+ baseUrl: C,
615
587
  tenantId: f.find((e) => e.id === s)?.tenantId
616
588
  });
617
- if (t.data?.issueWorkspaceToken?.success && t.data.issueWorkspaceToken.token) {
618
- if (e = t.data.issueWorkspaceToken.token, !I() || !C(e, {
589
+ if (e.data?.issueWorkspaceToken?.success && e.data.issueWorkspaceToken.token) {
590
+ if (n = e.data.issueWorkspaceToken.token, !F() || !x(n, {
619
591
  workspaceId: s,
620
592
  organizationId: r,
621
593
  projectId: h,
622
- workspaceWide: O
594
+ workspaceWide: D
623
595
  })) return;
624
- i.setWorkspaceToken(e);
596
+ i.setWorkspaceToken(n);
625
597
  } else return;
626
598
  }
627
- if (e && !F && !E) {
599
+ if (n && !P && !T) {
628
600
  let t = await l({
629
601
  gateway: "workspace",
630
602
  query: v,
631
- authToken: y,
632
- workspaceToken: e,
633
- baseUrl: w
603
+ authToken: b,
604
+ workspaceToken: n,
605
+ baseUrl: C
634
606
  });
635
- if (!I() || t.errors?.length) return;
636
- let n = t.data?.projects?.items ?? [];
637
- if (n.length === 0 && !O) {
638
- let t = await b({
639
- authToken: y,
640
- workspaceBaseUrl: w,
641
- workspaceToken: e
642
- });
643
- if (t) n = [t];
644
- else return;
645
- }
646
- if (!I()) return;
647
- k.current = O && n.length === 0 ? P : null, i.setProjects(n), n.length > 0 && !i.currentProjectId && !d({
607
+ if (!F() || t.errors?.length) return;
608
+ let a = t.data?.projects?.items ?? [];
609
+ O.current = a.length === 0 ? {
610
+ scopeKey: N,
611
+ projects: a
612
+ } : null, i.setProjects(a), h && !a.some((e) => e.id === h) && (i.setCurrentProjectId(null), i.setWorkspaceToken(null)), a.length > 0 && !e.getState().currentProjectId && !d({
648
613
  organizationId: r,
649
614
  workspaceId: s
650
- }) && i.setCurrentProjectId(n[0].id);
615
+ }) && i.setCurrentProjectId(a[0].id);
651
616
  }
652
617
  t = !0;
653
618
  } catch {} finally {
654
- i.setLoadingProjects(!1), D.current = !1;
655
- let n = I();
619
+ i.setLoadingProjects(!1), E.current = !1;
620
+ let n = F();
656
621
  n || ee((e) => e + 1);
657
- let r = j.current;
622
+ let r = A.current;
658
623
  if (n && t) {
659
624
  r.delete(s);
660
- let e = A.current.get(s);
661
- e && (clearTimeout(e), A.current.delete(s));
625
+ let e = k.current.get(s);
626
+ e && (clearTimeout(e), k.current.delete(s));
662
627
  } else if (n) {
663
628
  let t = (r.get(s)?.count ?? 0) + 1;
664
629
  if (r.set(s, {
665
630
  count: t,
666
631
  lastFailureAt: Date.now()
667
632
  }), t < 8) {
668
- let n = A.current.get(s);
633
+ let n = k.current.get(s);
669
634
  n && clearTimeout(n);
670
635
  let r = Math.min(1e3 * 2 ** (t - 1), 8e3), i = setTimeout(() => {
671
- A.current.delete(s);
636
+ k.current.delete(s);
672
637
  let t = e.getState();
673
- I() && t.currentWorkspaceId === s && !t.projects.some((e) => e.workspaceId === s) && !D.current && L();
638
+ F() && t.currentWorkspaceId === s && !t.projects.some((e) => e.workspaceId === s) && !E.current && I();
674
639
  }, r);
675
- A.current.set(s, i);
640
+ k.current.set(s, i);
676
641
  }
677
642
  }
678
643
  }
679
644
  };
680
- L();
645
+ I();
681
646
  }, [
682
- O,
647
+ D,
683
648
  s,
684
649
  c,
685
650
  f,
686
651
  m,
687
652
  h,
688
653
  g,
689
- y,
654
+ b,
655
+ C,
690
656
  w,
691
- T,
692
- E
657
+ T
693
658
  ]), r(() => {
694
- let e = A.current;
659
+ let e = k.current;
695
660
  return () => {
696
661
  e.forEach((e) => clearTimeout(e)), e.clear();
697
662
  };
698
663
  }, []);
699
664
  }
700
665
  //#endregion
701
- export { A as useContextSwitcherData, M as useProjectSyncEffect, j as useWorkspaceSyncEffect };
666
+ export { O as useContextSwitcherData, A as useProjectSyncEffect, k as useWorkspaceSyncEffect };
702
667
 
703
668
  //# sourceMappingURL=useContextSwitcherData.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"useContextSwitcherData.js","names":[],"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\";\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\ninterface CreateProjectResponse {\n createProject: Project;\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\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\nconst CREATE_DEFAULT_PROJECT_MUTATION = `\n mutation CreateDefaultProject($input: CreateProjectInput!) {\n createProject(input: $input) {\n id\n name\n key\n workspaceId\n status\n archived\n createdAt\n updatedAt\n }\n }\n`;\n\nasync function createDefaultProject({\n authToken,\n workspaceBaseUrl,\n workspaceToken,\n}: {\n authToken: string;\n workspaceBaseUrl: string;\n workspaceToken: string;\n}): Promise<Project | null> {\n const result = await graphqlFetch<CreateProjectResponse>({\n gateway: \"workspace\",\n query: CREATE_DEFAULT_PROJECT_MUTATION,\n variables: {\n input: {\n name: \"Default Project\",\n },\n },\n authToken,\n workspaceToken,\n baseUrl: workspaceBaseUrl,\n });\n\n if (result.errors?.length) {\n console.warn(\"Failed to create default project:\", result.errors);\n return null;\n }\n\n return result.data?.createProject ?? null;\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\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 {\n organizationId: activeOrganizationId,\n workspaceId: activeWorkspaceId,\n projectId: activeProjectId,\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 // 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 let result: GraphQLFetchResult<\n MyOrganizationsResponse & Partial<WorkspacesByOrgResponse>\n > = initialTargetOrgId\n ? await (async () => {\n const [organizationsResult, workspacesResult] = await Promise.all(\n [\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\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 // 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 const bootstrappedWorkspaces =\n initialTargetOrgId === targetOrgId\n ? result.data?.workspaces?.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 (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 }, [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 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 }, [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 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 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 let projs = await fetchProjects();\n if (!currentSelection())\n return { success: false, error: \"Context changed during selection\" };\n if (\n projs.length === 0 &&\n !isWorkspaceWideSelection({\n organizationId: workspace.organizationId,\n workspaceId: workspace.id,\n })\n ) {\n const authToken = resolveAccessToken();\n const workspaceToken = useAuthStore.getState().workspaceToken;\n if (authToken && workspaceToken) {\n const defaultProject = await createDefaultProject({\n authToken,\n workspaceBaseUrl,\n workspaceToken,\n });\n if (!currentSelection())\n return {\n success: false,\n error: \"Context changed during selection\",\n };\n if (defaultProject) {\n projs = [defaultProject];\n store.setProjects(projs);\n }\n }\n }\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, workspaceBaseUrl],\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 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 refreshWorkspaces();\n }\n });\n\n return () => {\n cancelled = true;\n unsubscribe();\n };\n }, [eventBus, fetchProjects, fetchWorkspacesForOrg]);\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 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 emptyWideProjectsScopeRef = useRef<string | 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, list, or default-create) fails. Without this, a persistent\n // backend failure (e.g. cross-layer workspace not yet synced) causes the\n // effect to re-fire every render: list returns empty → create-default fails\n // → setProjects([]) → new array reference → effect re-runs → loop.\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([organizationId, currentWorkspaceId]);\n const hasProjectsForWorkspace =\n projects.some((p) => p.workspaceId === currentWorkspaceId) ||\n (workspaceWide && emptyWideProjectsScopeRef.current === scopeKey);\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 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 let projs: Project[] = projectsResult.data?.projects?.items ?? [];\n if (projs.length === 0 && !workspaceWide) {\n const defaultProject = await createDefaultProject({\n authToken: accessToken,\n workspaceBaseUrl,\n workspaceToken: wsToken,\n });\n if (defaultProject) {\n projs = [defaultProject];\n } else {\n // Default-project creation failed (e.g. workspace not yet\n // propagated to the workspace layer). Do NOT write [] back —\n // that would change the projects reference and re-trigger\n // this effect on the next render.\n return;\n }\n }\n\n if (!contextStillCurrent()) return;\n emptyWideProjectsScopeRef.current =\n workspaceWide && projs.length === 0 ? scopeKey : null;\n store.setProjects(projs);\n\n // Auto-select first project if none selected and projects exist\n if (\n projs.length > 0 &&\n !store.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 ]);\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":";;;;;;;;;;AA4FA,IAAM,IAAyB,2RAoCzB,IAA0B,oSAoB1B,IAAiC,6SA0BjC,IAAiB,uPAkBjB,IAAkC;AAexC,eAAe,EAAqB,EAClC,cACA,qBACA,qBAK0B;CAC1B,IAAM,IAAS,MAAM,EAAoC;EACvD,SAAS;EACT,OAAO;EACP,WAAW,EACT,OAAO,EACL,MAAM,kBACR,EACF;EACA;EACA;EACA,SAAS;CACX,CAAC;CAOD,OALI,EAAO,QAAQ,UACjB,QAAQ,KAAK,qCAAqC,EAAO,MAAM,GACxD,QAGF,EAAO,MAAM,iBAAiB;AACvC;AAUA,SAAS,EAAe,GAAe,IAAW,KAAiB;CACjE,IAAI;EACF,IAAM,IAAU,KAAK,MAAM,KAAK,EAAM,MAAM,GAAG,EAAE,EAAE,CAAC;EAEpD,OADK,EAAQ,MACN,EAAQ,MAAM,MAAO,KAAK,IAAI,IAAI,IADhB;CAE3B,QAAQ;EACN,OAAO;CACT;AACF;AAEA,SAAS,EAAyB,GAKzB;CACP,IAAI;EACF,IAAM,IAAU,KAAK,MAAM,KAAK,EAAM,MAAM,GAAG,EAAE,EAAE,CAAC;EACpD,OAAO;GACL,aACE,OAAO,EAAQ,eAAgB,WAC3B,EAAQ,cACR,KAAA;GACN,gBACE,OAAO,EAAQ,kBAAmB,WAC9B,EAAQ,iBACR,KAAA;GACN,WACE,OAAO,EAAQ,aAAc,WAAW,EAAQ,YAAY,KAAA;GAC9D,KAAK,OAAO,EAAQ,OAAQ,WAAW,EAAQ,MAAM,KAAA;EACvD;CACF,QAAQ;EACN,OAAO;CACT;AAC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AAY,GAA2B;MACzC,IAAM,IAAgB,EAAc,QAAQ,IAAI,CAAkB;MAClE,AAAI,KAAe,aAAa,CAAa;MAC7C,IAAM,IAAY,KAAK,IAAI,MAAO,MAAM,IAAY,IAAI,GAAI,GACtD,IAAQ,iBAAiB;OAC7B,EAAc,QAAQ,OAAO,CAAkB;OAG/C,IAAM,IAAS,EAAa,SAAS;OACrC,AACE,EAAoB,KACpB,EAAO,uBAAuB,KAC9B,CAAC,EAAO,SAAS,MACd,MAAM,EAAE,gBAAgB,CAC3B,KACA,CAAC,EAAkB,WAMnB,EAAkB;MAEtB,GAAG,CAAS;MACZ,EAAc,QAAQ,IAAI,GAAoB,CAAK;KACrD;IACF;GACF;EACF;EAEA,EAAa;CACf,GAAG;EACD;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CAAC,GAID,QAAgB;EACd,IAAM,IAAS,EAAc;EAC7B,aAAa;GAEX,AADA,EAAO,SAAS,MAAU,aAAa,CAAK,CAAC,GAC7C,EAAO,MAAM;EACf;CACF,GAAG,CAAC,CAAC;AACP"}
1
+ {"version":3,"file":"useContextSwitcherData.js","names":[],"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\";\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\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\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 {\n organizationId: activeOrganizationId,\n workspaceId: activeWorkspaceId,\n projectId: activeProjectId,\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 // 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 let result: GraphQLFetchResult<\n MyOrganizationsResponse & Partial<WorkspacesByOrgResponse>\n > = initialTargetOrgId\n ? await (async () => {\n const [organizationsResult, workspacesResult] = await Promise.all(\n [\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\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 // 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 const bootstrappedWorkspaces =\n initialTargetOrgId === targetOrgId\n ? result.data?.workspaces?.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 (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 }, [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 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 }, [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 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 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 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 refreshWorkspaces();\n }\n });\n\n return () => {\n cancelled = true;\n unsubscribe();\n };\n }, [eventBus, fetchProjects, fetchWorkspacesForOrg]);\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 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 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 ]);\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":";;;;;;;;;;AAwFA,IAAM,IAAyB,2RAoCzB,IAA0B,oSAoB1B,IAAiC,6SA0BjC,IAAiB;AA0BvB,SAAS,EAAe,GAAe,IAAW,KAAiB;CACjE,IAAI;EACF,IAAM,IAAU,KAAK,MAAM,KAAK,EAAM,MAAM,GAAG,EAAE,EAAE,CAAC;EAEpD,OADK,EAAQ,MACN,EAAQ,MAAM,MAAO,KAAK,IAAI,IAAI,IADhB;CAE3B,QAAQ;EACN,OAAO;CACT;AACF;AAEA,SAAS,EAAyB,GAKzB;CACP,IAAI;EACF,IAAM,IAAU,KAAK,MAAM,KAAK,EAAM,MAAM,GAAG,EAAE,EAAE,CAAC;EACpD,OAAO;GACL,aACE,OAAO,EAAQ,eAAgB,WAC3B,EAAQ,cACR,KAAA;GACN,gBACE,OAAO,EAAQ,kBAAmB,WAC9B,EAAQ,iBACR,KAAA;GACN,WACE,OAAO,EAAQ,aAAc,WAAW,EAAQ,YAAY,KAAA;GAC9D,KAAK,OAAO,EAAQ,OAAQ,WAAW,EAAQ,MAAM,KAAA;EACvD;CACF,QAAQ;EACN,OAAO;CACT;AACF;AAEA,SAA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IACF;GACF;EACF;EAEA,EAAa;CACf,GAAG;EACD;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CAAC,GAID,QAAgB;EACd,IAAM,IAAS,EAAc;EAC7B,aAAa;GAEX,AADA,EAAO,SAAS,MAAU,aAAa,CAAK,CAAC,GAC7C,EAAO,MAAM;EACf;CACF,GAAG,CAAC,CAAC;AACP"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@burdenoff/microfe-auth",
3
- "version": "2026.1005.1",
3
+ "version": "2026.1013.1",
4
4
  "description": "Auth microfrontend for Burdenoff products",
5
5
  "type": "module",
6
6
  "imports": {