@trieoh/identityx-sdk-ts 0.12.6 → 0.12.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/index.js +2 -2
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/react.js +2 -2
- package/dist/cjs/react.js.map +1 -1
- package/dist/esm/{api-DH83FB5b.d.ts → api-BjzcDj0c.d.ts} +2 -2
- package/dist/esm/index.d.ts +1 -1
- package/dist/esm/index.js +2 -2
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/react.d.ts +61 -3
- package/dist/esm/react.js +2 -2
- package/dist/esm/react.js.map +1 -1
- package/package.json +14 -6
package/dist/cjs/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
'use strict';var envoyFetchTs=require('@trieoh/envoy-fetch-ts');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function
|
|
2
|
-
Object.defineProperty(exports,"ApiError",{enumerable:true,get:function(){return envoyFetchTs.FetchClientError}});exports.AuthInterceptor=
|
|
1
|
+
'use strict';var envoyFetchTs=require('@trieoh/envoy-fetch-ts');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function y(t,e){if(e.startsWith("http"))return e;let r=t.replace(/\/$/,""),n=e.replace(/^\//,"");return `${r}/${n}`}var d={isAuthenticated:false,isInitializing:true},I=new Set,F=()=>I.forEach(t=>t()),g={subscribe:t=>(I.add(t),()=>I.delete(t)),getSnapshot:()=>d,getServerSnapshot:()=>d,set:t=>{d={...d,...t},F();},reset:()=>{d={isAuthenticated:false,isInitializing:false},F();}};typeof window<"u"&&window.addEventListener("storage",t=>{if(t.key==="trieoh_access_expiry")if(!t.newValue)g.reset();else {let e=Number(t.newValue),r=!isNaN(e)&&e>Date.now();g.set({isAuthenticated:r,isInitializing:false});}});var i={getItem:t=>typeof window<"u"?localStorage.getItem(t):null,setItem:(t,e)=>{typeof window<"u"&&localStorage.setItem(t,e);},removeItem:t=>{typeof window<"u"&&localStorage.removeItem(t);}},m={getItem:t=>typeof window<"u"?sessionStorage.getItem(t):null,setItem:(t,e)=>{typeof window<"u"&&sessionStorage.setItem(t,e);},removeItem:t=>{typeof window<"u"&&sessionStorage.removeItem(t);}};var _="trieoh_access_token",a={getAccessToken:()=>m.getItem(_),setAccessToken:t=>{t?m.setItem(_,t):m.removeItem(_);},clear:()=>{m.removeItem(_);}};var T=null,w="trieoh_access_expiry",x="trieoh_refresh_expiry",S="trieoh_refresh_token";function q(t){try{let e=t.split(".")[1];if(!e)return null;let r=e.replace(/-/g,"+").replace(/_/g,"/");for(;r.length%4;)r+="=";let n=decodeURIComponent(atob(r).split("").map(s=>"%"+("00"+s.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(n)}catch(e){return envoyFetchTs.logger.error("Error decoding JWT:",e),null}}function D(t){let{access_token:e,refresh_token:r,access_expires_at:n,refresh_expires_at:s}=t,A=q(e);if(!A){envoyFetchTs.logger.error("Failed to decode tokens");return}a.setAccessToken(e);let p=new Date(s).getTime(),f=new Date(n).getTime();i.setItem(S,r),i.setItem(w,String(f)),i.setItem(x,String(p)),T={access_data:A,refresh_expiry_date:p},g.set({isAuthenticated:true,isInitializing:false}),envoyFetchTs.logger.log("Auth session saved");}function C(){return i.getItem(S)}function L(){if(T)return T;let t=a.getAccessToken();if(!t)return null;let e=q(t);if(!e||e.exp*1e3<=Date.now())return null;let r=i.getItem(x);if(!r)return null;let n=Number(r);if(isNaN(n))return null;let s={access_data:e,refresh_expiry_date:n};return T=s,s}function B(t,e){try{let r=i.getItem(t);if(!r)return !0;let n=Number(r);return isNaN(n)?!0:n-Date.now()<=e*1e3}catch(r){return envoyFetchTs.logger.warn("Error reading expiry:",r),true}}var b=(t=30)=>B(w,t),N=(t=10)=>B(x,t);function O(){T=null,a.clear(),i.removeItem(w),i.removeItem(x),i.removeItem(S),g.reset(),envoyFetchTs.logger.log("Auth tokens and claims cleared");}function J(){let t=typeof window>"u",e=typeof ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.js', document.baseURI).href)) })<"u"&&undefined?undefined:{},r=typeof process<"u"?process.env:{},n=e.VITE_TRIEOH_AUTH_PROJECT_ID||r.NEXT_PUBLIC_TRIEOH_AUTH_PROJECT_ID||r.PUBLIC_TRIEOH_AUTH_PROJECT_ID||"",s=t&&r.TRIEOH_AUTH_API_KEY||"";return {PROJECT_ID:n,API_KEY:s,BASE_URL:"https://api.trieauth.trieoh.com"}}var E=null,U={};function K(t){U={...U,...t},E=null;}function P(){return E||(E={...J(),...U}),E}var H={get BASE_URL(){return P().BASE_URL}};var l=class{constructor(e){this.isRefreshing=false;this.refreshPromise=null;this.baseURL=e?.baseURL||H.BASE_URL,this.authBaseURL=e?.authBaseURL||this.baseURL,this.onTokenRefreshed=e?.onTokenRefreshed,this.onRefreshFailed=e?.onRefreshFailed;}async refreshToken(){return this.isRefreshing&&this.refreshPromise?this.refreshPromise:(this.isRefreshing=true,this.refreshPromise=(async()=>{let e=true;try{let r=C();if(!r)throw e=!0,new Error("No refresh token available");let n=await envoyFetchTs.simpleFetch(y(this.authBaseURL,"/auth/refresh"),{method:"POST",credentials:"include",headers:{refresh_token:r}});if(n.code!==200||!n.data)throw e=n.code!==503,new Error(n.message||"Failed to refresh token");D(n.data);let s=L();s&&this.onTokenRefreshed?.(s),envoyFetchTs.logger.log("Token refreshed successfully");}catch(r){throw envoyFetchTs.logger.warn("Failed to refresh token:",r),e&&O(),this.onRefreshFailed?.(r),r}finally{this.isRefreshing=false,this.refreshPromise=null;}})(),this.refreshPromise)}async beforeRequest(){if(N()){O();return}if(!!!a.getAccessToken()||b(30))try{await this.refreshToken();}catch(r){envoyFetchTs.logger.warn("Proactive refresh failed:",r);}}async fetch(e,r){let n=r?.requiresAuth!==false,s=e.includes("/auth/refresh");n&&!s&&!r?.skipRefresh&&await this.beforeRequest();let A=y(this.baseURL,e),p=async()=>{let h=a.getAccessToken(),u=new Headers(r?.headers);return n&&h&&u.set("Authorization",`Bearer ${h}`),u.has("Content-Type")||u.set("Content-Type","application/json"),fetch(A,{...r,headers:u,credentials:"include"})},f=await p();if(f.status===401&&n&&!s){let h=!!C(),u=b(30);if(h&&u){envoyFetchTs.logger.log("401 detected and token is expiring/expired, attempting refresh...");try{await this.refreshToken(),f=await p();}catch{envoyFetchTs.logger.error("Retry failed after refresh error");}}}return f}},me=t=>new l(t),Te=t=>{let e=new l(t);return (r,n)=>e.fetch(r,n)};function c(t){if(!t)return;let{requiresAuth:e,skipRefresh:r,...n}=t,s={};return e!==void 0&&(s.requiresAuth=e),r!==void 0&&(s.skipRefresh=r),{...n,adapterInit:{...n.adapterInit,...s}}}var v=class{constructor(e,r,n,s){this.interceptor=new l({baseURL:e,authBaseURL:r,onTokenRefreshed:n}),this.client=envoyFetchTs.createDefaultFetchClient({...s,adapter:this.interceptor.fetch.bind(this.interceptor)});}request(e,r){return this.client.request(e,c(r))}get(e,r){return this.client.get(e,c(r))}post(e,r,n){return this.client.post(e,r,c(n))}put(e,r,n){return this.client.put(e,r,c(n))}patch(e,r,n){return this.client.patch(e,r,c(n))}delete(e,r,n){return this.client.delete(e,r,c(n))}query(e,r){return this.client.query(e,c(r))}};function $(t){let e=new v(t?.baseURL,t?.authBaseURL,void 0,t?.clientConfig);return {request:e.request.bind(e),get:e.get.bind(e),post:e.post.bind(e),put:e.put.bind(e),patch:e.patch.bind(e),delete:e.delete.bind(e),query:e.query.bind(e)}}function z(t){let e=new v(t?.baseURL,t?.authBaseURL,void 0,t?.clientConfig);return (r,n)=>e.query(r,n)}
|
|
2
|
+
Object.defineProperty(exports,"ApiError",{enumerable:true,get:function(){return envoyFetchTs.FetchClientError}});exports.AuthInterceptor=l;exports.configure=K;exports.createAuthInterceptor=me;exports.createAuthenticatedFetch=Te;exports.createFetcher=$;exports.createQueryFetcher=z;//# sourceMappingURL=index.js.map
|
|
3
3
|
//# sourceMappingURL=index.js.map
|
package/dist/cjs/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/url-utils.ts","../../src/store/auth-store.ts","../../src/utils/storage-adapter.ts","../../src/store/token-store.ts","../../src/utils/token-utils.ts","../../src/core/env.ts","../../src/core/interceptor.ts","../../src/core/api.ts"],"names":["joinUrl","base","path","cleanBase","cleanPath","_state","_listeners","notify","l","authStore","cb","partial","event","expiry","isAuthenticated","browserStorage","key","value","sessionBrowserStorage","cookieStorage","name","nameEQ","ca","i","c","options","expires","domain","secure","sameSite","isLocalhost","cookieParts","ACCESS_TOKEN_KEY","tokenStore","token","_cachedClaims","ACCESS_EXPIRY_KEY","REFRESH_EXPIRY_KEY","REFRESH_DOMAIN_KEY","getCookieDomain","returnedDomain","hostname","decodeJwt","payload","base64","jsonPayload","error","logger","saveAuthSession","tokens","access_token_string","refresh_token_string","access_expires_at","refresh_expires_at","claims","refreshExpiry","accessExpiry","getTokenClaims","refreshExpiryStr","sessionData","isExpiringSoon","thresholdSeconds","stored","e","isTokenExpiringSoon","isRefreshSessionExpired","clearAuthTokens","resolveEnv","isServer","viteEnv","safeProcessEnv","resolvedProjectId","resolvedApiKey","memoizedEnv","overrides","configure","config","getEnv","env","AuthInterceptor","shouldClear","res","simpleFetch","url","shouldAuth","isRefreshReq","finalUrl","executeFetch","accessToken","headers","response","hasRefreshCookie","isExpiring","createAuthInterceptor","createAuthenticatedFetch","interceptor","toFetchOptions","requiresAuth","skipRefresh","rest","interceptorFields","Api","baseURL","authBaseURL","onTokenRefreshed","clientConfig","createDefaultFetchClient","body","createFetcher","api","createQueryFetcher"],"mappings":"qJAAO,SAASA,CAAAA,CAAQC,EAAcC,CAAAA,CAAsB,CAC1D,GAAIA,CAAAA,CAAK,UAAA,CAAW,MAAM,CAAA,CAAG,OAAOA,EAEpC,IAAMC,CAAAA,CAAYF,EAAK,OAAA,CAAQ,KAAA,CAAO,EAAE,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AAMuB,CAAO,CAClC","file":"index.js","sourcesContent":["export function joinUrl(base: string, path: string): string {\n if (path.startsWith(\"http\")) return path;\n \n const cleanBase = base.replace(/\\/$/, \"\");\n const cleanPath = path.replace(/^\\//, \"\");\n \n return `${cleanBase}/${cleanPath}`;\n}\n","type AuthState = {\n isAuthenticated: boolean;\n isInitializing: boolean;\n};\n\nlet _state: AuthState = {\n isAuthenticated: false,\n isInitializing: true,\n};\nconst _listeners = new Set<() => void>();\n\nconst notify = () => _listeners.forEach((l) => l());\n\nexport const authStore = {\n subscribe: (cb: () => void) => {\n _listeners.add(cb);\n return () => _listeners.delete(cb);\n },\n getSnapshot: () => _state,\n getServerSnapshot: () => _state,\n set: (partial: Partial<AuthState>) => {\n _state = { ..._state, ...partial };\n notify();\n },\n reset: () => {\n _state = {\n isAuthenticated: false,\n isInitializing: false,\n };\n notify();\n },\n};\n\n// Sync between tabs\nif (typeof window !== \"undefined\") {\n window.addEventListener(\"storage\", (event) => {\n if (event.key === \"trieoh_access_expiry\") {\n if (!event.newValue) authStore.reset();\n else {\n const expiry = Number(event.newValue);\n const isAuthenticated = !isNaN(expiry) && expiry > Date.now();\n authStore.set({ isAuthenticated, isInitializing: false });\n }\n }\n });\n}\n","export interface StorageAdapter {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n removeItem(key: string): void;\n}\n\nexport const browserStorage: StorageAdapter = {\n getItem: (key) => (typeof window !== \"undefined\" ? localStorage.getItem(key) : null),\n setItem: (key, value) => {\n if (typeof window !== \"undefined\") localStorage.setItem(key, value);\n },\n removeItem: (key) => {\n if (typeof window !== \"undefined\") localStorage.removeItem(key);\n },\n};\n\nexport const sessionBrowserStorage: StorageAdapter = {\n getItem: (key) => (typeof window !== \"undefined\" ? sessionStorage.getItem(key) : null),\n setItem: (key, value) => {\n if (typeof window !== \"undefined\") sessionStorage.setItem(key, value);\n },\n removeItem: (key) => {\n if (typeof window !== \"undefined\") sessionStorage.removeItem(key);\n },\n};\n\nexport interface CookieOptions {\n expires?: string;\n path?: string;\n domain?: string | null;\n secure?: boolean;\n sameSite?: \"Lax\" | \"None\" | \"Strict\";\n}\n\nexport const cookieStorage = {\n get: (name: string): string | null => {\n if (typeof window === \"undefined\") return null;\n const nameEQ = name + \"=\";\n const ca = document.cookie.split(\";\");\n for (let i = 0; i < ca.length; i++) {\n let c = ca[i];\n while (c.charAt(0) === \" \") c = c.substring(1, c.length);\n if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);\n }\n return null;\n },\n\n set: (name: string, value: string, options: CookieOptions = {}) => {\n if (typeof window === \"undefined\") return;\n\n const {\n expires,\n path = \"/\",\n domain,\n secure = window.location.protocol === \"https:\",\n sameSite = secure ? \"None\" : \"Lax\",\n } = options;\n\n const isLocalhost = window.location.hostname === \"localhost\";\n\n const cookieParts = [\n `${name}=${value}`,\n domain && !isLocalhost ? `Domain=${domain}` : \"\",\n `Path=${path}`,\n `SameSite=${sameSite}`,\n secure ? \"Secure\" : \"\",\n expires ? `expires=${expires}` : \"\",\n ];\n\n document.cookie = cookieParts.filter(Boolean).join(\"; \");\n },\n\n remove: (name: string, domain?: string | null) => {\n cookieStorage.set(name, \"\", {\n expires: \"Thu, 01 Jan 1970 00:00:00 GMT\",\n domain: domain || undefined,\n });\n },\n};\n","import { sessionBrowserStorage } from \"../utils/storage-adapter\";\n\nconst ACCESS_TOKEN_KEY = \"trieoh_access_token\";\n\nexport const tokenStore = {\n getAccessToken: () => sessionBrowserStorage.getItem(ACCESS_TOKEN_KEY),\n setAccessToken: (token: string | null) => {\n if (token) sessionBrowserStorage.setItem(ACCESS_TOKEN_KEY, token);\n else sessionBrowserStorage.removeItem(ACCESS_TOKEN_KEY);\n },\n clear: () => {\n sessionBrowserStorage.removeItem(ACCESS_TOKEN_KEY);\n }\n};\n","import { authStore } from \"../store/auth-store\";\nimport { tokenStore } from \"../store/token-store\";\nimport { logger } from \"@trieoh/envoy-fetch-ts\";\nimport { browserStorage, cookieStorage } from \"./storage-adapter\";\n\nexport interface AuthTokens {\n access_token_string: string;\n refresh_token_string: string;\n access_expires_at: string;\n refresh_expires_at: string;\n domain: string;\n}\n\nexport interface TokenClaims {\n sub: {\n id: string;\n email: string;\n session_id: string;\n user_agent: string;\n user_ip: string;\n project_id: string | null;\n verified_at: string | null;\n is_verified: boolean;\n user_type: \"client\" | \"project\";\n metadata: Record<string, unknown> | null;\n };\n iss: string;\n exp: number;\n iat: number;\n jti: string;\n}\n\nexport interface AuthTokenClaims {\n access_data: TokenClaims;\n refresh_expiry_date: string | number;\n}\n\n// Stored only in memory\nlet _cachedClaims: AuthTokenClaims | null = null;\nconst ACCESS_EXPIRY_KEY = \"trieoh_access_expiry\";\nconst REFRESH_EXPIRY_KEY = \"trieoh_refresh_expiry\";\nconst REFRESH_DOMAIN_KEY = \"trieoh_refresh_domain\";\n\nexport function getCookieDomain(returnedDomain?: string) {\n if (typeof window === \"undefined\") return null;\n const hostname = window.location.hostname;\n const isLocalhost = hostname === \"localhost\" || hostname === \"127.0.0.1\" || hostname.includes(\"localhost\");\n if (isLocalhost) return null;\n\n if (returnedDomain) {\n try {\n let domain = returnedDomain;\n if (domain.startsWith(\"http\")) domain = new URL(domain).hostname;\n if (hostname === domain || hostname.endsWith(\".\" + domain)) return domain;\n return hostname;\n } catch { return hostname; }\n }\n\n return hostname;\n}\n\nexport function decodeJwt<T>(token: string): T | null {\n try {\n const payload = token.split(\".\")[1];\n if (!payload) return null;\n\n let base64 = payload.replace(/-/g, \"+\").replace(/_/g, \"/\");\n while (base64.length % 4) {\n base64 += \"=\";\n }\n\n const jsonPayload = decodeURIComponent(\n atob(base64)\n .split(\"\")\n .map((c) => \"%\" + (\"00\" + c.charCodeAt(0).toString(16)).slice(-2))\n .join(\"\")\n );\n\n return JSON.parse(jsonPayload);\n } catch (error) {\n logger.error(\"Error decoding JWT:\", error);\n return null;\n }\n}\n\nexport function saveAuthSession(tokens: AuthTokens): void {\n const {\n access_token_string,\n refresh_token_string,\n access_expires_at,\n refresh_expires_at,\n } = tokens;\n\n const claims = decodeJwt<TokenClaims>(access_token_string);\n\n if (!claims) {\n logger.error(\"Failed to decode tokens\");\n return;\n }\n\n tokenStore.setAccessToken(access_token_string);\n\n const refreshExpiry = new Date(refresh_expires_at).getTime();\n const accessExpiry = new Date(access_expires_at).getTime();\n const domain = getCookieDomain(tokens.domain);\n\n cookieStorage.set(\"refresh_token\", refresh_token_string, {\n expires: new Date(refreshExpiry).toUTCString(),\n domain\n });\n\n const sessionData: AuthTokenClaims = {\n access_data: claims,\n refresh_expiry_date: refreshExpiry,\n };\n\n _cachedClaims = sessionData;\n\n browserStorage.setItem(ACCESS_EXPIRY_KEY, String(accessExpiry));\n browserStorage.setItem(REFRESH_EXPIRY_KEY, String(refreshExpiry));\n if (domain) browserStorage.setItem(REFRESH_DOMAIN_KEY, domain);\n else browserStorage.removeItem(REFRESH_DOMAIN_KEY);\n\n authStore.set({\n isAuthenticated: true,\n isInitializing: false,\n });\n\n logger.log(\"Auth session saved\");\n}\n\nexport function getTokenClaims(): AuthTokenClaims | null {\n if (_cachedClaims) return _cachedClaims;\n\n const token = tokenStore.getAccessToken();\n if (!token) return null;\n\n const claims = decodeJwt<TokenClaims>(token);\n if (!claims) return null;\n\n // Check if token is expired\n if (claims.exp * 1000 <= Date.now()) return null;\n\n const refreshExpiryStr = browserStorage.getItem(REFRESH_EXPIRY_KEY);\n if (!refreshExpiryStr) return null;\n\n const refreshExpiry = Number(refreshExpiryStr);\n if (isNaN(refreshExpiry)) return null;\n\n const sessionData = {\n access_data: claims,\n refresh_expiry_date: refreshExpiry,\n };\n\n _cachedClaims = sessionData;\n\n return sessionData;\n}\n\nfunction isExpiringSoon(key: string, thresholdSeconds: number): boolean {\n try {\n const stored = browserStorage.getItem(key);\n if (!stored) return true;\n const expiry = Number(stored);\n if (isNaN(expiry)) return true;\n return (expiry - Date.now()) <= thresholdSeconds * 1000;\n } catch (e) {\n logger.warn(\"Error reading expiry:\", e);\n return true;\n }\n}\n\nexport const isTokenExpiringSoon = (t = 30) => isExpiringSoon(ACCESS_EXPIRY_KEY, t);\nexport const isRefreshSessionExpired = (t = 10) => isExpiringSoon(REFRESH_EXPIRY_KEY, t);\n\nexport function isAuthenticated(): boolean {\n if (!tokenStore.getAccessToken()) return false;\n const stored = browserStorage.getItem(ACCESS_EXPIRY_KEY);\n if (!stored) return false;\n const accessExpiryTimestamp = Number(stored);\n if (isNaN(accessExpiryTimestamp)) return false;\n return accessExpiryTimestamp > Date.now();\n}\n\nexport function clearAuthTokens(): void {\n _cachedClaims = null;\n tokenStore.clear();\n browserStorage.removeItem(ACCESS_EXPIRY_KEY);\n browserStorage.removeItem(REFRESH_EXPIRY_KEY);\n\n const domain = browserStorage.getItem(REFRESH_DOMAIN_KEY) || getCookieDomain();\n cookieStorage.remove(\"refresh_token\", domain);\n browserStorage.removeItem(REFRESH_DOMAIN_KEY);\n\n authStore.reset();\n\n logger.log(\"Auth tokens and claims cleared\");\n}\n\nexport function getUserInfo() {\n const claims = getTokenClaims();\n if (!claims) return null;\n\n return claims.access_data.sub\n}\n\nexport function decodeJwtExp(token: string): number | null {\n const decoded = decodeJwt<{ exp: number }>(token);\n return decoded?.exp ?? null;\n}\n","export interface TrieOHEnv {\n PROJECT_ID: string;\n API_KEY: string;\n BASE_URL: string;\n}\n\nexport function resolveEnv(): TrieOHEnv {\n const isServer = typeof window === \"undefined\";\n\n const viteEnv = (\n typeof import.meta !== \"undefined\" && import.meta.env\n ? import.meta.env\n : {}\n ) as Partial<ImportMetaEnv>;\n\n const safeProcessEnv: NodeJS.ProcessEnv =\n typeof process !== \"undefined\" ? process.env : {};\n\n const resolvedProjectId =\n viteEnv.VITE_TRIEOH_AUTH_PROJECT_ID ||\n safeProcessEnv.NEXT_PUBLIC_TRIEOH_AUTH_PROJECT_ID ||\n safeProcessEnv.PUBLIC_TRIEOH_AUTH_PROJECT_ID ||\n \"\";\n\n const resolvedApiKey = isServer\n ? (safeProcessEnv.TRIEOH_AUTH_API_KEY || \"\")\n : \"\";\n\n return {\n PROJECT_ID: resolvedProjectId,\n API_KEY: resolvedApiKey,\n BASE_URL: \"https://api.trieauth.trieoh.com\",\n };\n}\nlet memoizedEnv: TrieOHEnv | null = null;\nlet overrides: Partial<TrieOHEnv> = {};\n\n/**\n * Configure the SDK manually. This will override any environment variables.\n */\nexport function configure(config: Partial<TrieOHEnv>) {\n overrides = { ...overrides, ...config };\n memoizedEnv = null; // Reset memoization to apply new config\n}\n\nfunction getEnv(): TrieOHEnv {\n if (!memoizedEnv) {\n const resolved = resolveEnv();\n memoizedEnv = {\n ...resolved,\n ...overrides,\n };\n }\n return memoizedEnv;\n}\nexport const env: TrieOHEnv = {\n get PROJECT_ID() {\n return getEnv().PROJECT_ID;\n },\n get API_KEY() {\n return getEnv().API_KEY;\n },\n get BASE_URL() {\n return getEnv().BASE_URL;\n },\n};\n","import { joinUrl } from \"../utils/url-utils\";\nimport {\n clearAuthTokens,\n isRefreshSessionExpired,\n isTokenExpiringSoon,\n saveAuthSession,\n getTokenClaims,\n type AuthTokenClaims,\n type AuthTokens\n} from \"../utils/token-utils\";\nimport { env } from \"./env\";\nimport { logger, simpleFetch } from \"@trieoh/envoy-fetch-ts\";\nimport { cookieStorage } from \"../utils/storage-adapter\";\nimport { tokenStore } from \"../store/token-store\";\n\nexport interface RequestOptions extends RequestInit {\n requiresAuth?: boolean;\n skipRefresh?: boolean;\n}\n\ninterface InterceptorConfig {\n baseURL?: string;\n authBaseURL?: string;\n onTokenRefreshed?: (claims: AuthTokenClaims) => void;\n onRefreshFailed?: (error: Error) => void;\n}\n\nexport class AuthInterceptor {\n private baseURL: string;\n private authBaseURL: string;\n private isRefreshing = false;\n private refreshPromise: Promise<void> | null = null;\n private onTokenRefreshed?: (claims: AuthTokenClaims) => void;\n private onRefreshFailed?: (error: Error) => void;\n\n constructor(config?: InterceptorConfig) {\n this.baseURL = config?.baseURL || env.BASE_URL;\n this.authBaseURL = config?.authBaseURL || this.baseURL;\n this.onTokenRefreshed = config?.onTokenRefreshed;\n this.onRefreshFailed = config?.onRefreshFailed;\n }\n\n async refreshToken(): Promise<void> {\n if (this.isRefreshing && this.refreshPromise) return this.refreshPromise;\n\n this.isRefreshing = true;\n this.refreshPromise = (async () => {\n let shouldClear = true;\n try {\n const res = await simpleFetch<{ code: number; data?: AuthTokens; message?: string }>(\n joinUrl(this.authBaseURL, \"/auth/refresh\"),\n { method: \"POST\", credentials: \"include\" }\n );\n\n if (res.code !== 200 || !res.data) {\n shouldClear = res.code !== 503;\n throw new Error(res.message || \"Failed to refresh token\");\n }\n\n saveAuthSession(res.data);\n\n const claims = getTokenClaims();\n if (claims) this.onTokenRefreshed?.(claims);\n\n logger.log(\"Token refreshed successfully\");\n } catch (error) {\n logger.warn(\"Failed to refresh token:\", error);\n if (shouldClear) clearAuthTokens();\n this.onRefreshFailed?.(error as Error);\n throw error;\n } finally {\n this.isRefreshing = false;\n this.refreshPromise = null;\n }\n })();\n\n return this.refreshPromise;\n }\n\n async beforeRequest(): Promise<void> {\n if (isRefreshSessionExpired()) {\n clearAuthTokens();\n return;\n }\n\n const hasAccessToken = !!tokenStore.getAccessToken();\n\n if (!hasAccessToken || isTokenExpiringSoon(30)) {\n try {\n await this.refreshToken();\n } catch (error) {\n logger.warn(\"Proactive refresh failed:\", error);\n }\n }\n }\n\n async fetch(url: string, options?: RequestOptions): Promise<Response> {\n const shouldAuth = options?.requiresAuth !== false;\n const isRefreshReq = url.includes(\"/auth/refresh\");\n\n if (shouldAuth && !isRefreshReq && !options?.skipRefresh) {\n await this.beforeRequest();\n }\n\n const finalUrl = joinUrl(this.baseURL, url);\n\n const executeFetch = async (): Promise<Response> => {\n const accessToken = tokenStore.getAccessToken();\n const headers = new Headers(options?.headers);\n\n if (shouldAuth && accessToken) {\n headers.set(\"Authorization\", `Bearer ${accessToken}`);\n }\n if (!headers.has(\"Content-Type\")) {\n headers.set(\"Content-Type\", \"application/json\");\n }\n\n return fetch(finalUrl, {\n ...options,\n headers,\n credentials: \"include\",\n });\n };\n\n let response = await executeFetch();\n\n if (response.status === 401 && shouldAuth && !isRefreshReq) {\n const hasRefreshCookie = !!cookieStorage.get(\"refresh_token\");\n const isExpiring = isTokenExpiringSoon(30);\n\n if (hasRefreshCookie && isExpiring) {\n logger.log(\"401 detected and token is expiring/expired, attempting refresh...\");\n try {\n await this.refreshToken();\n response = await executeFetch();\n } catch (e) {\n logger.error(\"Retry failed after refresh error\");\n }\n }\n }\n\n return response;\n }\n}\n\nexport const createAuthInterceptor = (config?: InterceptorConfig) => new AuthInterceptor(config);\n\nexport const createAuthenticatedFetch = (config?: InterceptorConfig) => {\n const interceptor = new AuthInterceptor(config);\n return (url: string, options?: RequestOptions) => interceptor.fetch(url, options);\n};\n","import { AuthInterceptor, type RequestOptions as InterceptorOptions } from \"./interceptor\";\nimport type { AuthTokenClaims } from \"../utils/token-utils\";\nimport {\n createDefaultFetchClient,\n type DefaultFetchClientConfig,\n type DefaultFetchResult,\n type DefaultSuccessEnvelope,\n type DefaultFailureEnvelope,\n type FetchClient,\n type FetchClientOptions\n} from \"@trieoh/envoy-fetch-ts\";\n\nexport type { DefaultFetchResult as ApiResponse };\n\nexport interface ApiRequestOptions extends FetchClientOptions {\n requiresAuth?: boolean;\n skipRefresh?: boolean;\n}\n\nfunction toFetchOptions(options?: ApiRequestOptions): FetchClientOptions | undefined {\n if (!options) return undefined;\n\n const { requiresAuth, skipRefresh, ...rest } = options;\n\n const interceptorFields: Partial<InterceptorOptions> = {};\n if (requiresAuth !== undefined) interceptorFields.requiresAuth = requiresAuth;\n if (skipRefresh !== undefined) interceptorFields.skipRefresh = skipRefresh;\n\n return {\n ...rest,\n adapterInit: {\n ...rest.adapterInit,\n ...interceptorFields,\n },\n };\n}\n\nexport class Api {\n readonly interceptor: AuthInterceptor;\n private readonly client: FetchClient<DefaultSuccessEnvelope, DefaultFailureEnvelope>;\n\n constructor(\n baseURL?: string,\n authBaseURL?: string,\n onTokenRefreshed?: (claims: AuthTokenClaims) => void,\n clientConfig?: Omit<DefaultFetchClientConfig, \"adapter\">,\n ) {\n this.interceptor = new AuthInterceptor({\n baseURL,\n authBaseURL,\n onTokenRefreshed,\n });\n\n this.client = createDefaultFetchClient({\n ...clientConfig,\n adapter: this.interceptor.fetch.bind(this.interceptor),\n });\n }\n\n request<T>(path: string, options?: ApiRequestOptions) {\n return this.client.request<T>(path, toFetchOptions(options));\n }\n\n get<T>(path: string, options?: ApiRequestOptions) {\n return this.client.get<T>(path, toFetchOptions(options));\n }\n\n post<T>(path: string, body?: unknown, options?: ApiRequestOptions) {\n return this.client.post<T>(path, body, toFetchOptions(options));\n }\n\n put<T>(path: string, body?: unknown, options?: ApiRequestOptions) {\n return this.client.put<T>(path, body, toFetchOptions(options));\n }\n\n patch<T>(path: string, body?: unknown, options?: ApiRequestOptions) {\n return this.client.patch<T>(path, body, toFetchOptions(options));\n }\n\n delete<T>(path: string, body?: unknown, options?: ApiRequestOptions) {\n return this.client.delete<T>(path, body, toFetchOptions(options));\n }\n\n query<T>(path: string, options?: ApiRequestOptions) {\n return this.client.query<T>(path, toFetchOptions(options));\n }\n}\n\nexport function createFetcher(config?: {\n baseURL?: string;\n authBaseURL?: string;\n clientConfig?: Omit<DefaultFetchClientConfig, \"adapter\">;\n}) {\n const api = new Api(\n config?.baseURL,\n config?.authBaseURL,\n undefined,\n config?.clientConfig,\n );\n\n return {\n request: api.request.bind(api),\n get: api.get.bind(api),\n post: api.post.bind(api),\n put: api.put.bind(api),\n patch: api.patch.bind(api),\n delete: api.delete.bind(api),\n query: api.query.bind(api),\n };\n}\n\nexport function createQueryFetcher(config?: {\n baseURL?: string;\n authBaseURL?: string;\n clientConfig?: Omit<DefaultFetchClientConfig, \"adapter\">;\n}) {\n const api = new Api(\n config?.baseURL,\n config?.authBaseURL,\n undefined,\n config?.clientConfig,\n );\n\n return <TData>(path: string, options?: ApiRequestOptions): Promise<TData> =>\n api.query<TData>(path, options);\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/utils/url-utils.ts","../../src/store/auth-store.ts","../../src/utils/storage-adapter.ts","../../src/store/token-store.ts","../../src/utils/token-utils.ts","../../src/core/env.ts","../../src/core/interceptor.ts","../../src/core/api.ts"],"names":["joinUrl","base","path","cleanBase","cleanPath","_state","_listeners","notify","l","authStore","cb","partial","event","expiry","isAuthenticated","browserStorage","key","value","sessionBrowserStorage","ACCESS_TOKEN_KEY","tokenStore","token","_cachedClaims","ACCESS_EXPIRY_KEY","REFRESH_EXPIRY_KEY","REFRESH_TOKEN_KEY","decodeJwt","payload","base64","jsonPayload","c","error","logger","saveAuthSession","tokens","access_token","refresh_token","access_expires_at","refresh_expires_at","claims","refreshExpiry","accessExpiry","getStoredRefreshToken","getTokenClaims","refreshExpiryStr","sessionData","isExpiringSoon","thresholdSeconds","stored","e","isTokenExpiringSoon","isRefreshSessionExpired","clearAuthTokens","resolveEnv","isServer","viteEnv","safeProcessEnv","resolvedProjectId","resolvedApiKey","memoizedEnv","overrides","configure","config","getEnv","env","AuthInterceptor","shouldClear","refreshToken","res","simpleFetch","url","options","shouldAuth","isRefreshReq","finalUrl","executeFetch","accessToken","headers","response","hasRefreshToken","isExpiring","createAuthInterceptor","createAuthenticatedFetch","interceptor","toFetchOptions","requiresAuth","skipRefresh","rest","interceptorFields","Api","baseURL","authBaseURL","onTokenRefreshed","clientConfig","createDefaultFetchClient","body","createFetcher","api","createQueryFetcher"],"mappings":"qJAAO,SAASA,EAAQC,CAAAA,CAAcC,CAAAA,CAAsB,CAC1D,GAAIA,EAAK,UAAA,CAAW,MAAM,CAAA,CAAG,OAAOA,EAEpC,IAAMC,CAAAA,CAAYF,EAAK,OAAA,CAAQ,KAAA,CAAO,EAAE,CAAA,CAClCG,CAAAA,CAAYF,CAAAA,CAAK,OAAA,CAAQ,MAAO,EAAE,CAAA,CAExC,OAAO,CAAA,EAAGC,CAAS,CAAA,CAAA,EAAIC,CAAS,CAAA,CAClC,CCFA,IAAIC,CAAAA,CAAoB,CACtB,gBAAiB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O,CAAQ5D,CAAAA,CAAcqE,CAAAA,GAC3B0B,CAAAA,CAAI,MAAa/F,CAAAA,CAAMqE,CAAO,CAClC","file":"index.js","sourcesContent":["export function joinUrl(base: string, path: string): string {\n if (path.startsWith(\"http\")) return path;\n \n const cleanBase = base.replace(/\\/$/, \"\");\n const cleanPath = path.replace(/^\\//, \"\");\n \n return `${cleanBase}/${cleanPath}`;\n}\n","type AuthState = {\n isAuthenticated: boolean;\n isInitializing: boolean;\n};\n\nlet _state: AuthState = {\n isAuthenticated: false,\n isInitializing: true,\n};\nconst _listeners = new Set<() => void>();\n\nconst notify = () => _listeners.forEach((l) => l());\n\nexport const authStore = {\n subscribe: (cb: () => void) => {\n _listeners.add(cb);\n return () => _listeners.delete(cb);\n },\n getSnapshot: () => _state,\n getServerSnapshot: () => _state,\n set: (partial: Partial<AuthState>) => {\n _state = { ..._state, ...partial };\n notify();\n },\n reset: () => {\n _state = {\n isAuthenticated: false,\n isInitializing: false,\n };\n notify();\n },\n};\n\n// Sync between tabs\nif (typeof window !== \"undefined\") {\n window.addEventListener(\"storage\", (event) => {\n if (event.key === \"trieoh_access_expiry\") {\n if (!event.newValue) authStore.reset();\n else {\n const expiry = Number(event.newValue);\n const isAuthenticated = !isNaN(expiry) && expiry > Date.now();\n authStore.set({ isAuthenticated, isInitializing: false });\n }\n }\n });\n}\n","export interface StorageAdapter {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n removeItem(key: string): void;\n}\n\nexport const browserStorage: StorageAdapter = {\n getItem: (key) => (typeof window !== \"undefined\" ? localStorage.getItem(key) : null),\n setItem: (key, value) => {\n if (typeof window !== \"undefined\") localStorage.setItem(key, value);\n },\n removeItem: (key) => {\n if (typeof window !== \"undefined\") localStorage.removeItem(key);\n },\n};\n\nexport const sessionBrowserStorage: StorageAdapter = {\n getItem: (key) => (typeof window !== \"undefined\" ? sessionStorage.getItem(key) : null),\n setItem: (key, value) => {\n if (typeof window !== \"undefined\") sessionStorage.setItem(key, value);\n },\n removeItem: (key) => {\n if (typeof window !== \"undefined\") sessionStorage.removeItem(key);\n },\n};\n\nexport interface CookieOptions {\n expires?: string;\n path?: string;\n domain?: string | null;\n secure?: boolean;\n sameSite?: \"Lax\" | \"None\" | \"Strict\";\n}\n\nexport const cookieStorage = {\n get: (name: string): string | null => {\n if (typeof window === \"undefined\") return null;\n const nameEQ = name + \"=\";\n const ca = document.cookie.split(\";\");\n for (let i = 0; i < ca.length; i++) {\n let c = ca[i];\n while (c.charAt(0) === \" \") c = c.substring(1, c.length);\n if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);\n }\n return null;\n },\n\n set: (name: string, value: string, options: CookieOptions = {}) => {\n if (typeof window === \"undefined\") return;\n\n const {\n expires,\n path = \"/\",\n domain,\n secure = window.location.protocol === \"https:\",\n sameSite = secure ? \"None\" : \"Lax\",\n } = options;\n\n const isLocalhost = window.location.hostname === \"localhost\";\n\n const cookieParts = [\n `${name}=${value}`,\n domain && !isLocalhost ? `Domain=${domain}` : \"\",\n `Path=${path}`,\n `SameSite=${sameSite}`,\n secure ? \"Secure\" : \"\",\n expires ? `expires=${expires}` : \"\",\n ];\n\n document.cookie = cookieParts.filter(Boolean).join(\"; \");\n },\n\n remove: (name: string, domain?: string | null) => {\n cookieStorage.set(name, \"\", {\n expires: \"Thu, 01 Jan 1970 00:00:00 GMT\",\n domain: domain || undefined,\n });\n },\n};\n","import { sessionBrowserStorage } from \"../utils/storage-adapter\";\n\nconst ACCESS_TOKEN_KEY = \"trieoh_access_token\";\n\nexport const tokenStore = {\n getAccessToken: () => sessionBrowserStorage.getItem(ACCESS_TOKEN_KEY),\n setAccessToken: (token: string | null) => {\n if (token) sessionBrowserStorage.setItem(ACCESS_TOKEN_KEY, token);\n else sessionBrowserStorage.removeItem(ACCESS_TOKEN_KEY);\n },\n clear: () => {\n sessionBrowserStorage.removeItem(ACCESS_TOKEN_KEY);\n }\n};\n","import { authStore } from \"../store/auth-store\";\nimport { tokenStore } from \"../store/token-store\";\nimport { logger } from \"@trieoh/envoy-fetch-ts\";\nimport { browserStorage } from \"./storage-adapter\";\n\nexport interface AuthTokens {\n access_token: string;\n refresh_token: string;\n access_expires_at: string;\n refresh_expires_at: string;\n domain: string;\n}\n\nexport interface TokenClaims {\n sub: {\n id: string;\n email: string;\n session_id: string;\n user_agent: string;\n user_ip: string;\n project_id: string | null;\n verified_at: string | null;\n is_verified: boolean;\n user_type: \"client\" | \"project\";\n metadata: Record<string, unknown> | null;\n };\n iss: string;\n exp: number;\n iat: number;\n jti: string;\n}\n\nexport interface AuthTokenClaims {\n access_data: TokenClaims;\n refresh_expiry_date: string | number;\n}\n\n// Stored only in memory\nlet _cachedClaims: AuthTokenClaims | null = null;\nconst ACCESS_EXPIRY_KEY = \"trieoh_access_expiry\";\nconst REFRESH_EXPIRY_KEY = \"trieoh_refresh_expiry\";\nconst REFRESH_TOKEN_KEY = \"trieoh_refresh_token\";\n\nexport function decodeJwt<T>(token: string): T | null {\n try {\n const payload = token.split(\".\")[1];\n if (!payload) return null;\n\n let base64 = payload.replace(/-/g, \"+\").replace(/_/g, \"/\");\n while (base64.length % 4) {\n base64 += \"=\";\n }\n\n const jsonPayload = decodeURIComponent(\n atob(base64)\n .split(\"\")\n .map((c) => \"%\" + (\"00\" + c.charCodeAt(0).toString(16)).slice(-2))\n .join(\"\")\n );\n\n return JSON.parse(jsonPayload);\n } catch (error) {\n logger.error(\"Error decoding JWT:\", error);\n return null;\n }\n}\n\nexport function saveAuthSession(tokens: AuthTokens): void {\n const {\n access_token,\n refresh_token,\n access_expires_at,\n refresh_expires_at,\n } = tokens;\n\n const claims = decodeJwt<TokenClaims>(access_token);\n\n if (!claims) {\n logger.error(\"Failed to decode tokens\");\n return;\n }\n\n tokenStore.setAccessToken(access_token);\n\n const refreshExpiry = new Date(refresh_expires_at).getTime();\n const accessExpiry = new Date(access_expires_at).getTime();\n\n browserStorage.setItem(REFRESH_TOKEN_KEY, refresh_token);\n browserStorage.setItem(ACCESS_EXPIRY_KEY, String(accessExpiry));\n browserStorage.setItem(REFRESH_EXPIRY_KEY, String(refreshExpiry));\n\n const sessionData: AuthTokenClaims = {\n access_data: claims,\n refresh_expiry_date: refreshExpiry,\n };\n\n _cachedClaims = sessionData;\n\n authStore.set({\n isAuthenticated: true,\n isInitializing: false,\n });\n\n logger.log(\"Auth session saved\");\n}\n\nexport function getStoredRefreshToken(): string | null {\n return browserStorage.getItem(REFRESH_TOKEN_KEY);\n}\n\nexport function getTokenClaims(): AuthTokenClaims | null {\n if (_cachedClaims) return _cachedClaims;\n\n const token = tokenStore.getAccessToken();\n if (!token) return null;\n\n const claims = decodeJwt<TokenClaims>(token);\n if (!claims) return null;\n\n // Check if token is expired\n if (claims.exp * 1000 <= Date.now()) return null;\n\n const refreshExpiryStr = browserStorage.getItem(REFRESH_EXPIRY_KEY);\n if (!refreshExpiryStr) return null;\n\n const refreshExpiry = Number(refreshExpiryStr);\n if (isNaN(refreshExpiry)) return null;\n\n const sessionData = {\n access_data: claims,\n refresh_expiry_date: refreshExpiry,\n };\n\n _cachedClaims = sessionData;\n\n return sessionData;\n}\n\nfunction isExpiringSoon(key: string, thresholdSeconds: number): boolean {\n try {\n const stored = browserStorage.getItem(key);\n if (!stored) return true;\n const expiry = Number(stored);\n if (isNaN(expiry)) return true;\n return (expiry - Date.now()) <= thresholdSeconds * 1000;\n } catch (e) {\n logger.warn(\"Error reading expiry:\", e);\n return true;\n }\n}\n\nexport const isTokenExpiringSoon = (t = 30) => isExpiringSoon(ACCESS_EXPIRY_KEY, t);\nexport const isRefreshSessionExpired = (t = 10) => isExpiringSoon(REFRESH_EXPIRY_KEY, t);\n\nexport function isAuthenticated(): boolean {\n if (!tokenStore.getAccessToken()) return false;\n const stored = browserStorage.getItem(ACCESS_EXPIRY_KEY);\n if (!stored) return false;\n const accessExpiryTimestamp = Number(stored);\n if (isNaN(accessExpiryTimestamp)) return false;\n return accessExpiryTimestamp > Date.now();\n}\n\nexport function clearAuthTokens(): void {\n _cachedClaims = null;\n tokenStore.clear();\n browserStorage.removeItem(ACCESS_EXPIRY_KEY);\n browserStorage.removeItem(REFRESH_EXPIRY_KEY);\n browserStorage.removeItem(REFRESH_TOKEN_KEY);\n\n authStore.reset();\n\n logger.log(\"Auth tokens and claims cleared\");\n}\n\nexport function getUserInfo() {\n const claims = getTokenClaims();\n if (!claims) return null;\n\n return claims.access_data.sub\n}\n\nexport function decodeJwtExp(token: string): number | null {\n const decoded = decodeJwt<{ exp: number }>(token);\n return decoded?.exp ?? null;\n}\n","export interface TrieOHEnv {\n PROJECT_ID: string;\n API_KEY: string;\n BASE_URL: string;\n}\n\nexport function resolveEnv(): TrieOHEnv {\n const isServer = typeof window === \"undefined\";\n\n const viteEnv = (\n typeof import.meta !== \"undefined\" && import.meta.env\n ? import.meta.env\n : {}\n ) as Partial<ImportMetaEnv>;\n\n const safeProcessEnv: NodeJS.ProcessEnv =\n typeof process !== \"undefined\" ? process.env : {};\n\n const resolvedProjectId =\n viteEnv.VITE_TRIEOH_AUTH_PROJECT_ID ||\n safeProcessEnv.NEXT_PUBLIC_TRIEOH_AUTH_PROJECT_ID ||\n safeProcessEnv.PUBLIC_TRIEOH_AUTH_PROJECT_ID ||\n \"\";\n\n const resolvedApiKey = isServer\n ? (safeProcessEnv.TRIEOH_AUTH_API_KEY || \"\")\n : \"\";\n\n return {\n PROJECT_ID: resolvedProjectId,\n API_KEY: resolvedApiKey,\n BASE_URL: \"https://api.trieauth.trieoh.com\",\n };\n}\nlet memoizedEnv: TrieOHEnv | null = null;\nlet overrides: Partial<TrieOHEnv> = {};\n\n/**\n * Configure the SDK manually. This will override any environment variables.\n */\nexport function configure(config: Partial<TrieOHEnv>) {\n overrides = { ...overrides, ...config };\n memoizedEnv = null; // Reset memoization to apply new config\n}\n\nfunction getEnv(): TrieOHEnv {\n if (!memoizedEnv) {\n const resolved = resolveEnv();\n memoizedEnv = {\n ...resolved,\n ...overrides,\n };\n }\n return memoizedEnv;\n}\nexport const env: TrieOHEnv = {\n get PROJECT_ID() {\n return getEnv().PROJECT_ID;\n },\n get API_KEY() {\n return getEnv().API_KEY;\n },\n get BASE_URL() {\n return getEnv().BASE_URL;\n },\n};\n","import { joinUrl } from \"../utils/url-utils\";\nimport {\n clearAuthTokens,\n isRefreshSessionExpired,\n isTokenExpiringSoon,\n saveAuthSession,\n getTokenClaims,\n getStoredRefreshToken,\n type AuthTokenClaims,\n type AuthTokens\n} from \"../utils/token-utils\";\nimport { env } from \"./env\";\nimport { logger, simpleFetch } from \"@trieoh/envoy-fetch-ts\";\nimport { tokenStore } from \"../store/token-store\";\n\nexport interface RequestOptions extends RequestInit {\n requiresAuth?: boolean;\n skipRefresh?: boolean;\n}\n\ninterface InterceptorConfig {\n baseURL?: string;\n authBaseURL?: string;\n onTokenRefreshed?: (claims: AuthTokenClaims) => void;\n onRefreshFailed?: (error: Error) => void;\n}\n\nexport class AuthInterceptor {\n private baseURL: string;\n private authBaseURL: string;\n private isRefreshing = false;\n private refreshPromise: Promise<void> | null = null;\n private onTokenRefreshed?: (claims: AuthTokenClaims) => void;\n private onRefreshFailed?: (error: Error) => void;\n\n constructor(config?: InterceptorConfig) {\n this.baseURL = config?.baseURL || env.BASE_URL;\n this.authBaseURL = config?.authBaseURL || this.baseURL;\n this.onTokenRefreshed = config?.onTokenRefreshed;\n this.onRefreshFailed = config?.onRefreshFailed;\n }\n\n async refreshToken(): Promise<void> {\n if (this.isRefreshing && this.refreshPromise) return this.refreshPromise;\n\n this.isRefreshing = true;\n this.refreshPromise = (async () => {\n let shouldClear = true;\n try {\n const refreshToken = getStoredRefreshToken();\n if (!refreshToken) {\n shouldClear = true;\n throw new Error(\"No refresh token available\");\n }\n\n const res = await simpleFetch<{ code: number; data?: AuthTokens; message?: string }>(\n joinUrl(this.authBaseURL, \"/auth/refresh\"),\n {\n method: \"POST\",\n credentials: \"include\",\n headers: { \"refresh_token\": refreshToken },\n }\n );\n\n if (res.code !== 200 || !res.data) {\n shouldClear = res.code !== 503;\n throw new Error(res.message || \"Failed to refresh token\");\n }\n\n saveAuthSession(res.data);\n\n const claims = getTokenClaims();\n if (claims) this.onTokenRefreshed?.(claims);\n\n logger.log(\"Token refreshed successfully\");\n } catch (error) {\n logger.warn(\"Failed to refresh token:\", error);\n if (shouldClear) clearAuthTokens();\n this.onRefreshFailed?.(error as Error);\n throw error;\n } finally {\n this.isRefreshing = false;\n this.refreshPromise = null;\n }\n })();\n\n return this.refreshPromise;\n }\n\n async beforeRequest(): Promise<void> {\n if (isRefreshSessionExpired()) {\n clearAuthTokens();\n return;\n }\n\n const hasAccessToken = !!tokenStore.getAccessToken();\n\n if (!hasAccessToken || isTokenExpiringSoon(30)) {\n try {\n await this.refreshToken();\n } catch (error) {\n logger.warn(\"Proactive refresh failed:\", error);\n }\n }\n }\n\n async fetch(url: string, options?: RequestOptions): Promise<Response> {\n const shouldAuth = options?.requiresAuth !== false;\n const isRefreshReq = url.includes(\"/auth/refresh\");\n\n if (shouldAuth && !isRefreshReq && !options?.skipRefresh) {\n await this.beforeRequest();\n }\n\n const finalUrl = joinUrl(this.baseURL, url);\n\n const executeFetch = async (): Promise<Response> => {\n const accessToken = tokenStore.getAccessToken();\n const headers = new Headers(options?.headers);\n\n if (shouldAuth && accessToken) {\n headers.set(\"Authorization\", `Bearer ${accessToken}`);\n }\n if (!headers.has(\"Content-Type\")) {\n headers.set(\"Content-Type\", \"application/json\");\n }\n\n return fetch(finalUrl, {\n ...options,\n headers,\n credentials: \"include\",\n });\n };\n\n let response = await executeFetch();\n\n if (response.status === 401 && shouldAuth && !isRefreshReq) {\n const hasRefreshToken = !!getStoredRefreshToken();\n const isExpiring = isTokenExpiringSoon(30);\n\n if (hasRefreshToken && isExpiring) {\n logger.log(\"401 detected and token is expiring/expired, attempting refresh...\");\n try {\n await this.refreshToken();\n response = await executeFetch();\n } catch (e) {\n logger.error(\"Retry failed after refresh error\");\n }\n }\n }\n\n return response;\n }\n}\n\nexport const createAuthInterceptor = (config?: InterceptorConfig) => new AuthInterceptor(config);\n\nexport const createAuthenticatedFetch = (config?: InterceptorConfig) => {\n const interceptor = new AuthInterceptor(config);\n return (url: string, options?: RequestOptions) => interceptor.fetch(url, options);\n};\n","import { AuthInterceptor, type RequestOptions as InterceptorOptions } from \"./interceptor\";\nimport type { AuthTokenClaims } from \"../utils/token-utils\";\nimport {\n createDefaultFetchClient,\n type DefaultFetchClientConfig,\n type DefaultFetchResult,\n type DefaultSuccessEnvelope,\n type DefaultFailureEnvelope,\n type FetchClient,\n type FetchClientOptions\n} from \"@trieoh/envoy-fetch-ts\";\n\nexport type { DefaultFetchResult as ApiResponse };\n\nexport interface ApiRequestOptions extends FetchClientOptions {\n requiresAuth?: boolean;\n skipRefresh?: boolean;\n}\n\nfunction toFetchOptions(options?: ApiRequestOptions): FetchClientOptions | undefined {\n if (!options) return undefined;\n\n const { requiresAuth, skipRefresh, ...rest } = options;\n\n const interceptorFields: Partial<InterceptorOptions> = {};\n if (requiresAuth !== undefined) interceptorFields.requiresAuth = requiresAuth;\n if (skipRefresh !== undefined) interceptorFields.skipRefresh = skipRefresh;\n\n return {\n ...rest,\n adapterInit: {\n ...rest.adapterInit,\n ...interceptorFields,\n },\n };\n}\n\nexport class Api {\n readonly interceptor: AuthInterceptor;\n private readonly client: FetchClient<DefaultSuccessEnvelope, DefaultFailureEnvelope>;\n\n constructor(\n baseURL?: string,\n authBaseURL?: string,\n onTokenRefreshed?: (claims: AuthTokenClaims) => void,\n clientConfig?: Omit<DefaultFetchClientConfig, \"adapter\">,\n ) {\n this.interceptor = new AuthInterceptor({\n baseURL,\n authBaseURL,\n onTokenRefreshed,\n });\n\n this.client = createDefaultFetchClient({\n ...clientConfig,\n adapter: this.interceptor.fetch.bind(this.interceptor),\n });\n }\n\n request<T>(path: string, options?: ApiRequestOptions) {\n return this.client.request<T>(path, toFetchOptions(options));\n }\n\n get<T>(path: string, options?: ApiRequestOptions) {\n return this.client.get<T>(path, toFetchOptions(options));\n }\n\n post<T>(path: string, body?: unknown, options?: ApiRequestOptions) {\n return this.client.post<T>(path, body, toFetchOptions(options));\n }\n\n put<T>(path: string, body?: unknown, options?: ApiRequestOptions) {\n return this.client.put<T>(path, body, toFetchOptions(options));\n }\n\n patch<T>(path: string, body?: unknown, options?: ApiRequestOptions) {\n return this.client.patch<T>(path, body, toFetchOptions(options));\n }\n\n delete<T>(path: string, body?: unknown, options?: ApiRequestOptions) {\n return this.client.delete<T>(path, body, toFetchOptions(options));\n }\n\n query<T>(path: string, options?: ApiRequestOptions) {\n return this.client.query<T>(path, toFetchOptions(options));\n }\n}\n\nexport function createFetcher(config?: {\n baseURL?: string;\n authBaseURL?: string;\n clientConfig?: Omit<DefaultFetchClientConfig, \"adapter\">;\n}) {\n const api = new Api(\n config?.baseURL,\n config?.authBaseURL,\n undefined,\n config?.clientConfig,\n );\n\n return {\n request: api.request.bind(api),\n get: api.get.bind(api),\n post: api.post.bind(api),\n put: api.put.bind(api),\n patch: api.patch.bind(api),\n delete: api.delete.bind(api),\n query: api.query.bind(api),\n };\n}\n\nexport function createQueryFetcher(config?: {\n baseURL?: string;\n authBaseURL?: string;\n clientConfig?: Omit<DefaultFetchClientConfig, \"adapter\">;\n}) {\n const api = new Api(\n config?.baseURL,\n config?.authBaseURL,\n undefined,\n config?.clientConfig,\n );\n\n return <TData>(path: string, options?: ApiRequestOptions): Promise<TData> =>\n api.query<TData>(path, options);\n}\n"]}
|
package/dist/cjs/react.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
'use strict';var react=require('react'),envoyFetchTs=require('@trieoh/envoy-fetch-ts'),jsxRuntime=require('react/jsx-runtime'),ri=require('react-icons/ri'),go=require('react-icons/go'),im=require('react-icons/im'),fa=require('react-icons/fa'),uaParserJs=require('ua-parser-js'),fi=require('react-icons/fi');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function ve(e,r){if(r.startsWith("http"))return r;let t=e.replace(/\/$/,""),o=r.replace(/^\//,"");return `${t}/${o}`}var J={isAuthenticated:false,isInitializing:true},we=new Set,Le=()=>we.forEach(e=>e()),R={subscribe:e=>(we.add(e),()=>we.delete(e)),getSnapshot:()=>J,getServerSnapshot:()=>J,set:e=>{J={...J,...e},Le();},reset:()=>{J={isAuthenticated:false,isInitializing:false},Le();}};typeof window<"u"&&window.addEventListener("storage",e=>{if(e.key==="trieoh_access_expiry")if(!e.newValue)R.reset();else {let r=Number(e.newValue),t=!isNaN(r)&&r>Date.now();R.set({isAuthenticated:t,isInitializing:false});}});var A={getItem:e=>typeof window<"u"?localStorage.getItem(e):null,setItem:(e,r)=>{typeof window<"u"&&localStorage.setItem(e,r);},removeItem:e=>{typeof window<"u"&&localStorage.removeItem(e);}},j={getItem:e=>typeof window<"u"?sessionStorage.getItem(e):null,setItem:(e,r)=>{typeof window<"u"&&sessionStorage.setItem(e,r);},removeItem:e=>{typeof window<"u"&&sessionStorage.removeItem(e);}},H={get:e=>{if(typeof window>"u")return null;let r=e+"=",t=document.cookie.split(";");for(let o=0;o<t.length;o++){let i=t[o];for(;i.charAt(0)===" ";)i=i.substring(1,i.length);if(i.indexOf(r)===0)return i.substring(r.length,i.length)}return null},set:(e,r,t={})=>{if(typeof window>"u")return;let{expires:o,path:i="/",domain:s,secure:n=window.location.protocol==="https:",sameSite:l=n?"None":"Lax"}=t,a=window.location.hostname==="localhost",c=[`${e}=${r}`,s&&!a?`Domain=${s}`:"",`Path=${i}`,`SameSite=${l}`,n?"Secure":"",o?`expires=${o}`:""];document.cookie=c.filter(Boolean).join("; ");},remove:(e,r)=>{H.set(e,"",{expires:"Thu, 01 Jan 1970 00:00:00 GMT",domain:r||void 0});}};var se="trieoh_access_token",O={getAccessToken:()=>j.getItem(se),setAccessToken:e=>{e?j.setItem(se,e):j.removeItem(se);},clear:()=>{j.removeItem(se);}};var K=null,xe="trieoh_access_expiry",ae="trieoh_refresh_expiry",ne="trieoh_refresh_domain";function De(e){if(typeof window>"u")return null;let r=window.location.hostname;if(r==="localhost"||r==="127.0.0.1"||r.includes("localhost"))return null;if(e)try{let o=e;return o.startsWith("http")&&(o=new URL(o).hostname),r===o||r.endsWith("."+o)?o:r}catch{return r}return r}function Oe(e){try{let r=e.split(".")[1];if(!r)return null;let t=r.replace(/-/g,"+").replace(/_/g,"/");for(;t.length%4;)t+="=";let o=decodeURIComponent(atob(t).split("").map(i=>"%"+("00"+i.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(o)}catch(r){return envoyFetchTs.logger.error("Error decoding JWT:",r),null}}function G(e){let{access_token_string:r,refresh_token_string:t,access_expires_at:o,refresh_expires_at:i}=e,s=Oe(r);if(!s){envoyFetchTs.logger.error("Failed to decode tokens");return}O.setAccessToken(r);let n=new Date(i).getTime(),l=new Date(o).getTime(),a=De(e.domain);H.set("refresh_token",t,{expires:new Date(n).toUTCString(),domain:a}),K={access_data:s,refresh_expiry_date:n},A.setItem(xe,String(l)),A.setItem(ae,String(n)),a?A.setItem(ne,a):A.removeItem(ne),R.set({isAuthenticated:true,isInitializing:false}),envoyFetchTs.logger.log("Auth session saved");}function W(){if(K)return K;let e=O.getAccessToken();if(!e)return null;let r=Oe(e);if(!r||r.exp*1e3<=Date.now())return null;let t=A.getItem(ae);if(!t)return null;let o=Number(t);if(isNaN(o))return null;let i={access_data:r,refresh_expiry_date:o};return K=i,i}function Me(e,r){try{let t=A.getItem(e);if(!t)return !0;let o=Number(t);return isNaN(o)?!0:o-Date.now()<=r*1e3}catch(t){return envoyFetchTs.logger.warn("Error reading expiry:",t),true}}var be=(e=30)=>Me(xe,e),le=(e=10)=>Me(ae,e);function X(){K=null,O.clear(),A.removeItem(xe),A.removeItem(ae);let e=A.getItem(ne)||De();H.remove("refresh_token",e),A.removeItem(ne),R.reset(),envoyFetchTs.logger.log("Auth tokens and claims cleared");}function Be(){let e=W();return e?e.access_data.sub:null}function ot(){let e=typeof window>"u",r=typeof ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('react.js', document.baseURI).href)) })<"u"&&undefined?undefined:{},t=typeof process<"u"?process.env:{},o=r.VITE_TRIEOH_AUTH_PROJECT_ID||t.NEXT_PUBLIC_TRIEOH_AUTH_PROJECT_ID||t.PUBLIC_TRIEOH_AUTH_PROJECT_ID||"",i=e&&t.TRIEOH_AUTH_API_KEY||"";return {PROJECT_ID:o,API_KEY:i,BASE_URL:"https://api.trieauth.trieoh.com"}}var ce=null,Se={};function Fe(e){Se={...Se,...e},ce=null;}function ye(){return ce||(ce={...ot(),...Se}),ce}var x={get PROJECT_ID(){return ye().PROJECT_ID},get BASE_URL(){return ye().BASE_URL}};var ue=class{constructor(r){this.isRefreshing=false;this.refreshPromise=null;this.baseURL=r?.baseURL||x.BASE_URL,this.authBaseURL=r?.authBaseURL||this.baseURL,this.onTokenRefreshed=r?.onTokenRefreshed,this.onRefreshFailed=r?.onRefreshFailed;}async refreshToken(){return this.isRefreshing&&this.refreshPromise?this.refreshPromise:(this.isRefreshing=true,this.refreshPromise=(async()=>{let r=true;try{let t=await envoyFetchTs.simpleFetch(ve(this.authBaseURL,"/auth/refresh"),{method:"POST",credentials:"include"});if(t.code!==200||!t.data)throw r=t.code!==503,new Error(t.message||"Failed to refresh token");G(t.data);let o=W();o&&this.onTokenRefreshed?.(o),envoyFetchTs.logger.log("Token refreshed successfully");}catch(t){throw envoyFetchTs.logger.warn("Failed to refresh token:",t),r&&X(),this.onRefreshFailed?.(t),t}finally{this.isRefreshing=false,this.refreshPromise=null;}})(),this.refreshPromise)}async beforeRequest(){if(le()){X();return}if(!!!O.getAccessToken()||be(30))try{await this.refreshToken();}catch(t){envoyFetchTs.logger.warn("Proactive refresh failed:",t);}}async fetch(r,t){let o=t?.requiresAuth!==false,i=r.includes("/auth/refresh");o&&!i&&!t?.skipRefresh&&await this.beforeRequest();let s=ve(this.baseURL,r),n=async()=>{let a=O.getAccessToken(),c=new Headers(t?.headers);return o&&a&&c.set("Authorization",`Bearer ${a}`),c.has("Content-Type")||c.set("Content-Type","application/json"),fetch(s,{...t,headers:c,credentials:"include"})},l=await n();if(l.status===401&&o&&!i){let a=!!H.get("refresh_token"),c=be(30);if(a&&c){envoyFetchTs.logger.log("401 detected and token is expiring/expired, attempting refresh...");try{await this.refreshToken(),l=await n();}catch{envoyFetchTs.logger.error("Retry failed after refresh error");}}}return l}};function M(e){if(!e)return;let{requiresAuth:r,skipRefresh:t,...o}=e,i={};return r!==void 0&&(i.requiresAuth=r),t!==void 0&&(i.skipRefresh=t),{...o,adapterInit:{...o.adapterInit,...i}}}var me=class{constructor(r,t,o,i){this.interceptor=new ue({baseURL:r,authBaseURL:t,onTokenRefreshed:o}),this.client=envoyFetchTs.createDefaultFetchClient({...i,adapter:this.interceptor.fetch.bind(this.interceptor)});}request(r,t){return this.client.request(r,M(t))}get(r,t){return this.client.get(r,M(t))}post(r,t,o){return this.client.post(r,t,M(o))}put(r,t,o){return this.client.put(r,t,M(o))}patch(r,t,o){return this.client.patch(r,t,M(o))}delete(r,t,o){return this.client.delete(r,t,M(o))}query(r,t){return this.client.query(r,M(t))}};var z=()=>{if(!x.PROJECT_ID||x.PROJECT_ID.trim()==="")throw new Error("[TRIEOH SDK] Project ID is missing. Please set PUBLIC_TRIEOH_AUTH_PROJECT_ID, NEXT_PUBLIC_TRIEOH_AUTH_PROJECT_ID or VITE_TRIEOH_AUTH_PROJECT_ID.")};var Ue=(e,r)=>({login:async(t,o)=>{x.PROJECT_ID&&z();let i=`/auth/login${x.PROJECT_ID?`?project_id=${x.PROJECT_ID}`:""}`,s=await e.post(i,{email:t,password:o},{requiresAuth:false});return s.success&&(G(s.data),r?.onLogin?.(s)),s},register:async(t,o)=>{let i={requiresAuth:false},s=`/auth/register${x.PROJECT_ID?`?project_id=${x.PROJECT_ID}`:""}`;x.PROJECT_ID&&z();let n=await e.post(s,{email:t,password:o},i);return n.success&&r?.onRegister?.(n),n},logout:async t=>{let o=`/auth/logout${x.PROJECT_ID?`?project_id=${x.PROJECT_ID}`:""}`,i=await e.post(o);return (i.success||t?.forceLogout)&&X(),i},refresh:async()=>{let t=await e.post("/auth/refresh",void 0,{skipRefresh:true});return t.success&&(G(t.data),r?.onRefresh?.(t)),t},sessions:async()=>e.get("/sessions"),currentSession:async()=>e.get("/sessions/me"),revokeASession:async t=>e.delete(`/sessions/${t}`),revokeSessions:async(t=false)=>{let o=t?"/sessions":"/sessions/others";return e.delete(o)},profile:()=>Be(),sendForgotPassword:async t=>{let o={requiresAuth:false};return x.PROJECT_ID?(z(),e.post("/account/forgot-password",{email:t,project_id:x.PROJECT_ID},o)):e.post("/account/forgot-password",{email:t},o)},resetPassword:async(t,o)=>{let i=await e.post(`/account/reset-password?token=${t}`,{new_password:o},{requiresAuth:false});return i.success&&r?.onResetPassword?.(i),i},verifyEmail:async t=>{let o=`/account/verify?token=${t}`,i=await e.post(o);return i.success&&r?.onVerify?.(i),i},resendVerifyEmail:async()=>e.post("/account/verify/resend"),health:async()=>e.get("/health",{requiresAuth:false}),authHealth:async()=>e.get("/protected/health")});var ze=react.createContext(null);function Ur({children:e,baseURL:r,projectId:t,isProjectMode:o=true,fallback:i,waitSession:s=true,clientConfig:n,onLogin:l,onResetPassword:a,onRegister:c,onVerify:p,onRefresh:f}){let h=react.useRef(false),{isAuthenticated:d,isInitializing:u}=react.useSyncExternalStore(R.subscribe,R.getSnapshot,R.getServerSnapshot);react.useEffect(()=>{Fe({...t?{PROJECT_ID:t}:{},...r?{BASE_URL:r}:{}});},[t,r]);let y=react.useCallback(L=>{R.set({isAuthenticated:!!L.access_data,isInitializing:false}),f?.();},[f]),S=react.useMemo(()=>new me(r,void 0,y,n),[r,y,n]),w=react.useMemo(()=>Ue(S,{onLogin:l,onResetPassword:a,onRegister:c,onVerify:p,onRefresh:f}),[S,l,a,c,p,f]);react.useEffect(()=>{o&&z(),(async()=>{if(!h.current){if(h.current=true,W()){R.set({isAuthenticated:true,isInitializing:false});return}if(le()){R.reset(),R.set({isInitializing:false});return}envoyFetchTs.logger.log("No cached claims, attempting silent refresh...");try{await S.interceptor.refreshToken(),envoyFetchTs.logger.log("Session restored.");}catch{R.reset(),envoyFetchTs.logger.warn("Could not restore session (offline?).");}finally{R.set({isInitializing:false});}}})();},[w,o]);let C=react.useMemo(()=>({auth:w,isAuthenticated:d,isInitializing:u,isProjectMode:o}),[w,d,u,o]);return s&&u?i??null:jsxRuntime.jsx(ze.Provider,{value:C,children:e})}function b(){let e=react.useContext(ze);if(!e)throw new Error("useAuth must be used inside <AuthProvider>");return e}function Ee(e,{insertAt:r}={}){if(typeof document>"u")return;let t=document.head||document.getElementsByTagName("head")[0],o=document.createElement("style");o.type="text/css",r==="top"&&t.firstChild?t.insertBefore(o,t.firstChild):t.appendChild(o),o.styleSheet?o.styleSheet.cssText=e:o.appendChild(document.createTextNode(e));}Ee(`/*! tailwindcss v4.3.0 | MIT License | https://tailwindcss.com */@layer properties;@layer theme,base,components,utilities;@layer theme{:root,:host{--font-sans: ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";--font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;--spacing: .25rem;--font-weight-extralight: 200;--font-weight-light: 300;--font-weight-normal: 400;--font-weight-medium: 500;--font-weight-semibold: 600;--radius-lg: .5rem;--ease-in-out: cubic-bezier(.4, 0, .2, 1);--animate-spin: spin 1s linear infinite;--default-transition-duration: .15s;--default-transition-timing-function: cubic-bezier(.4, 0, .2, 1);--default-font-family: var(--font-sans);--default-mono-font-family: var(--font-mono);--color-trieoh-primary: oklch(.1139 .0789 264.05);--color-trieoh-secondary: oklch(.7975 .1018 262.7);--color-trieoh-neutral1: oklch(.9702 0 0);--color-trieoh-neutral2: oklch(.1944 .0051 248.09);--radius-trieoh-full: 50%;--font-inter: "Inter", sans-serif}}@layer base{*,:after,:before,::backdrop,::file-selector-button{box-sizing:border-box;margin:0;padding:0;border:0 solid}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;tab-size:4;font-family:var(--default-font-family, ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings, normal);font-variation-settings:var(--default-font-variation-settings, normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings, normal);font-variation-settings:var(--default-mono-font-variation-settings, normal);font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea,::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;border-radius:0;background-color:transparent;opacity:1}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not (-webkit-appearance: -apple-pay-button)) or (contain-intrinsic-size: 1px){::placeholder{color:currentcolor;@supports (color: color-mix(in lab,red,red)){color:color-mix(in oklab,currentcolor 50%,transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit,::-webkit-datetime-edit-year-field,::-webkit-datetime-edit-month-field,::-webkit-datetime-edit-day-field,::-webkit-datetime-edit-hour-field,::-webkit-datetime-edit-minute-field,::-webkit-datetime-edit-second-field,::-webkit-datetime-edit-millisecond-field,::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]),::file-selector-button{appearance:button}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}}@layer utilities{.\\@container{container-type:inline-size}.trieoh-button-loading{&:after{content:"";position:absolute;top:0;left:-150%;width:150%;height:100%;background:linear-gradient(120deg,transparent 0%,var(--trieoh-neutral2) 40%,transparent 80%);@supports (color: color-mix(in lab,red,red)){background:linear-gradient(120deg,transparent 0%,color-mix(in oklab,var(--trieoh-neutral2) 40%,white 15%) 40%,transparent 80%)}animation:trieoh-shine 1.5s infinite}}.absolute{position:absolute}.relative{position:relative}.top-0{top:calc(var(--spacing) * 0)}.right-0{right:calc(var(--spacing) * 0)}.m-0{margin:calc(var(--spacing) * 0)}.m-2{margin:calc(var(--spacing) * 2)}.m-\\[0\\.125rem\\]{margin:.125rem}.mt-2{margin-top:calc(var(--spacing) * 2)}.mt-4{margin-top:calc(var(--spacing) * 4)}.mb-1{margin-bottom:calc(var(--spacing) * 1)}.mb-2{margin-bottom:calc(var(--spacing) * 2)}.mb-\\[0\\.625rem\\]{margin-bottom:.625rem}.box-border{box-sizing:border-box}.block{display:block}.contents{display:contents}.flex{display:flex}.inline-block{display:inline-block}.inline-flex{display:inline-flex}.h-12{height:calc(var(--spacing) * 12)}.h-16{height:calc(var(--spacing) * 16)}.h-\\[3\\.25rem\\]{height:3.25rem}.h-\\[64px\\]{height:64px}.h-auto{height:auto}.h-full{height:100%}.max-h-\\[max\\(75dvh\\,32rem\\)\\]{max-height:max(75dvh,32rem)}.min-h-screen{min-height:100vh}.w-12{width:calc(var(--spacing) * 12)}.w-16{width:calc(var(--spacing) * 16)}.w-\\[64px\\]{width:64px}.w-full{width:100%}.max-w-\\[14rem\\]{max-width:14rem}.max-w-\\[25rem\\]{max-width:25rem}.max-w-\\[30rem\\]{max-width:30rem}.min-w-0{min-width:calc(var(--spacing) * 0)}.min-w-\\[10rem\\]{min-width:10rem}.min-w-\\[15rem\\]{min-width:15rem}.min-w-\\[20rem\\]{min-width:20rem}.flex-1{flex:1}.flex-\\[0_1_auto\\]{flex:0 1 auto}.flex-\\[1_1_auto\\]{flex:1 1 auto}.shrink-0{flex-shrink:0}.animate-spin{animation:var(--animate-spin)}.cursor-pointer{cursor:pointer}.appearance-none{appearance:none}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-center{align-items:center}.items-end{align-items:flex-end}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.gap-1{gap:calc(var(--spacing) * 1)}.gap-2{gap:calc(var(--spacing) * 2)}.gap-4{gap:calc(var(--spacing) * 4)}.gap-5{gap:calc(var(--spacing) * 5)}.gap-6{gap:calc(var(--spacing) * 6)}.gap-8{gap:calc(var(--spacing) * 8)}.gap-\\[0\\.625rem\\]{gap:.625rem}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.rounded-\\[0\\.25rem\\]{border-radius:.25rem}.rounded-full{border-radius:calc(infinity * 1px)}.rounded-lg{border-radius:var(--radius-lg)}.rounded-trieoh-full{border-radius:var(--radius-trieoh-full)}.border-2{border-style:var(--tw-border-style);border-width:2px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-b-2{border-bottom-style:var(--tw-border-style);border-bottom-width:2px}.border-none{--tw-border-style: none;border-style:none}.\\!border-\\[\\#e53935\\]{border-color:#e53935!important}.border-\\[rgba\\(0\\,0\\,0\\,0\\.3\\)\\]{border-color:#0000004d}.border-trieoh-neutral2{border-color:var(--color-trieoh-neutral2)}.border-trieoh-secondary{border-color:var(--color-trieoh-secondary)}.bg-\\[oklch\\(0\\.8853_0_0\\/30\\%\\)\\]{background-color:#d9d9d94d}.bg-transparent{background-color:transparent}.bg-trieoh-neutral1{background-color:var(--color-trieoh-neutral1)}.bg-trieoh-secondary\\/10{background-color:color-mix(in srgb,oklch(.7975 .1018 262.7) 10%,transparent);@supports (color: color-mix(in lab,red,red)){background-color:color-mix(in oklab,var(--color-trieoh-secondary) 10%,transparent)}}.p-2{padding:calc(var(--spacing) * 2)}.p-6{padding:calc(var(--spacing) * 6)}.p-\\[0\\.625rem\\]{padding:.625rem}.p-\\[1\\.5rem_0\\.5rem\\]{padding:1.5rem .5rem}.p-\\[1\\.25rem_0\\.75rem\\]{padding:1.25rem .75rem}.p-\\[1\\.25rem_1\\.5rem\\]{padding:1.25rem 1.5rem}.p-\\[1rem_0\\]{padding:1rem 0}.px-\\[0\\.75rem\\]{padding-inline:.75rem}.px-\\[0\\.625rem\\]{padding-inline:.625rem}.px-\\[1\\.5rem\\]{padding-inline:1.5rem}.py-4{padding-block:calc(var(--spacing) * 4)}.py-\\[0\\.125rem\\]{padding-block:.125rem}.py-\\[0\\.0625rem\\]{padding-block:.0625rem}.text-center{text-align:center}.font-inter{font-family:var(--font-inter)}.text-\\[0\\.75rem\\]{font-size:.75rem}.text-\\[0\\.875rem\\]{font-size:.875rem}.text-\\[1rem\\]{font-size:1rem}.font-extralight{--tw-font-weight: var(--font-weight-extralight);font-weight:var(--font-weight-extralight)}.font-light{--tw-font-weight: var(--font-weight-light);font-weight:var(--font-weight-light)}.font-medium{--tw-font-weight: var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-normal{--tw-font-weight: var(--font-weight-normal);font-weight:var(--font-weight-normal)}.font-semibold{--tw-font-weight: var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.text-\\[\\#6b7280\\]{color:#6b7280}.text-\\[\\#10b981\\]{color:#10b981}.text-\\[\\#e53935\\]{color:#e53935}.text-\\[oklch\\(0\\.628_0\\.2577_29\\.23\\)\\]{color:red}.text-trieoh-neutral2{color:var(--color-trieoh-neutral2)}.text-trieoh-primary{color:var(--color-trieoh-primary)}.text-trieoh-secondary{color:var(--color-trieoh-secondary)}.line-through{text-decoration-line:line-through}.opacity-50{opacity:50%}.opacity-60{opacity:60%}.opacity-95{opacity:95%}.opacity-100{opacity:100%}.\\!shadow-none{--tw-shadow: 0 0 #0000 !important;box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)!important}.shadow-\\[0_0\\.25rem_0\\.25rem_0_rgba\\(0\\,0\\,0\\,0\\.25\\)\\]{--tw-shadow: 0 .25rem .25rem 0 var(--tw-shadow-color, rgba(0,0,0,.25));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-\\[0_0\\.25rem_1rem_rgba\\(0\\,0\\,0\\,0\\.25\\)\\]{--tw-shadow: 0 .25rem 1rem var(--tw-shadow-color, rgba(0,0,0,.25));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.transition-\\[color\\,text-decoration\\,opacity\\]{transition-property:color,text-decoration,opacity;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-\\[opacity\\,transform\\]{transition-property:opacity,transform;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-opacity{transition-property:opacity;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-transform{transition-property:transform,translate,scale,rotate;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.duration-150{--tw-duration: .15s;transition-duration:.15s}.duration-200{--tw-duration: .2s;transition-duration:.2s}.duration-500{--tw-duration: .5s;transition-duration:.5s}.duration-\\[120ms\\]{--tw-duration: .12s;transition-duration:.12s}.ease-in-out{--tw-ease: var(--ease-in-out);transition-timing-function:var(--ease-in-out)}.outline-none{--tw-outline-style: none;outline-style:none}.select-none{-webkit-user-select:none;user-select:none}.hover\\:scale-\\[1\\.02\\]{&:hover{@media(hover:hover){scale:1.02}}}.hover\\:scale-\\[1\\.05\\]{&:hover{@media(hover:hover){scale:1.05}}}.hover\\:text-trieoh-primary{&:hover{@media(hover:hover){color:var(--color-trieoh-primary)}}}.hover\\:opacity-100{&:hover{@media(hover:hover){opacity:100%}}}.active\\:scale-\\[0\\.95\\]{&:active{scale:.95}}.active\\:scale-\\[0\\.98\\]{&:active{scale:.98}}.active\\:scale-\\[0\\.99\\]{&:active{scale:.99}}.disabled\\:\\!transform-none{&:disabled{transform:none!important}}.disabled\\:cursor-not-allowed{&:disabled{cursor:not-allowed}}.disabled\\:opacity-60{&:disabled{opacity:60%}}.\\@\\[640px\\]\\:flex-row{@container (width >= 640px){flex-direction:row}}.\\@\\[640px\\]\\:items-center{@container (width >= 640px){align-items:center}}.\\@\\[640px\\]\\:justify-between{@container (width >= 640px){justify-content:space-between}}.\\@\\[640px\\]\\:gap-2{@container (width >= 640px){gap:calc(var(--spacing) * 2)}}.\\@\\[640px\\]\\:gap-4{@container (width >= 640px){gap:calc(var(--spacing) * 4)}}.\\@\\[640px\\]\\:gap-8{@container (width >= 640px){gap:calc(var(--spacing) * 8)}}.\\@\\[640px\\]\\:text-left{@container (width >= 640px){text-align:left}}}@import url(https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap);@property --tw-border-style{syntax: "*"; inherits: false; initial-value: solid;}@property --tw-font-weight{syntax: "*"; inherits: false;}@property --tw-shadow{syntax: "*"; inherits: false; initial-value: 0 0 #0000;}@property --tw-shadow-color{syntax: "*"; inherits: false;}@property --tw-shadow-alpha{syntax: "<percentage>"; inherits: false; initial-value: 100%;}@property --tw-inset-shadow{syntax: "*"; inherits: false; initial-value: 0 0 #0000;}@property --tw-inset-shadow-color{syntax: "*"; inherits: false;}@property --tw-inset-shadow-alpha{syntax: "<percentage>"; inherits: false; initial-value: 100%;}@property --tw-ring-color{syntax: "*"; inherits: false;}@property --tw-ring-shadow{syntax: "*"; inherits: false; initial-value: 0 0 #0000;}@property --tw-inset-ring-color{syntax: "*"; inherits: false;}@property --tw-inset-ring-shadow{syntax: "*"; inherits: false; initial-value: 0 0 #0000;}@property --tw-ring-inset{syntax: "*"; inherits: false;}@property --tw-ring-offset-width{syntax: "<length>"; inherits: false; initial-value: 0px;}@property --tw-ring-offset-color{syntax: "*"; inherits: false; initial-value: #fff;}@property --tw-ring-offset-shadow{syntax: "*"; inherits: false; initial-value: 0 0 #0000;}@property --tw-duration{syntax: "*"; inherits: false;}@property --tw-ease{syntax: "*"; inherits: false;}@keyframes spin{to{transform:rotate(360deg)}}@keyframes trieoh-shine{0%{left:-150%}to{left:150%}}@layer properties{@supports ((-webkit-hyphens: none) and (not (margin-trim: inline))) or ((-moz-orient: inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-border-style: solid;--tw-font-weight: initial;--tw-shadow: 0 0 #0000;--tw-shadow-color: initial;--tw-shadow-alpha: 100%;--tw-inset-shadow: 0 0 #0000;--tw-inset-shadow-color: initial;--tw-inset-shadow-alpha: 100%;--tw-ring-color: initial;--tw-ring-shadow: 0 0 #0000;--tw-inset-ring-color: initial;--tw-inset-ring-shadow: 0 0 #0000;--tw-ring-inset: initial;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-offset-shadow: 0 0 #0000;--tw-duration: initial;--tw-ease: initial}}}
|
|
2
|
-
`);function _({name:e,label:r,placeholder:t,type:o="text",value:i,onValueChange:s,onBlur:n,autoComplete:l,rulesStatus:a=[],submitted:c=false,inputRef:p}){let[f,h]=react.useState(false),d=a.some(u=>!u.passed);return jsxRuntime.jsxs("div",{className:"font-inter relative w-full flex flex-col gap-1 text-trieoh-neutral2",children:[jsxRuntime.jsx("label",{htmlFor:e,className:"text-[1rem] font-semibold",children:r}),jsxRuntime.jsxs("div",{className:`flex justify-between items-center px-[0.625rem] py-[0.0625rem] gap-[0.625rem] border-b-2 border-trieoh-neutral2 ${d&&c?"!border-[#e53935]":""}`,children:[jsxRuntime.jsx("input",{type:f?"text":o,name:e,id:e,placeholder:t,value:i,onChange:u=>s&&s(u.target.value),onBlur:n,autoComplete:l,"aria-invalid":d&&c,ref:p,className:"min-w-[10rem] flex-1 text-trieoh-base font-light text-trieoh-neutral2 appearance-none bg-transparent outline-none border-none !shadow-none py-[0.125rem]"}),o==="password"&&(f?jsxRuntime.jsx(ri.RiEyeCloseLine,{className:"cursor-pointer shrink-0 select-none",size:24,onClick:()=>h(false)}):jsxRuntime.jsx(ri.RiEyeLine,{className:"cursor-pointer shrink-0 select-none",size:24,onClick:()=>h(true)}))]}),jsxRuntime.jsx("div",{className:"text-[0.75rem] text-[#6b7280] transition-opacity duration-200 ease-in-out",children:a.map((u,y)=>{let S=["transition-[color,text-decoration,opacity] duration-[120ms] ease opacity-95 m-[0.125rem]",u.passed?"line-through opacity-60 text-[#10b981]":"",!u.passed&&c?"text-[#e53935] font-semibold opacity-100":""].filter(Boolean).join(" ");return jsxRuntime.jsx("p",{className:S,children:u.message},u.id??y)})})]})}function E({label:e,onSubmit:r,loading:t}){return jsxRuntime.jsx("button",{type:"submit",onClick:r,disabled:t,className:`font-inter w-full h-[3.25rem] text-trieoh-xl font-semibold outline-none bg-transparent relative overflow-hidden min-w-[10rem] shrink-0 border-2 border-trieoh-neutral2 text-trieoh-neutral2 cursor-pointer px-[1.5rem] transition-transform duration-500 rounded-[0.25rem] hover:scale-[1.02] active:scale-[0.99] disabled:opacity-60 disabled:cursor-not-allowed disabled:!transform-none ${t?"trieoh-button-loading":""}`,children:e})}function k({mainText:e,subText:r}){return jsxRuntime.jsxs("div",{className:"font-inter flex flex-col items-center",children:[jsxRuntime.jsx("div",{className:"flex justify-center items-center p-2 bg-[oklch(0.8853_0_0/30%)] rounded-trieoh-full mb-[0.625rem]",children:jsxRuntime.jsx(go.GoPerson,{className:"w-[64px] h-[64px] p-[0.625rem] bg-trieoh-neutral1 rounded-trieoh-full shadow-[0_0.25rem_1rem_rgba(0,0,0,0.25)]",size:70})}),jsxRuntime.jsx("h3",{className:"text-center text-trieoh-xl font-medium m-0",children:e}),jsxRuntime.jsx("span",{className:"text-center text-[0.875rem] font-light opacity-60",children:r})]})}function T(e,r){return e.map(t=>({id:t.id,message:t.message,passed:!!t.test(r)}))}function wt({onSuccess:e,onFailed:r,signUpRedirect:t,forgotPasswordRedirect:o,emailRules:i}){let[s,n]=react.useState(""),[l,a]=react.useState(""),[c,p]=react.useState(false),[f,h]=react.useState(false),d=react.useRef(null),u=react.useRef(null),{auth:y}=b(),S={email:i||[{message:"Digite um e-mail v\xE1lido, ex: exemplo@dominio.com",test:v=>/\S+@\S+\.\S+/.test(v)}],password:[]},w=T(S.email,s),C=T(S.password,l);return jsxRuntime.jsxs("form",{className:"font-inter flex flex-col w-full max-w-[30rem] min-w-[15rem] max-h-[max(75dvh,32rem)] overflow-hidden gap-5 items-center bg-trieoh-neutral1 text-trieoh-neutral2 p-[1.25rem_1.5rem] shadow-[0_0.25rem_0.25rem_0_rgba(0,0,0,0.25)] transition-transform duration-150 ease-in-out rounded-[0.25rem]",children:[jsxRuntime.jsx(k,{mainText:"Fa\xE7a login na sua conta",subText:"Insira seus dados para fazer login"}),jsxRuntime.jsxs("div",{className:"w-full flex flex-col gap-[0.625rem] flex-[1_1_auto] overflow-y-auto mb-2",children:[jsxRuntime.jsx(_,{label:"Email",name:"email",placeholder:"teste@gmail.com",autoComplete:"email",type:"email",value:s,onValueChange:n,inputRef:d,rulesStatus:w,submitted:c}),jsxRuntime.jsx(_,{label:"Senha",name:"password",placeholder:"**********",autoComplete:"current-password",type:"password",value:l,onValueChange:a,inputRef:u,rulesStatus:C,submitted:c})]}),jsxRuntime.jsx(E,{label:"Entrar",onSubmit:async v=>{v.preventDefault(),p(true);let F=w.some(g=>!g.passed),U=C.some(g=>!g.passed);if(F){d.current?.focus();return}if(U){u.current?.focus();return}h(true);let P=await y.login(s,l);P.success?e&&await e(P.message):r&&await r(P.message,P.trace),h(false);},loading:f}),o&&jsxRuntime.jsx("span",{className:"text-trieoh-sm font-semibold text-center cursor-pointer",children:jsxRuntime.jsx("span",{className:"cursor-pointer text-trieoh-secondary transition-colors duration-200 hover:text-trieoh-primary",onClick:o,children:"Esqueceu sua senha?"})}),t&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-[0.625rem] w-full text-trieoh-base font-semibold opacity-60",children:[jsxRuntime.jsx("hr",{className:"flex-1"}),"OU",jsxRuntime.jsx("hr",{className:"flex-1"})]}),jsxRuntime.jsxs("span",{className:"text-trieoh-sm font-semibold",children:["Ainda n\xE3o possui uma conta? ",jsxRuntime.jsx("span",{className:"cursor-pointer text-trieoh-secondary transition-colors duration-200 hover:text-trieoh-primary",onClick:t,children:"Cadastra-se"})]})]})]})}function bt({onSuccess:e,onFailed:r,loginRedirect:t,emailRules:o,passwordRules:i}){let[s,n]=react.useState(""),[l,a]=react.useState(""),[c,p]=react.useState(""),[f,h]=react.useState(false),[d,u]=react.useState(false),y=react.useRef(null),S=react.useRef(null),w=react.useRef(null),{auth:C}=b(),L={email:o||[{message:"Digite um e-mail v\xE1lido, ex: exemplo@dominio.com",test:g=>/\S+@\S+\.\S+/.test(g)}],password:i||[{message:"M\xEDnimo de 8 caracteres.",test:g=>g.length>=8},{message:"Deve conter uma letra mai\xFAscula.",test:g=>/[A-Z]/.test(g)},{message:"Inclua pelo menos um caractere especial, ex: ! @ # $ % & * . ,",test:g=>/[!@#$%^&*(),.?":{}|<>_\-+=~`;/\\[\]]/.test(g)},{message:"Deve conter um n\xFAmero.",test:g=>/\d/.test(g)}],confirmPassword:[{message:"Senhas n\xE3o conferem.",test:g=>g===l}]},v=T(L.email,s),F=T(L.password,l),U=T(L.confirmPassword,c);return jsxRuntime.jsxs("form",{className:"font-inter flex flex-col w-full max-w-[30rem] min-w-[15rem] max-h-[max(75dvh,32rem)] overflow-hidden gap-5 items-center bg-trieoh-neutral1 text-trieoh-neutral2 p-[1.25rem_1.5rem] shadow-[0_0.25rem_0.25rem_0_rgba(0,0,0,0.25)] transition-transform duration-150 ease-in-out rounded-[0.25rem]",children:[jsxRuntime.jsx(k,{mainText:"Crie sua conta",subText:"Insira seus dados para come\xE7ar"}),jsxRuntime.jsxs("div",{className:"w-full flex flex-col gap-[0.625rem] flex-[1_1_auto] overflow-y-auto mb-2",children:[jsxRuntime.jsx(_,{label:"Email",name:"email",placeholder:"teste@gmail.com",autoComplete:"email",type:"email",value:s,onValueChange:n,inputRef:y,rulesStatus:v,submitted:f}),jsxRuntime.jsx(_,{label:"Senha",name:"password",placeholder:"**********",autoComplete:"new-password",type:"password",value:l,onValueChange:a,inputRef:S,rulesStatus:F,submitted:f}),jsxRuntime.jsx(_,{label:"Confirme a Senha",name:"confirm-password",placeholder:"**********",autoComplete:"new-password",type:"password",value:c,onValueChange:p,inputRef:w,rulesStatus:U,submitted:f})]}),jsxRuntime.jsx(E,{label:"Criar Conta",onSubmit:async g=>{g.preventDefault(),h(true);let et=v.some($=>!$.passed),tt=F.some($=>!$.passed),rt=U.some($=>!$.passed);if(et){y.current?.focus();return}if(tt){S.current?.focus();return}if(rt){w.current?.focus();return}u(true);let ie=await C.register(s,l);ie.success?e&&await e(ie.message):r&&await r(ie.message,ie.trace),u(false);},loading:d}),t&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-[0.625rem] w-full text-trieoh-base font-semibold opacity-60",children:[jsxRuntime.jsx("hr",{className:"flex-1"}),"OU",jsxRuntime.jsx("hr",{className:"flex-1"})]}),jsxRuntime.jsxs("span",{className:"text-trieoh-sm font-semibold",children:["J\xE1 possui uma conta? ",jsxRuntime.jsx("span",{className:"cursor-pointer text-trieoh-secondary transition-colors duration-200 hover:text-trieoh-primary",onClick:t,children:"Entre"})]})]})]})}var St={xs:"text-trieoh-sm",sm:"text-trieoh-base",md:"text-trieoh-xl",lg:"text-trieoh-2xl",xl:"text-trieoh-3xl","2xl":"text-trieoh-6xl"};function Rt({size:e}){let r=e?St[e]:"text-trieoh-xl";return jsxRuntime.jsxs("span",{className:`font-inter font-medium ${r}`,children:["\xA9 ",new Date().getFullYear()," TrieOH"]})}function Tt({onSuccess:e,onFailed:r,forceLogout:t}){let{auth:o}=b(),[i,s]=react.useState(false);return jsxRuntime.jsxs("button",{onClick:async l=>{if(l.preventDefault(),i)return;s(true);let a=await o.logout({forceLogout:t});a.success?e&&await e(a.message):r&&await r(a.message,a.trace),s(false);},type:"button",disabled:i,className:"font-inter border-none bg-transparent cursor-pointer flex items-end gap-1 text-trieoh-base font-medium text-[oklch(0.628_0.2577_29.23)] transition-transform duration-200 hover:scale-[1.05] active:scale-[0.98] disabled:opacity-60 disabled:cursor-not-allowed disabled:!transform-none",children:[jsxRuntime.jsx(im.ImExit,{size:24})," ",jsxRuntime.jsx("span",{children:"Log out"})]})}var Je={mobile:fa.FaMobileAlt,tablet:fa.FaTabletAlt,desktop:fa.FaDesktop};function je(e){let{device:r,os:t,browser:o}=uaParserJs.UAParser(e);return {deviceType:r.type??"desktop",os:t.name,browser:o.name}}function Ke(e){let r=je(e);return {device:Lt(r.deviceType),os:r.os,browser:r.browser}}function Lt(e){if(!e)return "desktop";switch(e){case "mobile":return "mobile";case "tablet":return "tablet";default:return "desktop"}}function Ye(e){let r=Date.now()-new Date(e).getTime(),t=Math.floor(r/1e3),o=Math.floor(t/60),i=Math.floor(o/60),s=Math.floor(i/24),n=Math.floor(s/7);return t<60?"agora mesmo":o<60?`${o} minutos atr\xE1s`:i<24?`${i} horas atr\xE1s`:s<7?`${s} dias atr\xE1s`:`${n} semanas atr\xE1s`}function Te({is_current:e,session_id:r,user_agent:t,issued_at:o,user_ip:i,onClick:s}){let n=Ke(t),l=Je[n.device];return jsxRuntime.jsx("div",{className:"border-t border-[rgba(0,0,0,0.3)] p-[1.25rem_0.75rem] text-trieoh-neutral2",children:jsxRuntime.jsxs("div",{className:"relative flex flex-col items-center gap-2 flex-1 text-center @[640px]:flex-row @[640px]:items-center @[640px]:gap-4 @[640px]:text-left",children:[jsxRuntime.jsx(l,{size:40}),jsxRuntime.jsxs("div",{className:"flex flex-col min-w-0",children:[jsxRuntime.jsxs("h3",{className:"text-trieoh-base font-semibold m-0",children:[n.browser," - ",n.os]}),jsxRuntime.jsxs("span",{className:"inline-flex flex-col text-trieoh-sm font-extralight @[640px]:flex-row @[640px]:gap-2 @[640px]:items-center",children:[e&&jsxRuntime.jsx("strong",{className:"text-trieoh-primary font-normal",children:"\u2022 Sess\xE3o Atual \u2022"}),jsxRuntime.jsx("span",{children:`${i} - ${Ye(o)}`})]})]}),!e&&jsxRuntime.jsx(fa.FaTrashAlt,{size:20,color:"red",onClick:a=>s(a,r),className:"absolute top-0 right-0 cursor-pointer opacity-60 transition-[opacity,transform] duration-200 hover:opacity-100 hover:scale-[1.05] active:scale-[0.95]"})]})})}function Mt({revokeAll:e=false,onSuccess:r}){let{auth:t}=b(),[o,i]=react.useState(false),[s,n]=react.useState([]),l=async()=>{let p=await t.sessions();if(p.success){let f=t.profile()?.session_id,h=p.data.sort((d,u)=>d.session_id===f?-1:u.session_id===f?1:0);n(h);}};react.useEffect(()=>{l();},[]);let a=async(p,f)=>{p.preventDefault();let h=s.find(d=>d.session_id===f);if(h){n(s.filter(d=>d.session_id!==f));try{(await t.revokeASession(f)).success||n(u=>[...u,h]);}catch{n(d=>[...d,h]);}}};return jsxRuntime.jsxs("div",{className:"font-inter w-full min-w-[20rem] m-2 @container bg-trieoh-neutral1 text-trieoh-neutral2 p-[1.5rem_0.5rem] rounded-lg",children:[jsxRuntime.jsxs("div",{className:"w-full flex flex-wrap items-center justify-center text-center gap-4 box-border px-[0.75rem] @[640px]:justify-between @[640px]:text-left @[640px]:gap-8",children:[jsxRuntime.jsxs("div",{className:"flex-[0_1_auto] max-w-[25rem]",children:[jsxRuntime.jsx("h3",{className:"font-semibold text-trieoh-2xl m-0 mb-1",children:"Navegadores e Dispositivos"}),jsxRuntime.jsx("p",{className:"font-extralight text-trieoh-base m-0",children:"Esses navegadores e dispositivos est\xE3o atualmente conectados \xE0 sua conta. Remova quaisquer dispositivos n\xE3o autorizados."})]}),jsxRuntime.jsx("button",{type:"submit",onClick:async p=>{if(p.preventDefault(),o)return;i(true);let f=await t.revokeSessions(e),h=t.profile()?.session_id;f.success&&(n(e?[]:s.filter(d=>d.session_id===h)),r&&r(f.message)),i(false);},disabled:o,className:`font-inter w-full max-w-[14rem] p-[1rem_0] h-auto text-trieoh-base font-semibold outline-none bg-transparent relative overflow-hidden shrink-0 border-2 border-trieoh-neutral2 text-trieoh-neutral2 cursor-pointer transition-transform duration-500 rounded-[0.25rem] hover:scale-[1.02] active:scale-[0.99] disabled:opacity-60 disabled:cursor-not-allowed disabled:!transform-none ${o?"trieoh-button-loading":""}`,children:"Revogar todas as sess\xF5es"})]}),jsxRuntime.jsx("div",{className:"mt-4",children:s.length>0?s.map(p=>jsxRuntime.jsx(Te,{...p,is_current:t.profile()?.session_id===p.session_id,onClick:a},p.session_id)):jsxRuntime.jsx("span",{className:"block border-t border-[rgba(0,0,0,0.3)] p-[1.25rem_0.75rem] text-center font-semibold",children:"Nenhuma Sess\xE3o Dispon\xEDvel"})})]})}function We({onSuccess:e,onFailed:r,loginRedirect:t,emailRules:o}){let[i,s]=react.useState(""),[n,l]=react.useState(false),[a,c]=react.useState(false),p=react.useRef(null),{auth:f}=b(),d=T({email:o||[{message:"Digite um e-mail v\xE1lido, ex: exemplo@dominio.com",test:y=>/\S+@\S+\.\S+/.test(y)}]}.email,i);return jsxRuntime.jsxs("form",{className:"font-inter flex flex-col w-full max-w-[30rem] min-w-[15rem] max-h-[max(75dvh,32rem)] overflow-hidden gap-5 items-center bg-trieoh-neutral1 text-trieoh-neutral2 p-[1.25rem_1.5rem] shadow-[0_0.25rem_0.25rem_0_rgba(0,0,0,0.25)] transition-transform duration-150 ease-in-out rounded-[0.25rem]",children:[jsxRuntime.jsx(k,{mainText:"Esqueci a senha",subText:"Insira seu e-mail para receber um link de redefini\xE7\xE3o."}),jsxRuntime.jsx("div",{className:"w-full flex flex-col gap-[0.625rem] flex-[1_1_auto] overflow-y-auto mb-2",children:jsxRuntime.jsx(_,{label:"Email",name:"email",placeholder:"teste@gmail.com",autoComplete:"email",type:"email",value:i,onValueChange:s,inputRef:p,rulesStatus:d,submitted:n})}),jsxRuntime.jsx(E,{label:a?"Enviando...":"Enviar link de redefini\xE7\xE3o",onSubmit:async y=>{if(y.preventDefault(),l(true),d.some(C=>!C.passed)){p.current?.focus();return}c(true);let w=await f.sendForgotPassword(i);w.success?e&&await e(w.message):r&&await r(w.message,w.trace),c(false);},loading:a}),t&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-[0.625rem] w-full text-trieoh-base font-semibold opacity-60",children:[jsxRuntime.jsx("hr",{className:"flex-1"}),"OU",jsxRuntime.jsx("hr",{className:"flex-1"})]}),jsxRuntime.jsxs("span",{className:"text-trieoh-sm font-semibold",children:["Lembrou-se da sua senha? ",jsxRuntime.jsx("span",{className:"cursor-pointer text-trieoh-secondary transition-colors duration-200 hover:text-trieoh-primary",onClick:t,children:"Login"})]})]})]})}function Ut({token:e,onSuccess:r,onFailed:t,loginRedirect:o,passwordRules:i}){let[s,n]=react.useState(""),[l,a]=react.useState(""),[c,p]=react.useState(false),[f,h]=react.useState(false),d=react.useRef(null),u=react.useRef(null),{auth:y}=b(),S={password:i||[{message:"M\xEDnimo de 8 caracteres.",test:v=>v.length>=8},{message:"Deve conter uma letra mai\xFAscula.",test:v=>/[A-Z]/.test(v)},{message:"Inclua pelo menos um caractere especial, ex: ! @ # $ % & * . ,",test:v=>/[!@#$%^&*(),.?":{}|<>_\-+=~`;/\\[\]]/.test(v)},{message:"Deve conter um n\xFAmero.",test:v=>/\d/.test(v)}],confirmPassword:[{message:"Senhas n\xE3o conferem.",test:v=>v===s}]},w=T(S.password,s),C=T(S.confirmPassword,l);return jsxRuntime.jsxs("form",{className:"font-inter flex flex-col w-full max-w-[30rem] min-w-[15rem] max-h-[max(75dvh,32rem)] overflow-hidden gap-5 items-center bg-trieoh-neutral1 text-trieoh-neutral2 p-[1.25rem_1.5rem] shadow-[0_0.25rem_0.25rem_0_rgba(0,0,0,0.25)] transition-transform duration-150 ease-in-out rounded-[0.25rem]",children:[jsxRuntime.jsx(k,{mainText:"Redefinir Senha",subText:"Crie uma nova senha para sua conta"}),jsxRuntime.jsxs("div",{className:"w-full flex flex-col gap-[0.625rem] flex-[1_1_auto] overflow-y-auto mb-2",children:[jsxRuntime.jsx(_,{label:"Nova Senha",name:"password",placeholder:"**********",autoComplete:"new-password",type:"password",value:s,onValueChange:n,inputRef:d,rulesStatus:w,submitted:c}),jsxRuntime.jsx(_,{label:"Confirme a Nova Senha",name:"confirm-password",placeholder:"**********",autoComplete:"new-password",type:"password",value:l,onValueChange:a,inputRef:u,rulesStatus:C,submitted:c})]}),jsxRuntime.jsx(E,{label:"Redefinir Senha",onSubmit:async v=>{v.preventDefault(),p(true);let F=w.some(g=>!g.passed),U=C.some(g=>!g.passed);if(F){d.current?.focus();return}if(U){u.current?.focus();return}h(true);let P=await y.resetPassword(e,s);P.success?r&&await r(P.message):t&&await t(P.message,P.trace),h(false);},loading:f}),o&&jsxRuntime.jsxs("span",{className:"text-trieoh-sm font-semibold",children:["Lembrou-se da sua senha? ",jsxRuntime.jsx("span",{className:"cursor-pointer text-trieoh-secondary transition-colors duration-200 hover:text-trieoh-primary",onClick:o,children:"Login"})]})]})}function $t(e,r,t){let[o,i]=react.useState(true),[s,n]=react.useState("verifying"),[l,a]=react.useState("Verificando seu e-mail..."),{auth:c}=b(),p=react.useRef(false),f=async()=>{if(!p.current){p.current=true,i(true),n("verifying");try{if(c.profile()?.is_verified){n("already_verified"),a("Seu e-mail j\xE1 est\xE1 verificado."),i(!1);return}let u=await c.verifyEmail(e);u.success?(await c.refresh(),n("success"),a(u.message||"E-mail verificado com sucesso!"),r&&await r(u.message)):(n("error"),a(u.message||"Falha na verifica\xE7\xE3o do e-mail."),t&&await t(u.message,u.trace));}catch{n("error"),a("Ocorreu um erro inesperado durante a verifica\xE7\xE3o.");}finally{i(false);}}};return react.useEffect(()=>{e&&!p.current&&f();},[e]),{loading:o,status:s,message:l,onRetry:d=>{d.preventDefault(),p.current=false,f();},setStatus:n,setLoading:i,setMessage:a}}function Jt({token:e,onSuccess:r,onFailed:t}){let{loading:o,status:i,message:s,onRetry:n}=$t(e,r,t);return jsxRuntime.jsx("div",{className:"font-inter flex flex-col w-full h-full min-h-screen items-center justify-center bg-trieoh-neutral1 text-trieoh-neutral2 p-6",children:jsxRuntime.jsxs("div",{className:"w-full max-w-[30rem] flex flex-col gap-8 items-center bg-trieoh-neutral1 text-trieoh-neutral2 p-[1.25rem_1.5rem] shadow-[0_0.25rem_0.25rem_0_rgba(0,0,0,0.25)] rounded-[0.25rem]",children:[jsxRuntime.jsx(k,{mainText:i==="verifying"?"Verificando...":i==="error"?"Ops! Falha na verifica\xE7\xE3o":"Tudo pronto!",subText:s}),i==="verifying"&&jsxRuntime.jsx("div",{className:"w-full flex justify-center py-4",children:jsxRuntime.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-trieoh-secondary"})}),i==="error"&&jsxRuntime.jsx("div",{className:"w-full flex flex-col gap-6 items-center",children:jsxRuntime.jsx("div",{className:"w-full mt-2",children:jsxRuntime.jsx(E,{label:"Tentar novamente",onSubmit:n,loading:o})})}),(i==="success"||i==="already_verified")&&jsxRuntime.jsxs("div",{className:"w-full flex flex-col gap-4 items-center",children:[jsxRuntime.jsx("div",{className:"w-16 h-16 flex items-center justify-center rounded-full bg-trieoh-secondary/10 text-trieoh-secondary",children:i==="success"?jsxRuntime.jsx(fi.FiCheck,{size:40}):jsxRuntime.jsx(fi.FiInfo,{size:40})}),jsxRuntime.jsx("p",{className:"text-trieoh-sm font-semibold opacity-50 text-center",children:"Voc\xEA j\xE1 pode fechar esta janela ou continuar navegando em sua conta."})]})]})})}function jt({onSuccess:e,onFailed:r}){let[t,o]=react.useState(false),[i,s]=react.useState(false),{auth:n}=b();return jsxRuntime.jsxs("div",{className:"font-inter flex flex-col w-full max-w-[30rem] min-w-[15rem] max-h-[max(75dvh,32rem)] overflow-hidden gap-5 items-center bg-trieoh-neutral1 text-trieoh-neutral2 p-[1.25rem_1.5rem] shadow-[0_0.25rem_0.25rem_0_rgba(0,0,0,0.25)] transition-transform duration-150 ease-in-out rounded-[0.25rem]",children:[jsxRuntime.jsx(k,{mainText:"Reenviar Verifica\xE7\xE3o",subText:"N\xE3o recebeu o e-mail de verifica\xE7\xE3o? Clique no bot\xE3o abaixo para reenviar."}),jsxRuntime.jsx(E,{label:i?"E-mail Reenviado":"Reenviar E-mail de Verifica\xE7\xE3o",onSubmit:async()=>{o(true);let a=await n.resendVerifyEmail();a.success?(s(true),e&&await e(a.message)):r&&await r(a.message,a.trace),o(false);},loading:t}),i&&jsxRuntime.jsx("p",{className:"text-trieoh-sm font-semibold text-trieoh-secondary",children:"Um novo link de verifica\xE7\xE3o foi enviado para seu e-mail."})]})}exports.AuthProvider=Ur;exports.BasicInputField=_;exports.BasicLogoutButton=Tt;exports.Copyright=Rt;exports.ForgotPassword=We;exports.ResendVerifyEmail=jt;exports.ResetPassword=Ut;exports.Sessions=Mt;exports.SignIn=wt;exports.SignUp=bt;exports.VerifyEmail=Jt;exports.useAuth=b;//# sourceMappingURL=react.js.map
|
|
1
|
+
'use strict';var react=require('react'),envoyFetchTs=require('@trieoh/envoy-fetch-ts'),jsxRuntime=require('react/jsx-runtime'),lucideReact=require('lucide-react'),uaParserJs=require('ua-parser-js'),sonner=require('sonner'),reactHookForm=require('react-hook-form'),zod$1=require('@hookform/resolvers/zod'),zod=require('zod'),clsx=require('clsx'),tailwindMerge=require('tailwind-merge'),react$1=require('motion/react'),classVarianceAuthority=require('class-variance-authority');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function Oe(e,r){if(r.startsWith("http"))return r;let t=e.replace(/\/$/,""),o=r.replace(/^\//,"");return `${t}/${o}`}var oe={isAuthenticated:false,isInitializing:true},Be=new Set,gt=()=>Be.forEach(e=>e()),E={subscribe:e=>(Be.add(e),()=>Be.delete(e)),getSnapshot:()=>oe,getServerSnapshot:()=>oe,set:e=>{oe={...oe,...e},gt();},reset:()=>{oe={isAuthenticated:false,isInitializing:false},gt();}};typeof window<"u"&&window.addEventListener("storage",e=>{if(e.key==="trieoh_access_expiry")if(!e.newValue)E.reset();else {let r=Number(e.newValue),t=!isNaN(r)&&r>Date.now();E.set({isAuthenticated:t,isInitializing:false});}});var V={getItem:e=>typeof window<"u"?localStorage.getItem(e):null,setItem:(e,r)=>{typeof window<"u"&&localStorage.setItem(e,r);},removeItem:e=>{typeof window<"u"&&localStorage.removeItem(e);}},ae={getItem:e=>typeof window<"u"?sessionStorage.getItem(e):null,setItem:(e,r)=>{typeof window<"u"&&sessionStorage.setItem(e,r);},removeItem:e=>{typeof window<"u"&&sessionStorage.removeItem(e);}};var be="trieoh_access_token",J={getAccessToken:()=>ae.getItem(be),setAccessToken:e=>{e?ae.setItem(be,e):ae.removeItem(be);},clear:()=>{ae.removeItem(be);}};var ie=null,De="trieoh_access_expiry",xe="trieoh_refresh_expiry",Ue="trieoh_refresh_token";function ht(e){try{let r=e.split(".")[1];if(!r)return null;let t=r.replace(/-/g,"+").replace(/_/g,"/");for(;t.length%4;)t+="=";let o=decodeURIComponent(atob(t).split("").map(a=>"%"+("00"+a.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(o)}catch(r){return envoyFetchTs.logger.error("Error decoding JWT:",r),null}}function W(e){let{access_token:r,refresh_token:t,access_expires_at:o,refresh_expires_at:a}=e,i=ht(r);if(!i){envoyFetchTs.logger.error("Failed to decode tokens");return}J.setAccessToken(r);let s=new Date(a).getTime(),c=new Date(o).getTime();V.setItem(Ue,t),V.setItem(De,String(c)),V.setItem(xe,String(s)),ie={access_data:i,refresh_expiry_date:s},E.set({isAuthenticated:true,isInitializing:false}),envoyFetchTs.logger.log("Auth session saved");}function He(){return V.getItem(Ue)}function ne(){if(ie)return ie;let e=J.getAccessToken();if(!e)return null;let r=ht(e);if(!r||r.exp*1e3<=Date.now())return null;let t=V.getItem(xe);if(!t)return null;let o=Number(t);if(isNaN(o))return null;let a={access_data:r,refresh_expiry_date:o};return ie=a,a}function vt(e,r){try{let t=V.getItem(e);if(!t)return !0;let o=Number(t);return isNaN(o)?!0:o-Date.now()<=r*1e3}catch(t){return envoyFetchTs.logger.warn("Error reading expiry:",t),true}}var qe=(e=30)=>vt(De,e),ye=(e=10)=>vt(xe,e);function le(){ie=null,J.clear(),V.removeItem(De),V.removeItem(xe),V.removeItem(Ue),E.reset(),envoyFetchTs.logger.log("Auth tokens and claims cleared");}function wt(){let e=ne();return e?e.access_data.sub:null}function Ht(){let e=typeof window>"u",r=typeof ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('react.js', document.baseURI).href)) })<"u"&&undefined?undefined:{},t=typeof process<"u"?process.env:{},o=r.VITE_TRIEOH_AUTH_PROJECT_ID||t.NEXT_PUBLIC_TRIEOH_AUTH_PROJECT_ID||t.PUBLIC_TRIEOH_AUTH_PROJECT_ID||"",a=e&&t.TRIEOH_AUTH_API_KEY||"";return {PROJECT_ID:o,API_KEY:a,BASE_URL:"https://api.trieauth.trieoh.com"}}var ke=null,$e={};function bt(e){$e={...$e,...e},ke=null;}function je(){return ke||(ke={...Ht(),...$e}),ke}var y={get PROJECT_ID(){return je().PROJECT_ID},get BASE_URL(){return je().BASE_URL}};var Se=class{constructor(r){this.isRefreshing=false;this.refreshPromise=null;this.baseURL=r?.baseURL||y.BASE_URL,this.authBaseURL=r?.authBaseURL||this.baseURL,this.onTokenRefreshed=r?.onTokenRefreshed,this.onRefreshFailed=r?.onRefreshFailed;}async refreshToken(){return this.isRefreshing&&this.refreshPromise?this.refreshPromise:(this.isRefreshing=true,this.refreshPromise=(async()=>{let r=true;try{let t=He();if(!t)throw r=!0,new Error("No refresh token available");let o=await envoyFetchTs.simpleFetch(Oe(this.authBaseURL,"/auth/refresh"),{method:"POST",credentials:"include",headers:{refresh_token:t}});if(o.code!==200||!o.data)throw r=o.code!==503,new Error(o.message||"Failed to refresh token");W(o.data);let a=ne();a&&this.onTokenRefreshed?.(a),envoyFetchTs.logger.log("Token refreshed successfully");}catch(t){throw envoyFetchTs.logger.warn("Failed to refresh token:",t),r&&le(),this.onRefreshFailed?.(t),t}finally{this.isRefreshing=false,this.refreshPromise=null;}})(),this.refreshPromise)}async beforeRequest(){if(ye()){le();return}if(!!!J.getAccessToken()||qe(30))try{await this.refreshToken();}catch(t){envoyFetchTs.logger.warn("Proactive refresh failed:",t);}}async fetch(r,t){let o=t?.requiresAuth!==false,a=r.includes("/auth/refresh");o&&!a&&!t?.skipRefresh&&await this.beforeRequest();let i=Oe(this.baseURL,r),s=async()=>{let n=J.getAccessToken(),d=new Headers(t?.headers);return o&&n&&d.set("Authorization",`Bearer ${n}`),d.has("Content-Type")||d.set("Content-Type","application/json"),fetch(i,{...t,headers:d,credentials:"include"})},c=await s();if(c.status===401&&o&&!a){let n=!!He(),d=qe(30);if(n&&d){envoyFetchTs.logger.log("401 detected and token is expiring/expired, attempting refresh...");try{await this.refreshToken(),c=await s();}catch{envoyFetchTs.logger.error("Retry failed after refresh error");}}}return c}};function K(e){if(!e)return;let{requiresAuth:r,skipRefresh:t,...o}=e,a={};return r!==void 0&&(a.requiresAuth=r),t!==void 0&&(a.skipRefresh=t),{...o,adapterInit:{...o.adapterInit,...a}}}var Re=class{constructor(r,t,o,a){this.interceptor=new Se({baseURL:r,authBaseURL:t,onTokenRefreshed:o}),this.client=envoyFetchTs.createDefaultFetchClient({...a,adapter:this.interceptor.fetch.bind(this.interceptor)});}request(r,t){return this.client.request(r,K(t))}get(r,t){return this.client.get(r,K(t))}post(r,t,o){return this.client.post(r,t,K(o))}put(r,t,o){return this.client.put(r,t,K(o))}patch(r,t,o){return this.client.patch(r,t,K(o))}delete(r,t,o){return this.client.delete(r,t,K(o))}query(r,t){return this.client.query(r,K(t))}};var Y=()=>{if(!y.PROJECT_ID||y.PROJECT_ID.trim()==="")throw new Error("[TRIEOH SDK] Project ID is missing. Please set PUBLIC_TRIEOH_AUTH_PROJECT_ID, NEXT_PUBLIC_TRIEOH_AUTH_PROJECT_ID or VITE_TRIEOH_AUTH_PROJECT_ID.")};var xt=(e,r)=>({isSetupDone:async()=>e.get("/auth/setup",{requiresAuth:false}),setup:async(t,o)=>{y.PROJECT_ID&&Y();let a=`/auth/setup${y.PROJECT_ID?`?project_id=${y.PROJECT_ID}`:""}`,i=await e.post(a,{email:t,password:o},{requiresAuth:false});return i.success&&(W(i.data),r?.onSetup?.(i)),i},login:async(t,o)=>{y.PROJECT_ID&&Y();let a=`/auth/login${y.PROJECT_ID?`?project_id=${y.PROJECT_ID}`:""}`,i=await e.post(a,{email:t,password:o},{requiresAuth:false});return i.success&&(W(i.data),r?.onLogin?.(i)),i},register:async(t,o)=>{let a={requiresAuth:false},i=`/auth/register${y.PROJECT_ID?`?project_id=${y.PROJECT_ID}`:""}`;y.PROJECT_ID&&Y();let s=await e.post(i,{email:t,password:o},a);return s.success&&r?.onRegister?.(s),s},logout:async t=>{let o=`/auth/logout${y.PROJECT_ID?`?project_id=${y.PROJECT_ID}`:""}`,a=await e.post(o);return (a.success||t?.forceLogout)&&le(),a},refresh:async()=>{let t=await e.post("/auth/refresh",void 0,{skipRefresh:true});return t.success&&(W(t.data),r?.onRefresh?.(t)),t},sessions:async()=>e.get("/sessions"),currentSession:async()=>e.get("/sessions/me"),revokeASession:async t=>e.delete(`/sessions/${t}`),revokeSessions:async(t=false)=>{let o=t?"/sessions":"/sessions/others";return e.delete(o)},profile:()=>wt(),sendForgotPassword:async t=>{let o={requiresAuth:false};return y.PROJECT_ID?(Y(),e.post("/account/forgot-password",{email:t,project_id:y.PROJECT_ID},o)):e.post("/account/forgot-password",{email:t},o)},resetPassword:async(t,o)=>{let a=await e.post(`/account/reset-password?token=${t}`,{new_password:o},{requiresAuth:false});return a.success&&r?.onResetPassword?.(a),a},verifyEmail:async t=>{let o=`/account/verify?token=${t}`,a=await e.post(o);return a.success&&r?.onVerify?.(a),a},resendVerifyEmail:async()=>e.post("/account/verify/resend"),health:async()=>e.get("/health",{requiresAuth:false}),authHealth:async()=>e.get("/protected/health")});var kt=react.createContext(null);function Fa({children:e,baseURL:r,projectId:t,isProjectMode:o=true,fallback:a,waitSession:i=true,clientConfig:s,onLogin:c,onSetup:n,onResetPassword:d,onRegister:p,onVerify:l,onRefresh:u}){let g=react.useRef(false),{isAuthenticated:f,isInitializing:b}=react.useSyncExternalStore(E.subscribe,E.getSnapshot,E.getServerSnapshot);react.useEffect(()=>{bt({...t?{PROJECT_ID:t}:{},...r?{BASE_URL:r}:{}});},[t,r]);let P=react.useCallback(v=>{E.set({isAuthenticated:!!v.access_data,isInitializing:false}),u?.();},[u]),x=react.useMemo(()=>new Re(r,void 0,P,s),[r,P,s]),T=react.useMemo(()=>xt(x,{onLogin:c,onSetup:n,onResetPassword:d,onRegister:p,onVerify:l,onRefresh:u}),[x,c,n,d,p,l,u]);react.useEffect(()=>{o&&Y(),(async()=>{if(!g.current){if(g.current=true,ne()){E.set({isAuthenticated:true,isInitializing:false});return}if(ye()){E.reset(),E.set({isInitializing:false});return}envoyFetchTs.logger.log("No cached claims, attempting silent refresh...");try{await x.interceptor.refreshToken(),envoyFetchTs.logger.log("Session restored.");}catch{E.reset(),envoyFetchTs.logger.warn("Could not restore session (offline?).");}finally{E.set({isInitializing:false});}}})();},[T,o]);let $=react.useMemo(()=>({auth:T,isAuthenticated:f,isInitializing:b,isProjectMode:o}),[T,f,b,o]);return i&&b?a??null:jsxRuntime.jsx(kt.Provider,{value:$,children:e})}function h(){let e=react.useContext(kt);if(!e)throw new Error("useAuth must be used inside <AuthProvider>");return e}function Ye(e,{insertAt:r}={}){if(typeof document>"u")return;let t=document.head||document.getElementsByTagName("head")[0],o=document.createElement("style");o.type="text/css",r==="top"&&t.firstChild?t.insertBefore(o,t.firstChild):t.appendChild(o),o.styleSheet?o.styleSheet.cssText=e:o.appendChild(document.createTextNode(e));}Ye(`/*! tailwindcss v4.3.0 | MIT License | https://tailwindcss.com */@layer properties;@layer theme,base,components,utilities;@layer theme,base,components,utilities;@layer theme{:root,:host{--font-sans: var(--font-sans, "Inter", sans-serif);--font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;--color-green-500: oklch(72.3% .219 149.579);--spacing: .25rem;--container-md: 28rem;--text-xs: .75rem;--text-xs--line-height: calc(1 / .75);--text-sm: .875rem;--text-sm--line-height: calc(1.25 / .875);--text-base: 1rem;--text-base--line-height: 1.5 ;--text-lg: 1.125rem;--text-lg--line-height: calc(1.75 / 1.125);--text-xl: 1.25rem;--text-xl--line-height: calc(1.75 / 1.25);--text-2xl: 1.5rem;--text-2xl--line-height: calc(2 / 1.5);--text-3xl: 1.875rem;--text-3xl--line-height: 1.2 ;--text-4xl: 2.25rem;--text-4xl--line-height: calc(2.5 / 2.25);--font-weight-extralight: 200;--font-weight-light: 300;--font-weight-normal: 400;--font-weight-medium: 500;--font-weight-semibold: 600;--font-weight-bold: 700;--tracking-tighter: -.05em;--tracking-tight: -.025em;--tracking-normal: 0em;--tracking-wider: .05em;--tracking-widest: .1em;--radius-sm: calc(var(--radius, .625rem) - 4px);--radius-md: calc(var(--radius, .625rem) - 2px);--radius-lg: var(--radius, .625rem);--radius-2xl: 1rem;--ease-out: cubic-bezier(0, 0, .2, 1);--ease-in-out: cubic-bezier(.4, 0, .2, 1);--animate-spin: spin 1s linear infinite;--blur-sm: 8px;--blur-3xl: 64px;--default-transition-duration: .15s;--default-transition-timing-function: cubic-bezier(.4, 0, .2, 1);--default-font-family: var(--font-sans);--default-mono-font-family: var(--font-mono);--color-background: var(--background, oklch(.9702 0 0));--color-foreground: var(--foreground, oklch(.1944 .0051 248.09));--color-primary: var(--primary, oklch(.7975 .1018 262.7));--color-primary-foreground: var(--primary-foreground, oklch(.9702 0 0));--color-secondary: var(--secondary, oklch(.1139 .0789 264.05));--color-secondary-foreground: var(--secondary-foreground, oklch(.9702 0 0));--color-muted: var(--muted, oklch(.9569 .0026 248.09));--color-muted-foreground: var(--muted-foreground, oklch(.5278 0 0));--color-border: var(--border, oklch(.869 .0093 248.09));--color-input: var(--input, oklch(.9145 .0062 248.09));--color-destructive: var(--destructive, oklch(.6373 .1718 28.92));--color-destructive-foreground: var(--destructive-foreground, oklch(.9851 0 0));--color-ring: var(--ring, oklch(.7975 .1018 262.7));--color-accent: var(--accent, oklch(.9326 .0313 262.7));--color-accent-foreground: var(--accent-foreground, oklch(.1944 .0051 248.09));--radius-full: 9999px}}@layer base{*,:after,:before,::backdrop,::file-selector-button{box-sizing:border-box;margin:0;padding:0;border:0 solid}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;tab-size:4;font-family:var(--default-font-family, ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings, normal);font-variation-settings:var(--default-font-variation-settings, normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings, normal);font-variation-settings:var(--default-mono-font-variation-settings, normal);font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea,::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;border-radius:0;background-color:transparent;opacity:1}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not (-webkit-appearance: -apple-pay-button)) or (contain-intrinsic-size: 1px){::placeholder{color:currentcolor;@supports (color: color-mix(in lab,red,red)){color:color-mix(in oklab,currentcolor 50%,transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit,::-webkit-datetime-edit-year-field,::-webkit-datetime-edit-month-field,::-webkit-datetime-edit-day-field,::-webkit-datetime-edit-hour-field,::-webkit-datetime-edit-minute-field,::-webkit-datetime-edit-second-field,::-webkit-datetime-edit-millisecond-field,::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]),::file-selector-button{appearance:button}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}}@layer utilities{.\\@container{container-type:inline-size}.pointer-events-none{pointer-events:none}.button-loading{&:after{content:"";position:absolute;top:0;left:-150%;width:150%;height:100%;background:linear-gradient(120deg,transparent 0%,var(--color-foreground) 40%,transparent 80%);@supports (color: color-mix(in lab,red,red)){background:linear-gradient(120deg,transparent 0%,color-mix(in oklab,var(--color-foreground) 40%,white 15%) 40%,transparent 80%)}animation:shine 1.5s infinite}}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.inset-0{inset:calc(var(--spacing) * 0)}.top-0{top:calc(var(--spacing) * 0)}.top-1\\.5{top:calc(var(--spacing) * 1.5)}.top-1\\/2{top:50%}.top-\\[-10\\%\\]{top:-10%}.right-0{right:calc(var(--spacing) * 0)}.right-3{right:calc(var(--spacing) * 3)}.right-\\[-10\\%\\]{right:-10%}.bottom-\\[-10\\%\\]{bottom:-10%}.left-3\\.5{left:calc(var(--spacing) * 3.5)}.left-\\[-10\\%\\]{left:-10%}.z-10{z-index:10}.m-0{margin:calc(var(--spacing) * 0)}.m-2{margin:calc(var(--spacing) * 2)}.m-\\[0\\.125rem\\]{margin:.125rem}.mx-auto{margin-inline:auto}.mt-2{margin-top:calc(var(--spacing) * 2)}.mt-4{margin-top:calc(var(--spacing) * 4)}.mt-8{margin-top:calc(var(--spacing) * 8)}.mb-1{margin-bottom:calc(var(--spacing) * 1)}.mb-2{margin-bottom:calc(var(--spacing) * 2)}.mb-2\\.5{margin-bottom:calc(var(--spacing) * 2.5)}.mb-3{margin-bottom:calc(var(--spacing) * 3)}.mb-4{margin-bottom:calc(var(--spacing) * 4)}.mb-6{margin-bottom:calc(var(--spacing) * 6)}.mb-10{margin-bottom:calc(var(--spacing) * 10)}.box-border{box-sizing:border-box}.block{display:block}.contents{display:contents}.flex{display:flex}.inline-block{display:inline-block}.inline-flex{display:inline-flex}.h-1{height:calc(var(--spacing) * 1)}.h-4{height:calc(var(--spacing) * 4)}.h-5{height:calc(var(--spacing) * 5)}.h-9{height:calc(var(--spacing) * 9)}.h-10{height:calc(var(--spacing) * 10)}.h-11{height:calc(var(--spacing) * 11)}.h-12{height:calc(var(--spacing) * 12)}.h-13{height:calc(var(--spacing) * 13)}.h-16{height:calc(var(--spacing) * 16)}.h-\\[40\\%\\]{height:40%}.h-auto{height:auto}.h-full{height:100%}.max-h-\\[max\\(75dvh\\,32rem\\)\\]{max-height:max(75dvh,32rem)}.min-h-80{min-height:calc(var(--spacing) * 80)}.min-h-screen{min-height:100vh}.w-4{width:calc(var(--spacing) * 4)}.w-5{width:calc(var(--spacing) * 5)}.w-10{width:calc(var(--spacing) * 10)}.w-12{width:calc(var(--spacing) * 12)}.w-16{width:calc(var(--spacing) * 16)}.w-\\[40\\%\\]{width:40%}.w-full{width:100%}.max-w-56{max-width:calc(var(--spacing) * 56)}.max-w-100{max-width:calc(var(--spacing) * 100)}.max-w-120{max-width:calc(var(--spacing) * 120)}.max-w-\\[320px\\]{max-width:320px}.max-w-md{max-width:var(--container-md)}.min-w-0{min-width:calc(var(--spacing) * 0)}.min-w-40{min-width:calc(var(--spacing) * 40)}.min-w-60{min-width:calc(var(--spacing) * 60)}.min-w-\\[20rem\\]{min-width:20rem}.flex-1{flex:1}.flex-\\[0_1_auto\\]{flex:0 1 auto}.flex-\\[1_1_auto\\]{flex:1 1 auto}.shrink-0{flex-shrink:0}.-translate-y-1\\/2{--tw-translate-y: -50% ;translate:var(--tw-translate-x) var(--tw-translate-y)}.animate-spin{animation:var(--animate-spin)}.cursor-pointer{cursor:pointer}.appearance-none{appearance:none}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-center{align-items:center}.items-end{align-items:flex-end}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.justify-end{justify-content:flex-end}.gap-1{gap:calc(var(--spacing) * 1)}.gap-1\\.5{gap:calc(var(--spacing) * 1.5)}.gap-2{gap:calc(var(--spacing) * 2)}.gap-2\\.5{gap:calc(var(--spacing) * 2.5)}.gap-4{gap:calc(var(--spacing) * 4)}.gap-5{gap:calc(var(--spacing) * 5)}.gap-6{gap:calc(var(--spacing) * 6)}.gap-8{gap:calc(var(--spacing) * 8)}.space-y-1{:where(&>:not(:last-child)){--tw-space-y-reverse: 0;margin-block-start:calc(calc(var(--spacing) * 1) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 1) * calc(1 - var(--tw-space-y-reverse)))}}.space-y-4{:where(&>:not(:last-child)){--tw-space-y-reverse: 0;margin-block-start:calc(calc(var(--spacing) * 4) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 4) * calc(1 - var(--tw-space-y-reverse)))}}.space-y-5{:where(&>:not(:last-child)){--tw-space-y-reverse: 0;margin-block-start:calc(calc(var(--spacing) * 5) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 5) * calc(1 - var(--tw-space-y-reverse)))}}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.rounded-2xl{border-radius:var(--radius-2xl)}.rounded-\\[14px\\]{border-radius:14px}.rounded-full{border-radius:var(--radius-full)}.rounded-lg{border-radius:var(--radius-lg)}.rounded-md{border-radius:var(--radius-md)}.rounded-sm{border-radius:var(--radius-sm)}.border{border-style:var(--tw-border-style);border-width:1px}.border-2{border-style:var(--tw-border-style);border-width:2px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-b-2{border-bottom-style:var(--tw-border-style);border-bottom-width:2px}.border-none{--tw-border-style: none;border-style:none}.border-border{border-color:var(--color-border)}.border-border\\/40{border-color:var(--color-border);@supports (color: color-mix(in lab,red,red)){border-color:color-mix(in oklab,var(--color-border) 40%,transparent)}}.border-border\\/50{border-color:var(--color-border);@supports (color: color-mix(in lab,red,red)){border-color:color-mix(in oklab,var(--color-border) 50%,transparent)}}.border-destructive\\!{border-color:var(--color-destructive)!important}.border-destructive\\/50{border-color:var(--color-destructive);@supports (color: color-mix(in lab,red,red)){border-color:color-mix(in oklab,var(--color-destructive) 50%,transparent)}}.border-foreground{border-color:var(--color-foreground)}.border-input{border-color:var(--color-input)}.border-primary{border-color:var(--color-primary)}.border-secondary\\/20{border-color:var(--color-secondary);@supports (color: color-mix(in lab,red,red)){border-color:color-mix(in oklab,var(--color-secondary) 20%,transparent)}}.bg-background{background-color:var(--color-background)}.bg-destructive{background-color:var(--color-destructive)}.bg-destructive\\/5{background-color:var(--color-destructive);@supports (color: color-mix(in lab,red,red)){background-color:color-mix(in oklab,var(--color-destructive) 5%,transparent)}}.bg-foreground\\/10{background-color:var(--color-foreground);@supports (color: color-mix(in lab,red,red)){background-color:color-mix(in oklab,var(--color-foreground) 10%,transparent)}}.bg-muted\\/30{background-color:var(--color-muted);@supports (color: color-mix(in lab,red,red)){background-color:color-mix(in oklab,var(--color-muted) 30%,transparent)}}.bg-muted\\/40{background-color:var(--color-muted);@supports (color: color-mix(in lab,red,red)){background-color:color-mix(in oklab,var(--color-muted) 40%,transparent)}}.bg-muted\\/50{background-color:var(--color-muted);@supports (color: color-mix(in lab,red,red)){background-color:color-mix(in oklab,var(--color-muted) 50%,transparent)}}.bg-primary{background-color:var(--color-primary)}.bg-primary\\/10{background-color:var(--color-primary);@supports (color: color-mix(in lab,red,red)){background-color:color-mix(in oklab,var(--color-primary) 10%,transparent)}}.bg-primary\\/20{background-color:var(--color-primary);@supports (color: color-mix(in lab,red,red)){background-color:color-mix(in oklab,var(--color-primary) 20%,transparent)}}.bg-primary\\/40{background-color:var(--color-primary);@supports (color: color-mix(in lab,red,red)){background-color:color-mix(in oklab,var(--color-primary) 40%,transparent)}}.bg-secondary{background-color:var(--color-secondary)}.bg-transparent{background-color:transparent}.p-1{padding:calc(var(--spacing) * 1)}.p-2{padding:calc(var(--spacing) * 2)}.p-2\\.5{padding:calc(var(--spacing) * 2.5)}.p-6{padding:calc(var(--spacing) * 6)}.p-\\[1\\.5rem_0\\.5rem\\]{padding:1.5rem .5rem}.p-\\[1\\.25rem_0\\.75rem\\]{padding:1.25rem .75rem}.p-\\[1\\.25rem_1\\.5rem\\]{padding:1.25rem 1.5rem}.p-\\[1rem_0\\]{padding:1rem 0}.px-1{padding-inline:calc(var(--spacing) * 1)}.px-2\\.5{padding-inline:calc(var(--spacing) * 2.5)}.px-3{padding-inline:calc(var(--spacing) * 3)}.px-3\\.5{padding-inline:calc(var(--spacing) * 3.5)}.px-4{padding-inline:calc(var(--spacing) * 4)}.px-6{padding-inline:calc(var(--spacing) * 6)}.px-8{padding-inline:calc(var(--spacing) * 8)}.py-0\\.5{padding-block:calc(var(--spacing) * .5)}.py-1{padding-block:calc(var(--spacing) * 1)}.py-1\\.5{padding-block:calc(var(--spacing) * 1.5)}.py-2{padding-block:calc(var(--spacing) * 2)}.py-4{padding-block:calc(var(--spacing) * 4)}.py-px{padding-block:1px}.pt-4{padding-top:calc(var(--spacing) * 4)}.pr-10{padding-right:calc(var(--spacing) * 10)}.pb-1{padding-bottom:calc(var(--spacing) * 1)}.text-center{text-align:center}.font-sans{font-family:var(--font-sans)}.text-2xl{font-size:var(--text-2xl);line-height:var(--tw-leading, var(--text-2xl--line-height))}.text-3xl{font-size:var(--text-3xl);line-height:var(--tw-leading, var(--text-3xl--line-height))}.text-4xl{font-size:var(--text-4xl);line-height:var(--tw-leading, var(--text-4xl--line-height))}.text-base{font-size:var(--text-base);line-height:var(--tw-leading, var(--text-base--line-height))}.text-lg{font-size:var(--text-lg);line-height:var(--tw-leading, var(--text-lg--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading, var(--text-sm--line-height))}.text-xl{font-size:var(--text-xl);line-height:var(--tw-leading, var(--text-xl--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading, var(--text-xs--line-height))}.text-\\[10px\\]{font-size:10px}.text-\\[11px\\]{font-size:11px}.leading-none{--tw-leading: 1;line-height:1}.font-bold{--tw-font-weight: var(--font-weight-bold);font-weight:var(--font-weight-bold)}.font-extralight{--tw-font-weight: var(--font-weight-extralight);font-weight:var(--font-weight-extralight)}.font-light{--tw-font-weight: var(--font-weight-light);font-weight:var(--font-weight-light)}.font-medium{--tw-font-weight: var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-normal{--tw-font-weight: var(--font-weight-normal);font-weight:var(--font-weight-normal)}.font-semibold{--tw-font-weight: var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.tracking-tight{--tw-tracking: var(--tracking-tight);letter-spacing:var(--tracking-tight)}.tracking-tighter{--tw-tracking: var(--tracking-tighter);letter-spacing:var(--tracking-tighter)}.tracking-wider{--tw-tracking: var(--tracking-wider);letter-spacing:var(--tracking-wider)}.tracking-widest{--tw-tracking: var(--tracking-widest);letter-spacing:var(--tracking-widest)}.whitespace-nowrap{white-space:nowrap}.text-destructive{color:var(--color-destructive)}.text-destructive-foreground{color:var(--color-destructive-foreground)}.text-destructive\\/80{color:var(--color-destructive);@supports (color: color-mix(in lab,red,red)){color:color-mix(in oklab,var(--color-destructive) 80%,transparent)}}.text-foreground{color:var(--color-foreground)}.text-green-500{color:var(--color-green-500)}.text-muted-foreground{color:var(--color-muted-foreground)}.text-primary{color:var(--color-primary)}.text-primary-foreground{color:var(--color-primary-foreground)}.text-primary\\/70{color:var(--color-primary);@supports (color: color-mix(in lab,red,red)){color:color-mix(in oklab,var(--color-primary) 70%,transparent)}}.text-secondary-foreground{color:var(--color-secondary-foreground)}.uppercase{text-transform:uppercase}.line-through{text-decoration-line:line-through}.underline-offset-4{text-underline-offset:4px}.antialiased{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.opacity-50{opacity:50%}.opacity-60{opacity:60%}.opacity-95{opacity:95%}.opacity-100{opacity:100%}.shadow-\\[0_0\\.25rem_0\\.25rem_0_rgba\\(0\\,0\\,0\\,0\\.25\\)\\]{--tw-shadow: 0 .25rem .25rem 0 var(--tw-shadow-color, rgba(0,0,0,.25));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-\\[0_0\\.25rem_1rem_rgba\\(0\\,0\\,0\\,0\\.25\\)\\]{--tw-shadow: 0 .25rem 1rem var(--tw-shadow-color, rgba(0,0,0,.25));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-lg{--tw-shadow: 0 10px 15px -3px var(--tw-shadow-color, rgb(0 0 0 / .1)), 0 4px 6px -4px var(--tw-shadow-color, rgb(0 0 0 / .1));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-none\\!{--tw-shadow: 0 0 #0000 !important;box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)!important}.shadow-sm{--tw-shadow: 0 1px 3px 0 var(--tw-shadow-color, rgb(0 0 0 / .1)), 0 1px 2px -1px var(--tw-shadow-color, rgb(0 0 0 / .1));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.ring-1{--tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-primary\\/10{--tw-shadow-color: var(--color-primary);@supports (color: color-mix(in lab,red,red)){--tw-shadow-color: color-mix(in oklab, color-mix(in oklab, var(--color-primary) 10%, transparent) var(--tw-shadow-alpha), transparent)}}.ring-destructive\\/20{--tw-ring-color: var(--color-destructive);@supports (color: color-mix(in lab,red,red)){--tw-ring-color: color-mix(in oklab, var(--color-destructive) 20%, transparent)}}.outline{outline-style:var(--tw-outline-style);outline-width:1px}.blur-3xl{--tw-blur: blur(var(--blur-3xl));filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.backdrop-blur-sm{--tw-backdrop-blur: blur(var(--blur-sm));-webkit-backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-\\[color\\,text-decoration\\,opacity\\]{transition-property:color,text-decoration,opacity;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-\\[opacity\\,transform\\]{transition-property:opacity,transform;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-all{transition-property:all;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-opacity{transition-property:opacity;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-transform{transition-property:transform,translate,scale,rotate;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.duration-150{--tw-duration: .15s;transition-duration:.15s}.duration-200{--tw-duration: .2s;transition-duration:.2s}.duration-500{--tw-duration: .5s;transition-duration:.5s}.duration-\\[120ms\\]{--tw-duration: .12s;transition-duration:.12s}.ease-in-out{--tw-ease: var(--ease-in-out);transition-timing-function:var(--ease-in-out)}.ease-out{--tw-ease: var(--ease-out);transition-timing-function:var(--ease-out)}.outline-none{--tw-outline-style: none;outline-style:none}.select-none{-webkit-user-select:none;user-select:none}.group-hover\\:translate-x-1{&:is(:where(.group):hover *){@media(hover:hover){--tw-translate-x: calc(var(--spacing) * 1);translate:var(--tw-translate-x) var(--tw-translate-y)}}}.peer-placeholder-shown\\:top-3\\.5{&:is(:where(.peer):placeholder-shown~*){top:calc(var(--spacing) * 3.5)}}.peer-placeholder-shown\\:text-\\[15px\\]{&:is(:where(.peer):placeholder-shown~*){font-size:15px}}.peer-placeholder-shown\\:font-normal{&:is(:where(.peer):placeholder-shown~*){--tw-font-weight: var(--font-weight-normal);font-weight:var(--font-weight-normal)}}.peer-placeholder-shown\\:tracking-normal{&:is(:where(.peer):placeholder-shown~*){--tw-tracking: var(--tracking-normal);letter-spacing:var(--tracking-normal)}}.peer-placeholder-shown\\:text-destructive\\/60{&:is(:where(.peer):placeholder-shown~*){color:var(--color-destructive);@supports (color: color-mix(in lab,red,red)){color:color-mix(in oklab,var(--color-destructive) 60%,transparent)}}}.peer-placeholder-shown\\:text-muted-foreground{&:is(:where(.peer):placeholder-shown~*){color:var(--color-muted-foreground)}}.peer-focus\\:top-1\\.5{&:is(:where(.peer):focus~*){top:calc(var(--spacing) * 1.5)}}.peer-focus\\:text-\\[10px\\]{&:is(:where(.peer):focus~*){font-size:10px}}.peer-focus\\:font-semibold{&:is(:where(.peer):focus~*){--tw-font-weight: var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}}.peer-focus\\:tracking-wider{&:is(:where(.peer):focus~*){--tw-tracking: var(--tracking-wider);letter-spacing:var(--tracking-wider)}}.peer-focus\\:text-destructive\\/80{&:is(:where(.peer):focus~*){color:var(--color-destructive);@supports (color: color-mix(in lab,red,red)){color:color-mix(in oklab,var(--color-destructive) 80%,transparent)}}}.peer-focus\\:text-primary\\/70{&:is(:where(.peer):focus~*){color:var(--color-primary);@supports (color: color-mix(in lab,red,red)){color:color-mix(in oklab,var(--color-primary) 70%,transparent)}}}.selection\\:bg-primary\\/10{& *::selection{background-color:var(--color-primary);@supports (color: color-mix(in lab,red,red)){background-color:color-mix(in oklab,var(--color-primary) 10%,transparent)}}&::selection{background-color:var(--color-primary);@supports (color: color-mix(in lab,red,red)){background-color:color-mix(in oklab,var(--color-primary) 10%,transparent)}}}.selection\\:text-primary{& *::selection{color:var(--color-primary)}&::selection{color:var(--color-primary)}}.placeholder\\:text-transparent{&::placeholder{color:transparent}}.hover\\:scale-\\[1\\.02\\]{&:hover{@media(hover:hover){scale:1.02}}}.hover\\:scale-\\[1\\.05\\]{&:hover{@media(hover:hover){scale:1.05}}}.hover\\:bg-accent{&:hover{@media(hover:hover){background-color:var(--color-accent)}}}.hover\\:text-accent-foreground{&:hover{@media(hover:hover){color:var(--color-accent-foreground)}}}.hover\\:text-primary\\/70{&:hover{@media(hover:hover){color:var(--color-primary);@supports (color: color-mix(in lab,red,red)){color:color-mix(in oklab,var(--color-primary) 70%,transparent)}}}}.hover\\:underline{&:hover{@media(hover:hover){text-decoration-line:underline}}}.hover\\:opacity-80{&:hover{@media(hover:hover){opacity:80%}}}.hover\\:opacity-90{&:hover{@media(hover:hover){opacity:90%}}}.hover\\:opacity-100{&:hover{@media(hover:hover){opacity:100%}}}.focus\\:bg-muted\\/60{&:focus{background-color:var(--color-muted);@supports (color: color-mix(in lab,red,red)){background-color:color-mix(in oklab,var(--color-muted) 60%,transparent)}}}.focus\\:outline-none{&:focus{--tw-outline-style: none;outline-style:none}}.focus-visible\\:ring-0{&:focus-visible{--tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(0px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}}.focus-visible\\:ring-1{&:focus-visible{--tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}}.focus-visible\\:ring-ring{&:focus-visible{--tw-ring-color: var(--color-ring)}}.focus-visible\\:outline-none{&:focus-visible{--tw-outline-style: none;outline-style:none}}.active\\:scale-\\[0\\.95\\]{&:active{scale:.95}}.active\\:scale-\\[0\\.98\\]{&:active{scale:.98}}.active\\:scale-\\[0\\.99\\]{&:active{scale:.99}}.disabled\\:pointer-events-none{&:disabled{pointer-events:none}}.disabled\\:transform-none\\!{&:disabled{transform:none!important}}.disabled\\:cursor-not-allowed{&:disabled{cursor:not-allowed}}.disabled\\:opacity-50{&:disabled{opacity:50%}}.disabled\\:opacity-60{&:disabled{opacity:60%}}.\\@\\[640px\\]\\:flex-row{@container (width >= 640px){flex-direction:row}}.\\@\\[640px\\]\\:items-center{@container (width >= 640px){align-items:center}}.\\@\\[640px\\]\\:justify-between{@container (width >= 640px){justify-content:space-between}}.\\@\\[640px\\]\\:gap-2{@container (width >= 640px){gap:calc(var(--spacing) * 2)}}.\\@\\[640px\\]\\:gap-4{@container (width >= 640px){gap:calc(var(--spacing) * 4)}}.\\@\\[640px\\]\\:gap-8{@container (width >= 640px){gap:calc(var(--spacing) * 8)}}.\\@\\[640px\\]\\:text-left{@container (width >= 640px){text-align:left}}}@import url(https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap);@layer base{button:not(:disabled),[role=button]:not(:disabled){cursor:pointer}}@property --tw-translate-x{syntax: "*"; inherits: false; initial-value: 0;}@property --tw-translate-y{syntax: "*"; inherits: false; initial-value: 0;}@property --tw-translate-z{syntax: "*"; inherits: false; initial-value: 0;}@property --tw-space-y-reverse{syntax: "*"; inherits: false; initial-value: 0;}@property --tw-border-style{syntax: "*"; inherits: false; initial-value: solid;}@property --tw-leading{syntax: "*"; inherits: false;}@property --tw-font-weight{syntax: "*"; inherits: false;}@property --tw-tracking{syntax: "*"; inherits: false;}@property --tw-shadow{syntax: "*"; inherits: false; initial-value: 0 0 #0000;}@property --tw-shadow-color{syntax: "*"; inherits: false;}@property --tw-shadow-alpha{syntax: "<percentage>"; inherits: false; initial-value: 100%;}@property --tw-inset-shadow{syntax: "*"; inherits: false; initial-value: 0 0 #0000;}@property --tw-inset-shadow-color{syntax: "*"; inherits: false;}@property --tw-inset-shadow-alpha{syntax: "<percentage>"; inherits: false; initial-value: 100%;}@property --tw-ring-color{syntax: "*"; inherits: false;}@property --tw-ring-shadow{syntax: "*"; inherits: false; initial-value: 0 0 #0000;}@property --tw-inset-ring-color{syntax: "*"; inherits: false;}@property --tw-inset-ring-shadow{syntax: "*"; inherits: false; initial-value: 0 0 #0000;}@property --tw-ring-inset{syntax: "*"; inherits: false;}@property --tw-ring-offset-width{syntax: "<length>"; inherits: false; initial-value: 0px;}@property --tw-ring-offset-color{syntax: "*"; inherits: false; initial-value: #fff;}@property --tw-ring-offset-shadow{syntax: "*"; inherits: false; initial-value: 0 0 #0000;}@property --tw-outline-style{syntax: "*"; inherits: false; initial-value: solid;}@property --tw-blur{syntax: "*"; inherits: false;}@property --tw-brightness{syntax: "*"; inherits: false;}@property --tw-contrast{syntax: "*"; inherits: false;}@property --tw-grayscale{syntax: "*"; inherits: false;}@property --tw-hue-rotate{syntax: "*"; inherits: false;}@property --tw-invert{syntax: "*"; inherits: false;}@property --tw-opacity{syntax: "*"; inherits: false;}@property --tw-saturate{syntax: "*"; inherits: false;}@property --tw-sepia{syntax: "*"; inherits: false;}@property --tw-drop-shadow{syntax: "*"; inherits: false;}@property --tw-drop-shadow-color{syntax: "*"; inherits: false;}@property --tw-drop-shadow-alpha{syntax: "<percentage>"; inherits: false; initial-value: 100%;}@property --tw-drop-shadow-size{syntax: "*"; inherits: false;}@property --tw-backdrop-blur{syntax: "*"; inherits: false;}@property --tw-backdrop-brightness{syntax: "*"; inherits: false;}@property --tw-backdrop-contrast{syntax: "*"; inherits: false;}@property --tw-backdrop-grayscale{syntax: "*"; inherits: false;}@property --tw-backdrop-hue-rotate{syntax: "*"; inherits: false;}@property --tw-backdrop-invert{syntax: "*"; inherits: false;}@property --tw-backdrop-opacity{syntax: "*"; inherits: false;}@property --tw-backdrop-saturate{syntax: "*"; inherits: false;}@property --tw-backdrop-sepia{syntax: "*"; inherits: false;}@property --tw-duration{syntax: "*"; inherits: false;}@property --tw-ease{syntax: "*"; inherits: false;}@keyframes spin{to{transform:rotate(360deg)}}@keyframes shine{0%{left:-150%}to{left:150%}}@layer properties{@supports ((-webkit-hyphens: none) and (not (margin-trim: inline))) or ((-moz-orient: inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-translate-x: 0;--tw-translate-y: 0;--tw-translate-z: 0;--tw-space-y-reverse: 0;--tw-border-style: solid;--tw-leading: initial;--tw-font-weight: initial;--tw-tracking: initial;--tw-shadow: 0 0 #0000;--tw-shadow-color: initial;--tw-shadow-alpha: 100%;--tw-inset-shadow: 0 0 #0000;--tw-inset-shadow-color: initial;--tw-inset-shadow-alpha: 100%;--tw-ring-color: initial;--tw-ring-shadow: 0 0 #0000;--tw-inset-ring-color: initial;--tw-inset-ring-shadow: 0 0 #0000;--tw-ring-inset: initial;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-offset-shadow: 0 0 #0000;--tw-outline-style: solid;--tw-blur: initial;--tw-brightness: initial;--tw-contrast: initial;--tw-grayscale: initial;--tw-hue-rotate: initial;--tw-invert: initial;--tw-opacity: initial;--tw-saturate: initial;--tw-sepia: initial;--tw-drop-shadow: initial;--tw-drop-shadow-color: initial;--tw-drop-shadow-alpha: 100%;--tw-drop-shadow-size: initial;--tw-backdrop-blur: initial;--tw-backdrop-brightness: initial;--tw-backdrop-contrast: initial;--tw-backdrop-grayscale: initial;--tw-backdrop-hue-rotate: initial;--tw-backdrop-invert: initial;--tw-backdrop-opacity: initial;--tw-backdrop-saturate: initial;--tw-backdrop-sepia: initial;--tw-duration: initial;--tw-ease: initial}}}
|
|
2
|
+
`);function A({name:e,label:r,placeholder:t,type:o="text",value:a,onValueChange:i,onBlur:s,autoComplete:c,rulesStatus:n=[],submitted:d=false,inputRef:p}){let[l,u]=react.useState(false),g=n.some(f=>!f.passed);return jsxRuntime.jsxs("div",{className:"font-sans relative w-full flex flex-col gap-1 text-foreground",children:[jsxRuntime.jsx("label",{htmlFor:e,className:"text-base font-semibold",children:r}),jsxRuntime.jsxs("div",{className:`flex justify-between items-center px-2.5 py-px gap-2.5 border-b-2 border-foreground ${g&&d?"border-destructive!":""}`,children:[jsxRuntime.jsx("input",{type:l?"text":o,name:e,id:e,placeholder:t,value:a,onChange:f=>i&&i(f.target.value),onBlur:s,autoComplete:c,"aria-invalid":g&&d,ref:p,className:"min-w-40 flex-1 text-base font-light text-foreground appearance-none bg-transparent outline-none border-none shadow-none! py-0.5"}),o==="password"&&(l?jsxRuntime.jsx(lucideReact.EyeOff,{className:"cursor-pointer shrink-0 select-none",size:24,onClick:()=>u(false)}):jsxRuntime.jsx(lucideReact.Eye,{className:"cursor-pointer shrink-0 select-none",size:24,onClick:()=>u(true)}))]}),jsxRuntime.jsx("div",{className:"text-xs text-muted-foreground transition-opacity duration-200 ease-in-out",children:n.map((f,b)=>{let P=["transition-[color,text-decoration,opacity] duration-[120ms] ease opacity-95 m-[0.125rem]",f.passed?"line-through opacity-60 text-green-500":"",!f.passed&&d?"text-destructive font-semibold opacity-100":""].filter(Boolean).join(" ");return jsxRuntime.jsx("p",{className:P,children:f.message},f.id??b)})})]})}function C({label:e,onSubmit:r,loading:t}){return jsxRuntime.jsx("button",{type:"submit",onClick:r,disabled:t,className:`font-sans w-full h-13 text-xl font-semibold outline-none bg-transparent relative overflow-hidden min-w-40 shrink-0 border-2 border-foreground text-foreground cursor-pointer px-6 transition-transform duration-500 rounded-lg hover:scale-[1.02] active:scale-[0.99] disabled:opacity-60 disabled:cursor-not-allowed disabled:transform-none! ${t?"button-loading":""}`,children:e})}function _({mainText:e,subText:r}){return jsxRuntime.jsxs("div",{className:"font-sans flex flex-col items-center",children:[jsxRuntime.jsx("div",{className:"flex justify-center items-center p-2 bg-foreground/10 rounded-full mb-2.5",children:jsxRuntime.jsx(lucideReact.User,{className:"w-16 h-16 p-2.5 bg-background rounded-full shadow-[0_0.25rem_1rem_rgba(0,0,0,0.25)]",size:70})}),jsxRuntime.jsx("h3",{className:"text-center text-xl font-medium m-0",children:e}),jsxRuntime.jsx("span",{className:"text-center text-sm font-light opacity-60",children:r})]})}function I(e,r){return e.map(t=>({id:t.id,message:t.message,passed:!!t.test(r)}))}function or({onSuccess:e,onFailed:r,signUpRedirect:t,forgotPasswordRedirect:o,emailRules:a}){let[i,s]=react.useState(""),[c,n]=react.useState(""),[d,p]=react.useState(false),[l,u]=react.useState(false),g=react.useRef(null),f=react.useRef(null),{auth:b}=h(),P={email:a||[{message:"Digite um e-mail v\xE1lido, ex: exemplo@dominio.com",test:v=>/\S+@\S+\.\S+/.test(v)}],password:[]},x=I(P.email,i),T=I(P.password,c);return jsxRuntime.jsxs("form",{className:"font-sans flex flex-col w-full max-w-120 min-w-60 max-h-[max(75dvh,32rem)] overflow-hidden gap-5 items-center bg-background text-foreground p-[1.25rem_1.5rem] shadow-[0_0.25rem_0.25rem_0_rgba(0,0,0,0.25)] transition-transform duration-150 ease-in-out rounded-lg",children:[jsxRuntime.jsx(_,{mainText:"Fa\xE7a login na sua conta",subText:"Insira seus dados para fazer login"}),jsxRuntime.jsxs("div",{className:"w-full flex flex-col gap-2.5 flex-[1_1_auto] overflow-y-auto mb-2",children:[jsxRuntime.jsx(A,{label:"Email",name:"email",placeholder:"teste@gmail.com",autoComplete:"email",type:"email",value:i,onValueChange:s,inputRef:g,rulesStatus:x,submitted:d}),jsxRuntime.jsx(A,{label:"Senha",name:"password",placeholder:"**********",autoComplete:"current-password",type:"password",value:c,onValueChange:n,inputRef:f,rulesStatus:T,submitted:d})]}),jsxRuntime.jsx(C,{label:"Entrar",onSubmit:async v=>{v.preventDefault(),p(true);let G=x.some(w=>!w.passed),Q=T.some(w=>!w.passed);if(G){g.current?.focus();return}if(Q){f.current?.focus();return}u(true);let z=await b.login(i,c);z.success?e&&await e(z.message):r&&await r(z.message,z.trace),u(false);},loading:l}),o&&jsxRuntime.jsx("span",{className:"text-sm font-semibold text-center cursor-pointer",children:jsxRuntime.jsx("span",{className:"cursor-pointer text-primary transition-colors duration-200 hover:opacity-80",onClick:o,children:"Esqueceu sua senha?"})}),t&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-2.5 w-full text-base font-semibold opacity-60",children:[jsxRuntime.jsx("hr",{className:"flex-1"}),"OU",jsxRuntime.jsx("hr",{className:"flex-1"})]}),jsxRuntime.jsxs("span",{className:"text-sm font-semibold",children:["Ainda n\xE3o possui uma conta? ",jsxRuntime.jsx("span",{className:"cursor-pointer text-primary transition-colors duration-200 hover:opacity-80",onClick:t,children:"Cadastra-se"})]})]})]})}function ir({onSuccess:e,onFailed:r,loginRedirect:t,emailRules:o,passwordRules:a}){let[i,s]=react.useState(""),[c,n]=react.useState(""),[d,p]=react.useState(""),[l,u]=react.useState(false),[g,f]=react.useState(false),b=react.useRef(null),P=react.useRef(null),x=react.useRef(null),{auth:T}=h(),$={email:o||[{message:"Digite um e-mail v\xE1lido, ex: exemplo@dominio.com",test:w=>/\S+@\S+\.\S+/.test(w)}],password:a||[{message:"M\xEDnimo de 8 caracteres.",test:w=>w.length>=8},{message:"Deve conter uma letra mai\xFAscula.",test:w=>/[A-Z]/.test(w)},{message:"Inclua pelo menos um caractere especial, ex: ! @ # $ % & * . ,",test:w=>/[!@#$%^&*(),.?":{}|<>_\-+=~`;/\\[\]]/.test(w)},{message:"Deve conter um n\xFAmero.",test:w=>/\d/.test(w)}],confirmPassword:[{message:"Senhas n\xE3o conferem.",test:w=>w===c}]},v=I($.email,i),G=I($.password,c),Q=I($.confirmPassword,d);return jsxRuntime.jsxs("form",{className:"font-sans flex flex-col w-full max-w-120 min-w-60 max-h-[max(75dvh,32rem)] overflow-hidden gap-5 items-center bg-background text-foreground p-[1.25rem_1.5rem] shadow-[0_0.25rem_0.25rem_0_rgba(0,0,0,0.25)] transition-transform duration-150 ease-in-out rounded-lg",children:[jsxRuntime.jsx(_,{mainText:"Crie sua conta",subText:"Insira seus dados para come\xE7ar"}),jsxRuntime.jsxs("div",{className:"w-full flex flex-col gap-2.5 flex-[1_1_auto] overflow-y-auto mb-2",children:[jsxRuntime.jsx(A,{label:"Email",name:"email",placeholder:"teste@gmail.com",autoComplete:"email",type:"email",value:i,onValueChange:s,inputRef:b,rulesStatus:v,submitted:l}),jsxRuntime.jsx(A,{label:"Senha",name:"password",placeholder:"**********",autoComplete:"new-password",type:"password",value:c,onValueChange:n,inputRef:P,rulesStatus:G,submitted:l}),jsxRuntime.jsx(A,{label:"Confirme a Senha",name:"confirm-password",placeholder:"**********",autoComplete:"new-password",type:"password",value:d,onValueChange:p,inputRef:x,rulesStatus:Q,submitted:l})]}),jsxRuntime.jsx(C,{label:"Criar Conta",onSubmit:async w=>{w.preventDefault(),u(true);let Bt=v.some(re=>!re.passed),Dt=G.some(re=>!re.passed),Ut=Q.some(re=>!re.passed);if(Bt){b.current?.focus();return}if(Dt){P.current?.focus();return}if(Ut){x.current?.focus();return}f(true);let we=await T.register(i,c);we.success?e&&await e(we.message):r&&await r(we.message,we.trace),f(false);},loading:g}),t&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-2.5 w-full text-base font-semibold opacity-60",children:[jsxRuntime.jsx("hr",{className:"flex-1"}),"OU",jsxRuntime.jsx("hr",{className:"flex-1"})]}),jsxRuntime.jsxs("span",{className:"text-sm font-semibold",children:["J\xE1 possui uma conta? ",jsxRuntime.jsx("span",{className:"cursor-pointer text-primary transition-colors duration-200 hover:opacity-80",onClick:t,children:"Entre"})]})]})]})}var nr={xs:"text-xs",sm:"text-sm",md:"text-base",lg:"text-lg",xl:"text-xl","2xl":"text-2xl"};function lr({size:e}){let r=e?nr[e]:"text-base";return jsxRuntime.jsxs("span",{className:`font-sans font-medium ${r}`,children:["\xA9 ",new Date().getFullYear()," TrieOH"]})}function mr({onSuccess:e,onFailed:r,forceLogout:t}){let{auth:o}=h(),[a,i]=react.useState(false);return jsxRuntime.jsxs("button",{onClick:async c=>{if(c.preventDefault(),a)return;i(true);let n=await o.logout({forceLogout:t});n.success?e&&await e(n.message):r&&await r(n.message,n.trace),i(false);},type:"button",disabled:a,className:"font-sans border-none bg-transparent cursor-pointer flex items-end gap-1 text-base font-medium text-destructive transition-transform duration-200 hover:scale-[1.05] active:scale-[0.98] disabled:opacity-60 disabled:cursor-not-allowed disabled:transform-none!",children:[jsxRuntime.jsx(lucideReact.LogOut,{size:24})," ",jsxRuntime.jsx("span",{children:"Log out"})]})}var Et={mobile:lucideReact.Smartphone,tablet:lucideReact.Tablet,desktop:lucideReact.Monitor};function At(e){let{device:r,os:t,browser:o}=uaParserJs.UAParser(e);return {deviceType:r.type??"desktop",os:t.name,browser:o.name}}function Tt(e){let r=At(e);return {device:wr(r.deviceType),os:r.os,browser:r.browser}}function wr(e){if(!e)return "desktop";switch(e){case "mobile":return "mobile";case "tablet":return "tablet";default:return "desktop"}}function Ct(e){let r=Date.now()-new Date(e).getTime(),t=Math.floor(r/1e3),o=Math.floor(t/60),a=Math.floor(o/60),i=Math.floor(a/24),s=Math.floor(i/7);return t<60?"agora mesmo":o<60?`${o} minutos atr\xE1s`:a<24?`${a} horas atr\xE1s`:i<7?`${i} dias atr\xE1s`:`${s} semanas atr\xE1s`}function Ge({is_current:e,session_id:r,user_agent:t,issued_at:o,user_ip:a,onClick:i}){let s=Tt(t),c=Et[s.device];return jsxRuntime.jsx("div",{className:"border-t border-border p-[1.25rem_0.75rem] text-foreground",children:jsxRuntime.jsxs("div",{className:"relative flex flex-col items-center gap-2 flex-1 text-center @[640px]:flex-row @[640px]:items-center @[640px]:gap-4 @[640px]:text-left",children:[jsxRuntime.jsx(c,{size:40}),jsxRuntime.jsxs("div",{className:"flex flex-col min-w-0",children:[jsxRuntime.jsxs("h3",{className:"text-base font-semibold m-0",children:[s.browser," - ",s.os]}),jsxRuntime.jsxs("span",{className:"inline-flex flex-col text-sm font-extralight @[640px]:flex-row @[640px]:gap-2 @[640px]:items-center",children:[e&&jsxRuntime.jsx("strong",{className:"text-primary font-normal",children:"\u2022 Sess\xE3o Atual \u2022"}),jsxRuntime.jsx("span",{children:`${a} - ${Ct(o)}`})]})]}),!e&&jsxRuntime.jsx(lucideReact.Trash2,{size:20,className:"absolute top-0 right-0 cursor-pointer text-destructive opacity-60 transition-[opacity,transform] duration-200 hover:opacity-100 hover:scale-[1.05] active:scale-[0.95]",onClick:n=>i(n,r)})]})})}function yr({revokeAll:e=false,onSuccess:r}){let{auth:t}=h(),[o,a]=react.useState(false),[i,s]=react.useState([]),c=async()=>{let p=await t.sessions();if(p.success){let l=t.profile()?.session_id,u=p.data.sort((g,f)=>g.session_id===l?-1:f.session_id===l?1:0);s(u);}};react.useEffect(()=>{c();},[]);let n=async(p,l)=>{p.preventDefault();let u=i.find(g=>g.session_id===l);if(u){s(i.filter(g=>g.session_id!==l));try{(await t.revokeASession(l)).success||s(f=>[...f,u]);}catch{s(g=>[...g,u]);}}};return jsxRuntime.jsxs("div",{className:"font-sans w-full min-w-[20rem] m-2 @container bg-background text-foreground p-[1.5rem_0.5rem] rounded-lg",children:[jsxRuntime.jsxs("div",{className:"w-full flex flex-wrap items-center justify-center text-center gap-4 box-border px-3 @[640px]:justify-between @[640px]:text-left @[640px]:gap-8",children:[jsxRuntime.jsxs("div",{className:"flex-[0_1_auto] max-w-100",children:[jsxRuntime.jsx("h3",{className:"font-semibold text-2xl m-0 mb-1",children:"Navegadores e Dispositivos"}),jsxRuntime.jsx("p",{className:"font-extralight text-base m-0",children:"Esses navegadores e dispositivos est\xE3o atualmente conectados \xE0 sua conta. Remova quaisquer dispositivos n\xE3o autorizados."})]}),jsxRuntime.jsx("button",{type:"submit",onClick:async p=>{if(p.preventDefault(),o)return;a(true);let l=await t.revokeSessions(e),u=t.profile()?.session_id;l.success&&(s(e?[]:i.filter(g=>g.session_id===u)),r&&r(l.message)),a(false);},disabled:o,className:`font-sans w-full max-w-56 p-[1rem_0] h-auto text-base font-semibold outline-none bg-transparent relative overflow-hidden shrink-0 border-2 border-foreground text-foreground cursor-pointer transition-transform duration-500 rounded-lg hover:scale-[1.02] active:scale-[0.99] disabled:opacity-60 disabled:cursor-not-allowed disabled:transform-none! ${o?"button-loading":""}`,children:"Revogar todas as sess\xF5es"})]}),jsxRuntime.jsx("div",{className:"mt-4",children:i.length>0?i.map(p=>jsxRuntime.jsx(Ge,{...p,is_current:t.profile()?.session_id===p.session_id,onClick:n},p.session_id)):jsxRuntime.jsx("span",{className:"block border-t border-border p-[1.25rem_0.75rem] text-center font-semibold",children:"Nenhuma Sess\xE3o Dispon\xEDvel"})})]})}function Nt({onSuccess:e,onFailed:r,loginRedirect:t,emailRules:o}){let[a,i]=react.useState(""),[s,c]=react.useState(false),[n,d]=react.useState(false),p=react.useRef(null),{auth:l}=h(),g=I({email:o||[{message:"Digite um e-mail v\xE1lido, ex: exemplo@dominio.com",test:b=>/\S+@\S+\.\S+/.test(b)}]}.email,a);return jsxRuntime.jsxs("form",{className:"font-sans flex flex-col w-full max-w-120 min-w-60 max-h-[max(75dvh,32rem)] overflow-hidden gap-5 items-center bg-background text-foreground p-[1.25rem_1.5rem] shadow-[0_0.25rem_0.25rem_0_rgba(0,0,0,0.25)] transition-transform duration-150 ease-in-out rounded-lg",children:[jsxRuntime.jsx(_,{mainText:"Esqueci a senha",subText:"Insira seu e-mail para receber um link de redefini\xE7\xE3o."}),jsxRuntime.jsx("div",{className:"w-full flex flex-col gap-2.5 flex-[1_1_auto] overflow-y-auto mb-2",children:jsxRuntime.jsx(A,{label:"Email",name:"email",placeholder:"teste@gmail.com",autoComplete:"email",type:"email",value:a,onValueChange:i,inputRef:p,rulesStatus:g,submitted:s})}),jsxRuntime.jsx(C,{label:n?"Enviando...":"Enviar link de redefini\xE7\xE3o",onSubmit:async b=>{if(b.preventDefault(),c(true),g.some(T=>!T.passed)){p.current?.focus();return}d(true);let x=await l.sendForgotPassword(a);x.success?e&&await e(x.message):r&&await r(x.message,x.trace),d(false);},loading:n}),t&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-2.5 w-full text-base font-semibold opacity-60",children:[jsxRuntime.jsx("hr",{className:"flex-1"}),"OU",jsxRuntime.jsx("hr",{className:"flex-1"})]}),jsxRuntime.jsxs("span",{className:"text-sm font-semibold",children:["Lembrou-se da sua senha? ",jsxRuntime.jsx("span",{className:"cursor-pointer text-primary transition-colors duration-200 hover:opacity-80",onClick:t,children:"Login"})]})]})]})}function Rr({token:e,onSuccess:r,onFailed:t,loginRedirect:o,passwordRules:a}){let[i,s]=react.useState(""),[c,n]=react.useState(""),[d,p]=react.useState(false),[l,u]=react.useState(false),g=react.useRef(null),f=react.useRef(null),{auth:b}=h(),P={password:a||[{message:"M\xEDnimo de 8 caracteres.",test:v=>v.length>=8},{message:"Deve conter uma letra mai\xFAscula.",test:v=>/[A-Z]/.test(v)},{message:"Inclua pelo menos um caractere especial, ex: ! @ # $ % & * . ,",test:v=>/[!@#$%^&*(),.?":{}|<>_\-+=~`;/\\[\]]/.test(v)},{message:"Deve conter um n\xFAmero.",test:v=>/\d/.test(v)}],confirmPassword:[{message:"Senhas n\xE3o conferem.",test:v=>v===i}]},x=I(P.password,i),T=I(P.confirmPassword,c);return jsxRuntime.jsxs("form",{className:"font-sans flex flex-col w-full max-w-120 min-w-60 max-h-[max(75dvh,32rem)] overflow-hidden gap-5 items-center bg-background text-foreground p-[1.25rem_1.5rem] shadow-[0_0.25rem_0.25rem_0_rgba(0,0,0,0.25)] transition-transform duration-150 ease-in-out rounded-lg",children:[jsxRuntime.jsx(_,{mainText:"Redefinir Senha",subText:"Crie uma nova senha para sua conta"}),jsxRuntime.jsxs("div",{className:"w-full flex flex-col gap-2.5 flex-[1_1_auto] overflow-y-auto mb-2",children:[jsxRuntime.jsx(A,{label:"Nova Senha",name:"password",placeholder:"**********",autoComplete:"new-password",type:"password",value:i,onValueChange:s,inputRef:g,rulesStatus:x,submitted:d}),jsxRuntime.jsx(A,{label:"Confirme a Nova Senha",name:"confirm-password",placeholder:"**********",autoComplete:"new-password",type:"password",value:c,onValueChange:n,inputRef:f,rulesStatus:T,submitted:d})]}),jsxRuntime.jsx(C,{label:"Redefinir Senha",onSubmit:async v=>{v.preventDefault(),p(true);let G=x.some(w=>!w.passed),Q=T.some(w=>!w.passed);if(G){g.current?.focus();return}if(Q){f.current?.focus();return}u(true);let z=await b.resetPassword(e,i);z.success?r&&await r(z.message):t&&await t(z.message,z.trace),u(false);},loading:l}),o&&jsxRuntime.jsxs("span",{className:"text-sm font-semibold",children:["Lembrou-se da sua senha? ",jsxRuntime.jsx("span",{className:"cursor-pointer text-primary transition-colors duration-200 hover:opacity-80",onClick:o,children:"Login"})]})]})}function Cr(e,r,t){let[o,a]=react.useState(true),[i,s]=react.useState("verifying"),[c,n]=react.useState("Verificando seu e-mail..."),{auth:d}=h(),p=react.useRef(false),l=async()=>{if(!p.current){p.current=true,a(true),s("verifying");try{if(d.profile()?.is_verified){s("already_verified"),n("Seu e-mail j\xE1 est\xE1 verificado."),a(!1);return}let f=await d.verifyEmail(e);f.success?(await d.refresh(),s("success"),n(f.message||"E-mail verificado com sucesso!"),r&&await r(f.message)):(s("error"),n(f.message||"Falha na verifica\xE7\xE3o do e-mail."),t&&await t(f.message,f.trace));}catch{s("error"),n("Ocorreu um erro inesperado durante a verifica\xE7\xE3o.");}finally{a(false);}}};return react.useEffect(()=>{e&&!p.current&&l();},[e]),{loading:o,status:i,message:c,onRetry:g=>{g.preventDefault(),p.current=false,l();},setStatus:s,setLoading:a,setMessage:n}}function _r({token:e,onSuccess:r,onFailed:t}){let{loading:o,status:a,message:i,onRetry:s}=Cr(e,r,t);return jsxRuntime.jsx("div",{className:"font-sans flex flex-col w-full h-full min-h-screen items-center justify-center bg-background text-foreground p-6",children:jsxRuntime.jsxs("div",{className:"w-full max-w-120 flex flex-col gap-8 items-center bg-background text-foreground p-[1.25rem_1.5rem] shadow-[0_0.25rem_0.25rem_0_rgba(0,0,0,0.25)] rounded-lg",children:[jsxRuntime.jsx(_,{mainText:a==="verifying"?"Verificando...":a==="error"?"Ops! Falha na verifica\xE7\xE3o":"Tudo pronto!",subText:i}),a==="verifying"&&jsxRuntime.jsx("div",{className:"w-full flex justify-center py-4",children:jsxRuntime.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-primary"})}),a==="error"&&jsxRuntime.jsx("div",{className:"w-full flex flex-col gap-6 items-center",children:jsxRuntime.jsx("div",{className:"w-full mt-2",children:jsxRuntime.jsx(C,{label:"Tentar novamente",onSubmit:s,loading:o})})}),(a==="success"||a==="already_verified")&&jsxRuntime.jsxs("div",{className:"w-full flex flex-col gap-4 items-center",children:[jsxRuntime.jsx("div",{className:"w-16 h-16 flex items-center justify-center rounded-full bg-primary/10 text-primary",children:a==="success"?jsxRuntime.jsx(lucideReact.Check,{size:40}):jsxRuntime.jsx(lucideReact.Info,{size:40})}),jsxRuntime.jsx("p",{className:"text-sm font-semibold opacity-50 text-center",children:"Voc\xEA j\xE1 pode fechar esta janela ou continuar navegando em sua conta."})]})]})})}function Nr({onSuccess:e,onFailed:r}){let[t,o]=react.useState(false),[a,i]=react.useState(false),{auth:s}=h();return jsxRuntime.jsxs("div",{className:"font-sans flex flex-col w-full max-w-120 min-w-60 max-h-[max(75dvh,32rem)] overflow-hidden gap-5 items-center bg-background text-foreground p-[1.25rem_1.5rem] shadow-[0_0.25rem_0.25rem_0_rgba(0,0,0,0.25)] transition-transform duration-150 ease-in-out rounded-lg",children:[jsxRuntime.jsx(_,{mainText:"Reenviar Verifica\xE7\xE3o",subText:"N\xE3o recebeu o e-mail de verifica\xE7\xE3o? Clique no bot\xE3o abaixo para reenviar."}),jsxRuntime.jsx(C,{label:a?"E-mail Reenviado":"Reenviar E-mail de Verifica\xE7\xE3o",onSubmit:async()=>{o(true);let n=await s.resendVerifyEmail();n.success?(i(true),e&&await e(n.message)):r&&await r(n.message,n.trace),o(false);},loading:t}),a&&jsxRuntime.jsx("p",{className:"text-sm font-semibold text-primary",children:"Um novo link de verifica\xE7\xE3o foi enviado para seu e-mail."})]})}function B(...e){return tailwindMerge.twMerge(clsx.clsx(e))}var Ft=react.forwardRef(({label:e,id:r,type:t="text",error:o,className:a,value:i,onChange:s,onFocus:c,onBlur:n,...d},p)=>{let[l,u]=react.useState(false),g=react.useId(),f=r??g,b=t==="password";return jsxRuntime.jsxs("div",{className:"w-full font-body group relative",children:[jsxRuntime.jsx("input",{ref:p,id:f,type:b?l?"text":"password":t,value:i,placeholder:" ",onChange:s,onFocus:c,onBlur:n,className:B("peer h-13 w-full rounded-sm text-sm text-foreground outline-none","border border-secondary/20 bg-muted/40 transition-all duration-200","placeholder:text-transparent focus-visible:ring-0 focus:bg-muted/60","px-3.5 pt-4 pb-1",b&&"pr-10",o&&"bg-destructive/5 ring-1 ring-destructive/20 border-destructive/50",a),...d}),jsxRuntime.jsx("label",{htmlFor:f,className:B("pointer-events-none absolute transition-all duration-200 ease-out left-3.5","top-1.5 text-[10px] font-semibold tracking-wider text-primary/70","peer-placeholder-shown:top-3.5 peer-placeholder-shown:text-[15px] peer-placeholder-shown:font-normal peer-placeholder-shown:tracking-normal peer-placeholder-shown:text-muted-foreground","peer-focus:top-1.5 peer-focus:text-[10px] peer-focus:font-semibold peer-focus:tracking-wider peer-focus:text-primary/70",o&&"text-destructive/80",o&&"peer-placeholder-shown:text-destructive/60",o&&"peer-focus:text-destructive/80"),children:e}),b&&jsxRuntime.jsx("button",{type:"button",tabIndex:-1,onClick:()=>{u(x=>!x);},className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground transition-colors hover:text-primary/70 focus:outline-none","aria-label":l?"Ocultar senha":"Mostrar senha",children:l?jsxRuntime.jsx(lucideReact.EyeOff,{size:16}):jsxRuntime.jsx(lucideReact.Eye,{size:16})})]})});Ft.displayName="FormInput";var S=Ft;var qr=({message:e,className:r})=>jsxRuntime.jsx(react$1.AnimatePresence,{children:e&&jsxRuntime.jsx(react$1.motion.p,{initial:{opacity:0,height:0,marginTop:0},animate:{opacity:1,height:"auto",marginTop:6},exit:{opacity:0,height:0,marginTop:0},transition:{duration:.2,ease:"easeOut"},className:B("text-[11px] font-medium text-destructive tracking-tight leading-none px-1 overflow-hidden",r),children:e})}),R=qr;var $r=classVarianceAuthority.cva("inline-flex items-center justify-center whitespace-nowrap rounded-sm text-sm font-semibold transition-all focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 active:scale-[0.98]",{variants:{variant:{default:"bg-primary text-primary-foreground hover:opacity-90",destructive:"bg-destructive text-destructive-foreground hover:opacity-90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:opacity-80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-12 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),N=({className:e,variant:r,size:t,...o})=>jsxRuntime.jsx("button",{className:B($r({variant:r,size:t,className:e})),...o});var Wr=zod.z.object({email:zod.z.email("E-mail inv\xE1lido"),password:zod.z.string().min(1,"A senha \xE9 obrigat\xF3ria")});function at({onSuccess:e,onFailed:r,signUpRedirect:t,forgotPasswordRedirect:o}){let[a,i]=react.useState(false),{auth:s}=h(),{register:c,handleSubmit:n,formState:{errors:d}}=reactHookForm.useForm({resolver:zod$1.zodResolver(Wr),defaultValues:{email:"",password:""}});return jsxRuntime.jsxs("form",{onSubmit:n(async l=>{i(true);try{let u=await s.login(l.email,l.password);u.success?e?await e(u.message):sonner.toast.success("Login realizado com sucesso!"):r?await r(u.message,u.trace):sonner.toast.error(u.message||"Erro ao entrar");}catch{sonner.toast.error("Ocorreu um erro inesperado");}finally{i(false);}}),className:"space-y-4",children:[jsxRuntime.jsxs("div",{className:"space-y-1",children:[jsxRuntime.jsx(S,{label:"E-mail",type:"email",autoComplete:"email",error:!!d.email,...c("email")}),jsxRuntime.jsx(R,{message:d.email?.message})]}),jsxRuntime.jsxs("div",{className:"space-y-1",children:[jsxRuntime.jsx(S,{label:"Senha",type:"password",autoComplete:"current-password",error:!!d.password,...c("password")}),jsxRuntime.jsx(R,{message:d.password?.message})]}),o&&jsxRuntime.jsx("div",{className:"flex justify-end",children:jsxRuntime.jsx("button",{type:"button",onClick:o,className:"text-xs text-primary hover:underline font-medium",children:"Esqueceu a senha?"})}),jsxRuntime.jsx(N,{type:"submit",disabled:a,className:"w-full flex items-center justify-center gap-2",children:a?jsxRuntime.jsx(lucideReact.Loader2,{className:"w-5 h-5 animate-spin"}):jsxRuntime.jsxs(jsxRuntime.Fragment,{children:["Entrar",jsxRuntime.jsx(lucideReact.ArrowRight,{className:"w-4 h-4"})]})})]})}var io=zod.z.object({email:zod.z.email("E-mail inv\xE1lido"),password:zod.z.string().min(6,"A senha deve ter pelo menos 6 caracteres"),confirmPassword:zod.z.string()}).refine(e=>e.password===e.confirmPassword,{message:"As senhas n\xE3o coincidem",path:["confirmPassword"]});function st({onSuccess:e,onFailed:r,signInRedirect:t}){let[o,a]=react.useState(false),{auth:i}=h(),{register:s,handleSubmit:c,formState:{errors:n}}=reactHookForm.useForm({resolver:zod$1.zodResolver(io),defaultValues:{email:"",password:"",confirmPassword:""}});return jsxRuntime.jsxs("form",{onSubmit:c(async p=>{a(true);try{let l=await i.register(p.email,p.password);l.success?e?await e(l.message):(sonner.toast.success("Conta criada com sucesso!"),t&&t()):r?await r(l.message,l.trace):sonner.toast.error(l.message||"Erro ao criar conta");}catch{sonner.toast.error("Ocorreu um erro inesperado");}finally{a(false);}}),className:"space-y-4",children:[jsxRuntime.jsxs("div",{className:"space-y-1",children:[jsxRuntime.jsx(S,{label:"E-mail",type:"email",autoComplete:"email",error:!!n.email,...s("email")}),jsxRuntime.jsx(R,{message:n.email?.message})]}),jsxRuntime.jsxs("div",{className:"space-y-1",children:[jsxRuntime.jsx(S,{label:"Senha",type:"password",autoComplete:"new-password",error:!!n.password,...s("password")}),jsxRuntime.jsx(R,{message:n.password?.message})]}),jsxRuntime.jsxs("div",{className:"space-y-1",children:[jsxRuntime.jsx(S,{label:"Confirmar Senha",type:"password",autoComplete:"new-password",error:!!n.confirmPassword,...s("confirmPassword")}),jsxRuntime.jsx(R,{message:n.confirmPassword?.message})]}),jsxRuntime.jsx(N,{type:"submit",disabled:o,className:"w-full flex items-center justify-center gap-2",children:o?jsxRuntime.jsx(lucideReact.Loader2,{className:"w-5 h-5 animate-spin"}):jsxRuntime.jsxs(jsxRuntime.Fragment,{children:["Criar Conta",jsxRuntime.jsx(lucideReact.ArrowRight,{className:"w-4 h-4"})]})})]})}var uo=zod.z.object({email:zod.z.email("E-mail inv\xE1lido")});function ct({onSuccess:e,onFailed:r,signInRedirect:t}){let[o,a]=react.useState(false),{auth:i}=h(),{register:s,handleSubmit:c,formState:{errors:n}}=reactHookForm.useForm({resolver:zod$1.zodResolver(uo),defaultValues:{email:""}});return jsxRuntime.jsxs("form",{onSubmit:c(async p=>{a(true);try{let l=await i.sendForgotPassword(p.email);l.success?e?await e(l.message):sonner.toast.success("Link de redefini\xE7\xE3o enviado com sucesso!"):r?await r(l.message,l.trace):sonner.toast.error(l.message||"Erro ao enviar link");}catch{sonner.toast.error("Ocorreu um erro inesperado");}finally{a(false);}}),className:"space-y-4",children:[jsxRuntime.jsxs("div",{className:"space-y-1",children:[jsxRuntime.jsx(S,{label:"E-mail",type:"email",autoComplete:"email",error:!!n.email,...s("email")}),jsxRuntime.jsx(R,{message:n.email?.message})]}),jsxRuntime.jsx(N,{type:"submit",disabled:o,className:"w-full flex items-center justify-center gap-2",children:o?jsxRuntime.jsx(lucideReact.Loader2,{className:"w-5 h-5 animate-spin"}):jsxRuntime.jsxs(jsxRuntime.Fragment,{children:["Enviar link",jsxRuntime.jsx(lucideReact.ArrowRight,{className:"w-4 h-4"})]})})]})}var yo=zod.z.object({password:zod.z.string().min(6,"A senha deve ter pelo menos 6 caracteres"),confirmPassword:zod.z.string()}).refine(e=>e.password===e.confirmPassword,{message:"As senhas n\xE3o coincidem",path:["confirmPassword"]});function ko({token:e,onSuccess:r,onFailed:t,signInRedirect:o}){let[a,i]=react.useState(false),{auth:s}=h(),{register:c,handleSubmit:n,formState:{errors:d}}=reactHookForm.useForm({resolver:zod$1.zodResolver(yo),defaultValues:{password:"",confirmPassword:""}}),p=async l=>{i(true);try{let u=await s.resetPassword(e,l.password);u.success?r?await r(u.message):sonner.toast.success("Senha redefinida com sucesso!"):t?await t(u.message,u.trace):sonner.toast.error(u.message||"Erro ao redefinir senha");}catch{sonner.toast.error("Ocorreu um erro inesperado");}finally{i(false);}};return jsxRuntime.jsxs("div",{className:"w-full max-w-md z-10 flex flex-col antialiased selection:bg-primary/10 selection:text-primary",children:[jsxRuntime.jsxs("div",{className:"text-center mb-6",children:[jsxRuntime.jsx(react$1.motion.h1,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},className:"font-heading text-3xl font-bold tracking-tight mb-2",children:"Redefinir Senha"}),jsxRuntime.jsx("p",{className:"text-muted-foreground text-sm mb-4",children:"Crie uma nova senha para sua conta"})]}),jsxRuntime.jsxs("form",{onSubmit:n(p),className:"space-y-4",children:[jsxRuntime.jsxs("div",{className:"space-y-1",children:[jsxRuntime.jsx(S,{label:"Nova Senha",type:"password",autoComplete:"new-password",error:!!d.password,...c("password")}),jsxRuntime.jsx(R,{message:d.password?.message})]}),jsxRuntime.jsxs("div",{className:"space-y-1",children:[jsxRuntime.jsx(S,{label:"Confirmar Nova Senha",type:"password",autoComplete:"new-password",error:!!d.confirmPassword,...c("confirmPassword")}),jsxRuntime.jsx(R,{message:d.confirmPassword?.message})]}),jsxRuntime.jsx(N,{type:"submit",disabled:a,className:"w-full flex items-center justify-center gap-2",children:a?jsxRuntime.jsx(lucideReact.Loader2,{className:"w-5 h-5 animate-spin"}):jsxRuntime.jsxs(jsxRuntime.Fragment,{children:["Redefinir Senha",jsxRuntime.jsx(lucideReact.ArrowRight,{className:"w-4 h-4"})]})}),o&&jsxRuntime.jsx("div",{className:"text-center mt-4",children:jsxRuntime.jsx("button",{type:"button",onClick:o,className:"text-xs text-primary font-semibold hover:underline",children:"Voltar para o login"})})]})]})}function _o({token:e,onSuccess:r,onFailed:t,signInRedirect:o}){let[a,i]=react.useState("verifying"),[s,c]=react.useState("Verificando seu e-mail..."),[n,d]=react.useState(true),{auth:p}=h(),l=react.useRef(false),u=async()=>{if(!l.current){l.current=true,d(true),i("verifying");try{if(p.profile()?.is_verified){i("already_verified"),c("Seu e-mail j\xE1 est\xE1 verificado."),d(!1);return}let f=await p.verifyEmail(e);f.success?(await p.refresh(),i("success"),c(f.message||"E-mail verificado com sucesso!"),r&&await r(f.message)):(i("error"),c(f.message||"Falha na verifica\xE7\xE3o do e-mail."),t&&await t(f.message,f.trace));}catch{i("error"),c("Ocorreu um erro inesperado durante a verifica\xE7\xE3o.");}finally{d(false);}}};return react.useEffect(()=>{e&&!l.current&&u();},[e]),jsxRuntime.jsx("div",{className:"w-full max-w-md z-10 flex flex-col antialiased selection:bg-primary/10 selection:text-primary",children:jsxRuntime.jsxs("div",{className:"text-center mb-6",children:[jsxRuntime.jsxs(react$1.motion.div,{initial:{scale:.8,opacity:0},animate:{scale:1,opacity:1},className:"flex justify-center mb-4",children:[a==="verifying"&&jsxRuntime.jsx(lucideReact.Loader2,{className:"w-12 h-12 text-primary animate-spin"}),(a==="success"||a==="already_verified")&&jsxRuntime.jsx(lucideReact.CheckCircle2,{className:"w-12 h-12 text-green-500"}),a==="error"&&jsxRuntime.jsx(lucideReact.XCircle,{className:"w-12 h-12 text-destructive"})]}),jsxRuntime.jsx(react$1.motion.h1,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},className:"font-heading text-3xl font-bold tracking-tight mb-2",children:a==="verifying"?"Verificando...":a==="error"?"Falha na verifica\xE7\xE3o":"E-mail Verificado!"}),jsxRuntime.jsx("p",{className:"text-muted-foreground text-sm mb-6",children:s}),a==="error"&&jsxRuntime.jsx(N,{onClick:()=>{l.current=false,u();},disabled:n,className:"w-full flex items-center justify-center gap-2",children:"Tentar novamente"}),(a==="success"||a==="already_verified")&&jsxRuntime.jsxs("div",{className:"space-y-4",children:[jsxRuntime.jsx("p",{className:"text-xs text-muted-foreground",children:"Voc\xEA j\xE1 pode continuar navegando em sua conta."}),o&&jsxRuntime.jsxs(N,{onClick:o,className:"w-full flex items-center justify-center gap-2",children:["Ir para o login",jsxRuntime.jsx(lucideReact.ArrowRight,{className:"w-4 h-4"})]})]})]})})}function Me({children:e,className:r,backLink:t}){return jsxRuntime.jsxs("main",{className:B("bg-background h-full text-foreground min-h-screen relative overflow-hidden","flex flex-col px-4","antialiased selection:bg-primary/10 selection:text-primary",r),children:[jsxRuntime.jsx("div",{className:"absolute top-[-10%] left-[-10%] w-[40%] h-[40%] bg-primary/20 rounded-full blur-3xl pointer-events-none"}),jsxRuntime.jsx("div",{className:"absolute bottom-[-10%] right-[-10%] w-[40%] h-[40%] bg-primary/20 rounded-full blur-3xl pointer-events-none"}),t&&jsxRuntime.jsx("div",{className:"relative z-10 pt-4",children:t}),jsxRuntime.jsx("div",{className:"relative z-10 flex-1 flex justify-center items-center",children:e})]})}var Oo=zod.z.object({email:zod.z.string().email("E-mail inv\xE1lido"),password:zod.z.string().min(8,"A senha deve ter pelo menos 8 caracteres"),confirmPassword:zod.z.string().min(1,"A confirma\xE7\xE3o de senha \xE9 obrigat\xF3ria")}).refine(e=>e.password===e.confirmPassword,{message:"As senhas n\xE3o coincidem",path:["confirmPassword"]});function Bo({onSuccess:e,onFailed:r,backLink:t}){let[o,a]=react.useState(false),{auth:i}=h(),{register:s,handleSubmit:c,formState:{errors:n}}=reactHookForm.useForm({resolver:zod$1.zodResolver(Oo),defaultValues:{email:"",password:"",confirmPassword:""}}),d=async p=>{a(true);try{let l=await i.setup(p.email,p.password);l.success?e?await e(l.message):sonner.toast.success("Configura\xE7\xE3o inicial realizada com sucesso!"):r?await r(l.message,l.trace):sonner.toast.error(l.message||"Erro ao realizar setup");}catch(l){console.error(l),sonner.toast.error("Ocorreu um erro inesperado");}finally{a(false);}};return jsxRuntime.jsx(Me,{backLink:t,children:jsxRuntime.jsxs("div",{className:"w-full max-w-md z-10 flex flex-col",children:[jsxRuntime.jsxs("div",{className:"mb-10 text-center",children:[jsxRuntime.jsxs(react$1.motion.div,{initial:{opacity:0,y:-20},animate:{opacity:1,y:0},className:"inline-flex items-center gap-2 px-3 py-1 rounded-full bg-primary/10 text-primary text-xs font-bold uppercase tracking-widest mb-4",children:[jsxRuntime.jsx(lucideReact.Sparkles,{size:14}),"Setup Inicial"]}),jsxRuntime.jsx("h1",{className:"font-heading text-4xl font-bold tracking-tight mb-3",children:"Bem-vindo ao IdentityX"}),jsxRuntime.jsx("p",{className:"text-muted-foreground text-base max-w-[320px] mx-auto",children:"Vamos come\xE7ar criando sua conta de administrador mestre."})]}),jsxRuntime.jsx(react$1.motion.div,{initial:{opacity:0,scale:.98},animate:{opacity:1,scale:1},transition:{delay:.1},className:"bg-card/50 backdrop-blur-sm border border-border/40 p-1 rounded-2xl",children:jsxRuntime.jsx("div",{className:"bg-background rounded-[14px] p-6 shadow-sm",children:jsxRuntime.jsxs("form",{onSubmit:c(d),className:"space-y-5",children:[jsxRuntime.jsxs("div",{className:"space-y-1",children:[jsxRuntime.jsx(S,{label:"E-mail do Administrador",type:"email",autoComplete:"email",error:!!n.email,...s("email")}),jsxRuntime.jsx(R,{message:n.email?.message})]}),jsxRuntime.jsxs("div",{className:"space-y-1",children:[jsxRuntime.jsx(S,{label:"Senha",type:"password",autoComplete:"new-password",error:!!n.password,...s("password")}),jsxRuntime.jsx(R,{message:n.password?.message})]}),jsxRuntime.jsxs("div",{className:"space-y-1",children:[jsxRuntime.jsx(S,{label:"Confirmar Senha",type:"password",autoComplete:"new-password",error:!!n.confirmPassword,...s("confirmPassword")}),jsxRuntime.jsx(R,{message:n.confirmPassword?.message})]}),jsxRuntime.jsx(N,{type:"submit",disabled:o,className:"w-full flex items-center justify-center gap-2 h-13 mt-4 text-base font-bold shadow-lg shadow-primary/10 group",children:o?jsxRuntime.jsx(lucideReact.Loader2,{className:"w-5 h-5 animate-spin"}):jsxRuntime.jsxs(jsxRuntime.Fragment,{children:["Finalizar Configura\xE7\xE3o",jsxRuntime.jsx(lucideReact.ArrowRight,{className:"w-4 h-4 transition-transform group-hover:translate-x-1"})]})})]})})}),jsxRuntime.jsxs("div",{className:"mt-8 text-center",children:[jsxRuntime.jsx("div",{className:"h-1 w-full bg-muted/30 rounded-full overflow-hidden",children:jsxRuntime.jsx(react$1.motion.div,{initial:{width:0},animate:{width:"100%"},transition:{duration:1.5,ease:"easeInOut"},className:"h-full bg-primary/40"})}),jsxRuntime.jsx("p",{className:"text-[10px] text-muted-foreground mt-2 font-medium uppercase tracking-tighter",children:"Passo 1 de 1 \u2022 Configurando ambiente"})]})]})})}var qo={signin:{title:"Bem-vindo de volta",subtitle:"Entre com suas credenciais para acessar a plataforma",toggleLabel:"Ainda n\xE3o tem uma conta?",toggleAction:"Cadastre-se",toggleTo:"signup"},signup:{title:"Criar sua conta",subtitle:"Preencha os dados abaixo para se cadastrar",toggleLabel:"J\xE1 possui uma conta?",toggleAction:"Fa\xE7a login",toggleTo:"signin"},"forgot-password":{title:"Recuperar senha",subtitle:"Digite seu e-mail para receber instru\xE7\xF5es",toggleLabel:"Lembrou da senha?",toggleAction:"Voltar ao login",toggleTo:"signin"}};function jo({initialView:e="signin",onLoginSuccess:r,onSignUpSuccess:t,onFailed:o,backLink:a}){let[i,s]=react.useState(e),c=async d=>{s("signin"),t&&await t(d);},n=qo[i];return jsxRuntime.jsx(Me,{backLink:a,children:jsxRuntime.jsxs("div",{className:"w-full max-w-md z-10 flex flex-col",children:[jsxRuntime.jsxs("div",{className:"text-center mb-6",children:[jsxRuntime.jsx(react$1.motion.h1,{initial:{opacity:0,x:-10},animate:{opacity:1,x:0},className:"font-heading text-3xl font-bold tracking-tight mb-2",children:n.title},i+"-h1"),jsxRuntime.jsx("p",{className:"text-muted-foreground text-sm mb-4",children:n.subtitle}),jsxRuntime.jsxs("div",{className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-muted/50 border border-border/50 text-xs font-medium text-muted-foreground",children:[n.toggleLabel,jsxRuntime.jsx("button",{type:"button",onClick:()=>s(n.toggleTo),className:"text-primary font-semibold hover:underline",children:n.toggleAction})]})]}),jsxRuntime.jsx("div",{className:"relative min-h-80",children:jsxRuntime.jsxs(react$1.AnimatePresence,{mode:"wait",children:[i==="signin"&&jsxRuntime.jsx(react$1.motion.div,{initial:{opacity:0,x:-10},animate:{opacity:1,x:0},exit:{opacity:0,x:10},transition:{duration:.2},className:"absolute inset-0",children:jsxRuntime.jsx(at,{onSuccess:r,onFailed:o,signUpRedirect:()=>s("signup"),forgotPasswordRedirect:()=>s("forgot-password")})},"signin"),i==="signup"&&jsxRuntime.jsx(react$1.motion.div,{initial:{opacity:0,x:10},animate:{opacity:1,x:0},exit:{opacity:0,x:-10},transition:{duration:.2},className:"absolute inset-0",children:jsxRuntime.jsx(st,{onSuccess:c,onFailed:o,signInRedirect:()=>s("signin")})},"signup"),i==="forgot-password"&&jsxRuntime.jsx(react$1.motion.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},transition:{duration:.2},className:"absolute inset-0",children:jsxRuntime.jsx(ct,{onFailed:o,signInRedirect:()=>s("signin")})},"forgot-password")]})})]})})}exports.AuthProvider=Fa;exports.BasicInputField=A;exports.BasicLogoutButton=mr;exports.Copyright=lr;exports.ForgotPassword=Nt;exports.ModernAuth=jo;exports.ModernForgotPassword=ct;exports.ModernResetPassword=ko;exports.ModernSetup=Bo;exports.ModernSignIn=at;exports.ModernSignUp=st;exports.ModernVerifyEmail=_o;exports.ResendVerifyEmail=Nr;exports.ResetPassword=Rr;exports.Sessions=yr;exports.SignIn=or;exports.SignUp=ir;exports.VerifyEmail=_r;exports.useAuth=h;//# sourceMappingURL=react.js.map
|
|
3
3
|
//# sourceMappingURL=react.js.map
|