@seliseblocks/genesis-os 4.4.8 → 4.4.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/{chunk-IPMRZNNS.cjs → chunk-A4MVNKXL.cjs} +20 -7
  2. package/dist/chunk-A4MVNKXL.cjs.map +1 -0
  3. package/dist/{chunk-KA2OOMCU.js → chunk-L4V72AAV.js} +180 -32
  4. package/dist/chunk-L4V72AAV.js.map +1 -0
  5. package/dist/{chunk-3OO2YVXW.js → chunk-LAWQOHY6.js} +3 -3
  6. package/dist/{chunk-3OO2YVXW.js.map → chunk-LAWQOHY6.js.map} +1 -1
  7. package/dist/{chunk-UDFH7SJI.js → chunk-OE5T43AS.js} +20 -7
  8. package/dist/chunk-OE5T43AS.js.map +1 -0
  9. package/dist/{chunk-VLZJP6FH.cjs → chunk-P4SL4PTY.cjs} +40 -40
  10. package/dist/{chunk-VLZJP6FH.cjs.map → chunk-P4SL4PTY.cjs.map} +1 -1
  11. package/dist/{chunk-QBL4VIE4.cjs → chunk-ZVYSSUHO.cjs} +279 -131
  12. package/dist/chunk-ZVYSSUHO.cjs.map +1 -0
  13. package/dist/components/index.cjs +342 -342
  14. package/dist/components/index.js +3 -3
  15. package/dist/guards/index.cjs +9 -9
  16. package/dist/guards/index.js +3 -3
  17. package/dist/hooks/index.cjs +59 -59
  18. package/dist/hooks/index.js +2 -2
  19. package/dist/index.cjs +440 -440
  20. package/dist/index.d.cts +1 -1
  21. package/dist/index.d.ts +1 -1
  22. package/dist/index.js +3 -3
  23. package/dist/layouts/index.cjs +10 -10
  24. package/dist/layouts/index.js +3 -3
  25. package/dist/lib/index.cjs +24 -24
  26. package/dist/lib/index.d.cts +9 -2
  27. package/dist/lib/index.d.ts +9 -2
  28. package/dist/lib/index.js +1 -1
  29. package/dist/observability/index.cjs.map +1 -1
  30. package/dist/observability/index.d.cts +5 -1
  31. package/dist/observability/index.d.ts +5 -1
  32. package/dist/observability/index.js.map +1 -1
  33. package/dist/pages/index.cjs +8 -8
  34. package/dist/pages/index.js +3 -3
  35. package/dist/{types-D9odiLzd.d.ts → types-Dz0dH1XK.d.ts} +5 -1
  36. package/dist/{types-CQX9_ck-.d.cts → types-VNffHJ1_.d.cts} +5 -1
  37. package/dist/utils/index.cjs +1 -1
  38. package/dist/utils/index.js +1 -1
  39. package/package.json +1 -1
  40. package/dist/chunk-IPMRZNNS.cjs.map +0 -1
  41. package/dist/chunk-KA2OOMCU.js.map +0 -1
  42. package/dist/chunk-QBL4VIE4.cjs.map +0 -1
  43. package/dist/chunk-UDFH7SJI.js.map +0 -1
@@ -381,8 +381,9 @@ var HttpClient = class _HttpClient {
381
381
  normalized,
382
382
  url,
383
383
  method,
384
- // Not already an HttpError means no HTTP response ever came back: DNS, CORS, TLS,
385
- // offline, abort, or a bug in this client.
384
+ // Not already an HttpError means the server gave no usable answer: no HTTP response
385
+ // came back (DNS, CORS, TLS, offline, abort), a success body could not be read or
386
+ // parsed as JSON, or this client threw.
386
387
  transport: !(error instanceof chunk2MP66EX3_cjs.HttpError)
387
388
  });
388
389
  } catch {
@@ -390,9 +391,18 @@ var HttpClient = class _HttpClient {
390
391
  }
391
392
  return normalized;
392
393
  }
394
+ /**
395
+ * Decodes a success response. A response without data resolves to the envelope
396
+ * `{ success: true, status }`: 204 and 205 (checked before the content type, since they never
397
+ * carry a body), no content type, and a JSON-branch response with `content-length: 0` or a blank
398
+ * body. JSON is read with `text()` and `JSON.parse`, so an empty body never reaches the parser,
399
+ * while a non-empty body that is not JSON still throws its `SyntaxError`.
400
+ */
393
401
  async parseSuccessResponse(response) {
402
+ const noData = { success: true, status: response.status };
403
+ if (response.status === 204 || response.status === 205) return noData;
394
404
  const contentType = response.headers.get("content-type")?.toLowerCase();
395
- if (!contentType) return { success: true, status: response.status };
405
+ if (!contentType) return noData;
396
406
  if (contentType.includes("text/html")) {
397
407
  throw new chunk2MP66EX3_cjs.HttpError(response.status, {
398
408
  errors: { general: "Unexpected HTML response from server" }
@@ -403,7 +413,10 @@ var HttpClient = class _HttpClient {
403
413
  if (contentType.includes("image/") || contentType.includes("application/octet-stream") || contentType.includes("application/pdf")) {
404
414
  return await response.blob();
405
415
  }
406
- return await response.json();
416
+ if (response.headers.get("content-length") === "0") return noData;
417
+ const text = await response.text();
418
+ if (text.trim() === "") return noData;
419
+ return JSON.parse(text);
407
420
  }
408
421
  async request(url, requestOption) {
409
422
  const {
@@ -447,7 +460,7 @@ var HttpClient = class _HttpClient {
447
460
  });
448
461
  }
449
462
  await this.throwIfNotOk(response);
450
- return this.parseSuccessResponse(response);
463
+ return await this.parseSuccessResponse(response);
451
464
  } catch (error) {
452
465
  throw this.failRequest(error, fullUrl, method);
453
466
  }
@@ -766,5 +779,5 @@ exports.staggerItem = staggerItem;
766
779
  exports.subscribeToSignOut = subscribeToSignOut;
767
780
  exports.subscribeToTenantClaims = subscribeToTenantClaims;
768
781
  exports.timeoutSignal = timeoutSignal;
769
- //# sourceMappingURL=chunk-IPMRZNNS.cjs.map
770
- //# sourceMappingURL=chunk-IPMRZNNS.cjs.map
782
+ //# sourceMappingURL=chunk-A4MVNKXL.cjs.map
783
+ //# sourceMappingURL=chunk-A4MVNKXL.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/http/util.ts","../src/constants/endpoint.constant.ts","../src/lib/http/session-lock.ts","../src/lib/http/client.ts","../src/lib/http/instances.ts","../src/lib/resolve-env.ts","../src/lib/motion-presets.ts","../src/lib/tenant-ownership.ts"],"names":["getRuntimeEnv","HttpError","getQueryClient","useAuthStore","useProjectStore","listener"],"mappings":";;;;;;;;AAEO,IAAM,cAAA,GAAiB,CAC5B,IAAA,KACW;AACX,EAAA,IAAI,OAAO,MAAA,KAAW,WAAA,EAAa,OAAO,EAAA;AAE1C,EAAA,MAAM,YAAA,GAAe;AAAA,IACnB,IAAA,EAAM,aAAA;AAAA,IACN,OAAA,EAAS,gBAAA;AAAA,IACT,YAAA,EA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,SAAQ,CAAA;AAAA,EACzD;AAIA,EAAA,MAAM,QAAA,GAAW,CAAC,KAAA,KAAwB;AACxC,IAAA,IAAI,KAAA,CAAM,GAAA,KAAQ,WAAA,IAAe,CAAC,MAAM,QAAA,EAAU;AAClD,IAAA,IAAI;AACF,MAAA,WAAA,CAAY,IAAA,CAAK,KAAA,CAAM,KAAA,CAAM,QAAQ,CAAC,CAAA;AAAA,IACxC,CAAA,CAAA,MAAQ;AAAA,IAGR;AAAA,EACF,CAAA;AACA,EAAA,MAAA,CAAO,gBAAA,CAAiB,WAAW,QAAQ,CAAA;AAC3C,EAAA,OAAO,MAAM,MAAA,CAAO,mBAAA,CAAoB,SAAA,EAAW,QAAQ,CAAA;AAC7D","file":"chunk-A4MVNKXL.cjs","sourcesContent":["import { getRuntimeEnv } from \"@/lib/runtime-env\";\n\nexport const resolveBaseUrl = (\n type: \"user\" | \"project\" | \"notification\",\n): string => {\n if (typeof window === \"undefined\") return \"\";\n\n const directKeyMap = {\n user: \"userBaseUrl\",\n project: \"projectBaseUrl\",\n notification: \"notificationBaseUrl\",\n } as const;\n const directKey = directKeyMap[type];\n const directVal = getRuntimeEnv(directKey);\n if (directVal) return directVal;\n\n if (type === \"user\") {\n return getRuntimeEnv(\"BLOCKS_IAM_BASE_URL\") || \"\";\n } else if (type === \"notification\") {\n return getRuntimeEnv(\"BLOCKS_LOGIC_BASE_URL\") || \"\";\n } else {\n return getRuntimeEnv(\"BLOCKS_OS_BASE_URL\") || \"\";\n }\n};\n","const API_BASE = \"/api\";\nconst AUTH_SUBPATH = \"auth\";\nconst NOTIFIER_SUBPATH = \"Notifier\";\nconst NOTIFICATION_SUBPATH = \"Notification\";\nconst PROJECT_SUBPATH = \"Project\";\nconst SERVICE_SUBPATH = \"Service\";\nconst DOMAIN_SUBPATH = \"Domain\";\nconst DEPLOYMENT_SUBPATH = \"Deployment\";\nconst IAM_SUBPATH = \"iam\";\n\nexport const AUTH_ENDPOINTS = {\n OIDC_TOKEN: `${API_BASE}/oidc/token`,\n LOGOUT: `${API_BASE}/${AUTH_SUBPATH}/Logout`,\n ME: `${API_BASE}/${AUTH_SUBPATH}/me`,\n} as const;\n\nexport const IAM_ENDPOINTS = {\n INITIATE: `${API_BASE}/idp/initiate`,\n} as const;\n\nexport const PROFILE_ENDPOINTS = {\n ME: `${API_BASE}/${IAM_SUBPATH}/me`,\n};\nexport const IMPERSONATE_ENDPOINTS = {\n IMPERSONATE: `${API_BASE}/${AUTH_SUBPATH}/impersonate`,\n STOP_IMPERSONATION: `${API_BASE}/${AUTH_SUBPATH}/impersonation/stop`,\n IMPERSONATION_STATUS: `${API_BASE}/${AUTH_SUBPATH}/impersonation/status`,\n} as const;\n\nexport const NOTIFICATION_ENDPOINTS = {\n GET_NOTIFICATIONS: `${API_BASE}/${NOTIFIER_SUBPATH}/GetNotifications`,\n MARK_AS_READ: `${API_BASE}/${NOTIFIER_SUBPATH}/MarkNotificationAsRead`,\n MARK_ALL_AS_READ: `${API_BASE}/${NOTIFIER_SUBPATH}/MarkAllNotificationAsRead`,\n} as const;\n\nexport const NOTIFICATION_CONFIG_ENDPOINTS = {\n GET_CONFIGS: `${API_BASE}/${NOTIFICATION_SUBPATH}/Gets`,\n} as const;\n\nexport const PROJECT_ENDPOINTS = {\n GETS: `${API_BASE}/${PROJECT_SUBPATH}/Gets`,\n GET: `${API_BASE}/${PROJECT_SUBPATH}/Get`,\n DISABLE: `${API_BASE}/${PROJECT_SUBPATH}/Disable`,\n UPDATE_PROJECT: `${API_BASE}/${PROJECT_SUBPATH}/UpdateProject`,\n UPDATE_TENANT_GROUP: `${API_BASE}/${PROJECT_SUBPATH}/UpdateTenantGroup`,\n CONFIGURE: `${API_BASE}/${DOMAIN_SUBPATH}/Configure`,\n REPOS_LIST: `${API_BASE}/${DEPLOYMENT_SUBPATH}/GetReposList`,\n REPO_UPDATE: `${API_BASE}/${DEPLOYMENT_SUBPATH}/UpdateRepoDomain`,\n} as const;\n\nexport const SERVICE_REGISTRY_ENDPOINTS = {\n GET_ALL: `${API_BASE}/${SERVICE_SUBPATH}/GetAll`,\n} as const;\n\nexport const ORGANIZATION_ENDPOINTS = {\n GET_ORGANIZATIONS: `${API_BASE}/${IAM_SUBPATH}/organizations`,\n GET_ORGANIZATION: `${API_BASE}/${IAM_SUBPATH}/organization`,\n CREATE_ORGANIZATION: `${API_BASE}/${IAM_SUBPATH}/organizations/create`,\n SAVE_ORGANIZATION: `${API_BASE}/${IAM_SUBPATH}/organizations`,\n UPDATE_ORGANIZATION: `${API_BASE}/${IAM_SUBPATH}/organizations`,\n GET_ORGANIZATION_CONFIG: `${API_BASE}/${IAM_SUBPATH}/organizations/config`,\n SAVE_ORGANIZATION_CONFIG: `${API_BASE}/${IAM_SUBPATH}/organizations/config`,\n GET_MY_ORGANIZATIONS: `${API_BASE}/${IAM_SUBPATH}/organizations/my`,\n GET_SIGNUP_SETTING: `${API_BASE}/${IAM_SUBPATH}/signup-settings`,\n SAVE_SIGNUP_SETTING: `${API_BASE}/${IAM_SUBPATH}/signup-settings`,\n} as const;\n","/**\n * One lock per shared session cookie, held across every tab of the application.\n *\n * Refreshing the token, opening a project and leaving it each replace the refresh token in the\n * shared cookie. Run side by side -- two tabs, or a refresh still in flight when the user opens a\n * project -- the browser keeps whichever response lands last, so a page that has just confirmed one\n * tenant can be left holding another tenant's cookie. The Web Locks API is scoped to the origin,\n * which is exactly the set of tabs that share the cookie, so holding it makes those writes take\n * turns.\n *\n * Where the API is missing, calls inside this tab still take turns; other tabs are not covered,\n * which is how every tab behaved before the lock existed.\n *\n * The lock is not re-entrant. Code running inside it must not call anything that takes it again --\n * in particular, its requests must skip the client's own 401 → refresh path (see\n * `HttpClient.refreshWithinSessionLock`).\n */\n\nconst LOCK_PREFIX = \"blocks-session:\";\n\n/**\n * How long to wait for another holder before going ahead without the lock. Every call made while\n * holding it is bounded below this, so only a tab that froze mid-call is waited out.\n */\nexport const SESSION_LOCK_WAIT_MS = 25_000;\n\nconst localTails = new Map<string, Promise<unknown>>();\n\nconst runLocally = <T>(name: string, fn: () => Promise<T>): Promise<T> => {\n const previous = localTails.get(name) ?? Promise.resolve();\n const run = previous.then(fn, fn);\n const tail = run.catch(() => undefined);\n localTails.set(name, tail);\n void tail.then(() => {\n if (localTails.get(name) === tail) localTails.delete(name);\n });\n return run;\n};\n\n/** An AbortSignal that fires after `ms`, on runtimes with or without `AbortSignal.timeout`. */\nexport const timeoutSignal = (ms: number): AbortSignal => {\n if (typeof AbortSignal !== \"undefined\" && \"timeout\" in AbortSignal) {\n return AbortSignal.timeout(ms);\n }\n const controller = new AbortController();\n setTimeout(() => controller.abort(), ms);\n return controller.signal;\n};\n\n/** Runs `fn` while holding the session lock called `name`, and returns what it returns. */\nexport const withSessionLock = async <T>(\n name: string,\n fn: () => Promise<T>,\n): Promise<T> => {\n const locks = typeof navigator !== \"undefined\" ? navigator.locks : undefined;\n if (!locks?.request) return runLocally(name, fn);\n\n const waitLimit = timeoutSignal(SESSION_LOCK_WAIT_MS);\n let acquired = false;\n try {\n return await locks.request(\n `${LOCK_PREFIX}${name}`,\n { signal: waitLimit },\n () => {\n acquired = true;\n return fn();\n },\n );\n } catch (error) {\n // The browser rejects a timed-out wait with the signal's reason, a TimeoutError, so the wait\n // limit itself tells whether that is what happened.\n if (acquired || !waitLimit.aborted) throw error;\n // Another tab has held the lock far longer than any call it makes should take. Going ahead\n // risks the overlap the lock exists to prevent; failing would block the user's action on a\n // tab that may never let go.\n console.error(\n `Session lock \"${name}\" was not released in time; continuing without it.`,\n );\n return fn();\n }\n};\n","import { getRuntimeEnv } from \"@/lib/runtime-env\";\nimport { resolveBaseUrl } from \"./util\";\nimport { AUTH_ENDPOINTS } from \"@/constants/endpoint.constant\";\nimport type { AuthTokenPair } from \"@/models\";\nimport type {\n HttpClientConfig,\n HttpRequestFailure,\n HttpClientOptions,\n HeadersInitValue,\n RequestOptions,\n RequestBody,\n SessionTenantGuard,\n} from \"./types\";\nimport { HttpError } from \"./error\";\nimport { timeoutSignal, withSessionLock } from \"./session-lock\";\nimport { getQueryClient } from \"@/providers/query-client\";\nimport { useAuthStore } from \"@/store/auth.store\";\nimport { useProjectStore } from \"@/store/project.store\";\n\nconst DEFAULT_EXCLUDED_PATHS = [\"/login\", \"/signup\"];\nconst DEFAULT_LOGIN_REDIRECT_PATH = \"/login\";\n\n/**\n * A refresh runs inside the session lock, so one that never answers would hold every tab. Kept\n * below `SESSION_LOCK_WAIT_MS`.\n */\nconst REFRESH_TIMEOUT_MS = 20_000;\n\n/**\n * IAM's answer to a refresh token that was replaced by opening, leaving or switching a project. The\n * cookie may already hold that replacement -- set by another tab -- so it is not a sign-out by\n * itself.\n */\nconst SESSION_CHANGED = \"session_changed\";\n\nconst isSameTenant = (a: string, b: string): boolean =>\n a.toLowerCase() === b.toLowerCase();\n\n/**\n * Thrown instead of retrying a request after a refresh moved the session to a tenant other than\n * the one the page was showing when the request started. Sending it again would answer the page\n * with another tenant's data.\n */\nconst sessionMovedError = (): HttpError =>\n new HttpError(409, {\n errors: {\n general:\n \"The session moved to another tenant, so the request was not sent again\",\n },\n });\n\nexport class HttpClient {\n private baseURL: string | (() => string);\n private blocksKey: string | (() => string);\n private onTokenRefresh?: () => Promise<AuthTokenPair>;\n private onUnauthorized?: (error: unknown) => void;\n private excludedPaths: string[];\n private loginRedirectPath: string;\n private autoRedirectOnAuthFailure: boolean;\n private onError?: (failure: HttpRequestFailure) => void;\n\n // Keyed by refresh target, not per instance.\n //\n // The lock used to be an instance field, on the reasoning that two clients pointed at different\n // baseURLs or tenants must not share one. That reasoning is sound but did not describe the actual\n // instances: iamClient, logicClient and notificationClient all carry the same blocks key, and\n // performRefresh always refreshes against IAM via resolveBaseUrl(\"user\") using the same\n // HttpOnly refresh cookie and therefore the same server-side token lineage.\n //\n // So a single window-focus event could fire three concurrent rotations of one refresh token. The\n // server rotates an impersonated lineage twice more per refresh, so up to six writes raced; the\n // losers came back invalid_grant, and handleRefreshFailure turned that into a forced redirect to\n // /login. Keying by the refresh target keeps the original guarantee for clients that genuinely\n // differ while collapsing the ones that do not into one in-flight refresh.\n //\n // Each entry resolves with the tenant the session was confirmed in after the refresh, or null when\n // that could not be checked.\n private static readonly refreshPromises = new Map<\n string,\n Promise<string | null>\n >();\n\n private static sessionGuard: SessionTenantGuard | null = null;\n\n /**\n * Registers the check run after every refresh (see `SessionTenantGuard`). Returns a function that\n * removes it again, unless another guard has replaced it since.\n */\n static setSessionGuard(guard: SessionTenantGuard): () => void {\n HttpClient.sessionGuard = guard;\n return () => {\n if (HttpClient.sessionGuard === guard) HttpClient.sessionGuard = null;\n };\n }\n\n private static expectedTenant(skip: boolean): string | null {\n if (skip || !HttpClient.sessionGuard) return null;\n try {\n return HttpClient.sessionGuard.expectedTenant();\n } catch {\n return null;\n }\n }\n\n private static async confirmSessionTenant(): Promise<string | null> {\n if (!HttpClient.sessionGuard) return null;\n try {\n return await HttpClient.sessionGuard.confirmTenant();\n } catch {\n // Unknown is not \"moved\": the server refuses a refresh that would cross tenants, so the\n // retry goes ahead as it did before this check existed.\n return null;\n }\n }\n\n /** Whether a request started for `expected` must not be retried in `confirmed`. */\n private static hasSessionMoved(\n expected: string | null,\n confirmed: string | null,\n ): boolean {\n return !!expected && !!confirmed && !isSameTenant(expected, confirmed);\n }\n\n constructor(config: HttpClientConfig) {\n this.baseURL = config.baseURL;\n this.blocksKey = config.blocksKey;\n this.onTokenRefresh = config.onTokenRefresh;\n this.onUnauthorized = config.onUnauthorized;\n this.excludedPaths = config.excludedPaths ?? DEFAULT_EXCLUDED_PATHS;\n this.loginRedirectPath =\n config.loginRedirectPath ?? DEFAULT_LOGIN_REDIRECT_PATH;\n this.autoRedirectOnAuthFailure = config.autoRedirectOnAuthFailure ?? true;\n this.onError = config.onError;\n }\n\n private getBaseURL(): string {\n return typeof this.baseURL === \"function\" ? this.baseURL() : this.baseURL;\n }\n\n private getBlocksKey(): string {\n return typeof this.blocksKey === \"function\"\n ? this.blocksKey()\n : this.blocksKey;\n }\n\n private normalizeHeaders(\n headers?: HeadersInitValue,\n skipBlocksKey?: boolean,\n ): Headers {\n const normalizedHeaders = new Headers({\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\",\n ...(!skipBlocksKey && this.getBlocksKey()\n ? { \"X-Blocks-Key\": this.getBlocksKey() }\n : {}),\n });\n\n if (headers instanceof Headers) {\n headers.forEach((value, key) => normalizedHeaders.set(key, value));\n } else if (Array.isArray(headers)) {\n headers.forEach(([key, value]) => normalizedHeaders.set(key, value));\n } else if (headers) {\n Object.entries(headers).forEach(([key, value]) =>\n normalizedHeaders.set(key, value),\n );\n }\n\n return normalizedHeaders;\n }\n\n // Shared by request() and stream() so binary/form bodies are handled\n // identically in both — stream() previously JSON.stringify'd\n // everything unconditionally, silently mangling FormData/Blob/File.\n private prepareBody(\n body: RequestBody,\n normalizedHeaders: Headers,\n ): BodyInit | undefined {\n if (body === undefined || body === null) return undefined;\n\n if (\n body instanceof FormData ||\n body instanceof URLSearchParams ||\n body instanceof File ||\n body instanceof Blob\n ) {\n normalizedHeaders.delete(\"Content-Type\");\n return body;\n }\n\n if (typeof body === \"string\") return body;\n\n return JSON.stringify(body);\n }\n\n // Identifies the credential a refresh actually rotates: the IAM base URL performRefresh posts to,\n // plus the tenant key it sends. Two clients that resolve to the same pair are rotating the same\n // token and must share one lock; two that do not are independent and must not.\n private refreshLockKey(): string {\n return `${resolveBaseUrl(\"user\")}::${this.getBlocksKey()}`;\n }\n\n // Ensures only one refresh request is ever in flight per refresh target.\n // Concurrent 401s from get/post/.../stream — across every client sharing\n // that target — all await this same promise instead of racing to refresh.\n //\n // The refresh also takes the session lock, so it never overlaps another tab's refresh, or an\n // impersonation start or stop from any tab: each of those replaces the same shared cookie.\n private refreshAccessToken(): Promise<string | null> {\n const key = this.refreshLockKey();\n const inFlight = HttpClient.refreshPromises.get(key);\n if (inFlight) return inFlight;\n\n const promise = withSessionLock(key, async () => {\n await this.performRefresh();\n return HttpClient.confirmSessionTenant();\n }).finally(() => {\n HttpClient.refreshPromises.delete(key);\n });\n HttpClient.refreshPromises.set(key, promise);\n return promise;\n }\n\n /**\n * Runs `fn` while holding the lock that refreshes and impersonation changes share across every\n * tab (see `withSessionLock`). Requests made inside must pass `skipTokenRotation` and use\n * `refreshWithinSessionLock` instead: the client's own refresh would wait for this very lock.\n */\n withSessionLock<T>(fn: () => Promise<T>): Promise<T> {\n return withSessionLock(this.refreshLockKey(), fn);\n }\n\n /**\n * Refreshes the access token from inside `withSessionLock`. Failure handling is the same as any\n * refresh: an unrecoverable one signs the user out.\n */\n refreshWithinSessionLock(): Promise<void> {\n return this.performRefresh();\n }\n\n /**\n * True for a refused refresh that only means the cookie's token was replaced by an impersonation\n * change, and the cookie now holds a working access token. Another tab can cause that, or a\n * response this tab never received.\n */\n private async isReplacedSession(response: Response): Promise<boolean> {\n const body = (await response.json().catch(() => null)) as {\n error?: unknown;\n error_description?: unknown;\n } | null;\n if (\n body?.error !== SESSION_CHANGED &&\n body?.error_description !== SESSION_CHANGED\n ) {\n return false;\n }\n return (await HttpClient.confirmSessionTenant()) !== null;\n }\n\n private async performRefresh(): Promise<void> {\n try {\n if (this.onTokenRefresh) await this.onTokenRefresh();\n\n const clientId = getRuntimeEnv(\"BLOCKS_OIDC_CLIENT_ID\");\n // Resolve IAM the same way iamClient does, so a blocks-iam preview refreshes\n // against itself rather than shared dev. Deliberately NOT this.getBaseURL():\n // non-IAM apps refresh against IAM, not against their own service. Falls back\n // to BLOCKS_IAM_BASE_URL when userBaseUrl has not been set yet.\n const baseUrl = resolveBaseUrl(\"user\");\n const blocksKey = this.getBlocksKey();\n\n if (!clientId || !baseUrl || !blocksKey) {\n throw new Error(\"Missing OIDC refresh configuration\");\n }\n\n const formData = new URLSearchParams();\n formData.append(\"grant_type\", \"refresh_token\");\n // Placeholder — the real refresh token lives in an HttpOnly\n // cookie and is sent automatically via credentials: \"include\".\n // The OIDC endpoint just requires this field to be present.\n formData.append(\"refresh_token\", '\"\"');\n formData.append(\"client_id\", clientId);\n\n const url = `${baseUrl.replace(/\\/$/, \"\")}${AUTH_ENDPOINTS.OIDC_TOKEN}?tenant_id=${blocksKey}`;\n\n const response = await fetch(url, {\n method: \"POST\",\n body: formData,\n headers: {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n \"X-Blocks-Key\": blocksKey,\n },\n credentials: \"include\",\n signal: timeoutSignal(REFRESH_TIMEOUT_MS),\n });\n\n if (!response.ok) {\n // Not a sign-out: the retry that follows is held to the same tenant check as after any\n // other refresh.\n if (await this.isReplacedSession(response)) return;\n throw new Error(\"Failed to refresh token\");\n }\n } catch (error) {\n this.handleRefreshFailure(error);\n throw error;\n }\n }\n\n // Runs exactly once per failed refresh, regardless of how many\n // concurrent requests were waiting on it.\n private handleRefreshFailure(error: unknown): void {\n if (this.onUnauthorized) this.onUnauthorized(error);\n\n const queryClient = getQueryClient();\n useAuthStore.getState().resetAuthStore();\n useProjectStore.getState().resetProjectStore();\n queryClient.cancelQueries();\n queryClient.clear();\n\n if (!this.autoRedirectOnAuthFailure) return;\n if (typeof window === \"undefined\") return;\n\n const { pathname } = window.location;\n const shouldRedirect = !this.excludedPaths.some((path) =>\n pathname.startsWith(path),\n );\n\n if (shouldRedirect) {\n window.location.replace(this.loginRedirectPath);\n }\n }\n\n private async throwIfNotOk(response: Response): Promise<void> {\n if (response.ok) return;\n const errorBody = await response.json().catch(() => ({}));\n throw new HttpError(response.status, {\n errors: errorBody?.errors || errorBody || { general: \"Request failed\" },\n });\n }\n\n private normalizeRequestError(error: unknown): HttpError {\n if (error instanceof HttpError) return error;\n if (typeof error === \"object\" && error !== null) {\n return new HttpError(500, {\n errors: error as Record<string, string | string[]>,\n });\n }\n return new HttpError(500, { errors: { general: \"Something went wrong\" } });\n }\n\n /**\n * Normalises a request failure and hands it to `onError` before it is thrown.\n *\n * Reporting happens here rather than at the call sites because this is the last point at which\n * the original error still exists: `normalizeRequestError` collapses everything to an\n * `HttpError` with status 500, so afterwards a transport failure is indistinguishable from a\n * server fault. Anything `onError` throws is swallowed -- a reporting failure must never turn a\n * handled request failure into an unhandled one.\n */\n private failRequest(\n error: unknown,\n url: string,\n method: RequestOptions[\"method\"],\n ): HttpError {\n const normalized = this.normalizeRequestError(error);\n\n if (this.onError) {\n try {\n this.onError({\n error,\n normalized,\n url,\n method,\n // Not already an HttpError means the server gave no usable answer: no HTTP response\n // came back (DNS, CORS, TLS, offline, abort), a success body could not be read or\n // parsed as JSON, or this client threw.\n transport: !(error instanceof HttpError),\n });\n } catch {\n // Intentionally swallowed.\n }\n }\n\n return normalized;\n }\n\n /**\n * Decodes a success response. A response without data resolves to the envelope\n * `{ success: true, status }`: 204 and 205 (checked before the content type, since they never\n * carry a body), no content type, and a JSON-branch response with `content-length: 0` or a blank\n * body. JSON is read with `text()` and `JSON.parse`, so an empty body never reaches the parser,\n * while a non-empty body that is not JSON still throws its `SyntaxError`.\n */\n private async parseSuccessResponse<T>(response: Response): Promise<T> {\n const noData = { success: true, status: response.status } as T;\n if (response.status === 204 || response.status === 205) return noData;\n\n const contentType = response.headers.get(\"content-type\")?.toLowerCase();\n if (!contentType) return noData;\n\n if (contentType.includes(\"text/html\")) {\n throw new HttpError(response.status, {\n errors: { general: \"Unexpected HTML response from server\" },\n });\n }\n\n if (contentType.includes(\"text/\"))\n return (await response.text()) as unknown as T;\n\n if (\n contentType.includes(\"image/\") ||\n contentType.includes(\"application/octet-stream\") ||\n contentType.includes(\"application/pdf\")\n ) {\n return (await response.blob()) as unknown as T;\n }\n\n if (response.headers.get(\"content-length\") === \"0\") return noData;\n\n const text = await response.text();\n if (text.trim() === \"\") return noData;\n return JSON.parse(text) as T;\n }\n\n private async request<T = unknown>(\n url: string,\n requestOption: RequestOptions,\n ): Promise<T> {\n const {\n method,\n body,\n headers,\n absoluteUrl = false,\n skipBlocksKey = false,\n withCredentials = true,\n skipTokenRotation = false,\n skipSessionCheck = false,\n signal,\n } = requestOption;\n\n const fullUrl = absoluteUrl ? url : `${this.getBaseURL()}${url}`;\n const normalizedHeaders = this.normalizeHeaders(headers, skipBlocksKey);\n // Read before sending: the page may move on while this request waits for a refresh.\n const expectedTenant = HttpClient.expectedTenant(skipSessionCheck);\n\n const config: RequestInit = {\n method,\n headers: normalizedHeaders,\n credentials: withCredentials ? \"include\" : \"omit\",\n body: this.prepareBody(body, normalizedHeaders),\n signal,\n };\n\n try {\n const response = await fetch(fullUrl, config);\n\n if (response.status === 401 && !skipTokenRotation) {\n let confirmedTenant: string | null;\n try {\n confirmedTenant = await this.refreshAccessToken();\n } catch {\n throw new HttpError(401, {\n errors: { general: \"Session expired\" },\n });\n }\n if (HttpClient.hasSessionMoved(expectedTenant, confirmedTenant)) {\n throw sessionMovedError();\n }\n return this.request<T>(url, {\n ...requestOption,\n skipTokenRotation: true,\n });\n }\n\n await this.throwIfNotOk(response);\n\n // Awaited so a decode failure lands in the catch below and goes through onError. The\n // retry above stays un-awaited: it runs its own failRequest, so onError fires once.\n return await this.parseSuccessResponse<T>(response);\n } catch (error) {\n throw this.failRequest(error, fullUrl, method);\n }\n }\n\n get<T = unknown>(\n url: string,\n headers?: HeadersInitValue,\n options?: HttpClientOptions,\n ): Promise<T> {\n return this.request<T>(url, { method: \"GET\", headers, ...options });\n }\n\n post<T = unknown>(\n url: string,\n body: RequestBody,\n headers?: HeadersInitValue,\n options?: HttpClientOptions,\n ): Promise<T> {\n return this.request<T>(url, { method: \"POST\", body, headers, ...options });\n }\n\n put<T = unknown>(\n url: string,\n body: RequestBody,\n headers?: HeadersInitValue,\n options?: HttpClientOptions,\n ): Promise<T> {\n return this.request<T>(url, { method: \"PUT\", body, headers, ...options });\n }\n\n patch<T = unknown>(\n url: string,\n body: RequestBody,\n headers?: HeadersInitValue,\n options?: HttpClientOptions,\n ): Promise<T> {\n return this.request<T>(url, { method: \"PATCH\", body, headers, ...options });\n }\n\n delete<T = unknown>(\n url: string,\n headers?: HeadersInitValue,\n options?: HttpClientOptions,\n ): Promise<T> {\n return this.request<T>(url, { method: \"DELETE\", headers, ...options });\n }\n\n async stream(\n url: string,\n body: RequestBody,\n headers?: HeadersInitValue,\n options?: HttpClientOptions,\n ): Promise<ReadableStream<Uint8Array>> {\n const {\n absoluteUrl = false,\n skipBlocksKey = false,\n withCredentials = true,\n skipTokenRotation = false,\n skipSessionCheck = false,\n signal,\n } = options || {};\n\n const fullUrl = absoluteUrl ? url : `${this.getBaseURL()}${url}`;\n const normalizedHeaders = this.normalizeHeaders(headers, skipBlocksKey);\n const expectedTenant = HttpClient.expectedTenant(skipSessionCheck);\n\n try {\n const response = await fetch(fullUrl, {\n method: \"POST\",\n headers: normalizedHeaders,\n credentials: withCredentials ? \"include\" : \"omit\",\n body: this.prepareBody(body, normalizedHeaders),\n signal,\n });\n\n if (response.status === 401 && !skipTokenRotation) {\n let confirmedTenant: string | null;\n try {\n confirmedTenant = await this.refreshAccessToken();\n } catch {\n throw new HttpError(401, {\n errors: { general: \"Session expired\" },\n });\n }\n if (HttpClient.hasSessionMoved(expectedTenant, confirmedTenant)) {\n throw sessionMovedError();\n }\n return this.stream(url, body, headers, {\n ...options,\n skipTokenRotation: true,\n });\n }\n\n await this.throwIfNotOk(response);\n\n if (!response.body) {\n throw new HttpError(response.status, {\n errors: { general: \"Response body is not readable\" },\n });\n }\n\n return response.body;\n } catch (error) {\n throw this.failRequest(error, fullUrl, \"POST\");\n }\n }\n}\n","import { HttpClient } from \"@/lib/http/client\";\nimport { getRuntimeEnv } from \"@/lib/runtime-env\";\nimport { resolveBaseUrl } from \"@/lib/http/util\";\n\nexport const iamClient = new HttpClient({\n baseURL: () => resolveBaseUrl(\"user\"),\n blocksKey: () => getRuntimeEnv(\"BLOCKS_X_BLOCKS_KEY\"),\n});\n\nexport const logicClient = new HttpClient({\n baseURL: () => resolveBaseUrl(\"project\"),\n blocksKey: () => getRuntimeEnv(\"BLOCKS_X_BLOCKS_KEY\"),\n});\n\nexport const notificationClient = new HttpClient({\n baseURL: () => resolveBaseUrl(\"notification\"),\n blocksKey: () => getRuntimeEnv(\"BLOCKS_X_BLOCKS_KEY\"),\n});\n","/**\n * Resolves placeholders in window.__BLOCKS_ENV__ using getRuntimeEnv.\n * This should be imported as early as possible in the application entry point\n * to ensure that all services and libraries receive the actual environment values\n * instead of the __BLOCKS_...__ placeholders.\n */\nexport const resolveEnv = () => {\n if (typeof window === \"undefined\") return;\n\n // Same wider cast here for the same reason\n const blocksEnv = window.__BLOCKS_ENV__ as\n Record<string, string | undefined> | undefined;\n\n if (!blocksEnv) return;\n\n for (const key in blocksEnv) {\n const value = blocksEnv[key];\n if (value?.startsWith(\"__BLOCKS_\") && value.endsWith(\"__\")) {\n blocksEnv[key] = import.meta.env[key] || \"\";\n }\n }\n};\n\n// Execute immediately upon import\nresolveEnv();\n","import type { Transition, Variants } from \"framer-motion\";\n\nexport const motionEase = [0.16, 1, 0.3, 1] as const;\n\nexport const fadeTransition: Transition = { duration: 0.2, ease: motionEase };\n\nexport const fadeInUp: Variants = {\n initial: { opacity: 0, y: 8 },\n animate: { opacity: 1, y: 0 },\n exit: { opacity: 0, y: -6 },\n};\n\nexport const fadeInScale: Variants = {\n initial: { opacity: 0, scale: 0.96 },\n animate: { opacity: 1, scale: 1 },\n exit: { opacity: 0, scale: 0.98 },\n};\n\nexport const staggerContainer: Variants = {\n animate: {\n transition: { staggerChildren: 0.06, delayChildren: 0.02 },\n },\n};\n\nexport const staggerItem: Variants = {\n initial: { opacity: 0, y: 10 },\n animate: { opacity: 1, y: 0 },\n};\n","/**\n * Cross-tab ownership of the impersonation cookie.\n *\n * The access token lives in a cookie named after the application domain alone -- no tenant, no\n * project, no per-tab discriminator -- so every tab on the origin shares exactly one token. The tab\n * that impersonated most recently owns it; every other tab is pointed somewhere it does not know\n * about.\n *\n * Nothing in the browser can detect that from inside a tab. The cookie is `HttpOnly`, so neither\n * `document.cookie` nor CookieStore change events can see it, and the only server-side signal --\n * the impersonation status endpoint -- is refetched on window focus. A tab that is *visible but not\n * focused* (a second monitor) therefore keeps polling happily under another project's token, with\n * its own store and its own route agreeing with each other and both being stale.\n *\n * Comparing two client-side values cannot catch that: the staleness is in both of them. The signal\n * has to come from outside the tab. This module is that signal.\n *\n * `BroadcastChannel` is scoped to the origin, which is precisely the set of tabs that share the\n * cookie -- coordination reach and conflict reach are the same set, so nothing is over- or\n * under-notified. Where it is unavailable we fall back to a `localStorage` write, whose `storage`\n * event fires in every *other* tab of the origin and gives the same reach.\n */\n\nconst CHANNEL_NAME = \"blocks:tenant\";\nconst STORAGE_KEY = \"blocks:tenant-owner\";\n\nexport interface TenantClaim {\n /** The tenant the claiming tab impersonated. */\n tenantId: string;\n /** Identifies the claiming tab so it can ignore its own message. */\n tabId: string;\n ts: number;\n}\n\n/**\n * Asks the other tabs whether any of them is still working inside `probedTenantId`.\n *\n * The field names deliberately share nothing with `TenantClaim`: a tab still running an older build\n * validates messages by `tenantId` and `tabId`, and must never mistake a question for a claim.\n */\ninterface OwnerProbe {\n kind: \"owner-probe\";\n probeId: string;\n probedTenantId: string;\n}\n\n/** The answer to an `OwnerProbe`, sent only by a tab that holds the probed tenant right now. */\ninterface OwnerPresent {\n kind: \"owner-present\";\n probeId: string;\n}\n\n/**\n * How long a probe waits for a live holder to answer before the claim is judged abandoned. A live\n * tab answers in milliseconds -- BroadcastChannel messages are not subject to background-timer\n * throttling -- so this bounds only the wait for a holder that is not there.\n */\nexport const OWNER_PROBE_TIMEOUT_MS = 300;\n\nconst randomId = (): string => {\n if (typeof crypto !== \"undefined\" && \"randomUUID\" in crypto) {\n return crypto.randomUUID();\n }\n return `${Date.now()}-${Math.random().toString(36).slice(2)}`;\n};\n\n/**\n * Stable for the lifetime of this document -- and only that. A reload is a new document with a new\n * id, while the stored claim survives it; that is why a stored claim from another id is never\n * trusted on its own (see `isTenantHeldElsewhere`).\n */\nexport const TAB_ID: string = randomId();\n\nconst isBrowser = () => typeof window !== \"undefined\";\n\nconst hasBroadcastChannel = () =>\n isBrowser() && typeof BroadcastChannel !== \"undefined\";\n\nlet channel: BroadcastChannel | null = null;\n\nconst getChannel = (): BroadcastChannel | null => {\n if (!hasBroadcastChannel()) return null;\n if (!channel) channel = new BroadcastChannel(CHANNEL_NAME);\n return channel;\n};\n\nconst isTenantClaim = (value: unknown): value is TenantClaim =>\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as TenantClaim).tenantId === \"string\" &&\n typeof (value as TenantClaim).tabId === \"string\";\n\nconst isOwnerProbe = (value: unknown): value is OwnerProbe =>\n typeof value === \"object\" &&\n value !== null &&\n (value as OwnerProbe).kind === \"owner-probe\" &&\n typeof (value as OwnerProbe).probeId === \"string\" &&\n typeof (value as OwnerProbe).probedTenantId === \"string\";\n\nconst isOwnerPresent = (value: unknown): value is OwnerPresent =>\n typeof value === \"object\" &&\n value !== null &&\n (value as OwnerPresent).kind === \"owner-present\" &&\n typeof (value as OwnerPresent).probeId === \"string\";\n\n/** The tenant this tab is working inside right now, as declared by the route guard. */\nlet heldTenantId: string | null = null;\nlet responderInstalled = false;\n\nconst installProbeResponder = () => {\n if (responderInstalled) return;\n const bc = getChannel();\n if (!bc) return;\n responderInstalled = true;\n bc.addEventListener(\"message\", (event: MessageEvent) => {\n const probe: unknown = event.data;\n if (!isOwnerProbe(probe)) return;\n if (!heldTenantId || probe.probedTenantId !== heldTenantId) return;\n const answer: OwnerPresent = {\n kind: \"owner-present\",\n probeId: probe.probeId,\n };\n bc.postMessage(answer);\n });\n};\n\n/**\n * Declare that this tab is working inside `tenantId`, so it answers probes for it. Returns a\n * release function.\n *\n * Held only by a window actually rendering a project's data, never by the console: a console tab\n * has nothing a newly opened project would break, so it must not make that project start detached.\n * The release only clears a hold it still owns, so a later hold is never undone by an earlier one's\n * cleanup.\n */\nexport const holdTenant = (tenantId: string): (() => void) => {\n if (!isBrowser() || !tenantId) return () => undefined;\n heldTenantId = tenantId;\n installProbeResponder();\n return () => {\n if (heldTenantId === tenantId) heldTenantId = null;\n };\n};\n\n/**\n * Whether some *other* live tab is working inside `tenantId` right now.\n *\n * The stored claim cannot answer this by itself. It outlives the tab that wrote it -- a reload\n * gives the same tab a new `TAB_ID`, and a closed tab never withdraws its claim -- so read alone it\n * made a window detach on a notice its own earlier page load had left, or one from a window that no\n * longer existed. Only a live holder answers, and `BroadcastChannel` never delivers a message back\n * to the object that posted it, so this tab cannot answer its own probe.\n *\n * Without `BroadcastChannel` there is no one to ask, and an unknown owner is treated as no owner:\n * the claim subscription still detaches the tab the moment a live window actually takes the cookie.\n */\nexport const isTenantHeldElsewhere = (\n tenantId: string,\n timeoutMs: number = OWNER_PROBE_TIMEOUT_MS,\n): Promise<boolean> => {\n const bc = getChannel();\n if (!bc || !tenantId) return Promise.resolve(false);\n\n const probe: OwnerProbe = {\n kind: \"owner-probe\",\n probeId: randomId(),\n probedTenantId: tenantId,\n };\n\n return new Promise((resolve) => {\n const finish = (held: boolean) => {\n clearTimeout(timer);\n bc.removeEventListener(\"message\", onMessage);\n resolve(held);\n };\n const onMessage = (event: MessageEvent) => {\n const answer: unknown = event.data;\n if (isOwnerPresent(answer) && answer.probeId === probe.probeId) {\n finish(true);\n }\n };\n const timer = setTimeout(() => finish(false), timeoutMs);\n bc.addEventListener(\"message\", onMessage);\n bc.postMessage(probe);\n });\n};\n\n/** Whether two reads of the stored claim describe the same claim, rather than one replacing it. */\nexport const isSameClaim = (\n a: TenantClaim | null,\n b: TenantClaim | null,\n): boolean =>\n !!a &&\n !!b &&\n a.tabId === b.tabId &&\n a.tenantId === b.tenantId &&\n a.ts === b.ts;\n\n/**\n * Announce that this tab has taken the cookie for `tenantId`.\n *\n * Called after a *successful* impersonation only. Announcing an attempt would detach other tabs on\n * the strength of a call that may still fail, leaving every tab detached and none of them owning\n * anything.\n */\nexport const claimTenant = (tenantId: string): void => {\n if (!isBrowser() || !tenantId) return;\n\n const claim: TenantClaim = { tenantId, tabId: TAB_ID, ts: Date.now() };\n\n // Written whether or not BroadcastChannel exists: this is also how a newly opened tab discovers\n // the current owner before it issues its first request (see `readCurrentOwner`).\n try {\n window.localStorage.setItem(STORAGE_KEY, JSON.stringify(claim));\n } catch {\n // Private mode or a storage quota error. The channel below still reaches live tabs; only\n // cold-start discovery is lost, and the guard treats an unknown owner as \"not detached\".\n }\n\n getChannel()?.postMessage(claim);\n};\n\n/**\n * Forget every claim, for a logout. The next user signs in to a root-scoped cookie, and a claim\n * left by the previous one names a tenant that session has nothing to do with.\n */\nexport const clearTenantClaims = (): void => {\n heldTenantId = null;\n if (!isBrowser()) return;\n try {\n window.localStorage.removeItem(STORAGE_KEY);\n } catch {\n // Storage unavailable: there was nothing stored to clear.\n }\n};\n\nconst SIGNED_OUT_STORAGE_KEY = \"blocks:signed-out\";\n\n/**\n * Tells the other tabs that this one signed out. Like the probe, it shares no field names with\n * `TenantClaim`, so a tab on an older build ignores it rather than mistaking it for a claim.\n */\ninterface SignedOut {\n kind: \"signed-out\";\n tabId: string;\n}\n\nconst isSignedOut = (value: unknown): value is SignedOut =>\n typeof value === \"object\" &&\n value !== null &&\n (value as SignedOut).kind === \"signed-out\" &&\n typeof (value as SignedOut).tabId === \"string\";\n\n/**\n * Announce that this tab signed out. The cookie is gone for every tab, but each one keeps showing\n * the previous user's data until its next request fails -- and if someone signs in again first,\n * that request carries the new user's cookie under the old user's page.\n */\nexport const announceSignOut = (): void => {\n if (!isBrowser()) return;\n const message: SignedOut = { kind: \"signed-out\", tabId: TAB_ID };\n const bc = getChannel();\n if (bc) {\n bc.postMessage(message);\n return;\n }\n try {\n window.localStorage.setItem(\n SIGNED_OUT_STORAGE_KEY,\n JSON.stringify({ ...message, ts: Date.now() }),\n );\n } catch {\n // Storage unavailable: the other tabs find out on their next request instead.\n }\n};\n\n/** Subscribe to sign-outs in other tabs. Returns an unsubscribe function. */\nexport const subscribeToSignOut = (onSignOut: () => void): (() => void) => {\n if (!isBrowser()) return () => undefined;\n\n const handle = (message: unknown) => {\n if (isSignedOut(message) && message.tabId !== TAB_ID) onSignOut();\n };\n\n const bc = getChannel();\n if (bc) {\n const listener = (event: MessageEvent) => handle(event.data);\n bc.addEventListener(\"message\", listener);\n return () => bc.removeEventListener(\"message\", listener);\n }\n\n const listener = (event: StorageEvent) => {\n if (event.key !== SIGNED_OUT_STORAGE_KEY || !event.newValue) return;\n try {\n handle(JSON.parse(event.newValue));\n } catch {\n // A malformed entry tells us nothing.\n }\n };\n window.addEventListener(\"storage\", listener);\n return () => window.removeEventListener(\"storage\", listener);\n};\n\n/**\n * The last claim made by any tab on this origin, or null if none is recorded.\n *\n * Used on mount so a tab opened while another already owns the cookie starts in the correct state\n * rather than waiting for the next claim that may never come. A claim from another `tabId` is only\n * a lead: confirm it with `isTenantHeldElsewhere` before acting on it.\n */\nexport const readCurrentOwner = (): TenantClaim | null => {\n if (!isBrowser()) return null;\n try {\n const raw = window.localStorage.getItem(STORAGE_KEY);\n if (!raw) return null;\n const parsed: unknown = JSON.parse(raw);\n return isTenantClaim(parsed) ? parsed : null;\n } catch {\n return null;\n }\n};\n\n/**\n * Subscribe to claims made by other tabs. Returns an unsubscribe function.\n *\n * This tab's own claims are filtered out, so a handler only ever sees a tenant change it did not\n * cause.\n */\nexport const subscribeToTenantClaims = (\n onClaim: (claim: TenantClaim) => void,\n): (() => void) => {\n if (!isBrowser()) return () => undefined;\n\n const handleClaim = (claim: unknown) => {\n if (!isTenantClaim(claim)) return;\n if (claim.tabId === TAB_ID) return;\n onClaim(claim);\n };\n\n const bc = getChannel();\n if (bc) {\n const listener = (event: MessageEvent) => handleClaim(event.data);\n bc.addEventListener(\"message\", listener);\n return () => bc.removeEventListener(\"message\", listener);\n }\n\n // Fallback: `storage` fires only in the tabs that did not write, which is the filtering we want\n // anyway. The tabId check stays as a second line of defence.\n const listener = (event: StorageEvent) => {\n if (event.key !== STORAGE_KEY || !event.newValue) return;\n try {\n handleClaim(JSON.parse(event.newValue));\n } catch {\n // A malformed entry tells us nothing; leaving the tab attached is the safe default because\n // the route guard still compares the tenant on every render.\n }\n };\n window.addEventListener(\"storage\", listener);\n return () => window.removeEventListener(\"storage\", listener);\n};\n"]}
@@ -1,7 +1,7 @@
1
1
  import { refractor } from './chunk-FGY7QM3Y.js';
2
- import { notificationService, useKeyboardShortcut, usePopoverWidth, useBlocksAppConfigStore, useTheme, useLogout, useGetMyOrganizations, useLanguageSwitcher, useGetBlocksNotificationConfig, useLogo, useStartImpersonation, useGetProjects, useGetProject, useImpersonationStatusChecker, useSessionTenantGuard, useStatusFirstOnTabReturn, useStopImpersonation, useRecordClaimedTenant, useSignOut, useLogin, useSignUpAffordance, useSignUpRedirect, useInitiateRedirect, useGetEnvRepositories, useUpdateTenantGroup, useIcon, useDisableProject, projectService, initiateService, useGetNotifications, useMarkAsRead, useMarkAllAsRead, impersonationService, useDebouncedFuseFilter, useUpdateRepositories, usePrefetchRedirect } from './chunk-3OO2YVXW.js';
2
+ import { notificationService, useKeyboardShortcut, usePopoverWidth, useBlocksAppConfigStore, useTheme, useLogout, useGetMyOrganizations, useLanguageSwitcher, useGetBlocksNotificationConfig, useLogo, useStartImpersonation, useGetProjects, useGetProject, useImpersonationStatusChecker, useSessionTenantGuard, useStatusFirstOnTabReturn, useStopImpersonation, useRecordClaimedTenant, useSignOut, useLogin, useSignUpAffordance, useSignUpRedirect, useInitiateRedirect, useGetEnvRepositories, useUpdateTenantGroup, useIcon, useDisableProject, projectService, initiateService, useGetNotifications, useMarkAsRead, useMarkAllAsRead, impersonationService, useDebouncedFuseFilter, useUpdateRepositories, usePrefetchRedirect } from './chunk-LAWQOHY6.js';
3
3
  import { showErrorToast, createStorage, getForwardedToPath, debounce, formatFullDate, formatDate, deepEqual, showSuccessToast, isErrorWithErrors, getServiceBaseUrl, getServiceSwaggerUrl } from './chunk-QHNZOBXR.js';
4
- import { fadeTransition, fadeInUp, staggerContainer, staggerItem, fadeInScale, subscribeToSignOut, subscribeToTenantClaims, holdTenant, iamClient, AUTH_ENDPOINTS, claimTenant, readCurrentOwner, TAB_ID, isTenantHeldElsewhere, isSameClaim, PROFILE_ENDPOINTS } from './chunk-UDFH7SJI.js';
4
+ import { fadeTransition, fadeInUp, staggerContainer, staggerItem, fadeInScale, subscribeToSignOut, subscribeToTenantClaims, holdTenant, iamClient, AUTH_ENDPOINTS, claimTenant, readCurrentOwner, TAB_ID, isTenantHeldElsewhere, isSameClaim, PROFILE_ENDPOINTS } from './chunk-OE5T43AS.js';
5
5
  import { HttpError } from './chunk-7ZZ3KLZD.js';
6
6
  import { defaultRightSidePanelContextValue, RightSidePanelContext, SidebarContext, DashboardLayoutProvider } from './chunk-ECDNFX6H.js';
7
7
  import { useIsMobile, useIsActiveMenu, useFilteredMenus } from './chunk-AHCHUUXM.js';
@@ -6120,12 +6120,12 @@ var ImportFileModalContent = ({
6120
6120
  ) }) });
6121
6121
  };
6122
6122
  var parentClasses = (isSidebarOpen, isActive) => cn(
6123
- "group relative flex h-10 w-full cursor-pointer items-center p-1.5 text-base text-[hsl(var(--low-emphasis))] transition-[padding,gap] duration-200 hover:text-[hsl(var(--high-emphasis))]",
6123
+ "group relative flex min-h-[2.5rem] w-full cursor-pointer items-center p-1.5 text-left text-base text-[hsl(var(--low-emphasis))] transition-[padding,gap] duration-200 hover:text-[hsl(var(--high-emphasis))]",
6124
6124
  isSidebarOpen ? "gap-3 px-4" : "gap-0 justify-center px-0",
6125
6125
  isActive && "!text-primary"
6126
6126
  );
6127
6127
  var childClasses = (isSidebarOpen, isActive) => cn(
6128
- "group relative flex h-10 w-full items-center text-base transition-[padding,gap,color] duration-200",
6128
+ "group relative flex min-h-[2.5rem] w-full items-center text-left text-base transition-[padding,gap,color] duration-200",
6129
6129
  isSidebarOpen ? "gap-2 px-4 pl-8" : "gap-0 justify-center px-4",
6130
6130
  isActive ? "!text-primary" : "text-[hsl(var(--low-emphasis))] hover:text-[hsl(var(--high-emphasis))]"
6131
6131
  );
@@ -6146,8 +6146,8 @@ var ChildMenuItem = ({ menu, isSidebarOpen }) => {
6146
6146
  "span",
6147
6147
  {
6148
6148
  className: cn(
6149
- "inline-block overflow-hidden whitespace-nowrap transition-all duration-200",
6150
- isSidebarOpen ? "w-auto opacity-100" : "w-0 opacity-0"
6149
+ "inline-block overflow-hidden transition-all duration-200",
6150
+ isSidebarOpen ? "min-w-0 flex-1 whitespace-normal break-words opacity-100" : "w-0 whitespace-nowrap opacity-0"
6151
6151
  ),
6152
6152
  children: menu.name
6153
6153
  }
@@ -6168,7 +6168,7 @@ function DesktopLeafMenuItem({
6168
6168
  {
6169
6169
  to: menu.path,
6170
6170
  className: cn(
6171
- "flex w-full items-center transition-[gap] duration-200",
6171
+ "flex w-full min-w-0 items-center transition-[gap] duration-200",
6172
6172
  isSidebarOpen ? "gap-3" : "justify-center gap-0",
6173
6173
  menu.disabled && "pointer-events-none opacity-50"
6174
6174
  ),
@@ -6178,8 +6178,8 @@ function DesktopLeafMenuItem({
6178
6178
  "span",
6179
6179
  {
6180
6180
  className: cn(
6181
- "inline-block overflow-hidden whitespace-nowrap transition-all duration-200",
6182
- isSidebarOpen ? "w-auto opacity-100" : "w-0 opacity-0"
6181
+ "inline-block overflow-hidden transition-all duration-200",
6182
+ isSidebarOpen ? "min-w-0 flex-1 whitespace-normal break-words opacity-100" : "w-0 whitespace-nowrap opacity-0"
6183
6183
  ),
6184
6184
  children: /* @__PURE__ */ jsxs("span", { className: "relative inline-block", children: [
6185
6185
  menu.name,
@@ -6265,7 +6265,7 @@ function DesktopMenuItem({
6265
6265
  {
6266
6266
  className: cn(
6267
6267
  "flex items-center transition-[gap] duration-200",
6268
- isSidebarOpen ? "gap-3" : "w-full justify-center gap-0"
6268
+ isSidebarOpen ? "min-w-0 flex-1 gap-3" : "w-full justify-center gap-0"
6269
6269
  ),
6270
6270
  children: [
6271
6271
  menu.icon ? /* @__PURE__ */ jsx(menu.icon, { className: "h-5 w-5 shrink-0" }) : null,
@@ -6273,8 +6273,8 @@ function DesktopMenuItem({
6273
6273
  "span",
6274
6274
  {
6275
6275
  className: cn(
6276
- "inline-block overflow-hidden whitespace-nowrap transition-all duration-200",
6277
- isSidebarOpen ? "w-auto opacity-100" : "w-0 opacity-0"
6276
+ "inline-block overflow-hidden transition-all duration-200",
6277
+ isSidebarOpen ? "min-w-0 flex-1 whitespace-normal break-words opacity-100" : "w-0 whitespace-nowrap opacity-0"
6278
6278
  ),
6279
6279
  children: /* @__PURE__ */ jsxs("span", { className: "relative inline-block", children: [
6280
6280
  menu.name,
@@ -7369,7 +7369,9 @@ function formatKBMetaDescription(meta, fallbackDescription, t = defaultT) {
7369
7369
  }
7370
7370
  function NotificationItem({
7371
7371
  notification,
7372
- onMarkAsRead
7372
+ onMarkAsRead,
7373
+ href,
7374
+ onOpen
7373
7375
  }) {
7374
7376
  const { t, language } = useT("genesis.shared");
7375
7377
  let denorm = {
@@ -7389,20 +7391,28 @@ function NotificationItem({
7389
7391
  notification.denormalizedPayload
7390
7392
  );
7391
7393
  }
7392
- return /* @__PURE__ */ jsx(
7393
- "div",
7394
- {
7395
- className: `flex cursor-pointer items-start gap-3 border-b px-4 py-3 last:border-b-0 ${!notification.isRead ? "bg-muted/60" : ""}`,
7396
- onMouseEnter: () => {
7397
- if (!notification.isRead) onMarkAsRead(notification.id);
7398
- },
7399
- children: /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1", children: [
7400
- /* @__PURE__ */ jsx("p", { className: "text-sm font-medium", children: formatKBTitle(denorm.title, t) }),
7401
- /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: formatKBMetaDescription(denorm.meta, denorm.description, t) }),
7402
- notification.createdTime && /* @__PURE__ */ jsx("p", { className: "mt-1 text-[11px] text-muted-foreground", children: new Date(notification.createdTime).toLocaleString(language) })
7403
- ] })
7404
- }
7405
- );
7394
+ const rowClassName = `flex w-full items-start gap-3 border-b px-4 py-3 text-left last:border-b-0 ${notification.isRead ? "" : "bg-muted/60"}`;
7395
+ const markAsRead = () => {
7396
+ if (!notification.isRead) onMarkAsRead(notification.id);
7397
+ };
7398
+ const content = /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1", children: [
7399
+ /* @__PURE__ */ jsx("p", { className: "text-sm font-medium", children: formatKBTitle(denorm.title, t) }),
7400
+ /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: formatKBMetaDescription(denorm.meta, denorm.description, t) }),
7401
+ notification.createdTime && /* @__PURE__ */ jsx("p", { className: "mt-1 text-[11px] text-muted-foreground", children: new Date(notification.createdTime).toLocaleString(language) })
7402
+ ] });
7403
+ if (href && onOpen) {
7404
+ return /* @__PURE__ */ jsx(
7405
+ "button",
7406
+ {
7407
+ type: "button",
7408
+ className: `${rowClassName} cursor-pointer hover:bg-muted`,
7409
+ onMouseEnter: markAsRead,
7410
+ onClick: () => onOpen(notification, href),
7411
+ children: content
7412
+ }
7413
+ );
7414
+ }
7415
+ return /* @__PURE__ */ jsx("div", { className: rowClassName, onMouseEnter: markAsRead, children: content });
7406
7416
  }
7407
7417
  function NotificationList({
7408
7418
  notifications,
@@ -7410,7 +7420,9 @@ function NotificationList({
7410
7420
  isFetching,
7411
7421
  listRef,
7412
7422
  onScroll,
7413
- onMarkAsRead
7423
+ onMarkAsRead,
7424
+ getHref,
7425
+ onOpen
7414
7426
  }) {
7415
7427
  const { t } = useT("genesis.shared");
7416
7428
  const isEmpty = notifications.length === 0;
@@ -7425,7 +7437,9 @@ function NotificationList({
7425
7437
  NotificationItem,
7426
7438
  {
7427
7439
  notification,
7428
- onMarkAsRead
7440
+ onMarkAsRead,
7441
+ href: getHref?.(notification),
7442
+ onOpen
7429
7443
  },
7430
7444
  notification.id || idx
7431
7445
  ));
@@ -7443,6 +7457,132 @@ function NotificationList({
7443
7457
  }
7444
7458
  );
7445
7459
  }
7460
+
7461
+ // src/components/common/notification/notification-link.ts
7462
+ var idOf = (payload, key) => {
7463
+ const value = payload[key];
7464
+ return typeof value === "string" && value.trim() !== "" ? encodeURIComponent(value) : null;
7465
+ };
7466
+ var scopedIn = (app) => (path) => ({ app, path, scoped: true });
7467
+ var logic = scopedIn("blocks-logic");
7468
+ var release = scopedIn("blocks-release");
7469
+ var osScoped = scopedIn("blocks-os");
7470
+ var osProject = (groupId, page) => ({
7471
+ app: "blocks-os",
7472
+ path: `/app/project/${groupId}/${page}`,
7473
+ scoped: false
7474
+ });
7475
+ var workflowRunFailed = (p) => {
7476
+ const workflowId = idOf(p, "workflowId");
7477
+ if (!workflowId) return null;
7478
+ const executionId = idOf(p, "executionId");
7479
+ const query = executionId ? `?tab=executions&executionId=${executionId}` : "?tab=executions";
7480
+ return logic(`workflow/${workflowId}${query}`);
7481
+ };
7482
+ var workflowPage = (p) => {
7483
+ const workflowId = idOf(p, "workflowId");
7484
+ return workflowId ? logic(`workflow/${workflowId}`) : null;
7485
+ };
7486
+ var functionRunFailed = (p) => {
7487
+ const functionId = idOf(p, "functionId");
7488
+ if (!functionId) return null;
7489
+ const runId = idOf(p, "runId");
7490
+ const query = runId ? `?tab=runs&runId=${runId}` : "?tab=runs";
7491
+ return logic(`functions/${functionId}${query}`);
7492
+ };
7493
+ var functionPage = (p) => {
7494
+ const functionId = idOf(p, "functionId");
7495
+ return functionId ? logic(`functions/${functionId}`) : null;
7496
+ };
7497
+ var functionChangedByOther = (p) => p.action === "deleted" ? logic("functions") : functionPage(p);
7498
+ var scheduleRegistrationFailed = (p) => {
7499
+ const scheduleId = idOf(p, "scheduleId");
7500
+ return scheduleId ? logic(`schedule/${scheduleId}`) : null;
7501
+ };
7502
+ var buildLogs = (p, tab) => {
7503
+ const repoId = idOf(p, "repoId");
7504
+ const buildId = idOf(p, "buildId");
7505
+ if (!repoId || !buildId) return null;
7506
+ return release(
7507
+ `deployment/repo/${repoId}/deployment-logs/${buildId}?tab=${tab}`
7508
+ );
7509
+ };
7510
+ var repoPage = (p) => {
7511
+ const repoId = idOf(p, "repoId");
7512
+ return repoId ? release(`deployment/repo/${repoId}`) : null;
7513
+ };
7514
+ var autoDeployStatus = (p) => {
7515
+ const repoId = idOf(p, "repoId");
7516
+ const buildId = idOf(p, "buildId");
7517
+ if (repoId && buildId) {
7518
+ return release(`deployment/repo/${repoId}/deployment-live/${buildId}`);
7519
+ }
7520
+ return repoPage(p);
7521
+ };
7522
+ var codeAnalysisFinished = (p) => buildLogs(p, p.analysisType === "SCA" ? "sca" : "sast");
7523
+ var projectPage = (key, page) => (p) => {
7524
+ const groupId = idOf(p, key);
7525
+ return groupId ? osProject(groupId, page) : null;
7526
+ };
7527
+ var organizationDetail = (p) => {
7528
+ const organizationId = idOf(p, "organizationId");
7529
+ return organizationId ? osScoped(`iam/organization-detail/${organizationId}`) : null;
7530
+ };
7531
+ var invitedUserDetail = (p) => {
7532
+ const userId = idOf(p, "invitedUserId");
7533
+ return userId ? osScoped(`iam/user-detail/${userId}`) : null;
7534
+ };
7535
+ var LINK_BUILDERS = {
7536
+ WorkflowRunFailed: workflowRunFailed,
7537
+ ScheduledTriggerDropped: workflowPage,
7538
+ FunctionRunFailed: functionRunFailed,
7539
+ FunctionBuildFinished: functionPage,
7540
+ FunctionChangedByOther: functionChangedByOther,
7541
+ ScheduleRegistrationFailed: scheduleRegistrationFailed,
7542
+ "release-build-finished": (p) => buildLogs(p, "deployment-logs"),
7543
+ "release-auto-deploy-status": autoDeployStatus,
7544
+ "release-deployment-deleted": repoPage,
7545
+ "release-code-analysis-finished": codeAnalysisFinished,
7546
+ "project-setup-failed": projectPage("tenantGroupId", "environments"),
7547
+ "project-ownership-transferred": projectPage("tenantGroupId", "people"),
7548
+ "project-access-changed": projectPage("projectGroupId", "environments"),
7549
+ "iam-organization-setup-finished": organizationDetail,
7550
+ "iam-invitation-mail-failed": invitedUserDetail
7551
+ };
7552
+ var parsePayload = (raw) => {
7553
+ try {
7554
+ const parsed = JSON.parse(raw);
7555
+ return parsed !== null && typeof parsed === "object" ? parsed : null;
7556
+ } catch {
7557
+ return null;
7558
+ }
7559
+ };
7560
+ function getNotificationLink(denormalizedPayload) {
7561
+ const payload = parsePayload(denormalizedPayload);
7562
+ const event = payload?.event;
7563
+ if (!payload || typeof event !== "string") return null;
7564
+ const build = Object.hasOwn(LINK_BUILDERS, event) ? LINK_BUILDERS[event] : void 0;
7565
+ return build ? build(payload) : null;
7566
+ }
7567
+ function getNotificationHref(denormalizedPayload, currentApp, projectItemId) {
7568
+ const link = getNotificationLink(denormalizedPayload);
7569
+ if (link?.app !== currentApp) return null;
7570
+ if (!link.scoped) return link.path;
7571
+ return projectItemId ? `/app/${encodeURIComponent(projectItemId)}/${link.path}` : null;
7572
+ }
7573
+
7574
+ // src/components/common/notification/use-notification-open.ts
7575
+ function useNotificationOpen() {
7576
+ const navigate = useNavigate();
7577
+ const { itemId } = useParams();
7578
+ const app = useBlocksAppConfigStore((state) => state.config.name);
7579
+ const getHref = useCallback(
7580
+ (notification) => getNotificationHref(notification.denormalizedPayload, app, itemId),
7581
+ [app, itemId]
7582
+ );
7583
+ const open = useCallback((href) => navigate(href), [navigate]);
7584
+ return { getHref, open };
7585
+ }
7446
7586
  function Notification() {
7447
7587
  const [open, setOpen] = useState(false);
7448
7588
  useNotificationSocket();
@@ -7456,6 +7596,12 @@ function Notification() {
7456
7596
  handleMarkAsRead,
7457
7597
  handleMarkAllAsRead
7458
7598
  } = useNotificationFeed(open);
7599
+ const { getHref, open: openPage } = useNotificationOpen();
7600
+ const handleOpen = (notification, href) => {
7601
+ if (!notification.isRead) handleMarkAsRead(notification.id);
7602
+ setOpen(false);
7603
+ openPage(href);
7604
+ };
7459
7605
  return /* @__PURE__ */ jsxs(Popover, { open, onOpenChange: setOpen, children: [
7460
7606
  /* @__PURE__ */ jsx(PopoverTrigger, { asChild: true, children: /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsx(NotificationBell, { unreadCount }) }) }),
7461
7607
  /* @__PURE__ */ jsxs(PopoverContent, { className: "w-[370px] p-0", children: [
@@ -7468,7 +7614,9 @@ function Notification() {
7468
7614
  isFetching,
7469
7615
  listRef,
7470
7616
  onScroll: handleScroll,
7471
- onMarkAsRead: handleMarkAsRead
7617
+ onMarkAsRead: handleMarkAsRead,
7618
+ getHref,
7619
+ onOpen: handleOpen
7472
7620
  }
7473
7621
  )
7474
7622
  ] })
@@ -13802,5 +13950,5 @@ var TablePagination2 = React8.forwardRef(
13802
13950
  TablePagination2.displayName = "TablePagination";
13803
13951
 
13804
13952
  export { Accordion, AccordionContent, AccordionItem, AccordionTrigger, Alert, AlertDescription, AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogOverlay, AlertDialogPortal, AlertDialogTitle, AlertDialogTrigger, AlertTitle, AppLoadingSpinner, AppSwitcher, ArchiveProject, AspectRatio, AuthLayout, AuthResolver, Avatar, AvatarFallback, AvatarImage, BackToConsoleNavigator, Badge, Breadcrumb, BreadcrumbEllipsis, BreadcrumbItem, BreadcrumbLink, BreadcrumbList, BreadcrumbPage, BreadcrumbSeparator, Button, Calendar, CallbackPage, Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle, Carousel, CarouselContent, CarouselItem, CarouselNext, CarouselPrevious, ChartContainer, ChartLegend, ChartLegendContent, ChartStyle, ChartTooltip, ChartTooltipContent, Checkbox, Collapsible, CollapsibleContent2 as CollapsibleContent, CollapsibleTrigger2 as CollapsibleTrigger, Command, CommandDialog, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandSeparator, CommandShortcut, ConfirmationModal, ConsoleHeader, ConsoleLayout, ConsolePage, ContextMenu, ContextMenuCheckboxItem, ContextMenuContent, ContextMenuGroup, ContextMenuItem, ContextMenuLabel, ContextMenuPortal, ContextMenuRadioGroup, ContextMenuRadioItem, ContextMenuSeparator, ContextMenuShortcut, ContextMenuSub, ContextMenuSubContent, ContextMenuSubTrigger, ContextMenuTrigger, CopyToClipboardButton, CopyableSnippet, DEFAULT_KANBAN_COLUMNS, DashboardHeader, DashboardLayout, DashboardOverview, DashboardRoute, DashboardSectionCard, DataTable, DataTableHeaderCell, DateRangePicker, DesktopMenuItem, Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogOverlay, DialogPortal, DialogTitle, DialogTrigger, Drawer, DrawerClose, DrawerContent, DrawerDescription, DrawerFooter, DrawerHeader, DrawerOverlay, DrawerPortal, DrawerTitle, DrawerTrigger, DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuPortal, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuSeparator, DropdownMenuShortcut, DropdownMenuSub, DropdownMenuSubContent, DropdownMenuSubTrigger, DropdownMenuTrigger, EditProject, EditProjectDialog, EditProjectForm, EnvironmentCard, EnvironmentList, ErrorBoundary, ErrorDisplay, ErrorDisplayWithCard, FileInput, FileUploader, FileUploaderContent, FileUploaderItem, FilterControls, FilterToolBarMobileView, FilterToolbar, Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage, HoverCard, HoverCardContent, HoverCardTrigger, ImpersonationChecker, ImpersonationSynchronizer, ImpersonationTerminator, ImportFileModalContent, InfiniteScroll, InfiniteScroller, InfoTooltip, Input, InputOTP, InputOTPGroup, InputOTPSeparator, InputOTPSlot, KanbanBoard, KanbanBoardColumn, KanbanBoardContainer, KanbanTaskCard, Label, LanguageSelector, LoadingButton, LoginPage, Logo, MaskedText, Menubar, MenubarCheckboxItem, MenubarContent, MenubarGroup, MenubarItem, MenubarLabel, MenubarMenu, MenubarPortal, MenubarRadioGroup, MenubarRadioItem, MenubarSeparator, MenubarShortcut, MenubarSub, MenubarSubContent, MenubarSubTrigger, MenubarTrigger, MobileMenuItem, MultiSelect, NavigationMenu, NavigationMenuContent, NavigationMenuIndicator, NavigationMenuItem, NavigationMenuLink, NavigationMenuList, NavigationMenuTrigger, NavigationMenuViewport, Notification, OidcLayout, Pagination, PaginationContent, PaginationEllipsis, PaginationItem, PaginationLink, PaginationNext, PaginationPrevious, PasswordInput, Popover, PopoverContent, PopoverTrigger, ProfilePage, Progress, ProjectActions, ProjectCardLoadingSkeleton, ProjectDetail, ProjectList2 as ProjectList, ProjectListRowLoadingSkeleton, ProjectOverview, ProjectRepoList, ProtectedGuard, PublicGuard, PublicLayout, RadioGroup4 as RadioGroup, RadioGroupItem, RenderAlternatively, RenderConditionally, ResizableHandle, ResizablePanel, ResizablePanelGroup, RightSidePanel, RightSidePanelBody, RightSidePanelClose, RightSidePanelDescription, RightSidePanelFooter, RightSidePanelHeader, RightSidePanelProvider, RightSidePanelTitle, RightSidePanelTrigger, ScrollArea, ScrollBar, Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectScrollDownButton, SelectScrollUpButton, SelectSeparator, SelectTrigger, SelectValue, SelectedEnvironment, SelectedProject, Separator, Sheet, SheetClose, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetOverlay, SheetPortal, SheetTitle, SheetTrigger, Sidebar, SidebarCollapsedTooltip, SidebarContent, SidebarFooter, SidebarGroup, SidebarGroupAction, SidebarGroupContent, SidebarGroupLabel, SidebarHeader, SidebarInput, SidebarInset, SidebarMenu, SidebarMenuAction, SidebarMenuBadge, SidebarMenuButton, SidebarMenuDesktop, SidebarMenuItem, SidebarMenuSkeleton, SidebarMenuSub, SidebarMenuSubButton, SidebarMenuSubItem, SidebarMobileView, SidebarProvider, SidebarRail, SidebarSeparator, SidebarTrigger, Skeleton, Slider, Spinner, Stepper, Switch, Table, TableBody, TableCaption, TableCell, TableFooter, TableHead, TableHeader, TableLoadingSkeleton, TablePagination2 as TablePagination, TableRow, Tabs, TabsContent, TabsList, TabsTrigger, Textarea, ThemeSwitcher, Timeline, Toggle, ToggleGroup, ToggleGroupItem, Tooltip, TooltipContent, TooltipProvider, TooltipTrigger, UserDropdownMenu, WizardHorizontalTrackBar, WizardStepContent, WizardStepIndicator, WizardStepViewport, WizardStepperProvider, WizardVerticalTrackBar, badgeVariants, buttonVariants, editProjectFormDefaultValues, editProjectFormSchema, filteredAppSwitcherData, hasDraggableData, kanbanKeyboardCoordinateGetter, navigationMenuTriggerStyle, paginationQueryParsers, sidebarCollapsedTooltipClass, sortQueryParsers, spinnerVariants, toggleVariants, useFileUpload, useFormField, useNotificationSocket, useOidcContext, usePaginationQueryParams, useRightSidePanel, useSortQueryParams, useWizardStepper };
13805
- //# sourceMappingURL=chunk-KA2OOMCU.js.map
13806
- //# sourceMappingURL=chunk-KA2OOMCU.js.map
13953
+ //# sourceMappingURL=chunk-L4V72AAV.js.map
13954
+ //# sourceMappingURL=chunk-L4V72AAV.js.map