@vertesia/ui 1.3.0-dev.20260620.091720Z → 1.3.0-dev.20260621.091702Z

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.
@@ -1 +1 @@
1
- {"version":3,"file":"vertesia-ui-session.js","sources":["session/constants.js","session/auth/firebase.js","session/auth/composable.js","session/auth/useAuthState.js","session/auth/domainRouting.js","session/UserSession.js","session/auth/useCurrentTenant.js","session/UserSessionProvider.js","session/useUXTracking.js"],"sourcesContent":["export const LastSelectedAccountId_KEY = 'composableai.lastSelectedAccountId';\nexport const LastSelectedProjectId_KEY = 'composableai.lastSelectedProjectId';\n//# sourceMappingURL=constants.js.map","import { Env } from '@vertesia/ui/env';\nimport { getAnalytics } from 'firebase/analytics';\nimport { initializeApp } from 'firebase/app';\nimport { getAuth } from 'firebase/auth';\n// Use lazy initialization to avoid accessing Env before it's initialized\nlet _firebaseApp = null;\nlet _analytics = null;\nlet _firebaseAuth = null;\n// Getters that lazily initialize Firebase components when first accessed\nexport function getFirebaseApp() {\n if (!_firebaseApp) {\n try {\n if (!Env.firebase) {\n throw new Error('Firebase configuration is not available in the environment');\n }\n _firebaseApp = initializeApp(Env.firebase);\n }\n catch (error) {\n console.error('Failed to initialize Firebase app:', error);\n throw new Error('Firebase initialization failed - environment may not be properly initialized', {\n cause: error,\n });\n }\n }\n return _firebaseApp;\n}\nexport function getFirebaseAnalytics() {\n if (!_analytics) {\n _analytics = getAnalytics(getFirebaseApp());\n }\n return _analytics;\n}\nexport function getFirebaseAuth() {\n if (!_firebaseAuth) {\n _firebaseAuth = getAuth(getFirebaseApp());\n }\n return _firebaseAuth;\n}\nexport async function setFirebaseTenant(tenantEmail) {\n if (!tenantEmail) {\n console.log('No tenant name or email specified, skipping tenant setup');\n return;\n }\n if (!Env.firebase) {\n console.log('Firebase configuration is not available in the environment');\n return;\n }\n try {\n if (tenantEmail)\n console.log(`Resolving tenant ID from email: ${tenantEmail}`);\n // Add retry logic with exponential backoff\n let retries = 3;\n let retryDelay = 250; // Start with 250ms delay\n while (retries > 0) {\n try {\n // Call the API endpoint to resolve the tenant ID\n const response = await fetch('/api/resolve-tenant', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n tenantEmail: tenantEmail,\n }),\n // Add timeout to prevent hanging requests\n signal: AbortSignal.timeout(5000),\n });\n // Check for network errors\n if (!response) {\n throw new Error('No response received from tenant API');\n }\n // Handle HTTP error responses\n if (!response.ok) {\n // Try to parse the error response\n try {\n const errorData = await response.json();\n console.error('Failed to resolve tenant ID:', errorData.error);\n }\n catch {\n console.error(`Failed to resolve tenant ID: HTTP ${response.status}`);\n }\n // If the error is 404 Not Found, no need to retry\n if (response.status === 404) {\n console.warn(`Tenant not found for ${tenantEmail}`);\n return;\n }\n throw new Error(`HTTP error ${response.status}`);\n }\n // Successfully got a response, parse it\n const data = (await response.json());\n if (data?.firebaseTenantId) {\n const auth = getFirebaseAuth();\n auth.tenantId = data.firebaseTenantId;\n Env.firebase.providerType = data.provider ?? 'oidc';\n console.log(`Tenant ID set to ${auth.tenantId}`);\n return data;\n }\n else {\n console.error(`Invalid response format, missing tenantId for ${tenantEmail}`);\n return; // No need to retry for invalid response format\n }\n }\n catch (fetchError) {\n // Only retry for network-related errors\n if (retries > 1) {\n console.warn(`Tenant resolution failed, retrying in ${retryDelay}ms...`, fetchError);\n await new Promise((resolve) => setTimeout(resolve, retryDelay));\n retryDelay *= 2; // Exponential backoff\n retries--;\n }\n else {\n throw fetchError; // Last retry failed, propagate error\n }\n }\n }\n }\n catch (error) {\n // Final error handler\n console.error('Error setting Firebase tenant:', error instanceof Error ? error.message : 'Unknown error');\n // Continue without tenant ID - authentication will work without multi-tenancy\n // but the user will access the default tenant\n }\n}\nexport async function getFirebaseAuthToken(refresh) {\n const auth = getFirebaseAuth();\n const user = auth.currentUser;\n if (user) {\n return user\n .getIdToken(refresh)\n .then((token) => {\n Env.logger.info('Got Firebase token', {\n vertesia: {\n user_email: user.email,\n user_name: user.displayName,\n user_id: user.uid,\n refresh: refresh,\n },\n });\n return token;\n })\n .catch((err) => {\n Env.logger.error('Failed to get Firebase token', {\n vertesia: {\n user_email: user.email,\n user_name: user.displayName,\n user_id: user.uid,\n refresh: refresh,\n error: err,\n },\n });\n console.error('Failed to get access token', err);\n return null;\n });\n }\n else {\n Env.logger.warn('No user found');\n return Promise.resolve(null);\n }\n}\n//# sourceMappingURL=firebase.js.map","import { Env } from '@vertesia/ui/env';\nimport { jwtDecode } from 'jwt-decode';\nimport { LastSelectedAccountId_KEY, LastSelectedProjectId_KEY } from '../constants';\nimport { getFirebaseAuth, getFirebaseAuthToken } from './firebase';\nlet AUTH_TOKEN_RAW;\nlet AUTH_TOKEN;\nfunction normalizeIssuer(value) {\n return value?.replace(/\\/+$/, '');\n}\nfunction decodeToken(token) {\n return jwtDecode(token);\n}\nfunction isVertesiaIssuedToken(token) {\n if (!token)\n return false;\n try {\n const decoded = decodeToken(token);\n return normalizeIssuer(decoded.iss) === normalizeIssuer(Env.endpoints.sts);\n }\n catch {\n return false;\n }\n}\nexport async function fetchComposableToken(getIdToken, accountId, projectId, ttl, retryCount = 0) {\n console.log(`Getting/refreshing composable token for account ${accountId} and project ${projectId} `);\n Env.logger.info('Getting/refreshing composable token', {\n vertesia: {\n account_id: accountId,\n project_id: projectId,\n retry_count: retryCount,\n },\n });\n const idToken = await getIdToken(); //get from firebase\n if (!idToken) {\n console.log('No id token found - using cookie auth');\n throw new Error('No id token found');\n }\n // Use STS endpoint - either configured or default to sts.vertesia.io\n const stsEndpoint = Env.endpoints.sts;\n console.log('Using STS for token generation:', stsEndpoint);\n Env.logger.info('Using STS for token generation', {\n vertesia: {\n account_id: accountId,\n project_id: projectId,\n sts_url: stsEndpoint,\n },\n });\n try {\n // Call STS to generate a user token\n const stsUrl = new URL(`${stsEndpoint}/token/issue`);\n const requestBody = {\n type: 'user',\n account_id: accountId,\n project_id: projectId,\n expires_at: ttl ? Math.floor(Date.now() / 1000) + ttl : undefined,\n };\n const stsRes = await fetch(stsUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${idToken}`, // Firebase token for authentication\n },\n body: JSON.stringify(requestBody),\n }).catch((error) => {\n console.error('Failed to call STS endpoint', error);\n Env.logger.error('Failed to call STS endpoint', {\n vertesia: {\n account_id: accountId,\n project_id: projectId,\n error: error,\n },\n });\n throw new STSError('Failed to call STS endpoint', stsEndpoint);\n });\n if (idToken && stsRes?.status === 404) {\n // User not found in token-server - call ensure-user endpoint\n console.log('404: User not found - calling ensure-user endpoint');\n Env.logger.info('404: User not found - calling ensure-user endpoint', {\n vertesia: {\n account_id: accountId,\n project_id: projectId,\n status: stsRes?.status,\n },\n });\n const ensureResponse = await fetch(`${Env.endpoints.studio}/auth/ensure-user`, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${idToken}`,\n 'Content-Type': 'application/json',\n },\n });\n if (ensureResponse.status === 412) {\n // No invite - trigger signup\n console.log('412: No invite found - signup required');\n Env.logger.info('412: No invite found - signup required', {\n vertesia: {\n account_id: accountId,\n project_id: projectId,\n },\n });\n const idTokenDecoded = jwtDecode(idToken);\n if (!idTokenDecoded?.email) {\n Env.logger.error('No email found in id token');\n throw new Error('No email found in id token');\n }\n throw new UserNotFoundError('User not found - signup required', idTokenDecoded.email);\n }\n if (ensureResponse.status === 403) {\n // SigninScreen keys the invite-required view off this message.\n Env.logger.warn('403: Customer-domain user requires an invite to join', {\n vertesia: {\n account_id: accountId,\n project_id: projectId,\n },\n });\n throw new Error('Customer-domain user requires an invite to join');\n }\n if (!ensureResponse.ok) {\n console.error('Failed to ensure user exists', ensureResponse.status);\n Env.logger.error('Failed to ensure user exists', {\n vertesia: {\n account_id: accountId,\n project_id: projectId,\n status: ensureResponse.status,\n },\n });\n throw new Error('Failed to ensure user exists');\n }\n // User created/exists - retry token generation\n console.log('User ensured - retrying token generation');\n Env.logger.info('User ensured - retrying token generation', {\n vertesia: {\n account_id: accountId,\n project_id: projectId,\n },\n });\n return fetchComposableToken(getIdToken, accountId, projectId, ttl, retryCount);\n }\n if (idToken && stsRes?.status === 412) {\n console.log(\"412: auth succeeded but user doesn't exist - signup required\", stsRes?.status);\n Env.logger.error(\"412: auth succeeded but user doesn't exist - signup required\", {\n vertesia: {\n account_id: accountId,\n project_id: projectId,\n status: stsRes?.status,\n },\n });\n const idTokenDecoded = jwtDecode(idToken);\n if (!idTokenDecoded?.email) {\n Env.logger.error('No email found in id token');\n throw new Error('No email found in id token');\n }\n Env.logger.error('User not found', {\n vertesia: {\n account_id: accountId,\n project_id: projectId,\n email: idTokenDecoded.email,\n },\n });\n throw new UserNotFoundError('User not found', idTokenDecoded.email);\n }\n if (stsRes.status === 403) {\n // User doesn't have access to the requested account/project, or has no accounts\n // This can happen with:\n // 1. Stale localStorage from previous user\n // 2. User invited to a new account (doesn't have access yet)\n // 3. User exists but has no accounts at all\n if (retryCount > 0) {\n // Already retried without account scope - this is a real authorization failure\n console.error('403: Access denied even without account scope - user may have no accounts');\n Env.logger.error('403: Access denied after retry - authorization failure', {\n vertesia: {\n account_id: accountId,\n project_id: projectId,\n status: stsRes.status,\n retry_count: retryCount,\n },\n });\n throw new Error('Access denied - user may not have access to any accounts');\n }\n console.log('403: Access denied - clearing cached account and retrying without account scope');\n Env.logger.warn('403: Access denied - clearing cached account and retrying', {\n vertesia: {\n account_id: accountId,\n project_id: projectId,\n status: stsRes.status,\n retry_count: retryCount,\n },\n });\n // Clear any stale account/project from localStorage\n localStorage.removeItem(LastSelectedAccountId_KEY);\n if (accountId) {\n localStorage.removeItem(`${LastSelectedProjectId_KEY}-${accountId}`);\n }\n // Retry without account/project scope - let user log in to their default account\n return fetchComposableToken(getIdToken, undefined, undefined, ttl, retryCount + 1);\n }\n if (!stsRes.ok) {\n const errorText = await stsRes.text();\n console.error('STS token generation failed:', stsRes.status, errorText);\n Env.logger.error('STS token generation failed', {\n vertesia: {\n status: stsRes.status,\n error: errorText,\n account_id: accountId,\n project_id: projectId,\n },\n });\n throw new Error(`Failed to get token from STS: ${stsRes.status}`);\n }\n const { token } = await stsRes.json();\n console.log('Successfully got token from STS');\n Env.logger.info('Successfully got token from STS');\n return token;\n }\n catch (error) {\n if (error instanceof UserNotFoundError || error instanceof STSError) {\n throw error; // Re-throw UserNotFoundError and STSError to be handled separately in the caller\n }\n // Clear any stale account/project from localStorage on error\n localStorage.removeItem(LastSelectedAccountId_KEY);\n if (accountId) {\n localStorage.removeItem(`${LastSelectedProjectId_KEY}-${accountId}`);\n }\n console.error('Failed to get composable token from STS', error);\n Env.logger.error('Failed to get composable token from STS', {\n vertesia: {\n account_id: accountId,\n project_id: projectId,\n error: error,\n },\n });\n throw new Error('Failed to get composable token', { cause: error });\n }\n}\n/**\n *\n * @param accountId\n * @param projectId\n * @param ttl time to live for the token in seconds\n * @returns\n */\nexport async function fetchComposableTokenFromFirebaseToken(accountId, projectId, ttl) {\n return fetchComposableToken(getFirebaseAuthToken, accountId, projectId, ttl);\n}\n/**\n * Mint a scoped Vertesia token from an existing Vertesia JWT. STS accepts STS-issued\n * tokens on /token/issue, so this works for sessions established via Central Auth where\n * the browser has no Firebase user.\n */\nexport async function fetchComposableTokenFromVertesiaToken(vertesiaToken, accountId, projectId, ttl) {\n return fetchComposableToken(() => Promise.resolve(vertesiaToken), accountId, projectId, ttl);\n}\n/** Returns the cached Vertesia raw JWT, if any. Does not refresh. */\nexport function getCurrentVertesiaToken() {\n return AUTH_TOKEN_RAW;\n}\nexport async function getComposableToken(accountId, projectId, initToken, forceRefresh = false, useInternalAuth = false) {\n const selectedAccount = accountId ?? localStorage.getItem(LastSelectedAccountId_KEY) ?? undefined;\n const selectedProject = projectId ?? localStorage.getItem(`${LastSelectedProjectId_KEY}-${selectedAccount}`) ?? undefined;\n const devAuthToken = Env.isLocalDev ? Env.devAuthToken : undefined;\n const suppliedToken = devAuthToken ?? initToken ?? AUTH_TOKEN_RAW;\n //token is still valid for more than 5 minutes\n if (!forceRefresh && AUTH_TOKEN_RAW && AUTH_TOKEN && AUTH_TOKEN.exp > Date.now() / 1000 + 300) {\n return { rawToken: AUTH_TOKEN_RAW, token: AUTH_TOKEN, error: false };\n }\n if (!forceRefresh && isVertesiaIssuedToken(suppliedToken)) {\n AUTH_TOKEN_RAW = suppliedToken;\n AUTH_TOKEN = decodeToken(AUTH_TOKEN_RAW);\n if (!AUTH_TOKEN.exp) {\n throw new Error('Invalid composable token');\n }\n return { rawToken: AUTH_TOKEN_RAW, token: AUTH_TOKEN, error: false };\n }\n //token is close to expire, refresh it\n if (!devAuthToken && !useInternalAuth && getFirebaseAuth().currentUser) {\n //we have a firebase user, get the token from there\n AUTH_TOKEN_RAW = await fetchComposableTokenFromFirebaseToken(selectedAccount, selectedProject);\n }\n else if (!devAuthToken && (initToken || AUTH_TOKEN_RAW)) {\n // we have a token already and no firebase user, refresh it\n AUTH_TOKEN_RAW = await fetchComposableToken(() => Promise.resolve(initToken ?? AUTH_TOKEN_RAW), selectedAccount, selectedProject);\n }\n else if (devAuthToken) {\n AUTH_TOKEN_RAW = devAuthToken;\n }\n if (!AUTH_TOKEN_RAW) {\n Env.logger.error('Cannot acquire a composable token', {\n vertesia: {\n account_id: selectedAccount,\n project_id: selectedProject,\n },\n });\n throw new Error('Cannot acquire a composable token');\n }\n AUTH_TOKEN = decodeToken(AUTH_TOKEN_RAW);\n if (!AUTH_TOKEN?.exp || !AUTH_TOKEN_RAW) {\n console.error('Invalid composable token', AUTH_TOKEN);\n Env.logger.error('Invalid composable token', {\n vertesia: {\n account_id: selectedAccount,\n project_id: selectedProject,\n },\n });\n throw new Error('Invalid composable token');\n }\n return { rawToken: AUTH_TOKEN_RAW, token: AUTH_TOKEN, error: false };\n}\nexport class UserNotFoundError extends Error {\n email;\n constructor(message, email) {\n super(message);\n this.name = 'UserNotFoundError';\n this.email = email;\n }\n}\nexport class STSError extends Error {\n stsURL;\n constructor(message, stsURL) {\n super(message);\n this.name = 'STSError';\n this.stsURL = stsURL;\n }\n}\n//# sourceMappingURL=composable.js.map","/**\n * This hook is used to generate and verify state for OAuth2 authorization requests.\n * @returns\n */\nimport { useCallback } from 'react';\nconst AUTH_STATE_KEY = 'auth_state';\nconst STATE_EXPIRY_KEY = 'auth_state_expiry';\nconst STATE_TTL = 5 * 60 * 1000; // 5 min\nexport function useAuthState() {\n // Generate new state\n const generateState = useCallback(() => {\n const state = crypto.randomUUID();\n const expiryTime = Date.now() + STATE_TTL;\n // Store state and expiry\n sessionStorage.setItem(AUTH_STATE_KEY, state);\n sessionStorage.setItem(STATE_EXPIRY_KEY, expiryTime.toString());\n return state;\n }, []);\n // Verify returned state\n const verifyState = useCallback((returnedState) => {\n if (!returnedState) {\n return 'Missing state';\n }\n const savedState = sessionStorage.getItem(AUTH_STATE_KEY);\n const expiryTime = parseInt(sessionStorage.getItem(STATE_EXPIRY_KEY) || '0', 10);\n let reason;\n // Verify state matches and hasn't expired\n if (savedState !== returnedState) {\n reason = `State mismatched (${savedState} !== ${returnedState})`;\n }\n else if (Date.now() > expiryTime) {\n reason = 'State expired';\n }\n else {\n reason = undefined; // No errors\n }\n return reason;\n }, []);\n // Clear state (useful for cleanup)\n const clearState = useCallback(() => {\n sessionStorage.removeItem(AUTH_STATE_KEY);\n sessionStorage.removeItem(STATE_EXPIRY_KEY);\n }, []);\n return { generateState, verifyState, clearState };\n}\n//# sourceMappingURL=useAuthState.js.map","export function shouldUseFirebaseAuth(_hostname) {\n return window.AUTH_MODE === 'firebase';\n}\nexport function shouldRedirectToCentralAuth(_hostname) {\n return !shouldUseFirebaseAuth();\n}\n/**\n * The page URL to return to after a central-auth round-trip (`redirect_uri`).\n *\n * Apps served under a deep gateway mount carry a `<base href=\"/tenants/<t>/apps/<app>/.../app/\">`\n * that the app-gateway injects at serve time. The in-app router rewrites the address bar relative\n * to the origin rather than that mount, so by the time the auth flow runs `window.location` can\n * read as the bare origin `/`. Building `redirect_uri` from that drops the app path, and the\n * post-login token bounces back to a URL that serves no app.\n *\n * Prefer the live location when it still sits under the mount (preserves the in-app deep route);\n * otherwise fall back to `document.baseURI` — the mount, which the router cannot clobber. With no\n * `<base>` element (the Studio UI), `document.baseURI` is the document URL and its `pathname` is a\n * prefix of the live location, so the live URL is used unchanged — no behavior change there.\n */\nexport function authReturnUrl() {\n const base = new URL(document.baseURI);\n const current = new URL(window.location.href);\n const target = current.pathname.startsWith(base.pathname) ? current : base;\n target.hash = '';\n return target;\n}\n//# sourceMappingURL=domainRouting.js.map","import { VertesiaClient } from '@vertesia/client';\nimport { Env } from '@vertesia/ui/env';\nimport { jwtDecode } from 'jwt-decode';\nimport { createContext, useContext } from 'react';\nimport { getComposableToken } from './auth/composable';\nimport { authReturnUrl, shouldRedirectToCentralAuth } from './auth/domainRouting';\nimport { getFirebaseAuth } from './auth/firebase';\nimport { LastSelectedAccountId_KEY, LastSelectedProjectId_KEY } from './constants';\nexport { LastSelectedAccountId_KEY, LastSelectedProjectId_KEY };\nconst CENTRAL_AUTH_REDIRECT = 'https://internal-auth.vertesia.app/';\nclass UserSession {\n isLoading = true;\n client;\n authError;\n authToken;\n setSession;\n lastSelectedAccount;\n lastSelectedProject;\n onboardingComplete;\n constructor(client, setSession) {\n if (client) {\n this.client = client;\n }\n else {\n this.client = new VertesiaClient({\n serverUrl: Env.endpoints.studio,\n storeUrl: Env.endpoints.zeno,\n tokenServerUrl: Env.endpoints.sts,\n });\n }\n if (setSession) {\n this.setSession = setSession;\n }\n this.logout = this.logout.bind(this);\n }\n get store() {\n return this.client.store;\n }\n get user() {\n //compatibility\n return this.authToken;\n }\n get account() {\n //compatibility\n return this.authToken?.account;\n }\n get project() {\n return this.authToken?.project;\n }\n get accounts() {\n //compatibility\n return this.authToken?.accounts;\n }\n get authCallback() {\n return this.rawAuthToken.then((token) => `Bearer ${token}`);\n }\n get rawAuthToken() {\n return getComposableToken().then((res) => {\n const token = res?.rawToken;\n if (!token) {\n throw new Error('No token available');\n }\n this.authToken = jwtDecode(token);\n return token;\n });\n }\n /**\n * Force a fresh Vertesia JWT from STS, bypassing the in-memory cache.\n * Use this when the current token's claims (e.g. `apps`) are suspected\n * stale — STS recomputes the `apps` claim from ACEs on every issuance.\n */\n async refreshAuthToken() {\n const res = await getComposableToken(undefined, undefined, undefined, true);\n const token = res?.rawToken;\n if (!token) {\n throw new Error('No token available');\n }\n this.authToken = jwtDecode(token);\n this.setSession?.(this.clone());\n return this.authToken;\n }\n signOut() {\n //compatibility\n this.logout();\n }\n getAccount() {\n return this.authToken?.account;\n }\n async login(token, options = {}) {\n this.authError = undefined;\n this.isLoading = false;\n this.client.withAuthCallback(() => this.authCallback);\n this.authToken = jwtDecode(token);\n console.log(`Logging in as ${this.authToken?.name} with account ${this.authToken?.account.name} (${this.authToken?.account.id}, and project ${this.authToken?.project?.name} (${this.authToken?.project?.id})`);\n //store selected account in local storage\n localStorage.setItem(LastSelectedAccountId_KEY, this.authToken.account.id);\n localStorage.setItem(`${LastSelectedProjectId_KEY}-${this.authToken.account.id}`, this.authToken.project?.id ?? '');\n // notify the host app of the login\n Env.onLogin?.(this.authToken);\n if (options.loadOnboardingStatus ?? true) {\n await this.fetchOnboardingStatus();\n }\n return Promise.resolve();\n }\n isLoggedIn() {\n return !!this.authToken;\n }\n logout() {\n console.log('Logging out');\n if (shouldRedirectToCentralAuth()) {\n // Redirect to central auth for logout\n // Central auth will handle Firebase logout\n console.log('Using central auth logout');\n this.authError = undefined;\n this.isLoading = false;\n this.authToken = undefined;\n this.setSession = undefined;\n this.client.withAuthCallback(undefined);\n const logoutUrl = new URL(CENTRAL_AUTH_REDIRECT);\n const currentUrl = authReturnUrl();\n logoutUrl.pathname = '/logout';\n logoutUrl.searchParams.set('redirect_uri', currentUrl.toString());\n location.replace(logoutUrl.toString());\n }\n else {\n // Use Firebase logout directly\n console.log('Using Firebase logout');\n const wasLoggedIn = !!this.authToken;\n if (this.authToken) {\n void getFirebaseAuth().signOut();\n }\n this.authError = undefined;\n this.isLoading = false;\n this.authToken = undefined;\n this.setSession = undefined;\n this.client.withAuthCallback(undefined);\n // Navigate to root to avoid React rendering errors when\n // unmounting deeply nested route components during logout.\n // Only navigate if user was actually logged in to avoid\n // infinite reload loop on fresh/incognito sessions.\n if (wasLoggedIn) {\n location.replace('/');\n }\n }\n }\n async switchAccount(targetAccountId) {\n localStorage.setItem(LastSelectedAccountId_KEY, targetAccountId);\n if (this) {\n if (this.account && this.project) {\n localStorage.setItem(`${LastSelectedProjectId_KEY}-${this.account.id}`, this.project.id);\n }\n else if (this.account) {\n localStorage.removeItem(`${LastSelectedProjectId_KEY}-${this.account.id}`);\n }\n }\n window.location.replace(`/?a=${targetAccountId}`);\n }\n async switchProject(targetProjectId) {\n if (this.account) {\n localStorage.setItem(`${LastSelectedProjectId_KEY}-${this.account.id}`, targetProjectId);\n }\n window.location.replace(`/?a=${this.account?.id}&p=${targetProjectId}`);\n }\n async fetchAccounts() {\n return this.client.accounts\n .list()\n .then((accounts) => {\n if (!this.authToken) {\n throw new Error('No token available');\n }\n this.authToken.accounts = accounts;\n this.setSession?.(this.clone());\n })\n .catch((err) => {\n console.error('Failed to fetch accounts', err);\n throw err;\n });\n }\n async fetchProjects(accountId) {\n return this.client.projects\n .list([accountId])\n .then((projects) => {\n if (!this.authToken) {\n throw new Error('No token available');\n }\n this.authToken = {\n ...this.authToken,\n accounts: this.authToken.accounts?.map((account) => {\n if (account.id === accountId) {\n return {\n ...account,\n projects: projects.filter((project) => project.account === accountId),\n };\n }\n return account;\n }),\n };\n this.setSession?.(this.clone());\n })\n .catch((err) => {\n console.error('Failed to fetch projects', err);\n throw err;\n });\n }\n async fetchOnboardingStatus() {\n if (this.onboardingComplete) {\n console.log('Onboarding already completed');\n return false;\n }\n const previousStatus = this.onboardingComplete;\n try {\n const onboarding = await this.client.account.onboardingProgress();\n this.onboardingComplete = Object.values(onboarding).every((value) => value === true);\n if (previousStatus !== this.onboardingComplete) {\n return true;\n }\n this.setSession?.(this.clone());\n }\n catch (error) {\n console.error('Error fetching onboarding status:', error);\n this.onboardingComplete = false;\n this.setSession?.(this.clone());\n }\n return false;\n }\n clone() {\n const session = new UserSession(this.client);\n session.isLoading = this.isLoading;\n session.authError = this.authError;\n session.authToken = this.authToken;\n session.setSession = this.setSession;\n session.lastSelectedAccount = this.lastSelectedAccount;\n session.switchAccount = this.switchAccount;\n session.onboardingComplete = this.onboardingComplete;\n return session;\n }\n}\nconst UserSessionContext = createContext(undefined);\nexport function useUserSession() {\n const session = useContext(UserSessionContext);\n if (!session) {\n throw new Error('useUserSession must be used within a UserSessionProvider');\n }\n return session;\n}\nexport { UserSession, UserSessionContext };\n//# sourceMappingURL=UserSession.js.map","import { i18nInstance, NAMESPACE } from '@vertesia/ui/i18n';\nimport { useEffect, useState } from 'react';\nimport { useUserSession } from '../UserSession';\nexport function useCurrentTenant() {\n const { user } = useUserSession();\n const [currentTenant, setCurrentTenant] = useState(null);\n const [isLoading, setIsLoading] = useState(true);\n const [error, setError] = useState(null);\n useEffect(() => {\n const loadCurrentTenant = async () => {\n if (!user?.email) {\n setCurrentTenant(null);\n setIsLoading(false);\n return;\n }\n try {\n const response = await fetch('/api/resolve-tenant', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n tenantEmail: user.email,\n }),\n });\n if (response.ok) {\n const tenantData = await response.json();\n if (tenantData) {\n // Convert the resolved tenant data to our TenantConfig format\n setCurrentTenant({\n tenantKey: tenantData.name || 'unknown',\n name: tenantData.label || tenantData.name || 'Unknown',\n domain: tenantData.domain || [],\n firebaseTenantId: tenantData.firebaseTenantId,\n provider: tenantData.provider,\n logo: tenantData.logo,\n });\n }\n else {\n setCurrentTenant(null);\n }\n }\n else {\n setCurrentTenant(null);\n }\n }\n catch (error) {\n console.error('Error loading current tenant:', error);\n setError(i18nInstance.getFixedT(null, NAMESPACE)('errors.failedToLoadTenantConfig'));\n setCurrentTenant(null);\n }\n finally {\n setIsLoading(false);\n }\n };\n void loadCurrentTenant();\n }, [user?.email]);\n return {\n currentTenant,\n isLoading,\n error,\n };\n}\n//# sourceMappingURL=useCurrentTenant.js.map","import { jsx as _jsx } from \"react/jsx-runtime\";\nimport { Env } from '@vertesia/ui/env';\nimport { onAuthStateChanged } from 'firebase/auth';\nimport { useEffect, useRef, useState } from 'react';\nimport { getComposableToken, STSError, UserNotFoundError } from './auth/composable';\nimport { authReturnUrl, shouldRedirectToCentralAuth } from './auth/domainRouting';\nimport { getFirebaseAuth } from './auth/firebase';\nimport { useAuthState } from './auth/useAuthState';\nimport { LastSelectedAccountId_KEY, LastSelectedProjectId_KEY, UserSession, UserSessionContext } from './UserSession';\nconst CENTRAL_AUTH_REDIRECT = 'https://internal-auth.vertesia.app/';\nexport function UserSessionProvider({ children, loadOnboardingStatus = true }) {\n const hashParams = new URLSearchParams(location.hash.substring(1));\n const token = hashParams.get('token');\n const state = hashParams.get('state');\n const [session, setSession] = useState(new UserSession());\n const { generateState, verifyState, clearState } = useAuthState();\n const hasInitiatedAuthRef = useRef(false);\n const authFlowRef = useRef(undefined);\n const redirectToCentralAuth = (projectId, accountId) => {\n const url = new URL(`${CENTRAL_AUTH_REDIRECT}?sts=${Env.endpoints.sts ?? 'https://sts.vertesia.io'}`);\n const currentUrl = authReturnUrl();\n if (projectId)\n currentUrl.searchParams.set('p', projectId);\n if (accountId)\n currentUrl.searchParams.set('a', accountId);\n url.searchParams.set('redirect_uri', currentUrl.toString());\n url.searchParams.set('state', generateState());\n location.replace(url.toString());\n };\n authFlowRef.current = () => {\n // Make this effect idempotent - only run auth flow once\n if (hasInitiatedAuthRef.current) {\n console.log('Auth: skipping duplicate auth flow initiation');\n return;\n }\n hasInitiatedAuthRef.current = true;\n console.log('Auth: starting auth flow');\n Env.logger.info('Starting auth flow');\n const currentUrl = new URL(window.location.href);\n const selectedAccount = currentUrl.searchParams.get('a') ?? localStorage.getItem(LastSelectedAccountId_KEY) ?? undefined;\n const selectedProject = currentUrl.searchParams.get('p') ??\n localStorage.getItem(`${LastSelectedProjectId_KEY}-${selectedAccount}`) ??\n undefined;\n console.log('Auth: selected account', selectedAccount);\n console.log('Auth: selected project', selectedProject);\n Env.logger.info('Selected account and project', {\n vertesia: {\n account_id: selectedAccount,\n project_id: selectedProject,\n },\n });\n if (Env.isLocalDev && Env.devAuthToken) {\n session.setSession = setSession;\n getComposableToken(selectedAccount, selectedProject, Env.devAuthToken)\n .then((res) => {\n session.login(res.rawToken).then(() => setSession(session.clone()));\n })\n .catch((err) => {\n console.error('Failed to initialize dev auth token', err);\n Env.logger.error('Failed to initialize dev auth token', {\n vertesia: {\n account_id: selectedAccount,\n project_id: selectedProject,\n error: err,\n },\n });\n session.isLoading = false;\n session.authError = err instanceof Error ? err : new Error(String(err));\n setSession(session.clone());\n });\n return;\n }\n if (token && state) {\n session.setSession = setSession;\n const validationError = verifyState(state);\n if (validationError) {\n console.error(`Auth: invalid state: ${validationError}`);\n Env.logger.error(`Invalid state: ${validationError}`, {\n vertesia: {\n state: state,\n },\n });\n redirectToCentralAuth();\n }\n else {\n clearState();\n }\n getComposableToken(selectedAccount, selectedProject, token, false, shouldRedirectToCentralAuth())\n .then((res) => {\n session.login(res.rawToken, { loadOnboardingStatus }).then(() => {\n setSession(session.clone());\n //cleanup the hash\n window.location.hash = '';\n });\n })\n .catch((err) => {\n // Don't redirect to central auth for UserNotFoundError - let signup flow handle it\n if (err instanceof UserNotFoundError) {\n console.log('User not found - will trigger signup flow', err);\n session.isLoading = false;\n session.authError = err;\n setSession(session.clone());\n return;\n }\n if (err instanceof STSError) {\n console.error('STS error during token exchange', err);\n Env.logger.error('STS error during token exchange', {\n vertesia: {\n account_id: selectedAccount,\n project_id: selectedProject,\n sts_url: err.stsURL,\n error: err,\n },\n });\n window.alert('Authentication failed due to an issue with the authentication service. Please try again later.');\n session.logout();\n setSession(session.clone());\n window.location.hash = '';\n return;\n }\n console.error('Failed to fetch user token from studio, redirecting to central auth', err);\n Env.logger.error('Failed to fetch user token from studio, redirecting to central auth', {\n vertesia: {\n error: err,\n },\n });\n redirectToCentralAuth();\n });\n return;\n }\n let cancelled = false;\n let unsubscribe;\n const startFirebaseOrCentralAuth = () => {\n if (cancelled)\n return;\n // If the current host is not in the Firebase allowlist, central auth owns sign-in.\n if (!session.isLoggedIn()) {\n console.log('Auth: not logged in & no token/state');\n Env.logger.info('Not logged in & no token/state', {\n vertesia: {\n account_id: selectedAccount,\n project_id: selectedProject,\n },\n });\n if (shouldRedirectToCentralAuth()) {\n console.log('Auth: host is not in Firebase auth allowlist, redirecting to central auth with selection', selectedAccount, selectedProject);\n Env.logger.info('Redirecting to central auth with selection', {\n vertesia: {\n account_id: selectedAccount,\n project_id: selectedProject,\n },\n });\n redirectToCentralAuth();\n return; // Don't register onAuthStateChanged listener when redirecting\n }\n console.log('Auth: host is in Firebase auth allowlist');\n Env.logger.info('Host is in Firebase auth allowlist', {\n vertesia: {\n account_id: selectedAccount,\n project_id: selectedProject,\n },\n });\n }\n unsubscribe = onAuthStateChanged(getFirebaseAuth(), async (firebaseUser) => {\n if (firebaseUser) {\n console.log('Auth: successful login with firebase');\n Env.logger.info('Successful login with firebase', {\n vertesia: {\n account_id: selectedAccount,\n project_id: selectedProject,\n },\n });\n session.setSession = setSession;\n await getComposableToken(selectedAccount, selectedProject, undefined, false, shouldRedirectToCentralAuth())\n .then((res) => {\n session\n .login(res.rawToken, { loadOnboardingStatus })\n .then(() => setSession(session.clone()));\n })\n .catch((err) => {\n console.error('Failed to fetch user token from studio', err);\n Env.logger.error('Failed to fetch user token from studio', {\n vertesia: {\n account_id: selectedAccount,\n project_id: selectedProject,\n error: err,\n },\n });\n if (!(err instanceof UserNotFoundError))\n session.logout();\n session.isLoading = false;\n session.authError = err;\n setSession(session.clone());\n });\n }\n else {\n // anonymous user\n console.log('Auth: using anonymous user');\n Env.logger.info('Using anonymous user', {\n vertesia: {\n account_id: selectedAccount,\n project_id: selectedProject,\n },\n });\n session.client.withAuthCallback(undefined);\n session.logout();\n setSession(session.clone());\n }\n });\n };\n if (Env.authTokenProvider) {\n session.setSession = setSession;\n void Env.authTokenProvider()\n .then(async (injectedToken) => {\n if (!injectedToken) {\n startFirebaseOrCentralAuth();\n return;\n }\n const res = await getComposableToken(selectedAccount, selectedProject, injectedToken, false, shouldRedirectToCentralAuth());\n await session.login(res.rawToken, { loadOnboardingStatus });\n if (!cancelled)\n setSession(session.clone());\n })\n .catch((err) => {\n console.warn('Auth: failed to initialize injected auth token', err);\n Env.logger.warn('Failed to initialize injected auth token', {\n vertesia: {\n account_id: selectedAccount,\n project_id: selectedProject,\n error: err,\n },\n });\n startFirebaseOrCentralAuth();\n });\n return () => {\n cancelled = true;\n unsubscribe?.();\n };\n }\n startFirebaseOrCentralAuth();\n return () => {\n cancelled = true;\n unsubscribe?.();\n };\n };\n useEffect(() => {\n return authFlowRef.current?.();\n }, []);\n return _jsx(UserSessionContext.Provider, { value: session, children: children });\n}\n//# sourceMappingURL=UserSessionProvider.js.map","import { Env } from '@vertesia/ui/env';\nimport { logEvent } from 'firebase/analytics';\nimport { getFirebaseAnalytics } from './auth/firebase';\nexport function useUXTracking() {\n //identify user in monitoring and UX systems\n const tagUserSession = async (user) => {\n const signupData = window.localStorage.getItem('composableSignupData');\n if (!user) {\n console.error('No user found -- skipping tagging');\n return;\n }\n if (signupData) {\n window.localStorage.removeItem('composableSignupData');\n }\n };\n //send event to analytics and UX systems\n const trackEvent = (eventName, eventProperties) => {\n if (!Env.isProd) {\n console.debug('track event', eventName, eventProperties);\n }\n //GA via firebase\n logEvent(getFirebaseAnalytics(), eventName, { ...eventProperties, debug_mode: !Env.isProd });\n };\n return {\n tagUserSession,\n trackEvent,\n };\n}\n//# sourceMappingURL=useUXTracking.js.map"],"names":["LastSelectedAccountId_KEY","LastSelectedProjectId_KEY","AUTH_TOKEN_RAW","AUTH_TOKEN","_firebaseApp","_analytics","_firebaseAuth","getFirebaseApp","Env","firebase","Error","initializeApp","error","console","cause","getFirebaseAnalytics","getAnalytics","getFirebaseAuth","getAuth","async","setFirebaseTenant","tenantEmail","log","retries","retryDelay","response","fetch","method","headers","body","JSON","stringify","signal","AbortSignal","timeout","ok","errorData","json","status","warn","data","firebaseTenantId","auth","tenantId","providerType","provider","fetchError","Promise","resolve","setTimeout","message","getFirebaseAuthToken","refresh","user","currentUser","getIdToken","then","token","logger","info","vertesia","user_email","email","user_name","displayName","user_id","uid","catch","err","normalizeIssuer","value","replace","decodeToken","jwtDecode","fetchComposableToken","accountId","projectId","ttl","retryCount","account_id","project_id","retry_count","idToken","stsEndpoint","endpoints","sts","sts_url","stsUrl","URL","requestBody","type","expires_at","Math","floor","Date","now","undefined","stsRes","Authorization","STSError","ensureResponse","studio","idTokenDecoded","UserNotFoundError","localStorage","removeItem","errorText","text","fetchComposableTokenFromFirebaseToken","fetchComposableTokenFromVertesiaToken","vertesiaToken","getCurrentVertesiaToken","getComposableToken","initToken","forceRefresh","useInternalAuth","selectedAccount","getItem","selectedProject","devAuthToken","isLocalDev","suppliedToken","exp","rawToken","iss","isVertesiaIssuedToken","constructor","super","this","name","stsURL","AUTH_STATE_KEY","STATE_EXPIRY_KEY","useAuthState","generateState","useCallback","state","crypto","randomUUID","expiryTime","sessionStorage","setItem","toString","verifyState","returnedState","savedState","parseInt","reason","clearState","shouldRedirectToCentralAuth","_hostname","window","AUTH_MODE","authReturnUrl","base","document","baseURI","current","location","href","target","pathname","startsWith","hash","UserSession","isLoading","client","authError","authToken","setSession","lastSelectedAccount","lastSelectedProject","onboardingComplete","VertesiaClient","serverUrl","storeUrl","zeno","tokenServerUrl","logout","bind","store","account","project","accounts","authCallback","rawAuthToken","res","refreshAuthToken","clone","signOut","getAccount","login","options","withAuthCallback","id","onLogin","loadOnboardingStatus","fetchOnboardingStatus","isLoggedIn","logoutUrl","currentUrl","searchParams","set","wasLoggedIn","switchAccount","targetAccountId","switchProject","targetProjectId","fetchAccounts","list","fetchProjects","projects","map","filter","previousStatus","onboarding","onboardingProgress","Object","values","every","session","UserSessionContext","createContext","useUserSession","useContext","useCurrentTenant","currentTenant","setCurrentTenant","useState","setIsLoading","setError","useEffect","tenantData","tenantKey","label","domain","logo","i18nInstance","getFixedT","NAMESPACE","loadCurrentTenant","UserSessionProvider","children","hashParams","URLSearchParams","substring","get","hasInitiatedAuthRef","useRef","authFlowRef","redirectToCentralAuth","url","String","validationError","alert","unsubscribe","cancelled","startFirebaseOrCentralAuth","onAuthStateChanged","firebaseUser","authTokenProvider","injectedToken","_jsx","Provider","useUXTracking","tagUserSession","signupData","trackEvent","eventName","eventProperties","isProd","debug","logEvent","debug_mode"],"mappings":"qgBAAY,MAACA,EAA4B,qCAC5BC,EAA4B,qCCIzC,ICDIC,EACAC,EDAAC,EAAe,KACfC,EAAa,KACbC,EAAgB,KAEb,SAASC,IACZ,IAAKH,EACD,IACI,IAAKI,EAAIC,SACL,MAAM,IAAIC,MAAM,8DAEpBN,EAAeO,EAAcH,EAAIC,SACrC,CACA,MAAOG,GAEH,MADAC,QAAQD,MAAM,qCAAsCA,GAC9C,IAAIF,MAAM,+EAAgF,CAC5FI,MAAOF,GAEf,CAEJ,OAAOR,CACX,CACO,SAASW,IAIZ,OAHKV,IACDA,EAAaW,EAAaT,MAEvBF,CACX,CACO,SAASY,IAIZ,OAHKX,IACDA,EAAgBY,EAAQX,MAErBD,CACX,CACOa,eAAeC,EAAkBC,GACpC,GAAKA,EAIL,GAAKb,EAAIC,SAIT,IACQY,GACAR,QAAQS,IAAI,mCAAmCD,KAEnD,IAAIE,EAAU,EACVC,EAAa,IACjB,KAAOD,EAAU,GACb,IAEI,MAAME,QAAiBC,MAAM,sBAAuB,CAChDC,OAAQ,OACRC,QAAS,CACL,eAAgB,oBAEpBC,KAAMC,KAAKC,UAAU,CACjBV,YAAaA,IAGjBW,OAAQC,YAAYC,QAAQ,OAGhC,IAAKT,EACD,MAAM,IAAIf,MAAM,wCAGpB,IAAKe,EAASU,GAAI,CAEd,IACI,MAAMC,QAAkBX,EAASY,OACjCxB,QAAQD,MAAM,+BAAgCwB,EAAUxB,MAC5D,CACA,MACIC,QA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ACZD,SAGRxB,EAAU,IACCkB,EAAY5F,YACpB,IACIyG,EAAKzC,EAAmB0C,SAAU,CAAEjM,MAAOsJ,EAASsB,SAAUA,GACzE,CCtPO,SAASsB,IAoBZ,MAAO,CACHC,eAnBmBtP,MAAOkC,IAC1B,MAAMqN,EAAanH,OAAO/C,aAAaa,QAAQ,wBAC1ChE,EAIDqN,GACAnH,OAAO/C,aAAaC,WAAW,wBAJ/B5F,QAAQD,MAAM,sCAiBlB+P,WATe,CAACC,EAAWC,KACtBrQ,EAAIsQ,QACLjQ,QAAQkQ,MAAM,cAAeH,EAAWC,GAG5CG,EAASjQ,IAAwB6P,EAAW,IAAKC,EAAiBI,YAAazQ,EAAIsQ,UAM3F"}
1
+ {"version":3,"file":"vertesia-ui-session.js","sources":["session/constants.js","session/auth/firebase.js","session/auth/composable.js","session/auth/useAuthState.js","session/auth/domainRouting.js","session/UserSession.js","session/auth/useCurrentTenant.js","session/UserSessionProvider.js","session/useUXTracking.js"],"sourcesContent":["export const LastSelectedAccountId_KEY = 'composableai.lastSelectedAccountId';\nexport const LastSelectedProjectId_KEY = 'composableai.lastSelectedProjectId';\n//# sourceMappingURL=constants.js.map","import { Env } from '@vertesia/ui/env';\nimport { getAnalytics } from 'firebase/analytics';\nimport { initializeApp } from 'firebase/app';\nimport { getAuth } from 'firebase/auth';\n// Use lazy initialization to avoid accessing Env before it's initialized\nlet _firebaseApp = null;\nlet _analytics = null;\nlet _firebaseAuth = null;\n// Getters that lazily initialize Firebase components when first accessed\nexport function getFirebaseApp() {\n if (!_firebaseApp) {\n try {\n if (!Env.firebase) {\n throw new Error('Firebase configuration is not available in the environment');\n }\n _firebaseApp = initializeApp(Env.firebase);\n }\n catch (error) {\n console.error('Failed to initialize Firebase app:', error);\n throw new Error('Firebase initialization failed - environment may not be properly initialized', {\n cause: error,\n });\n }\n }\n return _firebaseApp;\n}\nexport function getFirebaseAnalytics() {\n if (!_analytics) {\n _analytics = getAnalytics(getFirebaseApp());\n }\n return _analytics;\n}\nexport function getFirebaseAuth() {\n if (!_firebaseAuth) {\n _firebaseAuth = getAuth(getFirebaseApp());\n }\n return _firebaseAuth;\n}\nexport async function setFirebaseTenant(tenantEmail) {\n if (!tenantEmail) {\n console.log('No tenant name or email specified, skipping tenant setup');\n return;\n }\n if (!Env.firebase) {\n console.log('Firebase configuration is not available in the environment');\n return;\n }\n try {\n if (tenantEmail)\n console.log(`Resolving tenant ID from email: ${tenantEmail}`);\n // Add retry logic with exponential backoff\n let retries = 3;\n let retryDelay = 250; // Start with 250ms delay\n while (retries > 0) {\n try {\n // Call the API endpoint to resolve the tenant ID\n const response = await fetch('/api/resolve-tenant', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n tenantEmail: tenantEmail,\n }),\n // Add timeout to prevent hanging requests\n signal: AbortSignal.timeout(5000),\n });\n // Check for network errors\n if (!response) {\n throw new Error('No response received from tenant API');\n }\n // Handle HTTP error responses\n if (!response.ok) {\n // Try to parse the error response\n try {\n const errorData = await response.json();\n console.error('Failed to resolve tenant ID:', errorData.error);\n }\n catch {\n console.error(`Failed to resolve tenant ID: HTTP ${response.status}`);\n }\n // If the error is 404 Not Found, no need to retry\n if (response.status === 404) {\n console.warn(`Tenant not found for ${tenantEmail}`);\n return;\n }\n throw new Error(`HTTP error ${response.status}`);\n }\n // Successfully got a response, parse it\n const data = (await response.json());\n if (data?.firebaseTenantId) {\n const auth = getFirebaseAuth();\n auth.tenantId = data.firebaseTenantId;\n Env.firebase.providerType = data.provider ?? 'oidc';\n console.log(`Tenant ID set to ${auth.tenantId}`);\n return data;\n }\n else {\n console.error(`Invalid response format, missing tenantId for ${tenantEmail}`);\n return; // No need to retry for invalid response format\n }\n }\n catch (fetchError) {\n // Only retry for network-related errors\n if (retries > 1) {\n console.warn(`Tenant resolution failed, retrying in ${retryDelay}ms...`, fetchError);\n await new Promise((resolve) => setTimeout(resolve, retryDelay));\n retryDelay *= 2; // Exponential backoff\n retries--;\n }\n else {\n throw fetchError; // Last retry failed, propagate error\n }\n }\n }\n }\n catch (error) {\n // Final error handler\n console.error('Error setting Firebase tenant:', error instanceof Error ? error.message : 'Unknown error');\n // Continue without tenant ID - authentication will work without multi-tenancy\n // but the user will access the default tenant\n }\n}\nexport async function getFirebaseAuthToken(refresh) {\n const auth = getFirebaseAuth();\n const user = auth.currentUser;\n if (user) {\n return user\n .getIdToken(refresh)\n .then((token) => {\n Env.logger.info('Got Firebase token', {\n vertesia: {\n user_email: user.email,\n user_name: user.displayName,\n user_id: user.uid,\n refresh: refresh,\n },\n });\n return token;\n })\n .catch((err) => {\n Env.logger.error('Failed to get Firebase token', {\n vertesia: {\n user_email: user.email,\n user_name: user.displayName,\n user_id: user.uid,\n refresh: refresh,\n error: err,\n },\n });\n console.error('Failed to get access token', err);\n return null;\n });\n }\n else {\n Env.logger.warn('No user found');\n return Promise.resolve(null);\n }\n}\n//# sourceMappingURL=firebase.js.map","import { Env } from '@vertesia/ui/env';\nimport { jwtDecode } from 'jwt-decode';\nimport { LastSelectedAccountId_KEY, LastSelectedProjectId_KEY } from '../constants';\nimport { getFirebaseAuth, getFirebaseAuthToken } from './firebase';\nlet AUTH_TOKEN_RAW;\nlet AUTH_TOKEN;\nfunction normalizeIssuer(value) {\n return value?.replace(/\\/+$/, '');\n}\nfunction decodeToken(token) {\n return jwtDecode(token);\n}\nfunction isVertesiaIssuedToken(token) {\n if (!token)\n return false;\n try {\n const decoded = decodeToken(token);\n return normalizeIssuer(decoded.iss) === normalizeIssuer(Env.endpoints.sts);\n }\n catch {\n return false;\n }\n}\nexport async function fetchComposableToken(getIdToken, accountId, projectId, ttl, retryCount = 0) {\n console.log(`Getting/refreshing composable token for account ${accountId} and project ${projectId} `);\n Env.logger.info('Getting/refreshing composable token', {\n vertesia: {\n account_id: accountId,\n project_id: projectId,\n retry_count: retryCount,\n },\n });\n const idToken = await getIdToken(); //get from firebase\n if (!idToken) {\n console.log('No id token found - using cookie auth');\n throw new Error('No id token found');\n }\n // Use STS endpoint - either configured or default to sts.vertesia.io\n const stsEndpoint = Env.endpoints.sts;\n console.log('Using STS for token generation:', stsEndpoint);\n Env.logger.info('Using STS for token generation', {\n vertesia: {\n account_id: accountId,\n project_id: projectId,\n sts_url: stsEndpoint,\n },\n });\n try {\n // Call STS to generate a user token\n const stsUrl = new URL(`${stsEndpoint}/token/issue`);\n const requestBody = {\n type: 'user',\n account_id: accountId,\n project_id: projectId,\n expires_at: ttl ? Math.floor(Date.now() / 1000) + ttl : undefined,\n };\n const stsRes = await fetch(stsUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${idToken}`, // Firebase token for authentication\n },\n body: JSON.stringify(requestBody),\n }).catch((error) => {\n console.error('Failed to call STS endpoint', error);\n Env.logger.error('Failed to call STS endpoint', {\n vertesia: {\n account_id: accountId,\n project_id: projectId,\n error: error,\n },\n });\n throw new STSError('Failed to call STS endpoint', stsEndpoint);\n });\n if (idToken && stsRes?.status === 404) {\n // User not found in token-server - call ensure-user endpoint\n console.log('404: User not found - calling ensure-user endpoint');\n Env.logger.info('404: User not found - calling ensure-user endpoint', {\n vertesia: {\n account_id: accountId,\n project_id: projectId,\n status: stsRes?.status,\n },\n });\n const ensureResponse = await fetch(`${Env.endpoints.studio}/auth/ensure-user`, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${idToken}`,\n 'Content-Type': 'application/json',\n },\n });\n if (ensureResponse.status === 412) {\n // No invite - trigger signup\n console.log('412: No invite found - signup required');\n Env.logger.info('412: No invite found - signup required', {\n vertesia: {\n account_id: accountId,\n project_id: projectId,\n },\n });\n const idTokenDecoded = jwtDecode(idToken);\n if (!idTokenDecoded?.email) {\n Env.logger.error('No email found in id token');\n throw new Error('No email found in id token');\n }\n throw new UserNotFoundError('User not found - signup required', idTokenDecoded.email);\n }\n if (ensureResponse.status === 403) {\n // SigninScreen keys the invite-required view off this message.\n Env.logger.warn('403: Customer-domain user requires an invite to join', {\n vertesia: {\n account_id: accountId,\n project_id: projectId,\n },\n });\n throw new Error('Customer-domain user requires an invite to join');\n }\n if (!ensureResponse.ok) {\n console.error('Failed to ensure user exists', ensureResponse.status);\n Env.logger.error('Failed to ensure user exists', {\n vertesia: {\n account_id: accountId,\n project_id: projectId,\n status: ensureResponse.status,\n },\n });\n throw new Error('Failed to ensure user exists');\n }\n // User created/exists - retry token generation\n console.log('User ensured - retrying token generation');\n Env.logger.info('User ensured - retrying token generation', {\n vertesia: {\n account_id: accountId,\n project_id: projectId,\n },\n });\n return fetchComposableToken(getIdToken, accountId, projectId, ttl, retryCount);\n }\n if (idToken && stsRes?.status === 412) {\n console.log(\"412: auth succeeded but user doesn't exist - signup required\", stsRes?.status);\n Env.logger.error(\"412: auth succeeded but user doesn't exist - signup required\", {\n vertesia: {\n account_id: accountId,\n project_id: projectId,\n status: stsRes?.status,\n },\n });\n const idTokenDecoded = jwtDecode(idToken);\n if (!idTokenDecoded?.email) {\n Env.logger.error('No email found in id token');\n throw new Error('No email found in id token');\n }\n Env.logger.error('User not found', {\n vertesia: {\n account_id: accountId,\n project_id: projectId,\n email: idTokenDecoded.email,\n },\n });\n throw new UserNotFoundError('User not found', idTokenDecoded.email);\n }\n if (stsRes.status === 403) {\n // User doesn't have access to the requested account/project, or has no accounts\n // This can happen with:\n // 1. Stale localStorage from previous user\n // 2. User invited to a new account (doesn't have access yet)\n // 3. User exists but has no accounts at all\n if (retryCount > 0) {\n // Already retried without account scope - this is a real authorization failure\n console.error('403: Access denied even without account scope - user may have no accounts');\n Env.logger.error('403: Access denied after retry - authorization failure', {\n vertesia: {\n account_id: accountId,\n project_id: projectId,\n status: stsRes.status,\n retry_count: retryCount,\n },\n });\n throw new Error('Access denied - user may not have access to any accounts');\n }\n console.log('403: Access denied - clearing cached account and retrying without account scope');\n Env.logger.warn('403: Access denied - clearing cached account and retrying', {\n vertesia: {\n account_id: accountId,\n project_id: projectId,\n status: stsRes.status,\n retry_count: retryCount,\n },\n });\n // Clear any stale account/project from localStorage\n localStorage.removeItem(LastSelectedAccountId_KEY);\n if (accountId) {\n localStorage.removeItem(`${LastSelectedProjectId_KEY}-${accountId}`);\n }\n // Retry without account/project scope - let user log in to their default account\n return fetchComposableToken(getIdToken, undefined, undefined, ttl, retryCount + 1);\n }\n if (!stsRes.ok) {\n const errorText = await stsRes.text();\n console.error('STS token generation failed:', stsRes.status, errorText);\n Env.logger.error('STS token generation failed', {\n vertesia: {\n status: stsRes.status,\n error: errorText,\n account_id: accountId,\n project_id: projectId,\n },\n });\n throw new Error(`Failed to get token from STS: ${stsRes.status}`);\n }\n const { token } = await stsRes.json();\n console.log('Successfully got token from STS');\n Env.logger.info('Successfully got token from STS');\n return token;\n }\n catch (error) {\n if (error instanceof UserNotFoundError || error instanceof STSError) {\n throw error; // Re-throw UserNotFoundError and STSError to be handled separately in the caller\n }\n // Clear any stale account/project from localStorage on error\n localStorage.removeItem(LastSelectedAccountId_KEY);\n if (accountId) {\n localStorage.removeItem(`${LastSelectedProjectId_KEY}-${accountId}`);\n }\n console.error('Failed to get composable token from STS', error);\n Env.logger.error('Failed to get composable token from STS', {\n vertesia: {\n account_id: accountId,\n project_id: projectId,\n error: error,\n },\n });\n throw new Error('Failed to get composable token', { cause: error });\n }\n}\n/**\n *\n * @param accountId\n * @param projectId\n * @param ttl time to live for the token in seconds\n * @returns\n */\nexport async function fetchComposableTokenFromFirebaseToken(accountId, projectId, ttl) {\n return fetchComposableToken(getFirebaseAuthToken, accountId, projectId, ttl);\n}\n/**\n * Mint a scoped Vertesia token from an existing Vertesia JWT. STS accepts STS-issued\n * tokens on /token/issue, so this works for sessions established via Central Auth where\n * the browser has no Firebase user.\n */\nexport async function fetchComposableTokenFromVertesiaToken(vertesiaToken, accountId, projectId, ttl) {\n return fetchComposableToken(() => Promise.resolve(vertesiaToken), accountId, projectId, ttl);\n}\n/** Returns the cached Vertesia raw JWT, if any. Does not refresh. */\nexport function getCurrentVertesiaToken() {\n return AUTH_TOKEN_RAW;\n}\nexport async function getComposableToken(accountId, projectId, initToken, forceRefresh = false, useInternalAuth = false) {\n const selectedAccount = accountId ?? localStorage.getItem(LastSelectedAccountId_KEY) ?? undefined;\n const selectedProject = projectId ?? localStorage.getItem(`${LastSelectedProjectId_KEY}-${selectedAccount}`) ?? undefined;\n const devAuthToken = Env.isLocalDev ? Env.devAuthToken : undefined;\n const suppliedToken = devAuthToken ?? initToken ?? AUTH_TOKEN_RAW;\n //token is still valid for more than 5 minutes\n if (!forceRefresh && AUTH_TOKEN_RAW && AUTH_TOKEN && AUTH_TOKEN.exp > Date.now() / 1000 + 300) {\n return { rawToken: AUTH_TOKEN_RAW, token: AUTH_TOKEN, error: false };\n }\n if (!forceRefresh && isVertesiaIssuedToken(suppliedToken)) {\n AUTH_TOKEN_RAW = suppliedToken;\n AUTH_TOKEN = decodeToken(AUTH_TOKEN_RAW);\n if (!AUTH_TOKEN.exp) {\n throw new Error('Invalid composable token');\n }\n return { rawToken: AUTH_TOKEN_RAW, token: AUTH_TOKEN, error: false };\n }\n //token is close to expire, refresh it\n if (!devAuthToken && !useInternalAuth && getFirebaseAuth().currentUser) {\n //we have a firebase user, get the token from there\n AUTH_TOKEN_RAW = await fetchComposableTokenFromFirebaseToken(selectedAccount, selectedProject);\n }\n else if (!devAuthToken && (initToken || AUTH_TOKEN_RAW)) {\n // we have a token already and no firebase user, refresh it\n AUTH_TOKEN_RAW = await fetchComposableToken(() => Promise.resolve(initToken ?? AUTH_TOKEN_RAW), selectedAccount, selectedProject);\n }\n else if (devAuthToken) {\n AUTH_TOKEN_RAW = devAuthToken;\n }\n if (!AUTH_TOKEN_RAW) {\n Env.logger.error('Cannot acquire a composable token', {\n vertesia: {\n account_id: selectedAccount,\n project_id: selectedProject,\n },\n });\n throw new Error('Cannot acquire a composable token');\n }\n AUTH_TOKEN = decodeToken(AUTH_TOKEN_RAW);\n if (!AUTH_TOKEN?.exp || !AUTH_TOKEN_RAW) {\n console.error('Invalid composable token', AUTH_TOKEN);\n Env.logger.error('Invalid composable token', {\n vertesia: {\n account_id: selectedAccount,\n project_id: selectedProject,\n },\n });\n throw new Error('Invalid composable token');\n }\n return { rawToken: AUTH_TOKEN_RAW, token: AUTH_TOKEN, error: false };\n}\nexport class UserNotFoundError extends Error {\n email;\n constructor(message, email) {\n super(message);\n this.name = 'UserNotFoundError';\n this.email = email;\n }\n}\nexport class STSError extends Error {\n stsURL;\n constructor(message, stsURL) {\n super(message);\n this.name = 'STSError';\n this.stsURL = stsURL;\n }\n}\n//# sourceMappingURL=composable.js.map","/**\n * This hook is used to generate and verify state for OAuth2 authorization requests.\n * @returns\n */\nimport { useCallback } from 'react';\nconst AUTH_STATE_KEY = 'auth_state';\nconst STATE_EXPIRY_KEY = 'auth_state_expiry';\nconst STATE_TTL = 5 * 60 * 1000; // 5 min\nexport function useAuthState() {\n // Generate new state\n const generateState = useCallback(() => {\n const state = crypto.randomUUID();\n const expiryTime = Date.now() + STATE_TTL;\n // Store state and expiry\n sessionStorage.setItem(AUTH_STATE_KEY, state);\n sessionStorage.setItem(STATE_EXPIRY_KEY, expiryTime.toString());\n return state;\n }, []);\n // Verify returned state\n const verifyState = useCallback((returnedState) => {\n if (!returnedState) {\n return 'Missing state';\n }\n const savedState = sessionStorage.getItem(AUTH_STATE_KEY);\n const expiryTime = parseInt(sessionStorage.getItem(STATE_EXPIRY_KEY) || '0', 10);\n let reason;\n // Verify state matches and hasn't expired\n if (savedState !== returnedState) {\n reason = `State mismatched (${savedState} !== ${returnedState})`;\n }\n else if (Date.now() > expiryTime) {\n reason = 'State expired';\n }\n else {\n reason = undefined; // No errors\n }\n return reason;\n }, []);\n // Clear state (useful for cleanup)\n const clearState = useCallback(() => {\n sessionStorage.removeItem(AUTH_STATE_KEY);\n sessionStorage.removeItem(STATE_EXPIRY_KEY);\n }, []);\n return { generateState, verifyState, clearState };\n}\n//# sourceMappingURL=useAuthState.js.map","export function shouldUseFirebaseAuth(_hostname) {\n return window.AUTH_MODE === 'firebase';\n}\nexport function shouldRedirectToCentralAuth(_hostname) {\n return !shouldUseFirebaseAuth();\n}\n/**\n * The page URL to return to after a central-auth round-trip (`redirect_uri`).\n *\n * Apps served under a deep gateway mount carry a `<base href=\"/tenants/<t>/apps/<app>/.../app/\">`\n * that the app-gateway injects at serve time. The in-app router rewrites the address bar relative\n * to the origin rather than that mount, so by the time the auth flow runs `window.location` can\n * read as the bare origin `/`. Building `redirect_uri` from that drops the app path, and the\n * post-login token bounces back to a URL that serves no app.\n *\n * Prefer the live location when it still sits under the mount (preserves the in-app deep route);\n * otherwise fall back to `document.baseURI` — the mount, which the router cannot clobber. With no\n * `<base>` element (the Studio UI), `document.baseURI` is the document URL and its `pathname` is a\n * prefix of the live location, so the live URL is used unchanged — no behavior change there.\n */\nexport function authReturnUrl() {\n const base = new URL(document.baseURI);\n const current = new URL(window.location.href);\n const target = current.pathname.startsWith(base.pathname) ? current : base;\n target.hash = '';\n return target;\n}\n/**\n * The app's mount root URL — the served `<base href>` (or the origin root for the Studio UI).\n *\n * Used for full-reload navigations that intentionally reset to the app root (logout, account /\n * project switch). Building these from a bare `/` drops a gateway-mounted app off its mount and\n * lands on a URL that serves no app; resolving against `document.baseURI` keeps the reload inside\n * the mount. For the Studio UI (no `<base>` element) `document.baseURI` is the origin root, so the\n * behavior is unchanged.\n */\nexport function mountRootUrl() {\n const url = new URL(document.baseURI);\n url.hash = '';\n url.search = '';\n return url;\n}\n//# sourceMappingURL=domainRouting.js.map","import { VertesiaClient } from '@vertesia/client';\nimport { Env } from '@vertesia/ui/env';\nimport { jwtDecode } from 'jwt-decode';\nimport { createContext, useContext } from 'react';\nimport { getComposableToken } from './auth/composable';\nimport { authReturnUrl, mountRootUrl, shouldRedirectToCentralAuth } from './auth/domainRouting';\nimport { getFirebaseAuth } from './auth/firebase';\nimport { LastSelectedAccountId_KEY, LastSelectedProjectId_KEY } from './constants';\nexport { LastSelectedAccountId_KEY, LastSelectedProjectId_KEY };\nconst CENTRAL_AUTH_REDIRECT = 'https://internal-auth.vertesia.app/';\nclass UserSession {\n isLoading = true;\n client;\n authError;\n authToken;\n setSession;\n lastSelectedAccount;\n lastSelectedProject;\n onboardingComplete;\n constructor(client, setSession) {\n if (client) {\n this.client = client;\n }\n else {\n this.client = new VertesiaClient({\n serverUrl: Env.endpoints.studio,\n storeUrl: Env.endpoints.zeno,\n tokenServerUrl: Env.endpoints.sts,\n });\n }\n if (setSession) {\n this.setSession = setSession;\n }\n this.logout = this.logout.bind(this);\n }\n get store() {\n return this.client.store;\n }\n get user() {\n //compatibility\n return this.authToken;\n }\n get account() {\n //compatibility\n return this.authToken?.account;\n }\n get project() {\n return this.authToken?.project;\n }\n get accounts() {\n //compatibility\n return this.authToken?.accounts;\n }\n get authCallback() {\n return this.rawAuthToken.then((token) => `Bearer ${token}`);\n }\n get rawAuthToken() {\n return getComposableToken().then((res) => {\n const token = res?.rawToken;\n if (!token) {\n throw new Error('No token available');\n }\n this.authToken = jwtDecode(token);\n return token;\n });\n }\n /**\n * Force a fresh Vertesia JWT from STS, bypassing the in-memory cache.\n * Use this when the current token's claims (e.g. `apps`) are suspected\n * stale — STS recomputes the `apps` claim from ACEs on every issuance.\n */\n async refreshAuthToken() {\n const res = await getComposableToken(undefined, undefined, undefined, true);\n const token = res?.rawToken;\n if (!token) {\n throw new Error('No token available');\n }\n this.authToken = jwtDecode(token);\n this.setSession?.(this.clone());\n return this.authToken;\n }\n signOut() {\n //compatibility\n this.logout();\n }\n getAccount() {\n return this.authToken?.account;\n }\n async login(token, options = {}) {\n this.authError = undefined;\n this.isLoading = false;\n this.client.withAuthCallback(() => this.authCallback);\n this.authToken = jwtDecode(token);\n console.log(`Logging in as ${this.authToken?.name} with account ${this.authToken?.account.name} (${this.authToken?.account.id}, and project ${this.authToken?.project?.name} (${this.authToken?.project?.id})`);\n //store selected account in local storage\n localStorage.setItem(LastSelectedAccountId_KEY, this.authToken.account.id);\n localStorage.setItem(`${LastSelectedProjectId_KEY}-${this.authToken.account.id}`, this.authToken.project?.id ?? '');\n // notify the host app of the login\n Env.onLogin?.(this.authToken);\n if (options.loadOnboardingStatus ?? true) {\n await this.fetchOnboardingStatus();\n }\n return Promise.resolve();\n }\n isLoggedIn() {\n return !!this.authToken;\n }\n logout() {\n console.log('Logging out');\n if (shouldRedirectToCentralAuth()) {\n // Redirect to central auth for logout\n // Central auth will handle Firebase logout\n console.log('Using central auth logout');\n this.authError = undefined;\n this.isLoading = false;\n this.authToken = undefined;\n this.setSession = undefined;\n this.client.withAuthCallback(undefined);\n const logoutUrl = new URL(CENTRAL_AUTH_REDIRECT);\n const currentUrl = authReturnUrl();\n logoutUrl.pathname = '/logout';\n logoutUrl.searchParams.set('redirect_uri', currentUrl.toString());\n location.replace(logoutUrl.toString());\n }\n else {\n // Use Firebase logout directly\n console.log('Using Firebase logout');\n const wasLoggedIn = !!this.authToken;\n if (this.authToken) {\n void getFirebaseAuth().signOut();\n }\n this.authError = undefined;\n this.isLoading = false;\n this.authToken = undefined;\n this.setSession = undefined;\n this.client.withAuthCallback(undefined);\n // Navigate to the app root to avoid React rendering errors when\n // unmounting deeply nested route components during logout.\n // Use the mount root (not bare '/') so a gateway-mounted app stays\n // on its mount. Only navigate if user was actually logged in to\n // avoid an infinite reload loop on fresh/incognito sessions.\n if (wasLoggedIn) {\n location.replace(mountRootUrl().toString());\n }\n }\n }\n async switchAccount(targetAccountId) {\n localStorage.setItem(LastSelectedAccountId_KEY, targetAccountId);\n if (this) {\n if (this.account && this.project) {\n localStorage.setItem(`${LastSelectedProjectId_KEY}-${this.account.id}`, this.project.id);\n }\n else if (this.account) {\n localStorage.removeItem(`${LastSelectedProjectId_KEY}-${this.account.id}`);\n }\n }\n const url = mountRootUrl();\n url.searchParams.set('a', targetAccountId);\n window.location.replace(url.toString());\n }\n async switchProject(targetProjectId) {\n if (this.account) {\n localStorage.setItem(`${LastSelectedProjectId_KEY}-${this.account.id}`, targetProjectId);\n }\n const url = mountRootUrl();\n if (this.account?.id) {\n url.searchParams.set('a', this.account.id);\n }\n url.searchParams.set('p', targetProjectId);\n window.location.replace(url.toString());\n }\n async fetchAccounts() {\n return this.client.accounts\n .list()\n .then((accounts) => {\n if (!this.authToken) {\n throw new Error('No token available');\n }\n this.authToken.accounts = accounts;\n this.setSession?.(this.clone());\n })\n .catch((err) => {\n console.error('Failed to fetch accounts', err);\n throw err;\n });\n }\n async fetchProjects(accountId) {\n return this.client.projects\n .list([accountId])\n .then((projects) => {\n if (!this.authToken) {\n throw new Error('No token available');\n }\n this.authToken = {\n ...this.authToken,\n accounts: this.authToken.accounts?.map((account) => {\n if (account.id === accountId) {\n return {\n ...account,\n projects: projects.filter((project) => project.account === accountId),\n };\n }\n return account;\n }),\n };\n this.setSession?.(this.clone());\n })\n .catch((err) => {\n console.error('Failed to fetch projects', err);\n throw err;\n });\n }\n async fetchOnboardingStatus() {\n if (this.onboardingComplete) {\n console.log('Onboarding already completed');\n return false;\n }\n const previousStatus = this.onboardingComplete;\n try {\n const onboarding = await this.client.account.onboardingProgress();\n this.onboardingComplete = Object.values(onboarding).every((value) => value === true);\n if (previousStatus !== this.onboardingComplete) {\n return true;\n }\n this.setSession?.(this.clone());\n }\n catch (error) {\n console.error('Error fetching onboarding status:', error);\n this.onboardingComplete = false;\n this.setSession?.(this.clone());\n }\n return false;\n }\n clone() {\n const session = new UserSession(this.client);\n session.isLoading = this.isLoading;\n session.authError = this.authError;\n session.authToken = this.authToken;\n session.setSession = this.setSession;\n session.lastSelectedAccount = this.lastSelectedAccount;\n session.switchAccount = this.switchAccount;\n session.onboardingComplete = this.onboardingComplete;\n return session;\n }\n}\nconst UserSessionContext = createContext(undefined);\nexport function useUserSession() {\n const session = useContext(UserSessionContext);\n if (!session) {\n throw new Error('useUserSession must be used within a UserSessionProvider');\n }\n return session;\n}\nexport { UserSession, UserSessionContext };\n//# sourceMappingURL=UserSession.js.map","import { i18nInstance, NAMESPACE } from '@vertesia/ui/i18n';\nimport { useEffect, useState } from 'react';\nimport { useUserSession } from '../UserSession';\nexport function useCurrentTenant() {\n const { user } = useUserSession();\n const [currentTenant, setCurrentTenant] = useState(null);\n const [isLoading, setIsLoading] = useState(true);\n const [error, setError] = useState(null);\n useEffect(() => {\n const loadCurrentTenant = async () => {\n if (!user?.email) {\n setCurrentTenant(null);\n setIsLoading(false);\n return;\n }\n try {\n const response = await fetch('/api/resolve-tenant', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n tenantEmail: user.email,\n }),\n });\n if (response.ok) {\n const tenantData = await response.json();\n if (tenantData) {\n // Convert the resolved tenant data to our TenantConfig format\n setCurrentTenant({\n tenantKey: tenantData.name || 'unknown',\n name: tenantData.label || tenantData.name || 'Unknown',\n domain: tenantData.domain || [],\n firebaseTenantId: tenantData.firebaseTenantId,\n provider: tenantData.provider,\n logo: tenantData.logo,\n });\n }\n else {\n setCurrentTenant(null);\n }\n }\n else {\n setCurrentTenant(null);\n }\n }\n catch (error) {\n console.error('Error loading current tenant:', error);\n setError(i18nInstance.getFixedT(null, NAMESPACE)('errors.failedToLoadTenantConfig'));\n setCurrentTenant(null);\n }\n finally {\n setIsLoading(false);\n }\n };\n void loadCurrentTenant();\n }, [user?.email]);\n return {\n currentTenant,\n isLoading,\n error,\n };\n}\n//# sourceMappingURL=useCurrentTenant.js.map","import { jsx as _jsx } from \"react/jsx-runtime\";\nimport { Env } from '@vertesia/ui/env';\nimport { onAuthStateChanged } from 'firebase/auth';\nimport { useEffect, useRef, useState } from 'react';\nimport { getComposableToken, STSError, UserNotFoundError } from './auth/composable';\nimport { authReturnUrl, shouldRedirectToCentralAuth } from './auth/domainRouting';\nimport { getFirebaseAuth } from './auth/firebase';\nimport { useAuthState } from './auth/useAuthState';\nimport { LastSelectedAccountId_KEY, LastSelectedProjectId_KEY, UserSession, UserSessionContext } from './UserSession';\nconst CENTRAL_AUTH_REDIRECT = 'https://internal-auth.vertesia.app/';\nexport function UserSessionProvider({ children, loadOnboardingStatus = true }) {\n const hashParams = new URLSearchParams(location.hash.substring(1));\n const token = hashParams.get('token');\n const state = hashParams.get('state');\n const [session, setSession] = useState(new UserSession());\n const { generateState, verifyState, clearState } = useAuthState();\n const hasInitiatedAuthRef = useRef(false);\n const authFlowRef = useRef(undefined);\n const redirectToCentralAuth = (projectId, accountId) => {\n const url = new URL(`${CENTRAL_AUTH_REDIRECT}?sts=${Env.endpoints.sts ?? 'https://sts.vertesia.io'}`);\n const currentUrl = authReturnUrl();\n if (projectId)\n currentUrl.searchParams.set('p', projectId);\n if (accountId)\n currentUrl.searchParams.set('a', accountId);\n url.searchParams.set('redirect_uri', currentUrl.toString());\n url.searchParams.set('state', generateState());\n location.replace(url.toString());\n };\n authFlowRef.current = () => {\n // Make this effect idempotent - only run auth flow once\n if (hasInitiatedAuthRef.current) {\n console.log('Auth: skipping duplicate auth flow initiation');\n return;\n }\n hasInitiatedAuthRef.current = true;\n console.log('Auth: starting auth flow');\n Env.logger.info('Starting auth flow');\n const currentUrl = new URL(window.location.href);\n const selectedAccount = currentUrl.searchParams.get('a') ?? localStorage.getItem(LastSelectedAccountId_KEY) ?? undefined;\n const selectedProject = currentUrl.searchParams.get('p') ??\n localStorage.getItem(`${LastSelectedProjectId_KEY}-${selectedAccount}`) ??\n undefined;\n console.log('Auth: selected account', selectedAccount);\n console.log('Auth: selected project', selectedProject);\n Env.logger.info('Selected account and project', {\n vertesia: {\n account_id: selectedAccount,\n project_id: selectedProject,\n },\n });\n if (Env.isLocalDev && Env.devAuthToken) {\n session.setSession = setSession;\n getComposableToken(selectedAccount, selectedProject, Env.devAuthToken)\n .then((res) => {\n session.login(res.rawToken).then(() => setSession(session.clone()));\n })\n .catch((err) => {\n console.error('Failed to initialize dev auth token', err);\n Env.logger.error('Failed to initialize dev auth token', {\n vertesia: {\n account_id: selectedAccount,\n project_id: selectedProject,\n error: err,\n },\n });\n session.isLoading = false;\n session.authError = err instanceof Error ? err : new Error(String(err));\n setSession(session.clone());\n });\n return;\n }\n if (token && state) {\n session.setSession = setSession;\n const validationError = verifyState(state);\n if (validationError) {\n console.error(`Auth: invalid state: ${validationError}`);\n Env.logger.error(`Invalid state: ${validationError}`, {\n vertesia: {\n state: state,\n },\n });\n redirectToCentralAuth();\n }\n else {\n clearState();\n }\n getComposableToken(selectedAccount, selectedProject, token, false, shouldRedirectToCentralAuth())\n .then((res) => {\n session.login(res.rawToken, { loadOnboardingStatus }).then(() => {\n setSession(session.clone());\n //cleanup the hash\n window.location.hash = '';\n });\n })\n .catch((err) => {\n // Don't redirect to central auth for UserNotFoundError - let signup flow handle it\n if (err instanceof UserNotFoundError) {\n console.log('User not found - will trigger signup flow', err);\n session.isLoading = false;\n session.authError = err;\n setSession(session.clone());\n return;\n }\n if (err instanceof STSError) {\n console.error('STS error during token exchange', err);\n Env.logger.error('STS error during token exchange', {\n vertesia: {\n account_id: selectedAccount,\n project_id: selectedProject,\n sts_url: err.stsURL,\n error: err,\n },\n });\n window.alert('Authentication failed due to an issue with the authentication service. Please try again later.');\n session.logout();\n setSession(session.clone());\n window.location.hash = '';\n return;\n }\n console.error('Failed to fetch user token from studio, redirecting to central auth', err);\n Env.logger.error('Failed to fetch user token from studio, redirecting to central auth', {\n vertesia: {\n error: err,\n },\n });\n redirectToCentralAuth();\n });\n return;\n }\n let cancelled = false;\n let unsubscribe;\n const startFirebaseOrCentralAuth = () => {\n if (cancelled)\n return;\n // If the current host is not in the Firebase allowlist, central auth owns sign-in.\n if (!session.isLoggedIn()) {\n console.log('Auth: not logged in & no token/state');\n Env.logger.info('Not logged in & no token/state', {\n vertesia: {\n account_id: selectedAccount,\n project_id: selectedProject,\n },\n });\n if (shouldRedirectToCentralAuth()) {\n console.log('Auth: host is not in Firebase auth allowlist, redirecting to central auth with selection', selectedAccount, selectedProject);\n Env.logger.info('Redirecting to central auth with selection', {\n vertesia: {\n account_id: selectedAccount,\n project_id: selectedProject,\n },\n });\n redirectToCentralAuth();\n return; // Don't register onAuthStateChanged listener when redirecting\n }\n console.log('Auth: host is in Firebase auth allowlist');\n Env.logger.info('Host is in Firebase auth allowlist', {\n vertesia: {\n account_id: selectedAccount,\n project_id: selectedProject,\n },\n });\n }\n unsubscribe = onAuthStateChanged(getFirebaseAuth(), async (firebaseUser) => {\n if (firebaseUser) {\n console.log('Auth: successful login with firebase');\n Env.logger.info('Successful login with firebase', {\n vertesia: {\n account_id: selectedAccount,\n project_id: selectedProject,\n },\n });\n session.setSession = setSession;\n await getComposableToken(selectedAccount, selectedProject, undefined, false, shouldRedirectToCentralAuth())\n .then((res) => {\n session\n .login(res.rawToken, { loadOnboardingStatus })\n .then(() => setSession(session.clone()));\n })\n .catch((err) => {\n console.error('Failed to fetch user token from studio', err);\n Env.logger.error('Failed to fetch user token from studio', {\n vertesia: {\n account_id: selectedAccount,\n project_id: selectedProject,\n error: err,\n },\n });\n if (!(err instanceof UserNotFoundError))\n session.logout();\n session.isLoading = false;\n session.authError = err;\n setSession(session.clone());\n });\n }\n else {\n // anonymous user\n console.log('Auth: using anonymous user');\n Env.logger.info('Using anonymous user', {\n vertesia: {\n account_id: selectedAccount,\n project_id: selectedProject,\n },\n });\n session.client.withAuthCallback(undefined);\n session.logout();\n setSession(session.clone());\n }\n });\n };\n if (Env.authTokenProvider) {\n session.setSession = setSession;\n void Env.authTokenProvider()\n .then(async (injectedToken) => {\n if (!injectedToken) {\n startFirebaseOrCentralAuth();\n return;\n }\n const res = await getComposableToken(selectedAccount, selectedProject, injectedToken, false, shouldRedirectToCentralAuth());\n await session.login(res.rawToken, { loadOnboardingStatus });\n if (!cancelled)\n setSession(session.clone());\n })\n .catch((err) => {\n console.warn('Auth: failed to initialize injected auth token', err);\n Env.logger.warn('Failed to initialize injected auth token', {\n vertesia: {\n account_id: selectedAccount,\n project_id: selectedProject,\n error: err,\n },\n });\n startFirebaseOrCentralAuth();\n });\n return () => {\n cancelled = true;\n unsubscribe?.();\n };\n }\n startFirebaseOrCentralAuth();\n return () => {\n cancelled = true;\n unsubscribe?.();\n };\n };\n useEffect(() => {\n return authFlowRef.current?.();\n }, []);\n return _jsx(UserSessionContext.Provider, { value: session, children: children });\n}\n//# sourceMappingURL=UserSessionProvider.js.map","import { Env } from '@vertesia/ui/env';\nimport { logEvent } from 'firebase/analytics';\nimport { getFirebaseAnalytics } from './auth/firebase';\nexport function useUXTracking() {\n //identify user in monitoring and UX systems\n const tagUserSession = async (user) => {\n const signupData = window.localStorage.getItem('composableSignupData');\n if (!user) {\n console.error('No user found -- skipping tagging');\n return;\n }\n if (signupData) {\n window.localStorage.removeItem('composableSignupData');\n }\n };\n //send event to analytics and UX systems\n const trackEvent = (eventName, eventProperties) => {\n if (!Env.isProd) {\n console.debug('track event', eventName, eventProperties);\n }\n //GA via firebase\n logEvent(getFirebaseAnalytics(), eventName, { ...eventProperties, debug_mode: !Env.isProd });\n };\n return {\n tagUserSession,\n trackEvent,\n };\n}\n//# sourceMappingURL=useUXTracking.js.map"],"names":["LastSelectedAccountId_KEY","LastSelectedProjectId_KEY","AUTH_TOKEN_RAW","AUTH_TOKEN","_firebaseApp","_analytics","_firebaseAuth","getFirebaseApp","Env","firebase","Error","initializeApp","error","console","cause","getFirebaseAnalytics","getAnalytics","getFirebaseAuth","getAuth","async","setFirebaseTenant","tenantEmail","log","retries","retryDelay","response","fetch","method","headers","body","JSON","stringify","signal","AbortSignal","timeout","ok","errorData","json","status","warn","data","firebaseTenantId","auth","tenantId","providerType","provider","fetchError","Promise","resolve","setTimeout","message","getFirebaseAuthToken","refresh","user","currentUser","getIdToken","then","token","logger","info","vertesia","user_email","email","user_name","displayName","user_id","uid","catch","err","normalizeIssuer","value","replace","decodeToken","jwtDecode","fetchComposableToken","accountId","projectId","ttl","retryCount","account_id","project_id","retry_count","idToken","stsEndpoint","endpoints","sts","sts_url","stsUrl","URL","requestBody","type","expires_at","Math","floor","Date","now","undefined","stsRes","Authorization","STSError","ensureResponse","studio","idTokenDecoded","UserNotFoundError","localStorage","removeItem","errorText","text","fetchComposableTokenFromFirebaseToken","fetchComposableTokenFromVertesiaToken","vertesiaToken","getCurrentVertesiaToken","getComposableToken","initToken","forceRefresh","useInternalAuth","selectedAccount","getItem","selectedProject","devAuthToken","isLocalDev","suppliedToken","exp","rawToken","iss","isVertesiaIssuedToken","constructor","super","this","name","stsURL","AUTH_STATE_KEY","STATE_EXPIRY_KEY","useAuthState","generateState","useCallback","state","crypto","randomUUID","expiryTime","sessionStorage","setItem","toString","verifyState","returnedState","savedState","parseInt","reason","clearState","shouldRedirectToCentralAuth","_hostname","window","AUTH_MODE","authReturnUrl","base","document","baseURI","current","location","href","target","pathname","startsWith","hash","mountRootUrl","url","search","UserSession","isLoading","client","authError","authToken","setSession","lastSelectedAccount","lastSelectedProject","onboardingComplete","VertesiaClient","serverUrl","storeUrl","zeno","tokenServerUrl","logout","bind","store","account","project","accounts","authCallback","rawAuthToken","res","refreshAuthToken","clone","signOut","getAccount","login","options","withAuthCallback","id","onLogin","loadOnboardingStatus","fetchOnboardingStatus","isLoggedIn","logoutUrl","currentUrl","searchParams","set","wasLoggedIn","switchAccount","targetAccountId","switchProject","targetProjectId","fetchAccounts","list","fetchProjects","projects","map","filter","previousStatus","onboarding","onboardingProgress","Object","values","every","session","UserSessionContext","createContext","useUserSession","useContext","useCurrentTenant","currentTenant","setCurrentTenant","useState","setIsLoading","setError","useEffect","tenantData","tenantKey","label","domain","logo","i18nInstance","getFixedT","NAMESPACE","loadCurrentTenant","UserSessionProvider","children","hashParams","URLSearchParams","substring","get","hasInitiatedAuthRef","useRef","authFlowRef","redirectToCentralAuth","String","validationError","alert","unsubscribe","cancelled","startFirebaseOrCentralAuth","onAuthStateChanged","firebaseUser","authTokenProvider","injectedToken","_jsx","Provider","useUXTracking","tagUserSession","signupData","trackEvent","eventName","eventProperties","isProd","debug","logEvent","debug_mode"],"mappings":"qgBAAY,MAACA,EAA4B,qCAC5BC,EAA4B,qCCIzC,ICDIC,EACAC,EDAAC,EAAe,KACfC,EAAa,KACbC,EAAgB,KAEb,SAASC,IACZ,IAAKH,EACD,IACI,IAAKI,EAAIC,SACL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H,OAAO/C,aAAaa,QAAQ,wBAC1ChE,EAIDuN,GACArH,OAAO/C,aAAaC,WAAW,wBAJ/B5F,QAAQD,MAAM,sCAiBlBiQ,WATe,CAACC,EAAWC,KACtBvQ,EAAIwQ,QACLnQ,QAAQoQ,MAAM,cAAeH,EAAWC,GAG5CG,EAASnQ,IAAwB+P,EAAW,IAAKC,EAAiBI,YAAa3Q,EAAIwQ,UAM3F"}
@@ -1,2 +1,2 @@
1
- import{jsx as e,jsxs as t,Fragment as n}from"react/jsx-runtime";import{createContext as i,useContext as r,useState as a,useEffect as o,useMemo as l,useRef as c,useCallback as s}from"react";import{useFetch as d,errorMessage as u,SelectBox as m,Center as p,Button as h,Modal as g,ModalTitle as f,ModalBody as v,Spinner as x,RadioGroup as b,Input as y,useToast as N,ErrorBox as w,ModalFooter as k,Tabs as C,TabsBar as S,TabsPanel as j,VTooltip as z,Popover as I,PopoverTrigger as P,Avatar as A,PopoverContent as L,ModeToggle as T,MenuList as O,ToastProvider as B,ThemeProvider as R}from"@vertesia/ui/core";import{useUserSession as E,LastSelectedAccountId_KEY as D,LastSelectedProjectId_KEY as _,getFirebaseAuth as $,setFirebaseTenant as q,useUXTracking as F,UserNotFoundError as M,getCurrentVertesiaToken as W,fetchComposableTokenFromVertesiaToken as V,fetchComposableTokenFromFirebaseToken as U,UserSessionProvider as H}from"@vertesia/ui/session";import{useUITranslation as J,LanguageProvider as Y,LanguageBoundI18nProvider as G}from"@vertesia/ui/i18n";import{LockIcon as K,LockKeyhole as Q,ArrowRight as X,Mail as Z,ShieldOff as ee,Check as te,CopyIcon as ne}from"lucide-react";import{Env as ie}from"@vertesia/ui/env";import{RegionTag as re}from"@vertesia/ui/layout";import{signOut as ae,signInWithRedirect as oe,OAuthProvider as le,GithubAuthProvider as ce,GoogleAuthProvider as se}from"firebase/auth";import{useLocation as de,useNavigate as ue}from"@vertesia/ui/router";import{getTenantIdFromProject as me,Permission as pe}from"@vertesia/common";import{useUserPermissions as he,TypeRegistryProvider as ge,UserPermissionProvider as fe}from"@vertesia/ui/features";import ve from"clsx";import{AnimatePresence as xe,motion as be}from"framer-motion";const ye=i(null);function Ne({installation:t,children:n}){return e(ye.Provider,{value:t,children:n})}function we(){return r(ye)}function ke({app:n,onChange:i,placeholder:r}){const{client:a,project:o}=E(),{data:l,error:c}=d(()=>a.apps.getAppInstallationProjects(n),[n.id,n.name]);return c?t("span",{className:"text-red-600",children:["Error: failed to fetch projects: ",u(c)]}):e(Ce,{placeholder:r,initialValue:o?.id,projects:l||[],onChange:e=>{i&&!i(e)||(localStorage.setItem(D,e.account),localStorage.setItem(`${_}-${e.account}`,e.id),window.location.reload())}})}function Ce({initialValue:t,projects:n,onChange:i,placeholder:r="Select Project"}){const[o,l]=a(),c=!o&&t?n.find(e=>e.id===t):o;return e(m,{by:"id",value:c,options:n,optionLabel:e=>e.name,placeholder:r,onChange:e=>{l(e),i(e)}})}function Se({name:t,AccessDenied:n=ze,children:i}){return t?e(je,{name:t,AccessDenied:n,children:i}):e(Ie,{})}function je({name:t,AccessDenied:n=ze,children:i}){const{authToken:r,client:l}=E(),[c,s]=a(null),[d,u]=a("loading");return o(()=>{if(r){r.apps.includes(t)?l.apps.getAppInstallationByName(t).then(e=>{e?(u("loaded"),s(e)):(console.log(`App ${t} not found!`),u("error"))}):u("error")}else u("loading")},[t,r,l.apps.getAppInstallationByName]),"loading"===d?null:"error"===d?e(n,{name:t}):c?e(Ne,{installation:c,children:i}):void 0}function ze({name:n}){const{project:i,accounts:r,client:c}=E(),{t:s}=J(),[u,h]=a(),{data:g}=d(()=>c.apps.getAppInstallationProjects({name:n}),[n]),{projectsByOrg:f,orgOptions:v}=l(()=>{if(!g||!r)return{projectsByOrg:{},orgOptions:[]};const e={};for(const t of g)e[t.account]||(e[t.account]=[]),e[t.account].push(t);const t=r.filter(t=>e[t.id]?.length>0);return{projectsByOrg:e,orgOptions:t}},[g,r]);o(()=>{!u&&v.length>0&&h(v[0].id)},[v,u]);const x=u&&f[u]||[],b=v.find(e=>e.id===u);return t(p,{className:"pt-10 flex flex-col items-center text-center text-gray-700",children:[e(K,{className:"w-10 h-10 mb-4 text-gray-500"}),e("div",{className:"text-xl font-semibold",children:s("shell.accessDenied")}),t("div",{className:"mt-2 text-sm text-gray-500",children:["You don't have permission to view the ",e("span",{className:"font-semibold",children:n})," app in project:"," ",t("span",{className:"font-semibold",children:["«",i?.name,"»"]}),"."]}),0===v.length&&void 0!==g&&e("div",{className:"mt-4 text-sm text-gray-500",children:"This app is not installed in any project you have access to."}),v.length>0&&t("div",{className:"mt-4 flex flex-row gap-4 items-end",children:[v.length>1&&t("div",{children:[e("div",{className:"text-sm text-gray-500 mb-2",children:s("shell.organization")}),e(m,{by:"id",value:b,options:v,optionLabel:e=>e.name,placeholder:s("shell.selectOrganization"),onChange:e=>h(e.id)})]}),t("div",{children:[v.length>1&&e("div",{className:"text-sm text-gray-500 mb-2",children:s("login.terminal.project")}),e(m,{by:"id",value:void 0,options:x,optionLabel:e=>e.name,placeholder:s("shell.selectProject"),onChange:e=>{localStorage.setItem(D,e.account),localStorage.setItem(`${_}-${e.account}`,e.id),window.location.reload()}})]})]})]})}function Ie(){const{t:n}=J();return t(p,{className:"pt-10 flex flex-col items-center text-center text-gray-700",children:[e(K,{className:"w-10 h-10 mb-4 text-gray-500"}),e("div",{className:"text-xl font-semibold",children:n("shell.applicationNotRegistered")}),t("div",{className:"mt-2 text-sm text-gray-500",children:["Before starting to code a Vertesia application you must register an application manifest in Vertesia Studio then install it in one or more projects.",e("p",{}),"Then use the created app name as a parameter to"," ",e("code",{children:'<StandaloneApp name="your-app-name">'})," in the ",e("code",{children:"src/main.tsx"})," file."]})]})}function Pe(){const n=E(),{client:i}=n,{t:r}=J(),[l,c]=a(!1),[s,d]=a([]);o(()=>{i.account.listInvites().then(e=>{if(e.length>0){const t=e.filter(e=>e.data.account);if(0===t.length)return void console.log("No valid invites found, closing modal");console.log("Found valid invites",t.length),c(!0),d(t)}else console.log("No invites found, closing modal"),c(!1)}).catch(e=>{console.error("Error fetching invites",e)})},[i.account.listInvites]);const u=()=>c(!1),m=s.map(a=>a.data.account?t("div",{className:"flex flex-row w-full justify-between border rounded-sm px-2 py-2 ",children:[t("div",{className:"flex flex-col",children:[e("div",{className:"w-full font-semibold",children:a.data.account.name??a.data.account}),a.data.project&&t("div",{className:"w-full text-base",children:["- ",a.data.project.name]}),t("div",{className:"text-xs",children:["Role: ",a.data.role]}),a.data.invited_by&&t("div",{className:"text-xs",children:["by ",a.data.invited_by.name??a.data.invited_by]})]}),t("div",{className:"flex flex-col gap-4",children:[e(h,{size:"xs",onClick:()=>(async e=>{await i.account.acceptInvite(e.id),await n.authCallback,await n.fetchAccounts(),await n.fetchProjects(e.data.account.id);const t=s.filter(t=>t.id!==e.id).filter(e=>e.data.account);t.length>0?d(t):u()})(a),children:r("login.accept")})," ",e(h,{size:"xs",variant:"secondary",onClick:()=>(async e=>{await i.account.rejectInvite(e.id);const t=s.filter(t=>t.id!==e.id);d(t),0===t.length&&u()})(a),children:r("login.reject")})]})]},a.id):(console.warn("Invite has no account data",a),null));return e("div",{children:t(g,{isOpen:l,onClose:u,children:[e(f,{children:r("login.reviewInvites")}),t(v,{children:[e("div",{className:"text-sm pb-4",children:"You have received the following invites to join other accounts. Please review and accept or declined them."}),m]})]})})}const Ae=Q,Le={google:function(n){return t("svg",{viewBox:"0 0 48 48","aria-hidden":"true",...n,children:[e("path",{fill:"#FFC107",d:"M43.6 20.5H42V20H24v8h11.3c-1.6 4.7-6.1 8-11.3 8a12 12 0 0 1 0-24c3 0 5.8 1.1 7.9 3l5.7-5.7A20 20 0 1 0 24 44c11 0 20-9 20-20 0-1.2-.1-2.3-.4-3.5z"}),e("path",{fill:"#FF3D00",d:"M6.3 14.7l6.6 4.8A12 12 0 0 1 24 12c3 0 5.8 1.1 7.9 3l5.7-5.7A20 20 0 0 0 6.3 14.7z"}),e("path",{fill:"#4CAF50",d:"M24 44c5.2 0 10-2 13.6-5.2l-6.3-5.3A12 12 0 0 1 12.7 28.5l-6.6 5.1A20 20 0 0 0 24 44z"}),e("path",{fill:"#1976D2",d:"M43.6 20.5H42V20H24v8h11.3a12 12 0 0 1-4 5.5l6.3 5.3C37.9 36.6 44 31 44 24c0-1.2-.1-2.3-.4-3.5z"})]})},github:function(t){return e("svg",{viewBox:"0 0 24 24","aria-hidden":"true",...t,children:e("path",{fill:"currentColor",fillRule:"evenodd",clipRule:"evenodd",d:"M12 2C6.48 2 2 6.58 2 12.25c0 4.54 2.87 8.39 6.84 9.75.5.09.68-.22.68-.49v-1.7c-2.78.62-3.37-1.36-3.37-1.36-.46-1.18-1.11-1.5-1.11-1.5-.91-.63.07-.62.07-.62 1 .07 1.53 1.05 1.53 1.05.89 1.57 2.34 1.12 2.91.86.09-.66.35-1.12.63-1.38-2.22-.26-4.56-1.14-4.56-5.07 0-1.12.39-2.03 1.03-2.75-.1-.26-.45-1.3.1-2.7 0 0 .84-.28 2.76 1.05A9.4 9.4 0 0 1 12 7.07c.85 0 1.71.12 2.51.34 1.91-1.33 2.75-1.05 2.75-1.05.55 1.4.2 2.44.1 2.7.64.72 1.03 1.63 1.03 2.75 0 3.94-2.34 4.81-4.57 5.06.36.32.68.94.68 1.9v2.81c0 .27.18.59.69.49C19.13 20.64 22 16.78 22 12.25 22 6.58 17.52 2 12 2z"})})},microsoft:function(n){return t("svg",{viewBox:"0 0 24 24","aria-hidden":"true",...n,children:[e("path",{fill:"#F25022",d:"M2 2h9.5v9.5H2z"}),e("path",{fill:"#7FBA00",d:"M12.5 2H22v9.5h-9.5z"}),e("path",{fill:"#00A4EF",d:"M2 12.5h9.5V22H2z"}),e("path",{fill:"#FFB900",d:"M12.5 12.5H22V22h-9.5z"})]})},oidc:Ae};function Te(e){return e&&e in Le?Le[e]:Ae}function Oe({children:t,centered:n=!1}){return e("div",{className:n?"w-full max-w-[420px] flex flex-col gap-6 items-center text-center":"w-full max-w-[420px] flex flex-col gap-6",children:t})}function Be({eyebrow:n,title:i,body:r,variant:a="info"}){return t("div",{children:[n&&e("div",{className:`${"destructive"===a?"text-destructive":"text-info"} text-[12.5px] font-medium mb-2`,children:n}),e("h1",{className:"text-foreground text-[22px] font-semibold tracking-tight leading-tight mb-1.5",children:i}),r&&e("p",{className:"text-muted text-sm leading-relaxed",children:r})]})}const Re={primary:"h-[42px] gap-2.5 rounded-md bg-foreground text-background hover:opacity-90 disabled:opacity-50 disabled:cursor-not-allowed",loading:"h-[42px] gap-2.5 rounded-md bg-foreground text-background opacity-90",ghost:"h-9 text-muted hover:text-foreground"};function Ee({variant:t="primary",className:n="",type:i="button",disabled:r,...a}){return e(h,{variant:"unstyled",size:"none",type:i,disabled:"loading"===t||r,className:`cursor-pointer inline-flex items-center justify-center text-sm font-medium transition ${Re[t]} ${n}`.trim(),...a})}function De({size:t="xs",className:n="",type:i="button",...r}){const a=`cursor-pointer ${"smaller"===t?"!text-[11px]":"!text-xs"} text-muted hover:text-foreground !transition px-2 py-1 !rounded underline decoration-transparent hover:decoration-current underline-offset-[3px]`;return e(h,{variant:"unstyled",size:"none",type:i,className:n?`${a} ${n}`:a,...r})}const _e={circle:"size-9 rounded-full text-sm ring-4 ring-background ring-offset-1 ring-offset-border",square:"size-[30px] rounded-md text-[11px]"};function $e({initials:t,shape:n="circle"}){return e("span",{className:`bg-info text-info-foreground grid place-items-center font-semibold shrink-0 ${_e[n]}`,children:t})}function qe({children:t}){return e("div",{className:"inline-grid place-items-center size-14 rounded-xl bg-info-background border border-info/15 mb-3.5",children:t})}function Fe({title:n,subtitle:i,titleClass:r,subtitleClass:a}){return t("div",{className:"flex-1 min-w-0",children:[e("div",{className:r,children:n}),e("div",{className:a,children:i})]})}const Me={tenant:{topRow:"flex items-center gap-2.5 px-3 py-2.5",title:"text-[13.5px] font-semibold text-foreground leading-tight",subtitle:"text-[11.5px] text-muted leading-tight mt-0.5",bottomRow:"flex items-center gap-2.5 px-3 py-1.5 border-t border-border bg-muted-background",mailBox:"size-[30px] grid place-items-center shrink-0",mailIcon:"size-4 text-muted",email:"text-sm text-foreground/80 flex-1 truncate",actionSize:"xs"},returning:{topRow:"flex items-center gap-3 px-3.5 py-2.5",title:"text-sm font-semibold text-foreground truncate",subtitle:"text-xs text-foreground/80 truncate",bottomRow:"flex items-center gap-3 px-3.5 py-1 border-t border-border bg-muted-background",mailBox:"w-9 h-6 grid place-items-center shrink-0",mailIcon:"size-3.5 text-muted",email:"text-xs text-foreground/80 flex-1 truncate",actionSize:"smaller"}};function We({variant:n="returning",badge:i,title:r,subtitle:a,email:o,actionLabel:l,onAction:c}){const s=Me[n];return t("div",{className:"rounded-md border border-border bg-background overflow-hidden",children:[t("div",{className:s.topRow,children:[i,e(Fe,{title:r,subtitle:a,titleClass:s.title,subtitleClass:s.subtitle})]}),t("div",{className:s.bottomRow,children:[e("div",{className:s.mailBox,children:e(Z,{className:s.mailIcon})}),e("span",{className:s.email,children:o}),e(De,{size:s.actionSize,onClick:c,children:l})]})]})}function Ve({badge:n,title:i,subtitle:r,actionLabel:a,onAction:o}){return t("div",{className:"flex items-center gap-3 px-3.5 py-2.5 rounded-md border border-border bg-muted-background",children:[n,e(Fe,{title:i,subtitle:r,titleClass:"text-sm font-semibold text-foreground truncate",subtitleClass:"text-xs text-muted truncate"}),e(De,{onClick:o,children:a})]})}function Ue({email:n,actionLabel:i,onAction:r}){return t("div",{className:"flex items-center gap-2 px-3 py-2 rounded-md border border-border bg-muted-background",children:[e(Z,{className:"size-4 text-muted shrink-0"}),e("span",{className:"text-sm text-foreground/80 flex-1 truncate",children:n}),e(De,{onClick:r,children:i})]})}function He({provider:n,label:i,onClick:r,variant:a="outline"}){const o=Te(n);if("arrow"===a){const n="!size-3.5 text-muted opacity-0 group-hover:opacity-100 group-hover:translate-x-0.5 transition";return t(h,{variant:"unstyled",size:"none",onClick:r,className:"cursor-pointer group h-[42px] w-full inline-flex items-center gap-3 ps-3.5 pe-3 rounded-md border border-border bg-background text-sm font-medium text-foreground transition hover:bg-muted-background",children:[e(o,{className:"!size-[18px] shrink-0"}),e("span",{className:"flex-1 text-start",children:i}),e(X,{className:n})]})}return t(h,{variant:"outline",onClick:r,className:`w-full py-5 flex rounded-lg transition duration-150 text-center ${"filled"===a?"!bg-foreground text-background hover:!bg-foreground/90":"hover:shadow-sm"}`,children:[e(o,{className:"!size-[18px]"}),e("span",{className:"text-sm font-medium",children:i})]})}function Je({icon:n,title:i,meta:r}){return t("div",{className:"flex items-center gap-2.5 px-3 py-2.5 rounded-md bg-destructive-background border border-destructive/20",children:[e(n,{className:"size-5 text-destructive shrink-0"}),t("div",{className:"flex-1 min-w-0 text-sm",children:[e("div",{className:"font-semibold text-destructive",children:i}),e("div",{className:"text-xs text-destructive/80",children:r})]})]})}function Ye({inputRef:n,label:i,placeholder:r,value:a,onChange:o,invalid:l=!1,error:c}){return t("div",{className:"flex flex-col gap-1.5",children:[e("label",{htmlFor:"vt-login-email",className:"text-xs font-medium text-foreground/80",children:i}),e("input",{ref:n,id:"vt-login-email",name:"vt-login-email",type:"email",className:"h-[42px] px-3.5 rounded-md border border-border bg-background text-sm text-foreground placeholder:text-muted-foreground outline-none transition focus:border-info focus:ring-4 focus:ring-info/15 aria-[invalid=true]:border-destructive aria-[invalid=true]:ring-destructive/15",placeholder:r,value:a,onChange:e=>o(e.target.value),"aria-invalid":l,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",spellCheck:!1,"data-1p-ignore":!0,"data-lpignore":"true","data-form-type":"other"}),c&&e("div",{role:"alert",className:"text-xs text-destructive",children:c})]})}const Ge="vt.lastSuccessfulLogin",Ke="vt.pendingSignin";function Qe(){try{const e=localStorage.getItem(Ge);if(!e)return null;const t=JSON.parse(e);return t?.email&&t?.lastProvider?t:null}catch{return null}}function Xe(){try{localStorage.removeItem(Ge)}catch{}}function Ze(){try{const e=sessionStorage.getItem(Ke);return e?JSON.parse(e):null}catch{return null}}function et(){try{sessionStorage.removeItem(Ke)}catch{}}async function tt(){Xe(),et();try{await ae($())}catch{}}function nt(e){let t=e||window.location.pathname||"/";return"/"!==t[0]&&(t=`/${t}`),t}const it={google:(e,t)=>{const n=new se;return n.addScope("profile"),n.addScope("email"),n.setCustomParameters({redirect_uri:window.location.origin+nt(t),...e?{login_hint:e}:{prompt:"select_account"}}),n},github:e=>{const t=new ce;return t.addScope("profile"),t.addScope("email"),e&&t.setCustomParameters({login:e}),t},microsoft:e=>{const t=new le("microsoft.com");return t.addScope("profile"),t.addScope("email"),e&&t.setCustomParameters({login_hint:e}),t},oidc:e=>{const t=new le("oidc.main");return e&&t.setCustomParameters({login_hint:e}),t}};function rt(e,t,n){return it[e](t,n)}async function at(e,t,n){if(!t)return{ok:!1,reason:"no-email"};const i=await q(t),r=$();let a,o=e;return i?(i.provider&&(o=i.provider),a=i.label||i.name||void 0,localStorage.setItem("tenantName",a??"")):(localStorage.removeItem("tenantName"),r.tenantId&&(r.tenantId=null)),function(e){try{sessionStorage.setItem(Ke,JSON.stringify(e))}catch{}}({email:t,provider:o,tenantName:a}),oe(r,rt(o,t,n)),{ok:!0}}function ot(e){return"google"===e?"Google":"github"===e?"GitHub":"microsoft"===e?"Microsoft":"Sign In"}function lt(e){const t=function(e){if(!e)return"";const t=e.lastIndexOf("@");return t>0?e.slice(0,t):e}(e),n=t.split(/[._-]+/).filter(Boolean)[0]||"friend";return n.charAt(0).toUpperCase()+n.slice(1).toLowerCase()}function ct(e){let t=e;for(let e=0;null!=t&&e<8;e++){if((t instanceof Error?t.message:String(t)).includes("Customer-domain user requires an invite to join"))return!0;t=t instanceof Error?t.cause:void 0}return!1}function st({provider:n,onCancel:i}){const{t:r}=J(),a=Te(n),o="oidc"===n?r("auth.pending.genericProvider"):ot(n);return t(Oe,{centered:!0,children:[t("div",{children:[e(qe,{children:e(a,{className:"oidc"===n?"size-6 text-info":"size-6"})}),e(Be,{title:r("auth.pending.title",{provider:o}),body:r("auth.pending.body")})]}),t("div",{className:"w-full flex flex-col gap-2",children:[t(Ee,{variant:"loading",children:[e(x,{}),e("span",{children:r("auth.pending.authenticating")})]}),i&&e(Ee,{variant:"ghost",onClick:i,children:r("auth.pending.cancel")})]})]})}function dt({initialEmail:i,onProceed:r}){const{t:l}=J(),[s,d]=a(i??""),[u,m]=a(!1),[p,h]=a(!1),g=c(null);o(()=>{g.current?.focus()},[]);return t(Oe,{children:[e(Be,{eyebrow:l("auth.email.eyebrow"),title:l("auth.email.title"),body:l("auth.email.body")}),t("form",{onSubmit:async e=>{if(e.preventDefault(),!p)if(function(e){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test((e||"").trim())}(s)){m(!1),h(!0);try{const e=await q(s.trim().toLowerCase());r(s.trim().toLowerCase(),e??void 0)}catch{r(s.trim().toLowerCase(),void 0)}finally{h(!1)}}else m(!0)},noValidate:!0,className:"flex flex-col "+(u?"gap-2":"gap-6"),children:[e(Ye,{inputRef:g,label:l("auth.email.label"),placeholder:l("auth.email.placeholder"),value:s,onChange:e=>{d(e),u&&m(!1)},invalid:u,error:u?l("auth.email.invalidError"):void 0}),e(Ee,{type:"submit",disabled:p,children:p?e(x,{}):t(n,{children:[e("span",{children:l("auth.continue")}),e(X,{className:"!size-3.5"})]})})]})]})}const ut=["google","github","microsoft"];function mt({email:n,onBack:i,onProviderClicked:r,redirectTo:a}){const{t:o}=J();return t(Oe,{children:[e(Be,{eyebrow:o("auth.providers.eyebrow"),title:o("auth.providers.title"),body:o("auth.providers.bodyConsumer")}),e(Ue,{email:n,actionLabel:o("auth.change"),onAction:i}),e("div",{className:"flex flex-col gap-2",children:ut.map(t=>e(He,{provider:t,label:o("auth.continueWithProvider",{provider:ot(t)}),onClick:()=>(async e=>{r(e),await at(e,n,a)})(t),variant:"arrow"},t))})]})}function pt({session:n,onNotYou:i,onProviderClicked:r,redirectTo:a}){const{t:o}=J(),l=n.name?n.name.split(" ")[0]||n.name:lt(n.email),c=n.name||lt(n.email),s=e($e,{initials:(d=n.email,(d||"?").charAt(0).toUpperCase())});var d;const u=!!n.tenantName,m="oidc"===n.lastProvider?o("auth.continueWithSignIn"):o("auth.continueWithProvider",{provider:ot(n.lastProvider)});return t(Oe,{children:[e(Be,{eyebrow:o("auth.returning.eyebrow"),title:o("auth.returning.title",{name:l}),body:o("auth.returning.body")}),u&&n.tenantName?e(We,{variant:"returning",badge:s,title:c,subtitle:n.tenantName,email:n.email,actionLabel:o("auth.returning.notYou"),onAction:i}):e(Ve,{badge:s,title:c,subtitle:n.email,actionLabel:o("auth.returning.notYou"),onAction:i}),t("div",{className:"flex flex-col gap-2",children:[e(He,{provider:n.lastProvider,label:m,onClick:()=>(async e=>{r(e),await at(e,n.email,a)})(n.lastProvider),variant:"filled"}),e(Ee,{variant:"ghost",onClick:i,children:o("auth.returning.useDifferent")})]})]})}function ht({email:n,tenantName:i,onBack:r}){const{t:a}=J(),o=i||a("auth.blocked.tenantFallback"),l=function(e){if(!e)return"";const t=e.lastIndexOf("@");return t>0?e.slice(t+1):""}(n),c=i||(l?a("auth.blocked.teamFromDomain",{domain:(s=l,s?s.charAt(0).toUpperCase()+s.slice(1):s)}):a("auth.blocked.tenantFallback"));var s;return t(Oe,{children:[e(Be,{variant:"destructive",eyebrow:a("auth.blocked.eyebrow"),title:a("auth.blocked.title"),body:a("auth.blocked.body",{name:o,email:n})}),t("div",{className:"flex flex-col gap-2",children:[e(Je,{icon:ee,title:c,meta:a("auth.blocked.tenantMeta",{email:n})}),e(Ee,{variant:"ghost",onClick:r,children:a("auth.blocked.useDifferent")})]})]})}function gt({provider:t,email:n,redirectTo:i,variant:r="outline",onClick:a}){const{t:o}=J(),l="oidc"===t?o("auth.continueWithSignIn"):o("auth.continueWithProvider",{provider:ot(t)});return e(He,{provider:t,label:l,onClick:()=>{a?.(),n?at(t,n,i):function(e,t){const n=$();localStorage.removeItem("tenantName"),n.tenantId&&(n.tenantId=null),oe(n,rt(e,void 0,t))}(t,i)},variant:r})}function ft({email:n,tenant:i,onBack:r,onProviderClicked:a,redirectTo:o}){const{t:l}=J(),c=i.label||i.name||l("auth.blocked.tenantFallback"),s="google"===i.provider||"github"===i.provider||"microsoft"===i.provider?i.provider:"oidc",d="oidc"===s?l("auth.tenant.viaIdpFallback"):ot(s);return t(Oe,{children:[e(Be,{eyebrow:l("auth.tenant.eyebrow"),title:l("auth.tenant.title",{name:c}),body:l("auth.tenant.body")}),e(We,{variant:"tenant",badge:e($e,{initials:(u=c,u.split(/\s+/).filter(Boolean).slice(0,2).map(e=>e.charAt(0).toUpperCase()).join("")),shape:"square"}),title:c,subtitle:l("auth.tenant.viaIdp",{idp:d}),email:n,actionLabel:l("auth.change"),onAction:r}),t("div",{className:"flex flex-col gap-2",children:[e(gt,{provider:s,email:n,redirectTo:o,variant:"filled",onClick:a}),e(Ee,{variant:"ghost",onClick:r,children:l("auth.tenant.notPartOf",{name:c})})]})]});var u}function vt({onSignup:i,goBack:r}){const{t:l}=J(),[c,s]=a(void 0),[d,u]=a(void 0),[p,g]=a(void 0),[f,v]=a(void 0),[x,N]=a(void 0),[w,k]=a(void 0),[C,S]=a(void 0),j="company"===c,z=[{id:1,label:l("signup.size1to10")},{id:11,label:l("signup.size11to100")},{id:101,label:l("signup.size101to1000")},{id:1001,label:l("signup.size1001to5000")},{id:5001,label:l("signup.size5000plus")}],I=[{id:"personal",label:l("signup.personal"),description:l("signup.personalDescription")},{id:"company",label:l("signup.company"),description:l("signup.companyDescription")}],P=[{id:"testing",label:l("signup.justTesting")},{id:"exploring",label:l("signup.activelyExploring")},{id:"using",label:l("signup.alreadyUsing")},{id:"migrating",label:l("signup.migratingLLMs")},{id:"other",label:l("signup.other")}];o(()=>{const e=$().currentUser;e?k(e):console.error("No user found")},[]);return t("div",{className:"flex flex-col space-y-2",children:[t("div",{className:"prose",children:[e("p",{className:"prose text-sm text-muted pt-4",children:l("signup.welcomeMessage",{name:w?.displayName,email:w?.email})}),C&&e("div",{className:"text-destructive",children:C})]}),e(xt,{label:l("signup.accountType"),children:e(b,{options:I,selected:I.find(e=>e.id===c),onSelect:e=>s(e.id)})}),j&&t(n,{children:[e(xt,{label:l("signup.companySize"),children:e(m,{className:"w-full border border-accent bg-muted",value:d,options:z,onChange:u,optionLabel:e=>e?.label,placeholder:l("signup.selectCompanySize")})}),e(xt,{label:l("signup.companyName"),children:e(y,{value:p,onChange:g,type:"text",required:!0})}),e(xt,{label:l("signup.companyWebsite"),children:e(y,{value:f,onChange:v,type:"text"})})]}),e(xt,{label:l("signup.projectMaturity"),children:e(m,{className:"w-full border border-accent bg-muted",options:P,value:P.find(e=>e.id===x),optionLabel:e=>e?.label,placeholder:l("signup.selectProjectMaturity"),onChange:e=>N(e?.id)})}),t("div",{className:"pt-8 flex flex-col",children:[e(h,{variant:"primary",onClick:async()=>{if(!(c?j&&!p?(S(l("signup.pleaseEnterOrgName")),0):!j||d||(S(l("signup.pleaseSelectCompanySize")),0):(S(l("signup.pleaseSelectAccountType")),0)))return;if(!c)return;const e={accountType:c,companyName:p,companySize:d?.id,companyWebsite:f,maturity:x};window.localStorage.setItem("composableSignupData",JSON.stringify(e));const t=await($().currentUser?.getIdToken());console.log("Got firebase token",$(),t),t?i(e,t):console.error("No firebase token found")},size:"xl",children:e("span",{className:"text-lg",children:l("signup.signUp")})}),e(h,{variant:"ghost",size:"xl",className:"mt-4",onClick:r,children:e("span",{className:"",children:l("signup.wrongAccountGoBack")})})]})]})}function xt({label:n,children:i}){return t("div",{className:"flex flex-col space-y-2 pt-4",children:[e("div",{className:"text-sm text-muted",children:n}),i]})}function bt({allowedPrefix:t,isNested:n=!1,lightLogo:i,darkLogo:r,preservePath:a,suppressAuthErrorPrefix:o}){const l="undefined"==typeof window?"":window.location.pathname,c=yt(l,t),s=yt(l,o);return c?null:e(Nt,{isNested:n,lightLogo:i,darkLogo:r,preservePath:a,suppressAuthError:s})}function yt(e,t){return(Array.isArray(t)?t:t?[t]:[]).some(t=>e===t||e.startsWith(t.endsWith("/")?t:`${t}/`))}function Nt({isNested:n=!1,lightLogo:i,darkLogo:r,preservePath:l,suppressAuthError:c}){const{t:d}=J(),{isLoading:u,user:m,authError:p,signOut:h}=E(),{trackEvent:g}=F(),[f,v]=a(()=>Qe()),[x,b]=a(()=>Qe()?"returning":"email"),[y,N]=a(""),[w,k]=a(void 0),[C,S]=a(null);o(()=>{l||history.replaceState({},"","/")},[l]),o(()=>{if(p)if(p instanceof M)b("signup");else if(ct(p)){const e=Ze();e&&N(e.email),b("blocked")}},[p]),o(()=>{if(!m)return;const e=Ze();e&&(!function(e){try{localStorage.setItem(Ge,JSON.stringify(e))}catch{}}({email:e.email,lastProvider:e.provider,tenantName:e.tenantName,name:m.name||void 0}),et())},[m]);const j=s((e,t)=>{N(e),k(t),b(t?"tenant":"providers")},[]),z=s(()=>{b("email"),k(void 0)},[]),I=s(()=>{Xe(),et(),v(null),N(""),k(void 0),b("email"),h()},[h]),P=s(e=>{(!!w||!!f?.tenantName)&&g("enterprise_signin",{provider:e}),S(e),b("pending")},[g,f?.tenantName,w]),A=s(()=>{v(null),N(""),k(void 0),b("email"),tt()},[]),L=(e,t)=>{const n={signupData:e,firebaseToken:t};fetch(`${ie.endpoints.studio}/auth/signup`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}).then(()=>{g("sign_up"),window.location.href="/"})};if(u||m||c&&void 0!==p&&!(p instanceof M))return null;let T=null;return T="pending"===x&&C?e(st,{provider:C}):"blocked"===x?e(ht,{email:y||f?.email||"",tenantName:w?.label||w?.name||f?.tenantName||void 0,onBack:A}):"signup"!==x||localStorage.getItem("tenantName")?"tenant"===x&&w?e(ft,{email:y,tenant:w,onBack:z,onProviderClicked:()=>P(w.provider??"oidc")}):"providers"===x?e(mt,{email:y,onBack:z,onProviderClicked:P}):"returning"===x&&f?e(pt,{session:f,onNotYou:I,onProviderClicked:P}):e(dt,{initialEmail:y,onProceed:j}):e(vt,{onSignup:L,goBack:A}),e("div",{style:{zIndex:999998},className:(n?"absolute":"fixed")+" inset-0 overflow-y-auto bg-background",children:e("div",{className:"min-h-full flex flex-col items-center justify-center py-12 px-4",children:t("div",{className:"flex flex-col items-center w-full",children:[(i||r)&&t("div",{className:"mb-7",children:[i&&e("img",{src:i,alt:"Vertesia",className:"h-10 block dark:hidden"}),r&&e("img",{src:r,alt:"Vertesia",className:"h-10 hidden dark:block"})]}),T,p&&!(p instanceof M)&&!ct(p)&&e("div",{className:"mt-6 max-w-[420px] text-center text-sm text-muted",children:t("div",{children:[d("auth.signInError"),e("br",{}),d("auth.signInErrorContact"),e("a",{className:"text-info mx-1",href:"mailto:support@vertesiahq.com",children:"support@vertesiahq.com"}),d("auth.signInErrorPersists"),e("pre",{className:"mt-2 text-xs",children:d("auth.error",{message:p.message})})]})}),t("div",{className:"flex items-center gap-5 mt-10 text-xs text-muted-foreground",children:[e("a",{href:"https://vertesiahq.com/privacy",className:"hover:text-foreground transition",children:d("auth.privacyPolicy")}),e("span",{className:"text-border",children:"·"}),e("a",{href:"https://vertesiahq.com/terms",className:"hover:text-foreground transition",children:d("auth.termsOfService")}),e("span",{className:"text-border",children:"·"}),e(re,{className:"cursor-default"})]})]})})})}const wt=new Set(["127.0.0.1","localhost"]);function kt(e){const t=new URLSearchParams(e.search),n=function(e){if(!e)return null;let t,n;try{t=decodeURIComponent(e)}catch{return null}try{n=new URL(t)}catch{return null}return"http:"!==n.protocol?null:n.port?n.username||n.password?null:wt.has(n.hostname)?n.toString():null:null}(t.get("redirect_uri")),i=t.get("code");if(!n||!i)return null;return{redirect:n,code:i,profile:t.get("profile")??"default",project:t.get("project")??void 0,account:t.get("account")??void 0}}function Ct(){const[t,n]=a(),[i,r]=a(),o=kt(de()),l=N(),{t:c}=J(),s=async e=>{if(!o)return;if(!e.profile)return void l({title:c("login.terminal.profileRequired"),description:c("login.terminal.profileRequiredDesc"),status:"error",duration:2e3});if(!e.account)return void l({title:c("login.terminal.accountRequired"),description:c("login.terminal.accountRequiredDesc"),status:"error",duration:2e3});if(!e.project)return void l({title:c("login.terminal.projectRequired"),description:c("login.terminal.projectRequiredDesc"),status:"error",duration:2e3});let t;try{const i=W(),r=i?await V(i,e.account,e.project,86400):await U(e.account,e.project,86400);r?(t={...e,studio_server_url:ie.endpoints.studio,zeno_server_url:ie.endpoints.zeno,token:r},await fetch(o.redirect,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),n(t)):l({title:c("login.terminal.failedToGetToken"),status:"error",duration:5e3})}catch(e){t?(r(e instanceof Error?e:new Error(u(e))),n(t)):l({title:c("login.terminal.errorAuthorizingClient"),description:u(e),status:"error",duration:5e3})}},d=o?t?e(jt,{payload:t,error:i}):e(St,{clientInfo:o,onAccept:s}):e(w,{title:c("login.terminal.invalidRequest"),children:c("login.terminal.invalidRequestDesc")});return e("div",{className:"w-full flex flex-col items-center gap-4 mt-24",children:d})}function St({onAccept:i,clientInfo:r}){const{client:a,user:o}=E(),{data:l,error:c}=d(()=>o?a.projects.list():Promise.resolve([]),[o]),{t:s}=J();if(c)return e(w,{title:s("login.terminal.errorLoadingProjects"),children:u(c)});const m=ie.isLocalDev?s("login.terminal.envLocalDev"):ie.isDev?s("login.terminal.envStaging"):s("login.terminal.envProduction");return o&&l?t(n,{children:[t("div",{className:"w-1/3",children:[t("div",{className:"mb-4 text-xl font-semibold text-info",children:["Authorizing client on ",m," environment."]}),t("div",{className:"mb-2 text-md text-muted-foreground",children:[e("div",{children:s("login.terminal.clientWantsAuth")}),t("div",{children:["The client app code is ",e("b",{className:"text-foreground",children:r.code}),". You can check if the code is correct in the terminal."]})]}),t("div",{className:"mb-2 text-sm text-muted-foreground",children:[e("div",{children:s("login.terminal.chooseAccountProject")}),e("div",{children:s("login.terminal.profileNameNote")})]})]}),e(zt,{onAccept:i,allProjects:l,data:r})]}):e(x,{size:"lg"})}function jt({payload:n,error:i}){const r=N(),{t:a}=J();return t("div",{children:[e("div",i?{children:e(w,{title:a("login.terminal.failedToSendToken"),children:a("login.terminal.failedToSendTokenDesc",{error:i.message})})}:{children:a("login.terminal.clientAuthenticated")}),e(p,{className:"mt-4",children:e(h,{variant:"secondary",onClick:()=>{n&&(navigator.clipboard.writeText(JSON.stringify(n)),r({title:a("login.terminal.authPayloadCopied"),description:i?a("login.terminal.authPayloadCopiedWithError",{error:i.message}):a("login.terminal.authPayloadCopiedSuccess"),status:"success",duration:5e3}))},children:a("login.terminal.copyAuthPayload")})})]})}function zt({allProjects:n,data:i,onAccept:r}){const{accounts:o,account:l,project:c}=E(),{t:s}=J(),[d,u]=a(()=>({profile:i.profile,account:i.account??l?.id,project:i.project??c?.id})),m=n.filter(e=>e.account===d.account);return t("div",{className:"w-1/3",children:[t("div",{className:"mb-4 flex flex-col gap-2",children:[e("span",{className:"font-semibold text-muted-foreground",children:s("login.terminal.profileName")}),e(y,{type:"text",value:d.profile,onChange:e=>{u({...d,profile:e})}})]}),t("div",{className:"mb-4 flex flex-col gap-2",children:[e("span",{className:"font-semibold text-muted-foreground",children:s("login.terminal.account")}),e(It,{value:d.account,onChange:e=>{u({...d,account:e.id,project:void 0})},accounts:o||[]})]}),t("div",{className:"mb-4 flex flex-col gap-2",children:[e("span",{className:"font-semibold text-muted-foreground",children:s("login.terminal.project")}),e(Pt,{value:d.project,onChange:e=>{u({...d,project:e.id})},projects:m})]}),e("div",{className:"mb-4 text-sm text-attention",children:s("login.terminal.browserPermissionNote")}),e("div",{children:e(h,{size:"xl",onClick:()=>r(d),children:s("login.terminal.authorizeClient")})})]})}function It({value:t,accounts:n,onChange:i}){const{t:r}=J();return e(m,{options:n,value:n?.find(e=>e.id===t),onChange:e=>{i(e)},by:"id",optionLabel:e=>e.name,placeholder:r("login.terminal.selectAccount")})}function Pt({value:t,projects:n,onChange:i}){const{t:r}=J();return e(m,{by:"id",value:n.find(e=>e.id===t),options:n,optionLabel:e=>e.name,placeholder:r("login.terminal.selectProject"),onChange:e=>{i(e)}})}function At({isOpen:n,onClose:i}){return t(g,{isOpen:n,onClose:i,children:[e(f,{children:"Sign In"}),t(v,{className:"flex flex-col gap-2",children:[e(gt,{provider:"google"}),e(gt,{provider:"github"}),e(gt,{provider:"microsoft"})]}),e(k,{align:"right",children:e(h,{variant:"ghost",onClick:i,children:"Cancel"})})]})}function Lt({title:n,value:i}){const[r,o]=a(!1);return t("div",{className:"w-full flex justify-between items-center mb-1",children:[t("div",{className:"flex flex-col w-[calc(100%-3rem)]",children:[e("div",{className:"text-sm px-2 dark:text-slate-200",children:n}),e(z,{description:i,size:"xs",placement:"left",children:t("div",{className:"text-xs truncate text-muted w-full text-start px-2",children:[i," "]})})]}),r?e(te,{className:"size-4 cursor-pointer text-success"}):e(ne,{className:"size-4 cursor-pointer text-gray-400 dark:text-slate-400",onClick:()=>function(e){navigator.clipboard.writeText(e),o(!0),setTimeout(()=>o(!1),2e3)}(i)})]})}function Tt(){const{t:n}=J(),i=E(),{account:r,project:a,client:o,authToken:l}=i,c=o.baseUrl,s=o.store.baseUrl,d=s.replace(/\/+$/,"")!==c.replace(/\/+$/,""),u=ie.endpoints.mcp??n("user.unknown"),m=a?me(a):"",p=[{name:"user",label:n("user.user"),content:t("div",{className:"space-y-1 p-2",children:[e(Lt,{title:n("user.organizationId"),value:r?.id??n("user.unknown")}),e(Lt,{title:n("user.projectId"),value:a?.id??n("user.unknown")}),e(Lt,{title:n("user.userId"),value:l?.sub??n("user.unknown")}),e(Lt,{title:n("user.organizationRoles"),value:l?.account_roles?.join(",")??n("user.unknown")}),e(Lt,{title:n("user.projectRoles"),value:l?.project_roles?.join(",")??n("user.unknown")})]})},{name:"environment",label:n("user.environment"),content:t("div",{className:"space-y-1 p-2",children:[e(Lt,{title:n("user.tenantId"),value:m}),e(Lt,{title:n("user.environment"),value:ie.type}),e(Lt,{title:n("user.server"),value:c}),d&&e(Lt,{title:n("user.store"),value:s}),e(Lt,{title:n("user.mcpServer"),value:u}),e(Lt,{title:n("user.appVersion"),value:ie.version}),e(Lt,{title:n("user.sdkVersion"),value:ie.sdkVersion||n("user.unknown")})]})}];return e("div",{className:"w-full",children:t(C,{defaultValue:"user",tabs:p,fullWidth:!0,updateHash:!1,children:[e(S,{}),e(j,{})]})})}function Ot(i){const{user:r,isLoading:o}=E(),[l,c]=a(!1);return o?e(x,{}):r?e("div",{className:"px-3",children:e(Bt,{asMenuTrigger:!0})}):t(n,{children:[e(h,{onClick:()=>c(!0),children:"Sign In"}),e(At,{isOpen:l,onClose:()=>c(!1)})]})}function Bt({className:n,asMenuTrigger:i=!1}){const r=E(),a=ue(),o=he(),{user:l}=r;if(!r||!l)return null;const c=o.hasPermission(pe.project_admin);return t(I,{click:!0,children:[e(P,{children:e("div",{className:ve(n,"flex items-center justify-start",i&&"cursor-pointer"),children:e(A,{size:"sm",color:"bg-amber-500",shape:"circle",name:l?.name})})}),e(L,{align:"start",className:"w-[280px] mx-2 my-1 p-0",children:t("div",{className:"divide-y divide-gray-200 dark:divide-slate-700",children:[t("div",{className:"py-2 ps-2",children:[e("p",{className:"px-4 dark:text-white mb-1",children:l?.name??"Unknown"}),e("p",{className:"px-4 text-xs text-gray-500",children:l?.email??""})]}),e("div",{className:"w-full p-1",children:e(Tt,{})}),e("div",{className:"py-2 ps-2",children:e(T,{})}),e("div",{className:"py-2",children:t(O,{children:[c&&e(O.Item,{className:"px-2",onClick:()=>a("/settings",{replace:!0}),children:"Settings"}),e(O.Item,{className:"px-2",onClick:()=>r.logout(),children:"Sign out"})]})})]})})]})}function Rt(e){return!!e&&(e.endsWith("@vertesiahq.com")||e.endsWith("@becomposable.com")||e.endsWith("@composableprompts.com"))}function Et({icon:t}){const{isLoading:n}=E(),[i,r]=a(!0);return o(()=>{n||r(!1)},[n]),e(xe,{children:i&&e(be.div,{style:{zIndex:999999,position:"fixed",inset:0},className:"fixed inset-x-0 inset-y-0",initial:{opacity:1},exit:{opacity:0},transition:{ease:"easeIn",duration:.5},children:e("div",{style:{display:"flex",width:"100%",height:"100%",alignItems:"center",justifyContent:"center"},className:"flex w-full h-full items-center justify-center",children:e("div",{className:"animate-[spin_4s_linear_infinite]",children:e("div",{className:"animate-pulse rounded-full bg-transparent",children:t||e(Dt,{})})})})})})}function Dt(){return t("svg",{width:"32",height:"32",className:"w-8 h-8 text-indigo-600",viewBox:"0 0 50 50",xmlns:"http://www.w3.org/2000/svg",role:"img","aria-label":"Loading",children:[e("title",{children:"Loading"}),e("defs",{children:t("linearGradient",{id:"spinner-gradient",x1:"1",y1:"0",x2:"0",y2:"1",children:[e("stop",{offset:"0%",stopColor:"currentColor",stopOpacity:"1"}),e("stop",{offset:"100%",stopColor:"currentColor",stopOpacity:"0"})]})}),e("circle",{cx:"25",cy:"25",r:"20",stroke:"url(#spinner-gradient)",strokeWidth:"5",fill:"none",strokeLinecap:"round"})]})}function _t({children:n,lightLogo:i,darkLogo:r,loadingIcon:a,loadOnboardingStatus:o,preserveSignInPath:l,suppressSignInErrorPrefixes:c,defaultLanguage:s}){return e(B,{children:e(H,{loadOnboardingStatus:o,children:e(ge,{children:e(R,{defaultTheme:"system",storageKey:"vite-ui-theme",children:e(Y,{defaultLanguage:s,children:t(G,{children:[e(Et,{icon:a}),e(bt,{allowedPrefix:"/shared/",darkLogo:r,lightLogo:i,preservePath:l,suppressAuthErrorPrefix:c}),e(fe,{children:n})]})})})})})})}export{ye as AppInstallationContext,Ne as AppInstallationProvider,ke as AppProjectSelector,Pe as InviteAcceptModal,bt as SigninScreen,Se as StandaloneApp,je as StandaloneAppImpl,Ct as TerminalLogin,Ot as UserSessionMenu,_t as VertesiaShell,Rt as isVertesiaEmail,we as useAppInstallation};
1
+ import{jsx as e,jsxs as t,Fragment as n}from"react/jsx-runtime";import{createContext as i,useContext as r,useState as a,useEffect as o,useMemo as l,useRef as c,useCallback as s}from"react";import{useFetch as d,errorMessage as u,SelectBox as m,Center as p,Button as h,Modal as g,ModalTitle as f,ModalBody as v,Spinner as x,RadioGroup as b,Input as y,useToast as N,ErrorBox as w,ModalFooter as k,Tabs as C,TabsBar as S,TabsPanel as j,VTooltip as z,Popover as I,PopoverTrigger as P,Avatar as A,PopoverContent as L,ModeToggle as T,MenuList as O,ToastProvider as R,ThemeProvider as B}from"@vertesia/ui/core";import{useUserSession as E,LastSelectedAccountId_KEY as D,LastSelectedProjectId_KEY as _,getFirebaseAuth as $,setFirebaseTenant as q,useUXTracking as F,UserNotFoundError as M,getCurrentVertesiaToken as U,fetchComposableTokenFromVertesiaToken as W,fetchComposableTokenFromFirebaseToken as V,UserSessionProvider as H}from"@vertesia/ui/session";import{useUITranslation as J,LanguageProvider as Y,LanguageBoundI18nProvider as G}from"@vertesia/ui/i18n";import{LockIcon as K,LockKeyhole as Q,ArrowRight as X,Mail as Z,ShieldOff as ee,Check as te,CopyIcon as ne}from"lucide-react";import{Env as ie}from"@vertesia/ui/env";import{RegionTag as re}from"@vertesia/ui/layout";import{signOut as ae,signInWithRedirect as oe,OAuthProvider as le,GithubAuthProvider as ce,GoogleAuthProvider as se}from"firebase/auth";import{useLocation as de,useNavigate as ue}from"@vertesia/ui/router";import{getTenantIdFromProject as me,Permission as pe}from"@vertesia/common";import{useUserPermissions as he,TypeRegistryProvider as ge,UserPermissionProvider as fe}from"@vertesia/ui/features";import ve from"clsx";import{AnimatePresence as xe,motion as be}from"framer-motion";const ye=i(null);function Ne({installation:t,children:n}){return e(ye.Provider,{value:t,children:n})}function we(){return r(ye)}function ke({app:n,onChange:i,placeholder:r}){const{client:a,project:o}=E(),{data:l,error:c}=d(()=>a.apps.getAppInstallationProjects(n),[n.id,n.name]);return c?t("span",{className:"text-red-600",children:["Error: failed to fetch projects: ",u(c)]}):e(Ce,{placeholder:r,initialValue:o?.id,projects:l||[],onChange:e=>{i&&!i(e)||(localStorage.setItem(D,e.account),localStorage.setItem(`${_}-${e.account}`,e.id),window.location.reload())}})}function Ce({initialValue:t,projects:n,onChange:i,placeholder:r="Select Project"}){const[o,l]=a(),c=!o&&t?n.find(e=>e.id===t):o;return e(m,{by:"id",value:c,options:n,optionLabel:e=>e.name,placeholder:r,onChange:e=>{l(e),i(e)}})}function Se({name:t,AccessDenied:n=ze,children:i}){return t?e(je,{name:t,AccessDenied:n,children:i}):e(Ie,{})}function je({name:t,AccessDenied:n=ze,children:i}){const{authToken:r,client:l}=E(),[c,s]=a(null),[d,u]=a("loading");return o(()=>{if(r){r.apps.includes(t)?l.apps.getAppInstallationByName(t).then(e=>{e?(u("loaded"),s(e)):(console.log(`App ${t} not found!`),u("error"))}):u("error")}else u("loading")},[t,r,l.apps.getAppInstallationByName]),"loading"===d?null:"error"===d?e(n,{name:t}):c?e(Ne,{installation:c,children:i}):void 0}function ze({name:n}){const{project:i,accounts:r,client:c}=E(),{t:s}=J(),[u,h]=a(),{data:g}=d(()=>c.apps.getAppInstallationProjects({name:n}),[n]),{projectsByOrg:f,orgOptions:v}=l(()=>{if(!g||!r)return{projectsByOrg:{},orgOptions:[]};const e={};for(const t of g)e[t.account]||(e[t.account]=[]),e[t.account].push(t);const t=r.filter(t=>e[t.id]?.length>0);return{projectsByOrg:e,orgOptions:t}},[g,r]);o(()=>{!u&&v.length>0&&h(v[0].id)},[v,u]);const x=u&&f[u]||[],b=v.find(e=>e.id===u);return t(p,{className:"pt-10 flex flex-col items-center text-center text-gray-700",children:[e(K,{className:"w-10 h-10 mb-4 text-gray-500"}),e("div",{className:"text-xl font-semibold",children:s("shell.accessDenied")}),t("div",{className:"mt-2 text-sm text-gray-500",children:["You don't have permission to view the ",e("span",{className:"font-semibold",children:n})," app in project:"," ",t("span",{className:"font-semibold",children:["«",i?.name,"»"]}),"."]}),0===v.length&&void 0!==g&&e("div",{className:"mt-4 text-sm text-gray-500",children:"This app is not installed in any project you have access to."}),v.length>0&&t("div",{className:"mt-4 flex flex-row gap-4 items-end",children:[v.length>1&&t("div",{children:[e("div",{className:"text-sm text-gray-500 mb-2",children:s("shell.organization")}),e(m,{by:"id",value:b,options:v,optionLabel:e=>e.name,placeholder:s("shell.selectOrganization"),onChange:e=>h(e.id)})]}),t("div",{children:[v.length>1&&e("div",{className:"text-sm text-gray-500 mb-2",children:s("login.terminal.project")}),e(m,{by:"id",value:void 0,options:x,optionLabel:e=>e.name,placeholder:s("shell.selectProject"),onChange:e=>{localStorage.setItem(D,e.account),localStorage.setItem(`${_}-${e.account}`,e.id),window.location.reload()}})]})]})]})}function Ie(){const{t:n}=J();return t(p,{className:"pt-10 flex flex-col items-center text-center text-gray-700",children:[e(K,{className:"w-10 h-10 mb-4 text-gray-500"}),e("div",{className:"text-xl font-semibold",children:n("shell.applicationNotRegistered")}),t("div",{className:"mt-2 text-sm text-gray-500",children:["Before starting to code a Vertesia application you must register an application manifest in Vertesia Studio then install it in one or more projects.",e("p",{}),"Then use the created app name as a parameter to"," ",e("code",{children:'<StandaloneApp name="your-app-name">'})," in the ",e("code",{children:"src/main.tsx"})," file."]})]})}function Pe(){const n=E(),{client:i}=n,{t:r}=J(),[l,c]=a(!1),[s,d]=a([]);o(()=>{i.account.listInvites().then(e=>{if(e.length>0){const t=e.filter(e=>e.data.account);if(0===t.length)return void console.log("No valid invites found, closing modal");console.log("Found valid invites",t.length),c(!0),d(t)}else console.log("No invites found, closing modal"),c(!1)}).catch(e=>{console.error("Error fetching invites",e)})},[i.account.listInvites]);const u=()=>c(!1),m=s.map(a=>a.data.account?t("div",{className:"flex flex-row w-full justify-between border rounded-sm px-2 py-2 ",children:[t("div",{className:"flex flex-col",children:[e("div",{className:"w-full font-semibold",children:a.data.account.name??a.data.account}),a.data.project&&t("div",{className:"w-full text-base",children:["- ",a.data.project.name]}),t("div",{className:"text-xs",children:["Role: ",a.data.role]}),a.data.invited_by&&t("div",{className:"text-xs",children:["by ",a.data.invited_by.name??a.data.invited_by]})]}),t("div",{className:"flex flex-col gap-4",children:[e(h,{size:"xs",onClick:()=>(async e=>{await i.account.acceptInvite(e.id),await n.authCallback,await n.fetchAccounts(),await n.fetchProjects(e.data.account.id);const t=s.filter(t=>t.id!==e.id).filter(e=>e.data.account);t.length>0?d(t):u()})(a),children:r("login.accept")})," ",e(h,{size:"xs",variant:"secondary",onClick:()=>(async e=>{await i.account.rejectInvite(e.id);const t=s.filter(t=>t.id!==e.id);d(t),0===t.length&&u()})(a),children:r("login.reject")})]})]},a.id):(console.warn("Invite has no account data",a),null));return e("div",{children:t(g,{isOpen:l,onClose:u,children:[e(f,{children:r("login.reviewInvites")}),t(v,{children:[e("div",{className:"text-sm pb-4",children:"You have received the following invites to join other accounts. Please review and accept or declined them."}),m]})]})})}const Ae=Q,Le={google:function(n){return t("svg",{viewBox:"0 0 48 48","aria-hidden":"true",...n,children:[e("path",{fill:"#FFC107",d:"M43.6 20.5H42V20H24v8h11.3c-1.6 4.7-6.1 8-11.3 8a12 12 0 0 1 0-24c3 0 5.8 1.1 7.9 3l5.7-5.7A20 20 0 1 0 24 44c11 0 20-9 20-20 0-1.2-.1-2.3-.4-3.5z"}),e("path",{fill:"#FF3D00",d:"M6.3 14.7l6.6 4.8A12 12 0 0 1 24 12c3 0 5.8 1.1 7.9 3l5.7-5.7A20 20 0 0 0 6.3 14.7z"}),e("path",{fill:"#4CAF50",d:"M24 44c5.2 0 10-2 13.6-5.2l-6.3-5.3A12 12 0 0 1 12.7 28.5l-6.6 5.1A20 20 0 0 0 24 44z"}),e("path",{fill:"#1976D2",d:"M43.6 20.5H42V20H24v8h11.3a12 12 0 0 1-4 5.5l6.3 5.3C37.9 36.6 44 31 44 24c0-1.2-.1-2.3-.4-3.5z"})]})},github:function(t){return e("svg",{viewBox:"0 0 24 24","aria-hidden":"true",...t,children:e("path",{fill:"currentColor",fillRule:"evenodd",clipRule:"evenodd",d:"M12 2C6.48 2 2 6.58 2 12.25c0 4.54 2.87 8.39 6.84 9.75.5.09.68-.22.68-.49v-1.7c-2.78.62-3.37-1.36-3.37-1.36-.46-1.18-1.11-1.5-1.11-1.5-.91-.63.07-.62.07-.62 1 .07 1.53 1.05 1.53 1.05.89 1.57 2.34 1.12 2.91.86.09-.66.35-1.12.63-1.38-2.22-.26-4.56-1.14-4.56-5.07 0-1.12.39-2.03 1.03-2.75-.1-.26-.45-1.3.1-2.7 0 0 .84-.28 2.76 1.05A9.4 9.4 0 0 1 12 7.07c.85 0 1.71.12 2.51.34 1.91-1.33 2.75-1.05 2.75-1.05.55 1.4.2 2.44.1 2.7.64.72 1.03 1.63 1.03 2.75 0 3.94-2.34 4.81-4.57 5.06.36.32.68.94.68 1.9v2.81c0 .27.18.59.69.49C19.13 20.64 22 16.78 22 12.25 22 6.58 17.52 2 12 2z"})})},microsoft:function(n){return t("svg",{viewBox:"0 0 24 24","aria-hidden":"true",...n,children:[e("path",{fill:"#F25022",d:"M2 2h9.5v9.5H2z"}),e("path",{fill:"#7FBA00",d:"M12.5 2H22v9.5h-9.5z"}),e("path",{fill:"#00A4EF",d:"M2 12.5h9.5V22H2z"}),e("path",{fill:"#FFB900",d:"M12.5 12.5H22V22h-9.5z"})]})},oidc:Ae};function Te(e){return e&&e in Le?Le[e]:Ae}function Oe({children:t,centered:n=!1}){return e("div",{className:n?"w-full max-w-[420px] flex flex-col gap-6 items-center text-center":"w-full max-w-[420px] flex flex-col gap-6",children:t})}function Re({eyebrow:n,title:i,body:r,variant:a="info"}){return t("div",{children:[n&&e("div",{className:`${"destructive"===a?"text-destructive":"text-info"} text-[12.5px] font-medium mb-2`,children:n}),e("h1",{className:"text-foreground text-[22px] font-semibold tracking-tight leading-tight mb-1.5",children:i}),r&&e("p",{className:"text-muted text-sm leading-relaxed",children:r})]})}const Be={primary:"h-[42px] gap-2.5 rounded-md bg-foreground text-background hover:opacity-90 disabled:opacity-50 disabled:cursor-not-allowed",loading:"h-[42px] gap-2.5 rounded-md bg-foreground text-background opacity-90",ghost:"h-9 text-muted hover:text-foreground"};function Ee({variant:t="primary",className:n="",type:i="button",disabled:r,...a}){return e(h,{variant:"unstyled",size:"none",type:i,disabled:"loading"===t||r,className:`cursor-pointer inline-flex items-center justify-center text-sm font-medium transition ${Be[t]} ${n}`.trim(),...a})}function De({size:t="xs",className:n="",type:i="button",...r}){const a=`cursor-pointer ${"smaller"===t?"!text-[11px]":"!text-xs"} text-muted hover:text-foreground !transition px-2 py-1 !rounded underline decoration-transparent hover:decoration-current underline-offset-[3px]`;return e(h,{variant:"unstyled",size:"none",type:i,className:n?`${a} ${n}`:a,...r})}const _e={circle:"size-9 rounded-full text-sm ring-4 ring-background ring-offset-1 ring-offset-border",square:"size-[30px] rounded-md text-[11px]"};function $e({initials:t,shape:n="circle"}){return e("span",{className:`bg-info text-info-foreground grid place-items-center font-semibold shrink-0 ${_e[n]}`,children:t})}function qe({children:t}){return e("div",{className:"inline-grid place-items-center size-14 rounded-xl bg-info-background border border-info/15 mb-3.5",children:t})}function Fe({title:n,subtitle:i,titleClass:r,subtitleClass:a}){return t("div",{className:"flex-1 min-w-0",children:[e("div",{className:r,children:n}),e("div",{className:a,children:i})]})}const Me={tenant:{topRow:"flex items-center gap-2.5 px-3 py-2.5",title:"text-[13.5px] font-semibold text-foreground leading-tight",subtitle:"text-[11.5px] text-muted leading-tight mt-0.5",bottomRow:"flex items-center gap-2.5 px-3 py-1.5 border-t border-border bg-muted-background",mailBox:"size-[30px] grid place-items-center shrink-0",mailIcon:"size-4 text-muted",email:"text-sm text-foreground/80 flex-1 truncate",actionSize:"xs"},returning:{topRow:"flex items-center gap-3 px-3.5 py-2.5",title:"text-sm font-semibold text-foreground truncate",subtitle:"text-xs text-foreground/80 truncate",bottomRow:"flex items-center gap-3 px-3.5 py-1 border-t border-border bg-muted-background",mailBox:"w-9 h-6 grid place-items-center shrink-0",mailIcon:"size-3.5 text-muted",email:"text-xs text-foreground/80 flex-1 truncate",actionSize:"smaller"}};function Ue({variant:n="returning",badge:i,title:r,subtitle:a,email:o,actionLabel:l,onAction:c}){const s=Me[n];return t("div",{className:"rounded-md border border-border bg-background overflow-hidden",children:[t("div",{className:s.topRow,children:[i,e(Fe,{title:r,subtitle:a,titleClass:s.title,subtitleClass:s.subtitle})]}),t("div",{className:s.bottomRow,children:[e("div",{className:s.mailBox,children:e(Z,{className:s.mailIcon})}),e("span",{className:s.email,children:o}),e(De,{size:s.actionSize,onClick:c,children:l})]})]})}function We({badge:n,title:i,subtitle:r,actionLabel:a,onAction:o}){return t("div",{className:"flex items-center gap-3 px-3.5 py-2.5 rounded-md border border-border bg-muted-background",children:[n,e(Fe,{title:i,subtitle:r,titleClass:"text-sm font-semibold text-foreground truncate",subtitleClass:"text-xs text-muted truncate"}),e(De,{onClick:o,children:a})]})}function Ve({email:n,actionLabel:i,onAction:r}){return t("div",{className:"flex items-center gap-2 px-3 py-2 rounded-md border border-border bg-muted-background",children:[e(Z,{className:"size-4 text-muted shrink-0"}),e("span",{className:"text-sm text-foreground/80 flex-1 truncate",children:n}),e(De,{onClick:r,children:i})]})}function He({provider:n,label:i,onClick:r,variant:a="outline"}){const o=Te(n);if("arrow"===a){const n="!size-3.5 text-muted opacity-0 group-hover:opacity-100 group-hover:translate-x-0.5 transition";return t(h,{variant:"unstyled",size:"none",onClick:r,className:"cursor-pointer group h-[42px] w-full inline-flex items-center gap-3 ps-3.5 pe-3 rounded-md border border-border bg-background text-sm font-medium text-foreground transition hover:bg-muted-background",children:[e(o,{className:"!size-[18px] shrink-0"}),e("span",{className:"flex-1 text-start",children:i}),e(X,{className:n})]})}return t(h,{variant:"outline",onClick:r,className:`w-full py-5 flex rounded-lg transition duration-150 text-center ${"filled"===a?"!bg-foreground text-background hover:!bg-foreground/90":"hover:shadow-sm"}`,children:[e(o,{className:"!size-[18px]"}),e("span",{className:"text-sm font-medium",children:i})]})}function Je({icon:n,title:i,meta:r}){return t("div",{className:"flex items-center gap-2.5 px-3 py-2.5 rounded-md bg-destructive-background border border-destructive/20",children:[e(n,{className:"size-5 text-destructive shrink-0"}),t("div",{className:"flex-1 min-w-0 text-sm",children:[e("div",{className:"font-semibold text-destructive",children:i}),e("div",{className:"text-xs text-destructive/80",children:r})]})]})}function Ye({inputRef:n,label:i,placeholder:r,value:a,onChange:o,invalid:l=!1,error:c}){return t("div",{className:"flex flex-col gap-1.5",children:[e("label",{htmlFor:"vt-login-email",className:"text-xs font-medium text-foreground/80",children:i}),e("input",{ref:n,id:"vt-login-email",name:"vt-login-email",type:"email",className:"h-[42px] px-3.5 rounded-md border border-border bg-background text-sm text-foreground placeholder:text-muted-foreground outline-none transition focus:border-info focus:ring-4 focus:ring-info/15 aria-[invalid=true]:border-destructive aria-[invalid=true]:ring-destructive/15",placeholder:r,value:a,onChange:e=>o(e.target.value),"aria-invalid":l,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",spellCheck:!1,"data-1p-ignore":!0,"data-lpignore":"true","data-form-type":"other"}),c&&e("div",{role:"alert",className:"text-xs text-destructive",children:c})]})}const Ge="vt.lastSuccessfulLogin",Ke="vt.pendingSignin";function Qe(){try{const e=localStorage.getItem(Ge);if(!e)return null;const t=JSON.parse(e);return t?.email&&t?.lastProvider?t:null}catch{return null}}function Xe(){try{localStorage.removeItem(Ge)}catch{}}function Ze(){try{const e=sessionStorage.getItem(Ke);return e?JSON.parse(e):null}catch{return null}}function et(){try{sessionStorage.removeItem(Ke)}catch{}}async function tt(){Xe(),et();try{await ae($())}catch{}}function nt(e){let t=e||window.location.pathname||"/";return"/"!==t[0]&&(t=`/${t}`),t}const it={google:(e,t)=>{const n=new se;return n.addScope("profile"),n.addScope("email"),n.setCustomParameters({redirect_uri:window.location.origin+nt(t),...e?{login_hint:e}:{prompt:"select_account"}}),n},github:e=>{const t=new ce;return t.addScope("profile"),t.addScope("email"),e&&t.setCustomParameters({login:e}),t},microsoft:e=>{const t=new le("microsoft.com");return t.addScope("profile"),t.addScope("email"),e&&t.setCustomParameters({login_hint:e}),t},oidc:e=>{const t=new le("oidc.main");return e&&t.setCustomParameters({login_hint:e}),t}};function rt(e,t,n){return it[e](t,n)}async function at(e,t,n){if(!t)return{ok:!1,reason:"no-email"};const i=await q(t),r=$();let a,o=e;return i?(i.provider&&(o=i.provider),a=i.label||i.name||void 0,localStorage.setItem("tenantName",a??"")):(localStorage.removeItem("tenantName"),r.tenantId&&(r.tenantId=null)),function(e){try{sessionStorage.setItem(Ke,JSON.stringify(e))}catch{}}({email:t,provider:o,tenantName:a}),oe(r,rt(o,t,n)),{ok:!0}}function ot(e){return"google"===e?"Google":"github"===e?"GitHub":"microsoft"===e?"Microsoft":"Sign In"}function lt(e){const t=function(e){if(!e)return"";const t=e.lastIndexOf("@");return t>0?e.slice(0,t):e}(e),n=t.split(/[._-]+/).filter(Boolean)[0]||"friend";return n.charAt(0).toUpperCase()+n.slice(1).toLowerCase()}function ct(e){let t=e;for(let e=0;null!=t&&e<8;e++){if((t instanceof Error?t.message:String(t)).includes("Customer-domain user requires an invite to join"))return!0;t=t instanceof Error?t.cause:void 0}return!1}function st({provider:n,onCancel:i}){const{t:r}=J(),a=Te(n),o="oidc"===n?r("auth.pending.genericProvider"):ot(n);return t(Oe,{centered:!0,children:[t("div",{children:[e(qe,{children:e(a,{className:"oidc"===n?"size-6 text-info":"size-6"})}),e(Re,{title:r("auth.pending.title",{provider:o}),body:r("auth.pending.body")})]}),t("div",{className:"w-full flex flex-col gap-2",children:[t(Ee,{variant:"loading",children:[e(x,{}),e("span",{children:r("auth.pending.authenticating")})]}),i&&e(Ee,{variant:"ghost",onClick:i,children:r("auth.pending.cancel")})]})]})}function dt({initialEmail:i,onProceed:r}){const{t:l}=J(),[s,d]=a(i??""),[u,m]=a(!1),[p,h]=a(!1),g=c(null);o(()=>{g.current?.focus()},[]);return t(Oe,{children:[e(Re,{eyebrow:l("auth.email.eyebrow"),title:l("auth.email.title"),body:l("auth.email.body")}),t("form",{onSubmit:async e=>{if(e.preventDefault(),!p)if(function(e){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test((e||"").trim())}(s)){m(!1),h(!0);try{const e=await q(s.trim().toLowerCase());r(s.trim().toLowerCase(),e??void 0)}catch{r(s.trim().toLowerCase(),void 0)}finally{h(!1)}}else m(!0)},noValidate:!0,className:"flex flex-col "+(u?"gap-2":"gap-6"),children:[e(Ye,{inputRef:g,label:l("auth.email.label"),placeholder:l("auth.email.placeholder"),value:s,onChange:e=>{d(e),u&&m(!1)},invalid:u,error:u?l("auth.email.invalidError"):void 0}),e(Ee,{type:"submit",disabled:p,children:p?e(x,{}):t(n,{children:[e("span",{children:l("auth.continue")}),e(X,{className:"!size-3.5"})]})})]})]})}const ut=["google","github","microsoft"];function mt({email:n,onBack:i,onProviderClicked:r,redirectTo:a}){const{t:o}=J();return t(Oe,{children:[e(Re,{eyebrow:o("auth.providers.eyebrow"),title:o("auth.providers.title"),body:o("auth.providers.bodyConsumer")}),e(Ve,{email:n,actionLabel:o("auth.change"),onAction:i}),e("div",{className:"flex flex-col gap-2",children:ut.map(t=>e(He,{provider:t,label:o("auth.continueWithProvider",{provider:ot(t)}),onClick:()=>(async e=>{r(e),await at(e,n,a)})(t),variant:"arrow"},t))})]})}function pt({session:n,onNotYou:i,onProviderClicked:r,redirectTo:a}){const{t:o}=J(),l=n.name?n.name.split(" ")[0]||n.name:lt(n.email),c=n.name||lt(n.email),s=e($e,{initials:(d=n.email,(d||"?").charAt(0).toUpperCase())});var d;const u=!!n.tenantName,m="oidc"===n.lastProvider?o("auth.continueWithSignIn"):o("auth.continueWithProvider",{provider:ot(n.lastProvider)});return t(Oe,{children:[e(Re,{eyebrow:o("auth.returning.eyebrow"),title:o("auth.returning.title",{name:l}),body:o("auth.returning.body")}),u&&n.tenantName?e(Ue,{variant:"returning",badge:s,title:c,subtitle:n.tenantName,email:n.email,actionLabel:o("auth.returning.notYou"),onAction:i}):e(We,{badge:s,title:c,subtitle:n.email,actionLabel:o("auth.returning.notYou"),onAction:i}),t("div",{className:"flex flex-col gap-2",children:[e(He,{provider:n.lastProvider,label:m,onClick:()=>(async e=>{r(e),await at(e,n.email,a)})(n.lastProvider),variant:"filled"}),e(Ee,{variant:"ghost",onClick:i,children:o("auth.returning.useDifferent")})]})]})}function ht({email:n,tenantName:i,onBack:r}){const{t:a}=J(),o=i||a("auth.blocked.tenantFallback"),l=function(e){if(!e)return"";const t=e.lastIndexOf("@");return t>0?e.slice(t+1):""}(n),c=i||(l?a("auth.blocked.teamFromDomain",{domain:(s=l,s?s.charAt(0).toUpperCase()+s.slice(1):s)}):a("auth.blocked.tenantFallback"));var s;return t(Oe,{children:[e(Re,{variant:"destructive",eyebrow:a("auth.blocked.eyebrow"),title:a("auth.blocked.title"),body:a("auth.blocked.body",{name:o,email:n})}),t("div",{className:"flex flex-col gap-2",children:[e(Je,{icon:ee,title:c,meta:a("auth.blocked.tenantMeta",{email:n})}),e(Ee,{variant:"ghost",onClick:r,children:a("auth.blocked.useDifferent")})]})]})}function gt({provider:t,email:n,redirectTo:i,variant:r="outline",onClick:a}){const{t:o}=J(),l="oidc"===t?o("auth.continueWithSignIn"):o("auth.continueWithProvider",{provider:ot(t)});return e(He,{provider:t,label:l,onClick:()=>{a?.(),n?at(t,n,i):function(e,t){const n=$();localStorage.removeItem("tenantName"),n.tenantId&&(n.tenantId=null),oe(n,rt(e,void 0,t))}(t,i)},variant:r})}function ft({email:n,tenant:i,onBack:r,onProviderClicked:a,redirectTo:o}){const{t:l}=J(),c=i.label||i.name||l("auth.blocked.tenantFallback"),s="google"===i.provider||"github"===i.provider||"microsoft"===i.provider?i.provider:"oidc",d="oidc"===s?l("auth.tenant.viaIdpFallback"):ot(s);return t(Oe,{children:[e(Re,{eyebrow:l("auth.tenant.eyebrow"),title:l("auth.tenant.title",{name:c}),body:l("auth.tenant.body")}),e(Ue,{variant:"tenant",badge:e($e,{initials:(u=c,u.split(/\s+/).filter(Boolean).slice(0,2).map(e=>e.charAt(0).toUpperCase()).join("")),shape:"square"}),title:c,subtitle:l("auth.tenant.viaIdp",{idp:d}),email:n,actionLabel:l("auth.change"),onAction:r}),t("div",{className:"flex flex-col gap-2",children:[e(gt,{provider:s,email:n,redirectTo:o,variant:"filled",onClick:a}),e(Ee,{variant:"ghost",onClick:r,children:l("auth.tenant.notPartOf",{name:c})})]})]});var u}function vt({onSignup:i,goBack:r}){const{t:l}=J(),[c,s]=a(void 0),[d,u]=a(void 0),[p,g]=a(void 0),[f,v]=a(void 0),[x,N]=a(void 0),[w,k]=a(void 0),[C,S]=a(void 0),j="company"===c,z=[{id:1,label:l("signup.size1to10")},{id:11,label:l("signup.size11to100")},{id:101,label:l("signup.size101to1000")},{id:1001,label:l("signup.size1001to5000")},{id:5001,label:l("signup.size5000plus")}],I=[{id:"personal",label:l("signup.personal"),description:l("signup.personalDescription")},{id:"company",label:l("signup.company"),description:l("signup.companyDescription")}],P=[{id:"testing",label:l("signup.justTesting")},{id:"exploring",label:l("signup.activelyExploring")},{id:"using",label:l("signup.alreadyUsing")},{id:"migrating",label:l("signup.migratingLLMs")},{id:"other",label:l("signup.other")}];o(()=>{const e=$().currentUser;e?k(e):console.error("No user found")},[]);return t("div",{className:"flex flex-col space-y-2",children:[t("div",{className:"prose",children:[e("p",{className:"prose text-sm text-muted pt-4",children:l("signup.welcomeMessage",{name:w?.displayName,email:w?.email})}),C&&e("div",{className:"text-destructive",children:C})]}),e(xt,{label:l("signup.accountType"),children:e(b,{options:I,selected:I.find(e=>e.id===c),onSelect:e=>s(e.id)})}),j&&t(n,{children:[e(xt,{label:l("signup.companySize"),children:e(m,{className:"w-full border border-accent bg-muted",value:d,options:z,onChange:u,optionLabel:e=>e?.label,placeholder:l("signup.selectCompanySize")})}),e(xt,{label:l("signup.companyName"),children:e(y,{value:p,onChange:g,type:"text",required:!0})}),e(xt,{label:l("signup.companyWebsite"),children:e(y,{value:f,onChange:v,type:"text"})})]}),e(xt,{label:l("signup.projectMaturity"),children:e(m,{className:"w-full border border-accent bg-muted",options:P,value:P.find(e=>e.id===x),optionLabel:e=>e?.label,placeholder:l("signup.selectProjectMaturity"),onChange:e=>N(e?.id)})}),t("div",{className:"pt-8 flex flex-col",children:[e(h,{variant:"primary",onClick:async()=>{if(!(c?j&&!p?(S(l("signup.pleaseEnterOrgName")),0):!j||d||(S(l("signup.pleaseSelectCompanySize")),0):(S(l("signup.pleaseSelectAccountType")),0)))return;if(!c)return;const e={accountType:c,companyName:p,companySize:d?.id,companyWebsite:f,maturity:x};window.localStorage.setItem("composableSignupData",JSON.stringify(e));const t=await($().currentUser?.getIdToken());console.log("Got firebase token",$(),t),t?i(e,t):console.error("No firebase token found")},size:"xl",children:e("span",{className:"text-lg",children:l("signup.signUp")})}),e(h,{variant:"ghost",size:"xl",className:"mt-4",onClick:r,children:e("span",{className:"",children:l("signup.wrongAccountGoBack")})})]})]})}function xt({label:n,children:i}){return t("div",{className:"flex flex-col space-y-2 pt-4",children:[e("div",{className:"text-sm text-muted",children:n}),i]})}function bt({allowedPrefix:t,isNested:n=!1,lightLogo:i,darkLogo:r,preservePath:a,suppressAuthErrorPrefix:o}){const l="undefined"==typeof window?"":window.location.pathname,c=yt(l,t),s=yt(l,o);return c?null:e(Nt,{isNested:n,lightLogo:i,darkLogo:r,preservePath:a,suppressAuthError:s})}function yt(e,t){return(Array.isArray(t)?t:t?[t]:[]).some(t=>e===t||e.startsWith(t.endsWith("/")?t:`${t}/`))}function Nt({isNested:n=!1,lightLogo:i,darkLogo:r,preservePath:l,suppressAuthError:c}){const{t:d}=J(),{isLoading:u,user:m,authError:p,signOut:h}=E(),{trackEvent:g}=F(),[f,v]=a(()=>Qe()),[x,b]=a(()=>Qe()?"returning":"email"),[y,N]=a(""),[w,k]=a(void 0),[C,S]=a(null);o(()=>{if(!l){const e=new URL(document.baseURI).pathname||"/";history.replaceState({},"",e)}},[l]),o(()=>{if(p)if(p instanceof M)b("signup");else if(ct(p)){const e=Ze();e&&N(e.email),b("blocked")}},[p]),o(()=>{if(!m)return;const e=Ze();e&&(!function(e){try{localStorage.setItem(Ge,JSON.stringify(e))}catch{}}({email:e.email,lastProvider:e.provider,tenantName:e.tenantName,name:m.name||void 0}),et())},[m]);const j=s((e,t)=>{N(e),k(t),b(t?"tenant":"providers")},[]),z=s(()=>{b("email"),k(void 0)},[]),I=s(()=>{Xe(),et(),v(null),N(""),k(void 0),b("email"),h()},[h]),P=s(e=>{(!!w||!!f?.tenantName)&&g("enterprise_signin",{provider:e}),S(e),b("pending")},[g,f?.tenantName,w]),A=s(()=>{v(null),N(""),k(void 0),b("email"),tt()},[]),L=(e,t)=>{const n={signupData:e,firebaseToken:t};fetch(`${ie.endpoints.studio}/auth/signup`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}).then(()=>{g("sign_up"),window.location.href="/"})};if(u||m||c&&void 0!==p&&!(p instanceof M))return null;let T=null;return T="pending"===x&&C?e(st,{provider:C}):"blocked"===x?e(ht,{email:y||f?.email||"",tenantName:w?.label||w?.name||f?.tenantName||void 0,onBack:A}):"signup"!==x||localStorage.getItem("tenantName")?"tenant"===x&&w?e(ft,{email:y,tenant:w,onBack:z,onProviderClicked:()=>P(w.provider??"oidc")}):"providers"===x?e(mt,{email:y,onBack:z,onProviderClicked:P}):"returning"===x&&f?e(pt,{session:f,onNotYou:I,onProviderClicked:P}):e(dt,{initialEmail:y,onProceed:j}):e(vt,{onSignup:L,goBack:A}),e("div",{style:{zIndex:999998},className:(n?"absolute":"fixed")+" inset-0 overflow-y-auto bg-background",children:e("div",{className:"min-h-full flex flex-col items-center justify-center py-12 px-4",children:t("div",{className:"flex flex-col items-center w-full",children:[(i||r)&&t("div",{className:"mb-7",children:[i&&e("img",{src:i,alt:"Vertesia",className:"h-10 block dark:hidden"}),r&&e("img",{src:r,alt:"Vertesia",className:"h-10 hidden dark:block"})]}),T,p&&!(p instanceof M)&&!ct(p)&&e("div",{className:"mt-6 max-w-[420px] text-center text-sm text-muted",children:t("div",{children:[d("auth.signInError"),e("br",{}),d("auth.signInErrorContact"),e("a",{className:"text-info mx-1",href:"mailto:support@vertesiahq.com",children:"support@vertesiahq.com"}),d("auth.signInErrorPersists"),e("pre",{className:"mt-2 text-xs",children:d("auth.error",{message:p.message})})]})}),t("div",{className:"flex items-center gap-5 mt-10 text-xs text-muted-foreground",children:[e("a",{href:"https://vertesiahq.com/privacy",className:"hover:text-foreground transition",children:d("auth.privacyPolicy")}),e("span",{className:"text-border",children:"·"}),e("a",{href:"https://vertesiahq.com/terms",className:"hover:text-foreground transition",children:d("auth.termsOfService")}),e("span",{className:"text-border",children:"·"}),e(re,{className:"cursor-default"})]})]})})})}const wt=new Set(["127.0.0.1","localhost"]);function kt(e){const t=new URLSearchParams(e.search),n=function(e){if(!e)return null;let t,n;try{t=decodeURIComponent(e)}catch{return null}try{n=new URL(t)}catch{return null}return"http:"!==n.protocol?null:n.port?n.username||n.password?null:wt.has(n.hostname)?n.toString():null:null}(t.get("redirect_uri")),i=t.get("code");if(!n||!i)return null;return{redirect:n,code:i,profile:t.get("profile")??"default",project:t.get("project")??void 0,account:t.get("account")??void 0}}function Ct(){const[t,n]=a(),[i,r]=a(),o=kt(de()),l=N(),{t:c}=J(),s=async e=>{if(!o)return;if(!e.profile)return void l({title:c("login.terminal.profileRequired"),description:c("login.terminal.profileRequiredDesc"),status:"error",duration:2e3});if(!e.account)return void l({title:c("login.terminal.accountRequired"),description:c("login.terminal.accountRequiredDesc"),status:"error",duration:2e3});if(!e.project)return void l({title:c("login.terminal.projectRequired"),description:c("login.terminal.projectRequiredDesc"),status:"error",duration:2e3});let t;try{const i=U(),r=i?await W(i,e.account,e.project,86400):await V(e.account,e.project,86400);r?(t={...e,studio_server_url:ie.endpoints.studio,zeno_server_url:ie.endpoints.zeno,token:r},await fetch(o.redirect,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),n(t)):l({title:c("login.terminal.failedToGetToken"),status:"error",duration:5e3})}catch(e){t?(r(e instanceof Error?e:new Error(u(e))),n(t)):l({title:c("login.terminal.errorAuthorizingClient"),description:u(e),status:"error",duration:5e3})}},d=o?t?e(jt,{payload:t,error:i}):e(St,{clientInfo:o,onAccept:s}):e(w,{title:c("login.terminal.invalidRequest"),children:c("login.terminal.invalidRequestDesc")});return e("div",{className:"w-full flex flex-col items-center gap-4 mt-24",children:d})}function St({onAccept:i,clientInfo:r}){const{client:a,user:o}=E(),{data:l,error:c}=d(()=>o?a.projects.list():Promise.resolve([]),[o]),{t:s}=J();if(c)return e(w,{title:s("login.terminal.errorLoadingProjects"),children:u(c)});const m=ie.isLocalDev?s("login.terminal.envLocalDev"):ie.isDev?s("login.terminal.envStaging"):s("login.terminal.envProduction");return o&&l?t(n,{children:[t("div",{className:"w-1/3",children:[t("div",{className:"mb-4 text-xl font-semibold text-info",children:["Authorizing client on ",m," environment."]}),t("div",{className:"mb-2 text-md text-muted-foreground",children:[e("div",{children:s("login.terminal.clientWantsAuth")}),t("div",{children:["The client app code is ",e("b",{className:"text-foreground",children:r.code}),". You can check if the code is correct in the terminal."]})]}),t("div",{className:"mb-2 text-sm text-muted-foreground",children:[e("div",{children:s("login.terminal.chooseAccountProject")}),e("div",{children:s("login.terminal.profileNameNote")})]})]}),e(zt,{onAccept:i,allProjects:l,data:r})]}):e(x,{size:"lg"})}function jt({payload:n,error:i}){const r=N(),{t:a}=J();return t("div",{children:[e("div",i?{children:e(w,{title:a("login.terminal.failedToSendToken"),children:a("login.terminal.failedToSendTokenDesc",{error:i.message})})}:{children:a("login.terminal.clientAuthenticated")}),e(p,{className:"mt-4",children:e(h,{variant:"secondary",onClick:()=>{n&&(navigator.clipboard.writeText(JSON.stringify(n)),r({title:a("login.terminal.authPayloadCopied"),description:i?a("login.terminal.authPayloadCopiedWithError",{error:i.message}):a("login.terminal.authPayloadCopiedSuccess"),status:"success",duration:5e3}))},children:a("login.terminal.copyAuthPayload")})})]})}function zt({allProjects:n,data:i,onAccept:r}){const{accounts:o,account:l,project:c}=E(),{t:s}=J(),[d,u]=a(()=>({profile:i.profile,account:i.account??l?.id,project:i.project??c?.id})),m=n.filter(e=>e.account===d.account);return t("div",{className:"w-1/3",children:[t("div",{className:"mb-4 flex flex-col gap-2",children:[e("span",{className:"font-semibold text-muted-foreground",children:s("login.terminal.profileName")}),e(y,{type:"text",value:d.profile,onChange:e=>{u({...d,profile:e})}})]}),t("div",{className:"mb-4 flex flex-col gap-2",children:[e("span",{className:"font-semibold text-muted-foreground",children:s("login.terminal.account")}),e(It,{value:d.account,onChange:e=>{u({...d,account:e.id,project:void 0})},accounts:o||[]})]}),t("div",{className:"mb-4 flex flex-col gap-2",children:[e("span",{className:"font-semibold text-muted-foreground",children:s("login.terminal.project")}),e(Pt,{value:d.project,onChange:e=>{u({...d,project:e.id})},projects:m})]}),e("div",{className:"mb-4 text-sm text-attention",children:s("login.terminal.browserPermissionNote")}),e("div",{children:e(h,{size:"xl",onClick:()=>r(d),children:s("login.terminal.authorizeClient")})})]})}function It({value:t,accounts:n,onChange:i}){const{t:r}=J();return e(m,{options:n,value:n?.find(e=>e.id===t),onChange:e=>{i(e)},by:"id",optionLabel:e=>e.name,placeholder:r("login.terminal.selectAccount")})}function Pt({value:t,projects:n,onChange:i}){const{t:r}=J();return e(m,{by:"id",value:n.find(e=>e.id===t),options:n,optionLabel:e=>e.name,placeholder:r("login.terminal.selectProject"),onChange:e=>{i(e)}})}function At({isOpen:n,onClose:i}){return t(g,{isOpen:n,onClose:i,children:[e(f,{children:"Sign In"}),t(v,{className:"flex flex-col gap-2",children:[e(gt,{provider:"google"}),e(gt,{provider:"github"}),e(gt,{provider:"microsoft"})]}),e(k,{align:"right",children:e(h,{variant:"ghost",onClick:i,children:"Cancel"})})]})}function Lt({title:n,value:i}){const[r,o]=a(!1);return t("div",{className:"w-full flex justify-between items-center mb-1",children:[t("div",{className:"flex flex-col w-[calc(100%-3rem)]",children:[e("div",{className:"text-sm px-2 dark:text-slate-200",children:n}),e(z,{description:i,size:"xs",placement:"left",children:t("div",{className:"text-xs truncate text-muted w-full text-start px-2",children:[i," "]})})]}),r?e(te,{className:"size-4 cursor-pointer text-success"}):e(ne,{className:"size-4 cursor-pointer text-gray-400 dark:text-slate-400",onClick:()=>function(e){navigator.clipboard.writeText(e),o(!0),setTimeout(()=>o(!1),2e3)}(i)})]})}function Tt(){const{t:n}=J(),i=E(),{account:r,project:a,client:o,authToken:l}=i,c=o.baseUrl,s=o.store.baseUrl,d=s.replace(/\/+$/,"")!==c.replace(/\/+$/,""),u=ie.endpoints.mcp??n("user.unknown"),m=a?me(a):"",p=[{name:"user",label:n("user.user"),content:t("div",{className:"space-y-1 p-2",children:[e(Lt,{title:n("user.organizationId"),value:r?.id??n("user.unknown")}),e(Lt,{title:n("user.projectId"),value:a?.id??n("user.unknown")}),e(Lt,{title:n("user.userId"),value:l?.sub??n("user.unknown")}),e(Lt,{title:n("user.organizationRoles"),value:l?.account_roles?.join(",")??n("user.unknown")}),e(Lt,{title:n("user.projectRoles"),value:l?.project_roles?.join(",")??n("user.unknown")})]})},{name:"environment",label:n("user.environment"),content:t("div",{className:"space-y-1 p-2",children:[e(Lt,{title:n("user.tenantId"),value:m}),e(Lt,{title:n("user.environment"),value:ie.type}),e(Lt,{title:n("user.server"),value:c}),d&&e(Lt,{title:n("user.store"),value:s}),e(Lt,{title:n("user.mcpServer"),value:u}),e(Lt,{title:n("user.appVersion"),value:ie.version}),e(Lt,{title:n("user.sdkVersion"),value:ie.sdkVersion||n("user.unknown")})]})}];return e("div",{className:"w-full",children:t(C,{defaultValue:"user",tabs:p,fullWidth:!0,updateHash:!1,children:[e(S,{}),e(j,{})]})})}function Ot(i){const{user:r,isLoading:o}=E(),[l,c]=a(!1);return o?e(x,{}):r?e("div",{className:"px-3",children:e(Rt,{asMenuTrigger:!0})}):t(n,{children:[e(h,{onClick:()=>c(!0),children:"Sign In"}),e(At,{isOpen:l,onClose:()=>c(!1)})]})}function Rt({className:n,asMenuTrigger:i=!1}){const r=E(),a=ue(),o=he(),{user:l}=r;if(!r||!l)return null;const c=o.hasPermission(pe.project_admin);return t(I,{click:!0,children:[e(P,{children:e("div",{className:ve(n,"flex items-center justify-start",i&&"cursor-pointer"),children:e(A,{size:"sm",color:"bg-amber-500",shape:"circle",name:l?.name})})}),e(L,{align:"start",className:"w-[280px] mx-2 my-1 p-0",children:t("div",{className:"divide-y divide-gray-200 dark:divide-slate-700",children:[t("div",{className:"py-2 ps-2",children:[e("p",{className:"px-4 dark:text-white mb-1",children:l?.name??"Unknown"}),e("p",{className:"px-4 text-xs text-gray-500",children:l?.email??""})]}),e("div",{className:"w-full p-1",children:e(Tt,{})}),e("div",{className:"py-2 ps-2",children:e(T,{})}),e("div",{className:"py-2",children:t(O,{children:[c&&e(O.Item,{className:"px-2",onClick:()=>a("/settings",{replace:!0}),children:"Settings"}),e(O.Item,{className:"px-2",onClick:()=>r.logout(),children:"Sign out"})]})})]})})]})}function Bt(e){return!!e&&(e.endsWith("@vertesiahq.com")||e.endsWith("@becomposable.com")||e.endsWith("@composableprompts.com"))}function Et({icon:t}){const{isLoading:n}=E(),[i,r]=a(!0);return o(()=>{n||r(!1)},[n]),e(xe,{children:i&&e(be.div,{style:{zIndex:999999,position:"fixed",inset:0},className:"fixed inset-x-0 inset-y-0",initial:{opacity:1},exit:{opacity:0},transition:{ease:"easeIn",duration:.5},children:e("div",{style:{display:"flex",width:"100%",height:"100%",alignItems:"center",justifyContent:"center"},className:"flex w-full h-full items-center justify-center",children:e("div",{className:"animate-[spin_4s_linear_infinite]",children:e("div",{className:"animate-pulse rounded-full bg-transparent",children:t||e(Dt,{})})})})})})}function Dt(){return t("svg",{width:"32",height:"32",className:"w-8 h-8 text-indigo-600",viewBox:"0 0 50 50",xmlns:"http://www.w3.org/2000/svg",role:"img","aria-label":"Loading",children:[e("title",{children:"Loading"}),e("defs",{children:t("linearGradient",{id:"spinner-gradient",x1:"1",y1:"0",x2:"0",y2:"1",children:[e("stop",{offset:"0%",stopColor:"currentColor",stopOpacity:"1"}),e("stop",{offset:"100%",stopColor:"currentColor",stopOpacity:"0"})]})}),e("circle",{cx:"25",cy:"25",r:"20",stroke:"url(#spinner-gradient)",strokeWidth:"5",fill:"none",strokeLinecap:"round"})]})}function _t({children:n,lightLogo:i,darkLogo:r,loadingIcon:a,loadOnboardingStatus:o,preserveSignInPath:l,suppressSignInErrorPrefixes:c,defaultLanguage:s}){return e(R,{children:e(H,{loadOnboardingStatus:o,children:e(ge,{children:e(B,{defaultTheme:"system",storageKey:"vite-ui-theme",children:e(Y,{defaultLanguage:s,children:t(G,{children:[e(Et,{icon:a}),e(bt,{allowedPrefix:"/shared/",darkLogo:r,lightLogo:i,preservePath:l,suppressAuthErrorPrefix:c}),e(fe,{children:n})]})})})})})})}export{ye as AppInstallationContext,Ne as AppInstallationProvider,ke as AppProjectSelector,Pe as InviteAcceptModal,bt as SigninScreen,Se as StandaloneApp,je as StandaloneAppImpl,Ct as TerminalLogin,Ot as UserSessionMenu,_t as VertesiaShell,Bt as isVertesiaEmail,we as useAppInstallation};
2
2
  //# sourceMappingURL=vertesia-ui-shell.js.map