@trieoh/identityx-sdk-ts 0.11.6 → 0.11.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/index.js +1 -1
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/react.js +2 -5
- package/dist/cjs/react.js.map +1 -1
- package/dist/esm/{api-DO5uH1oU.d.ts → api-DjM6jYaR.d.ts} +6 -6
- 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 +32 -10
- package/dist/esm/react.js +2 -5
- package/dist/esm/react.js.map +1 -1
- package/package.json +4 -1
|
@@ -2,11 +2,11 @@ import * as _trieoh_envoy_fetch_ts from '@trieoh/envoy-fetch-ts';
|
|
|
2
2
|
import { DefaultFetchClientConfig, FetchClientOptions, DefaultFailureEnvelope } from '@trieoh/envoy-fetch-ts';
|
|
3
3
|
|
|
4
4
|
interface AuthTokens {
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
5
|
+
access_token_string: string;
|
|
6
|
+
refresh_token_string: string;
|
|
7
|
+
access_expires_at: string;
|
|
8
|
+
refresh_expires_at: string;
|
|
9
|
+
domain: string;
|
|
10
10
|
}
|
|
11
11
|
interface TokenClaims {
|
|
12
12
|
sub: {
|
|
@@ -91,4 +91,4 @@ declare function createQueryFetcher(config?: {
|
|
|
91
91
|
clientConfig?: Omit<DefaultFetchClientConfig, "adapter">;
|
|
92
92
|
}): <TData>(path: string, options?: ApiRequestOptions) => Promise<TData>;
|
|
93
93
|
|
|
94
|
-
export { AuthInterceptor as A, type RequestOptions as R, createAuthenticatedFetch as a, createFetcher as b, createAuthInterceptor as c, createQueryFetcher as d,
|
|
94
|
+
export { AuthInterceptor as A, type RequestOptions as R, createAuthenticatedFetch as a, createFetcher as b, createAuthInterceptor as c, createQueryFetcher as d, type AuthTokens as e, Api as f };
|
package/dist/esm/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { A as AuthInterceptor, R as RequestOptions, c as createAuthInterceptor, a as createAuthenticatedFetch, b as createFetcher, d as createQueryFetcher } from './api-
|
|
1
|
+
export { A as AuthInterceptor, R as RequestOptions, c as createAuthInterceptor, a as createAuthenticatedFetch, b as createFetcher, d as createQueryFetcher } from './api-DjM6jYaR.js';
|
|
2
2
|
export { FetchClientError as ApiError, DefaultFetchResult as ApiResponse } from '@trieoh/envoy-fetch-ts';
|
|
3
3
|
|
|
4
4
|
interface TrieOHEnv {
|
package/dist/esm/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import {simpleFetch,logger,createDefaultFetchClient}from'@trieoh/envoy-fetch-ts';export{FetchClientError as ApiError}from'@trieoh/envoy-fetch-ts';function C(t,e){if(e.startsWith("http"))return e;let r=t.replace(/\/$/,""),n=e.replace(/^\//,"");return `${r}/${n}`}var R={isAuthenticated:false,isInitializing:true},O=new Set,
|
|
2
|
-
export{T as AuthInterceptor,$ as configure,Re as createAuthInterceptor,
|
|
1
|
+
import {simpleFetch,logger,createDefaultFetchClient}from'@trieoh/envoy-fetch-ts';export{FetchClientError as ApiError}from'@trieoh/envoy-fetch-ts';function C(t,e){if(e.startsWith("http"))return e;let r=t.replace(/\/$/,""),n=e.replace(/^\//,"");return `${r}/${n}`}var R={isAuthenticated:false,isInitializing:true},O=new Set,q=()=>O.forEach(t=>t()),_={subscribe:t=>(O.add(t),()=>O.delete(t)),getSnapshot:()=>R,getServerSnapshot:()=>R,set:t=>{R={...R,...t},q();},reset:()=>{R={isAuthenticated:false,isInitializing:false},q();}};typeof window<"u"&&window.addEventListener("storage",t=>{if(t.key==="trieoh_access_expiry")if(!t.newValue)_.reset();else {let e=parseInt(t.newValue,10),r=!isNaN(e)&&e>Date.now();_.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);}},x={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);}},m={get:t=>{if(typeof window>"u")return null;let e=t+"=",r=document.cookie.split(";");for(let n=0;n<r.length;n++){let s=r[n];for(;s.charAt(0)===" ";)s=s.substring(1,s.length);if(s.indexOf(e)===0)return s.substring(e.length,s.length)}return null},set:(t,e,r={})=>{if(typeof window>"u")return;let{expires:n,path:s="/",domain:l,secure:o=window.location.protocol==="https:",sameSite:p=o?"None":"Lax"}=r,a=window.location.hostname==="localhost",f=[`${t}=${e}`,l&&!a?`Domain=${l}`:"",`Path=${s}`,`SameSite=${p}`,o?"Secure":"",n?`expires=${n}`:""];document.cookie=f.filter(Boolean).join("; ");},remove:(t,e)=>{m.set(t,"",{expires:"Thu, 01 Jan 1970 00:00:00 GMT",domain:e});}};var A="trieoh_access_token",h={getAccessToken:()=>x.getItem(A),setAccessToken:t=>{t?x.setItem(A,t):x.removeItem(A);},clear:()=>{x.removeItem(A);}};var g=null,b="trieoh_access_expiry",I="trieoh_refresh_expiry",y="trieoh_refresh_domain";function L(t){if(typeof window>"u")return null;let e=window.location.hostname;if(t)try{let r=t;return r.startsWith("http")&&(r=new URL(r).hostname),r}catch{return t}return e}function D(t){try{let e=t.split(".")[1];return JSON.parse(atob(e))}catch{return null}}function B(t){let{access_token_string:e,refresh_token_string:r,access_expires_at:n,refresh_expires_at:s}=t,l=D(e);if(!l){logger.error("Failed to decode tokens");return}h.setAccessToken(e);let o=new Date(s).getTime(),p=new Date(n).getTime(),a=L(t.domain);m.set("refresh_token",r,{expires:new Date(o).toUTCString(),domain:a}),g={access_data:l,refresh_expiry_date:o},i.setItem(b,String(p)),i.setItem(I,String(o)),a?i.setItem(y,a):i.removeItem(y),_.set({isAuthenticated:true,isInitializing:false}),logger.log("Auth session saved");}function H(){if(g)return g;let t=h.getAccessToken();if(!t)return null;let e=D(t);if(!e||e.exp*1e3<=Date.now())return null;let r=i.getItem(I);return r?(g={access_data:e,refresh_expiry_date:parseInt(r,10)},g):null}function J(t,e){try{let r=i.getItem(t);if(!r)return !0;let n=parseInt(r,10);return isNaN(n)?!0:n-Date.now()<=e*1e3}catch(r){return logger.warn("Error reading expiry:",r),true}}var P=(t=30)=>J(b,t),K=(t=10)=>J(I,t);function v(){g=null,h.clear(),i.removeItem(b),i.removeItem(I);let t=i.getItem(y)||L();m.remove("refresh_token",t),i.removeItem(y),_.reset(),logger.log("Auth tokens and claims cleared");}function Y(){let t=typeof window>"u",e=typeof import.meta<"u"&&import.meta.env?import.meta.env:{},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 w=null,F={};function $(t){F={...F,...t},w=null;}function U(){return w||(w={...Y(),...F}),w}var N={get BASE_URL(){return U().BASE_URL}};var T=class{constructor(e){this.isRefreshing=false;this.refreshPromise=null;this.baseURL=e?.baseURL||N.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()=>{try{let e=await simpleFetch(C(this.authBaseURL,"/auth/refresh"),{method:"POST",credentials:"include"});if(e.code!==200||!e.data)throw e.code!==503&&v(),new Error(e.message||"Failed to refresh token");B(e.data);let r=H();r&&this.onTokenRefreshed?.(r),logger.log("Token refreshed successfully");}catch(e){throw logger.warn("Failed to refresh token:",e),v(),this.onRefreshFailed?.(e),e}finally{this.isRefreshing=false,this.refreshPromise=null;}})(),this.refreshPromise)}async beforeRequest(){if(K()){v();return}let e=!!h.getAccessToken(),r=!!m.get("refresh_token");if(!e&&r||e&&P(30))try{await this.refreshToken();}catch(n){logger.warn("Proactive refresh failed:",n);}}async fetch(e,r){let n=r?.requiresAuth!==false,s=e.includes("/auth/refresh");n&&!s&&!r?.skipRefresh&&await this.beforeRequest();let l=C(this.baseURL,e),o=async()=>{let a=h.getAccessToken(),f=new Headers(r?.headers);return n&&a&&f.set("Authorization",`Bearer ${a}`),f.has("Content-Type")||f.set("Content-Type","application/json"),fetch(l,{...r,headers:f,credentials:"include"})},p=await o();if(p.status===401&&n&&!s&&P(30)){logger.log("401 detected and token is expiring/expired, attempting refresh...");try{await this.refreshToken(),p=await o();}catch{logger.error("Retry failed after refresh error");}}return p}},Re=t=>new T(t),_e=t=>{let e=new T(t);return (r,n)=>e.fetch(r,n)};function d(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 S=class{constructor(e,r,n,s){this.interceptor=new T({baseURL:e,authBaseURL:r,onTokenRefreshed:n}),this.client=createDefaultFetchClient({...s,adapter:this.interceptor.fetch.bind(this.interceptor)});}request(e,r){return this.client.request(e,d(r))}get(e,r){return this.client.get(e,d(r))}post(e,r,n){return this.client.post(e,r,d(n))}put(e,r,n){return this.client.put(e,r,d(n))}patch(e,r,n){return this.client.patch(e,r,d(n))}delete(e,r,n){return this.client.delete(e,r,d(n))}query(e,r){return this.client.query(e,d(r))}};function M(t){let e=new S(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 Q(t){let e=new S(t?.baseURL,t?.authBaseURL,void 0,t?.clientConfig);return (r,n)=>e.query(r,n)}
|
|
2
|
+
export{T as AuthInterceptor,$ as configure,Re as createAuthInterceptor,_e as createAuthenticatedFetch,M as createFetcher,Q as createQueryFetcher};//# sourceMappingURL=index.js.map
|
|
3
3
|
//# sourceMappingURL=index.js.map
|
package/dist/esm/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","cookieParts","ACCESS_TOKEN_KEY","tokenStore","token","memoryClaims","ACCESS_EXPIRY_KEY","REFRESH_EXPIRY_KEY","REFRESH_DOMAIN_KEY","getCookieDomain","returnedDomain","hostname","decodeJwt","payload","saveAuthSession","tokens","AccessTokenString","RefreshTokenString","AccessExpiresAt","RefreshExpiresAt","Domain","claims","logger","refreshExpiry","accessExpiry","getTokenClaims","refreshExpiryStr","isExpiringSoon","thresholdSeconds","expiryStr","e","isTokenExpiringSoon","isRefreshSessionExpired","clearAuthTokens","resolveEnv","isServer","viteEnv","safeProcessEnv","resolvedProjectId","resolvedApiKey","memoizedEnv","overrides","configure","config","getEnv","env","AuthInterceptor","res","simpleFetch","error","hasAccessToken","hasRefreshToken","url","shouldAuth","isRefreshReq","finalUrl","executeFetch","accessToken","headers","response","createAuthInterceptor","createAuthenticatedFetch","interceptor","toFetchOptions","requiresAuth","skipRefresh","rest","interceptorFields","Api","baseURL","authBaseURL","onTokenRefreshed","clientConfig","createDefaultFetchClient","body","createFetcher","api","createQueryFetcher"],"mappings":"kJAAO,SAASA,EAAQC,CAAAA,CAAcC,CAAAA,CAAsB,CAC1D,GAAIA,CAAAA,CAAK,WAA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,CACD,IAAMiC,CAAAA,CAAM,IAAIR,CAAAA,CACdzB,CAAAA,EAAQ,QACRA,CAAAA,EAAQ,WAAA,CACR,OACAA,CAAAA,EAAQ,YACV,EAEA,OAAO,CAAQtE,EAAcuB,CAAAA,GAC3BgF,CAAAA,CAAI,MAAavG,CAAAA,CAAMuB,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 = parseInt(event.newValue, 10);\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 cookieParts = [\n `${name}=${value}`,\n domain ? `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,\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 AccessTokenString: string;\n RefreshTokenString: string;\n AccessExpiresAt: string;\n RefreshExpiresAt: 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 memoryClaims: 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\n // Localhost should never have a domain set for cookies to avoid issues\n if (hostname === 'localhost') return null;\n\n if (returnedDomain) {\n try {\n let domain = returnedDomain;\n if (domain.startsWith(\"http\")) domain = new URL(domain).hostname;\n return domain;\n } catch {\n return returnedDomain;\n }\n }\n\n return hostname;\n}\nexport function decodeJwt<T>(token: string): T | null {\n try {\n const payload = token.split(\".\")[1];\n return JSON.parse(atob(payload));\n } catch {\n return null;\n }\n}\n\nexport function saveAuthSession(tokens: AuthTokens): void {\n const {\n AccessTokenString,\n RefreshTokenString,\n AccessExpiresAt,\n RefreshExpiresAt,\n Domain\n } = tokens;\n\n const claims = decodeJwt<TokenClaims>(AccessTokenString);\n\n if (!claims) {\n logger.error(\"Failed to decode tokens\");\n return;\n }\n\n tokenStore.setAccessToken(AccessTokenString);\n\n const refreshExpiry = new Date(RefreshExpiresAt).getTime();\n const accessExpiry = new Date(AccessExpiresAt).getTime();\n const domain = getCookieDomain(Domain);\n\n cookieStorage.set(\"refresh_token\", RefreshTokenString, {\n expires: new Date(refreshExpiry).toUTCString(),\n domain\n });\n\n memoryClaims = {\n access_data: claims,\n refresh_expiry_date: refreshExpiry,\n };\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 (memoryClaims) return memoryClaims;\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 memoryClaims = {\n access_data: claims,\n refresh_expiry_date: parseInt(refreshExpiryStr, 10),\n };\n\n return memoryClaims;\n}\n\nfunction isExpiringSoon(key: string, thresholdSeconds: number): boolean {\n try {\n const expiryStr = browserStorage.getItem(key);\n if (!expiryStr) return true;\n const expiry = parseInt(expiryStr, 10);\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 expiryStr = browserStorage.getItem(ACCESS_EXPIRY_KEY);\n if (!expiryStr) return false;\n const accessExpiryTimestamp = parseInt(expiryStr, 10);\n return accessExpiryTimestamp > Date.now();\n}\n\nexport function clearAuthTokens(): void {\n memoryClaims = 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 private async refreshToken(): Promise<void> {\n if (this.isRefreshing && this.refreshPromise) return this.refreshPromise;\n\n this.isRefreshing = true;\n this.refreshPromise = (async () => {\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 if (res.code !== 503) clearAuthTokens();\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 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 const hasRefreshToken = !!cookieStorage.get(\"refresh_token\");\n\n if ((!hasAccessToken && hasRefreshToken) || (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 logger.log(\"401 detected, attempting one-time retry after 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 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","cookieStorage","name","nameEQ","ca","i","c","options","expires","domain","secure","sameSite","isLocalhost","cookieParts","ACCESS_TOKEN_KEY","tokenStore","token","memoryClaims","ACCESS_EXPIRY_KEY","REFRESH_EXPIRY_KEY","REFRESH_DOMAIN_KEY","getCookieDomain","returnedDomain","hostname","decodeJwt","payload","saveAuthSession","tokens","access_token_string","refresh_token_string","access_expires_at","refresh_expires_at","claims","logger","refreshExpiry","accessExpiry","getTokenClaims","refreshExpiryStr","isExpiringSoon","thresholdSeconds","expiryStr","e","isTokenExpiringSoon","isRefreshSessionExpired","clearAuthTokens","resolveEnv","isServer","viteEnv","safeProcessEnv","resolvedProjectId","resolvedApiKey","memoizedEnv","overrides","configure","config","getEnv","env","AuthInterceptor","res","simpleFetch","error","hasAccessToken","hasRefreshToken","url","shouldAuth","isRefreshReq","finalUrl","executeFetch","accessToken","headers","response","createAuthInterceptor","createAuthenticatedFetch","interceptor","toFetchOptions","requiresAuth","skipRefresh","rest","interceptorFields","Api","baseURL","authBaseURL","onTokenRefreshed","clientConfig","createDefaultFetchClient","body","createFetcher","api","createQueryFetcher"],"mappings":"kJAAO,SAASA,EAAQC,CAAAA,CAAcC,CAAAA,CAAsB,CAC1D,GAAIA,CAAAA,CAAK,WAAW,MAAM,CAAA,CAAG,OAAOA,CAAAA,CAEpC,IAAMC,EAAYF,CAAAA,CAAK,OAAA,CAAQ,MAAO,EAAE,CAAA,CAClCG,EAAYF,CAAAA,CAAK,OAAA,CAAQ,MAAO,EAAE,CAAA,CAExC,OAAO,CAAA,EAAGC,CAAS,IAAIC,CAAS,CAAA,CAClC,CCFA,IAAIC,CAAAA,CAAoB,CACtB,eAAA,CAAiB,KAAA,CACjB,eAAgB,IAClB,CAAA,CACMC,EAAa,IAAI,GAAA,CAEjBC,EAAS,IAAMD,CAAAA,CAAW,OAAA,CAASE,CAAAA,EAAMA,GAAG,CAAA,CAErCC,EAAY,CACvB,SAAA,CAAYC,IACVJ,CAAAA,CAAW,GAAA,CAAII,CAAE,CAAA,CACV,IAAMJ,EAAW,MAAA,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AAAA,CAAenE,CAAO,CAAC,CAClE,CAEA,MAASvB,CAAAA,CAAcuB,CAAAA,CAA6B,CAClD,OAAO,IAAA,CAAK,OAAO,KAAA,CAASvB,CAAAA,CAAM0F,EAAenE,CAAO,CAAC,CAC3D,CACF,EAEO,SAAS+E,CAAAA,CAAchC,EAI3B,CACD,IAAMiC,EAAM,IAAIR,CAAAA,CACdzB,GAAQ,OAAA,CACRA,CAAAA,EAAQ,YACR,MAAA,CACAA,CAAAA,EAAQ,YACV,CAAA,CAEA,OAAO,CACL,OAAA,CAASiC,CAAAA,CAAI,QAAQ,IAAA,CAAKA,CAAG,EAC7B,GAAA,CAAKA,CAAAA,CAAI,IAAI,IAAA,CAAKA,CAAG,EACrB,IAAA,CAAMA,CAAAA,CAAI,KAAK,IAAA,CAAKA,CAAG,EACvB,GAAA,CAAKA,CAAAA,CAAI,IAAI,IAAA,CAAKA,CAAG,EACrB,KAAA,CAAOA,CAAAA,CAAI,MAAM,IAAA,CAAKA,CAAG,EACzB,MAAA,CAAQA,CAAAA,CAAI,OAAO,IAAA,CAAKA,CAAG,EAC3B,KAAA,CAAOA,CAAAA,CAAI,MAAM,IAAA,CAAKA,CAAG,CAC3B,CACF,CAEO,SAASC,CAAAA,CAAmBlC,CAAAA,CAIhC,CACD,IAAMiC,CAAAA,CAAM,IAAIR,CAAAA,CACdzB,CAAAA,EAAQ,QACRA,CAAAA,EAAQ,WAAA,CACR,OACAA,CAAAA,EAAQ,YACV,EAEA,OAAO,CAAQtE,EAAcuB,CAAAA,GAC3BgF,CAAAA,CAAI,MAAavG,CAAAA,CAAMuB,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 = parseInt(event.newValue, 10);\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,\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 memoryClaims: 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\n if (returnedDomain) {\n try {\n let domain = returnedDomain;\n if (domain.startsWith(\"http\")) domain = new URL(domain).hostname;\n return domain;\n } catch {\n return returnedDomain;\n }\n }\n\n return hostname;\n}\nexport function decodeJwt<T>(token: string): T | null {\n try {\n const payload = token.split(\".\")[1];\n return JSON.parse(atob(payload));\n } catch {\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 memoryClaims = {\n access_data: claims,\n refresh_expiry_date: refreshExpiry,\n };\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 (memoryClaims) return memoryClaims;\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 memoryClaims = {\n access_data: claims,\n refresh_expiry_date: parseInt(refreshExpiryStr, 10),\n };\n\n return memoryClaims;\n}\n\nfunction isExpiringSoon(key: string, thresholdSeconds: number): boolean {\n try {\n const expiryStr = browserStorage.getItem(key);\n if (!expiryStr) return true;\n const expiry = parseInt(expiryStr, 10);\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 expiryStr = browserStorage.getItem(ACCESS_EXPIRY_KEY);\n if (!expiryStr) return false;\n const accessExpiryTimestamp = parseInt(expiryStr, 10);\n return accessExpiryTimestamp > Date.now();\n}\n\nexport function clearAuthTokens(): void {\n memoryClaims = 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 private async refreshToken(): Promise<void> {\n if (this.isRefreshing && this.refreshPromise) return this.refreshPromise;\n\n this.isRefreshing = true;\n this.refreshPromise = (async () => {\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 if (res.code !== 503) clearAuthTokens();\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 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 const hasRefreshToken = !!cookieStorage.get(\"refresh_token\");\n\n if ((!hasAccessToken && hasRefreshToken) || (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 isExpiring = isTokenExpiringSoon(30);\n\n if (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/esm/react.d.ts
CHANGED
|
@@ -2,8 +2,8 @@ import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
|
2
2
|
import * as react from 'react';
|
|
3
3
|
import { MouseEvent } from 'react';
|
|
4
4
|
import * as _trieoh_envoy_fetch_ts from '@trieoh/envoy-fetch-ts';
|
|
5
|
-
import { DefaultFetchClientConfig } from '@trieoh/envoy-fetch-ts';
|
|
6
|
-
import { e as
|
|
5
|
+
import { DefaultFetchResult, DefaultFetchClientConfig } from '@trieoh/envoy-fetch-ts';
|
|
6
|
+
import { e as AuthTokens, f as Api } from './api-DjM6jYaR.js';
|
|
7
7
|
|
|
8
8
|
interface SessionI {
|
|
9
9
|
session_id: string;
|
|
@@ -27,11 +27,11 @@ interface CurrentSessionI {
|
|
|
27
27
|
}
|
|
28
28
|
|
|
29
29
|
interface AuthCallbacks {
|
|
30
|
-
onLogin?: () => void;
|
|
31
|
-
onRegister?: () => void;
|
|
32
|
-
onVerify?: () => void;
|
|
33
|
-
|
|
34
|
-
onRefresh?: () => void;
|
|
30
|
+
onLogin?: (res: DefaultFetchResult<AuthTokens>) => void;
|
|
31
|
+
onRegister?: (res: DefaultFetchResult<void>) => void;
|
|
32
|
+
onVerify?: (res: DefaultFetchResult<void>) => void;
|
|
33
|
+
onResetPassword?: (res: DefaultFetchResult<void>) => void;
|
|
34
|
+
onRefresh?: (res?: DefaultFetchResult<AuthTokens>) => void;
|
|
35
35
|
}
|
|
36
36
|
declare const createAuthService: (apiInstance: Api, callbacks?: AuthCallbacks) => {
|
|
37
37
|
login: (email: string, password: string) => Promise<_trieoh_envoy_fetch_ts.FetchResult<AuthTokens, _trieoh_envoy_fetch_ts.DefaultBaseEnvelope, _trieoh_envoy_fetch_ts.DefaultFailureEnvelope>>;
|
|
@@ -58,7 +58,7 @@ declare const createAuthService: (apiInstance: Api, callbacks?: AuthCallbacks) =
|
|
|
58
58
|
} | null;
|
|
59
59
|
sendForgotPassword: (email: string) => Promise<_trieoh_envoy_fetch_ts.FetchResult<void, _trieoh_envoy_fetch_ts.DefaultBaseEnvelope, _trieoh_envoy_fetch_ts.DefaultFailureEnvelope>>;
|
|
60
60
|
resetPassword: (token: string, new_password: string) => Promise<_trieoh_envoy_fetch_ts.FetchResult<void, _trieoh_envoy_fetch_ts.DefaultBaseEnvelope, _trieoh_envoy_fetch_ts.DefaultFailureEnvelope>>;
|
|
61
|
-
verifyEmail: () => Promise<_trieoh_envoy_fetch_ts.FetchResult<void, _trieoh_envoy_fetch_ts.DefaultBaseEnvelope, _trieoh_envoy_fetch_ts.DefaultFailureEnvelope>>;
|
|
61
|
+
verifyEmail: (token: string) => Promise<_trieoh_envoy_fetch_ts.FetchResult<void, _trieoh_envoy_fetch_ts.DefaultBaseEnvelope, _trieoh_envoy_fetch_ts.DefaultFailureEnvelope>>;
|
|
62
62
|
resendVerifyEmail: () => Promise<_trieoh_envoy_fetch_ts.FetchResult<void, _trieoh_envoy_fetch_ts.DefaultBaseEnvelope, _trieoh_envoy_fetch_ts.DefaultFailureEnvelope>>;
|
|
63
63
|
health: () => Promise<_trieoh_envoy_fetch_ts.FetchResult<{
|
|
64
64
|
service: string;
|
|
@@ -77,7 +77,7 @@ type AuthContextType = {
|
|
|
77
77
|
isInitializing: boolean;
|
|
78
78
|
isProjectMode?: boolean;
|
|
79
79
|
};
|
|
80
|
-
declare function AuthProvider({ children, baseURL, projectId, isProjectMode, fallback, waitSession, clientConfig, onLogin,
|
|
80
|
+
declare function AuthProvider({ children, baseURL, projectId, isProjectMode, fallback, waitSession, clientConfig, onLogin, onResetPassword, onRegister, onVerify, onRefresh, }: {
|
|
81
81
|
children: React.ReactNode;
|
|
82
82
|
baseURL?: string;
|
|
83
83
|
projectId?: string;
|
|
@@ -148,6 +148,28 @@ interface ForgotPasswordProps {
|
|
|
148
148
|
}
|
|
149
149
|
declare function ForgotPassword({ onSuccess, onFailed, loginRedirect, emailRules, }: ForgotPasswordProps): react_jsx_runtime.JSX.Element;
|
|
150
150
|
|
|
151
|
+
interface ResetPasswordProps {
|
|
152
|
+
token: string;
|
|
153
|
+
onSuccess?: (message?: string) => Promise<void>;
|
|
154
|
+
onFailed?: (message: string, trace?: string[]) => Promise<void>;
|
|
155
|
+
loginRedirect?: (e: MouseEvent<HTMLSpanElement>) => void;
|
|
156
|
+
passwordRules?: Rule[];
|
|
157
|
+
}
|
|
158
|
+
declare function ResetPassword({ token, onSuccess, onFailed, loginRedirect, passwordRules, }: ResetPasswordProps): react_jsx_runtime.JSX.Element;
|
|
159
|
+
|
|
160
|
+
interface VerifyEmailProps {
|
|
161
|
+
token: string;
|
|
162
|
+
onSuccess?: (message?: string) => Promise<void>;
|
|
163
|
+
onFailed?: (message: string, trace?: string[]) => Promise<void>;
|
|
164
|
+
}
|
|
165
|
+
declare function VerifyEmail({ token, onSuccess, onFailed, }: VerifyEmailProps): react_jsx_runtime.JSX.Element;
|
|
166
|
+
|
|
167
|
+
interface ResendVerifyEmailProps {
|
|
168
|
+
onSuccess?: (message?: string) => Promise<void>;
|
|
169
|
+
onFailed?: (message: string, trace?: string[]) => Promise<void>;
|
|
170
|
+
}
|
|
171
|
+
declare function ResendVerifyEmail({ onSuccess, onFailed, }: ResendVerifyEmailProps): react_jsx_runtime.JSX.Element;
|
|
172
|
+
|
|
151
173
|
interface BasicInputFieldProps {
|
|
152
174
|
/** The Input ID/Name */
|
|
153
175
|
name: string;
|
|
@@ -174,4 +196,4 @@ interface BasicInputFieldProps {
|
|
|
174
196
|
}
|
|
175
197
|
declare function BasicInputField({ name, label, placeholder, type, value, onValueChange, onBlur, autoComplete, rulesStatus, submitted, inputRef, }: BasicInputFieldProps): react_jsx_runtime.JSX.Element;
|
|
176
198
|
|
|
177
|
-
export { type AuthCallbacks, AuthProvider, BasicInputField, BasicLogoutButton, Copyright, ForgotPassword, Sessions, SignIn, SignUp, useAuth };
|
|
199
|
+
export { type AuthCallbacks, AuthProvider, BasicInputField, BasicLogoutButton, Copyright, ForgotPassword, ResendVerifyEmail, ResetPassword, Sessions, SignIn, SignUp, VerifyEmail, useAuth };
|
package/dist/esm/react.js
CHANGED
|
@@ -1,6 +1,3 @@
|
|
|
1
|
-
import {createContext,useRef,useSyncExternalStore,useEffect,useCallback,useMemo,useContext,useState}from'react';import {logger,createDefaultFetchClient,simpleFetch}from'@trieoh/envoy-fetch-ts';import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {RiEyeCloseLine,RiEyeLine}from'react-icons/ri';import {GoPerson}from'react-icons/go';import {ImExit}from'react-icons/im';import {FaDesktop,FaTabletAlt,FaMobileAlt,FaTrashAlt}from'react-icons/fa';import {UAParser}from'ua-parser-js';function ve(e,t){if(t.startsWith("http"))return t;let r=e.replace(/\/$/,""),o=t.replace(/^\//,"");return `${r}/${o}`}var K={isAuthenticated:false,isInitializing:true},_e=new Set,Ae=()=>_e.forEach(e=>e()),_={subscribe:e=>(_e.add(e),()=>_e.delete(e)),getSnapshot:()=>K,getServerSnapshot:()=>K,set:e=>{K={...K,...e},Ae();},reset:()=>{K={isAuthenticated:false,isInitializing:false},Ae();}};typeof window<"u"&&window.addEventListener("storage",e=>{if(e.key==="trieoh_access_expiry")if(!e.newValue)_.reset();else {let t=parseInt(e.newValue,10),r=!isNaN(t)&&t>Date.now();_.set({isAuthenticated:r,isInitializing:false});}});var S={getItem:e=>typeof window<"u"?localStorage.getItem(e):null,setItem:(e,t)=>{typeof window<"u"&&localStorage.setItem(e,t);},removeItem:e=>{typeof window<"u"&&localStorage.removeItem(e);}},Y={getItem:e=>typeof window<"u"?sessionStorage.getItem(e):null,setItem:(e,t)=>{typeof window<"u"&&sessionStorage.setItem(e,t);},removeItem:e=>{typeof window<"u"&&sessionStorage.removeItem(e);}},C={get:e=>{if(typeof window>"u")return null;let t=e+"=",r=document.cookie.split(";");for(let o=0;o<r.length;o++){let s=r[o];for(;s.charAt(0)===" ";)s=s.substring(1,s.length);if(s.indexOf(t)===0)return s.substring(t.length,s.length)}return null},set:(e,t,r={})=>{if(typeof window>"u")return;let{expires:o,path:s="/",domain:i,secure:n=window.location.protocol==="https:",sameSite:a=n?"None":"Lax"}=r,u=[`${e}=${t}`,i?`Domain=${i}`:"",`Path=${s}`,`SameSite=${a}`,n?"Secure":"",o?`expires=${o}`:""];document.cookie=u.filter(Boolean).join("; ");},remove:(e,t)=>{C.set(e,"",{expires:"Thu, 01 Jan 1970 00:00:00 GMT",domain:t});}};var se="trieoh_access_token",O={getAccessToken:()=>Y.getItem(se),setAccessToken:e=>{e?Y.setItem(se,e):Y.removeItem(se);},clear:()=>{Y.removeItem(se);}};var U=null,ye="trieoh_access_expiry",ae="trieoh_refresh_expiry",ne="trieoh_refresh_domain";function Ie(e){if(typeof window>"u")return null;let t=window.location.hostname;if(t==="localhost")return null;if(e)try{let r=e;return r.startsWith("http")&&(r=new URL(r).hostname),r}catch{return e}return t}function Ce(e){try{let t=e.split(".")[1];return JSON.parse(atob(t))}catch{return null}}function j(e){let{AccessTokenString:t,RefreshTokenString:r,AccessExpiresAt:o,RefreshExpiresAt:s,Domain:i}=e,n=Ce(t);if(!n){logger.error("Failed to decode tokens");return}O.setAccessToken(t);let a=new Date(s).getTime(),u=new Date(o).getTime(),d=Ie(i);C.set("refresh_token",r,{expires:new Date(a).toUTCString(),domain:d}),U={access_data:n,refresh_expiry_date:a},S.setItem(ye,String(u)),S.setItem(ae,String(a)),d?S.setItem(ne,d):S.removeItem(ne),_.set({isAuthenticated:true,isInitializing:false}),logger.log("Auth session saved");}function G(){if(U)return U;let e=O.getAccessToken();if(!e)return null;let t=Ce(e);if(!t||t.exp*1e3<=Date.now())return null;let r=S.getItem(ae);return r?(U={access_data:t,refresh_expiry_date:parseInt(r,10)},U):null}function ke(e,t){try{let r=S.getItem(e);if(!r)return !0;let o=parseInt(r,10);return isNaN(o)?!0:o-Date.now()<=t*1e3}catch(r){return logger.warn("Error reading expiry:",r),true}}var Pe=(e=30)=>ke(ye,e),le=(e=10)=>ke(ae,e);function H(){U=null,O.clear(),S.removeItem(ye),S.removeItem(ae);let e=S.getItem(ne)||Ie();C.remove("refresh_token",e),S.removeItem(ne),_.reset(),logger.log("Auth tokens and claims cleared");}function De(){let e=G();return e?e.access_data.sub:null}function Ge(){let e=typeof window>"u",t=typeof import.meta<"u"&&import.meta.env?import.meta.env:{},r=typeof process<"u"?process.env:{},o=t.VITE_TRIEOH_AUTH_PROJECT_ID||r.NEXT_PUBLIC_TRIEOH_AUTH_PROJECT_ID||r.PUBLIC_TRIEOH_AUTH_PROJECT_ID||"",s=e&&r.TRIEOH_AUTH_API_KEY||"";return {PROJECT_ID:o,API_KEY:s,BASE_URL:"https://api.trieauth.trieoh.com"}}var ce=null,be={};function Oe(e){be={...be,...e},ce=null;}function xe(){return ce||(ce={...Ge(),...be}),ce}var y={get PROJECT_ID(){return xe().PROJECT_ID},get BASE_URL(){return xe().BASE_URL}};var ue=class{constructor(t){this.isRefreshing=false;this.refreshPromise=null;this.baseURL=t?.baseURL||y.BASE_URL,this.authBaseURL=t?.authBaseURL||this.baseURL,this.onTokenRefreshed=t?.onTokenRefreshed,this.onRefreshFailed=t?.onRefreshFailed;}async refreshToken(){return this.isRefreshing&&this.refreshPromise?this.refreshPromise:(this.isRefreshing=true,this.refreshPromise=(async()=>{try{let t=await simpleFetch(ve(this.authBaseURL,"/auth/refresh"),{method:"POST",credentials:"include"});if(t.code!==200||!t.data)throw t.code!==503&&H(),new Error(t.message||"Failed to refresh token");j(t.data);let r=G();r&&this.onTokenRefreshed?.(r),logger.log("Token refreshed successfully");}catch(t){throw logger.warn("Failed to refresh token:",t),H(),this.onRefreshFailed?.(t),t}finally{this.isRefreshing=false,this.refreshPromise=null;}})(),this.refreshPromise)}async beforeRequest(){if(le()){H();return}let t=!!O.getAccessToken(),r=!!C.get("refresh_token");if(!t&&r||t&&Pe(30))try{await this.refreshToken();}catch(o){logger.warn("Proactive refresh failed:",o);}}async fetch(t,r){let o=r?.requiresAuth!==false,s=t.includes("/auth/refresh");o&&!s&&!r?.skipRefresh&&await this.beforeRequest();let i=ve(this.baseURL,t),n=async()=>{let u=O.getAccessToken(),d=new Headers(r?.headers);return o&&u&&d.set("Authorization",`Bearer ${u}`),d.has("Content-Type")||d.set("Content-Type","application/json"),fetch(i,{...r,headers:d,credentials:"include"})},a=await n();if(a.status===401&&o&&!s){logger.log("401 detected, attempting one-time retry after refresh...");try{await this.refreshToken(),a=await n();}catch{logger.error("Retry failed after refresh error");}}return a}};function L(e){if(!e)return;let{requiresAuth:t,skipRefresh:r,...o}=e,s={};return t!==void 0&&(s.requiresAuth=t),r!==void 0&&(s.skipRefresh=r),{...o,adapterInit:{...o.adapterInit,...s}}}var de=class{constructor(t,r,o,s){this.interceptor=new ue({baseURL:t,authBaseURL:r,onTokenRefreshed:o}),this.client=createDefaultFetchClient({...s,adapter:this.interceptor.fetch.bind(this.interceptor)});}request(t,r){return this.client.request(t,L(r))}get(t,r){return this.client.get(t,L(r))}post(t,r,o){return this.client.post(t,r,L(o))}put(t,r,o){return this.client.put(t,r,L(o))}patch(t,r,o){return this.client.patch(t,r,L(o))}delete(t,r,o){return this.client.delete(t,r,L(o))}query(t,r){return this.client.query(t,L(r))}};var M=()=>{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 Le=(e,t)=>({login:async(r,o)=>{y.PROJECT_ID&&M();let s=`/auth/login${y.PROJECT_ID?`?project_id=${y.PROJECT_ID}`:""}`,i=await e.post(s,{email:r,password:o},{requiresAuth:false});return i.success&&(j(i.data),t?.onLogin?.()),i},register:async(r,o)=>{let s={requiresAuth:false},i=`/auth/register${y.PROJECT_ID?`?project_id=${y.PROJECT_ID}`:""}`;y.PROJECT_ID&&M();let n=await e.post(i,{email:r,password:o},s);return n.success&&t?.onRegister?.(),n},logout:async r=>{let o=`/auth/logout${y.PROJECT_ID?`?project_id=${y.PROJECT_ID}`:""}`,s=await e.post(o);return (s.success||r?.forceLogout)&&H(),s},refresh:async()=>{let r=await e.post("/auth/refresh",void 0,{skipRefresh:true});return r.success&&(j(r.data),t?.onRefresh?.()),r},sessions:async()=>e.get("/sessions"),currentSession:async()=>e.get("/sessions/me"),revokeASession:async r=>e.delete(`/sessions/${r}`),revokeSessions:async(r=false)=>{let o=r?"/sessions":"/sessions/others";return e.delete(o)},profile:()=>De(),sendForgotPassword:async r=>{let o={requiresAuth:false},s=await(async()=>y.PROJECT_ID?(M(),e.post("/account/forgot-password",{email:r,project_id:y.PROJECT_ID},o)):e.post("/account/forgot-password",{email:r},o))();return s.success&&t?.onForgotPassword?.(),s},resetPassword:async(r,o)=>e.post(`/account/reset-password?token=${r}`,{new_password:o},{requiresAuth:false}),verifyEmail:async()=>{let r=await e.get("/account/verify",{requiresAuth:false});return r.success&&t?.onVerify?.(),r},resendVerifyEmail:async()=>e.post("/account/verify/resend"),health:async()=>e.get("/health",{requiresAuth:false}),authHealth:async()=>e.get("/protected/health")});var Ne=createContext(null);function wr({children:e,baseURL:t,projectId:r,isProjectMode:o=true,fallback:s,waitSession:i=true,clientConfig:n,onLogin:a,onForgotPassword:u,onRegister:d,onVerify:f,onRefresh:m}){let g=useRef(false),{isAuthenticated:p,isInitializing:h}=useSyncExternalStore(_.subscribe,_.getSnapshot,_.getServerSnapshot);useEffect(()=>{Oe({...r?{PROJECT_ID:r}:{},...t?{BASE_URL:t}:{}});},[r,t]);let b=useCallback(P=>{_.set({isAuthenticated:!!P.access_data,isInitializing:false}),m?.();},[m]),w=useMemo(()=>new de(t,void 0,b,n),[t,b,n]),x=useMemo(()=>Le(w,{onLogin:a,onForgotPassword:u,onRegister:d,onVerify:f,onRefresh:m}),[w,a,u,d,f,m]);useEffect(()=>{o&&M(),(async()=>{if(g.current)return;if(g.current=true,G()){_.set({isAuthenticated:true,isInitializing:false});return}if(!!!C.get("refresh_token")||le()){_.reset(),_.set({isInitializing:false});return}logger.log("No cached claims, attempting silent refresh...");try{(await x.refresh()).success?(_.set({isAuthenticated:!0,isInitializing:!1}),logger.log("Session restored.")):(_.reset(),logger.warn("No active session."));}catch{_.reset(),logger.warn("Could not restore session (offline?).");}finally{_.set({isInitializing:false});}})();},[x,o]);let I=useMemo(()=>({auth:x,isAuthenticated:p,isInitializing:h,isProjectMode:o}),[x,p,h,o]);return i&&h?s??null:jsx(Ne.Provider,{value:I,children:e})}function T(){let e=useContext(Ne);if(!e)throw new Error("useAuth must be used inside <AuthProvider>");return e}function Q(e,{insertAt:t}={}){if(!e||typeof document>"u")return;let r=document.head||document.getElementsByTagName("head")[0],o=document.createElement("style");o.type="text/css",t==="top"&&r.firstChild?r.insertBefore(o,r.firstChild):r.appendChild(o),o.styleSheet?o.styleSheet.cssText=e:o.appendChild(document.createTextNode(e));}Q(`@import"https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap";:root{--trieoh-primary: oklch(.1139 .0789 264.05);--trieoh-secondary: oklch(.7975 .1018 262.7);--trieoh-neutral1: oklch(.9702 0 0);--trieoh-neutral2: oklch(.1944 .0051 248.09);--trieoh-radius-full: 50%;--trieoh-text-sm: .75rem;--trieoh-text-base: .875rem;--trieoh-text-xl: 1.25rem;--trieoh-text-2xl: 1.5rem;--trieoh-text-3xl: 1.875rem;--trieoh-text-6xl: 3.75rem}
|
|
2
|
-
`);Q(`.trieoh{font-family:Inter,sans-serif}.trieoh-input{position:relative;width:100%;display:flex;flex-direction:column;gap:.25rem;color:var(--trieoh-neutral2)}.trieoh-input__label{font-size:1rem;font-weight:600}.trieoh-input__container{display:flex;justify-content:space-between;align-items:center;padding:.0625rem .625rem;gap:.625rem;border-bottom:solid .125rem var(--trieoh-neutral2)}.trieoh-input__container--error{border-color:#e53935!important}.trieoh-input__container-field{min-width:10rem;flex:1;font-size:var(--trieoh-text-base);font-weight:300;color:var(--trieoh-neutral2);-webkit-appearance:none;background:none;outline:none;border:none;box-shadow:none!important;padding:.125rem 0}.trieoh-input__container-icon{cursor:pointer;flex-shrink:0;-webkit-user-select:none;user-select:none}.trieoh-input__hint{font-size:.75rem;color:#6b7280;transition:opacity .2s ease-in-out}.trieoh-input__hint .hint-part{transition:color .12s ease,text-decoration .12s ease,opacity .12s ease;opacity:.95;margin:.125rem}.trieoh-input__hint .hint-part.passed{text-decoration:line-through;opacity:.6;color:#10b981}.trieoh-input__hint .hint-part.failed-on-submit{color:#e53935;font-weight:600;opacity:1}.trieoh-button{--trieoh-button-color: var(--trieoh-neutral2);width:100%;height:3.25rem;font-size:var(--trieoh-text-xl);font-weight:600;color:var(--trieoh-button-color);outline:none;background:none;position:relative;overflow:hidden;min-width:10rem;flex-shrink:0;border:.125rem solid var(--trieoh-button-color);cursor:pointer;padding:0 1.5rem;transition:transform .5s}.trieoh-button--all-rounded{border-radius:.25rem}.trieoh-button:hover{transform:scale(102%)}.trieoh-button:active{transform:scale(99%)}.trieoh-button[disabled],.trieoh-button--logout[disabled]{opacity:.6;cursor:not-allowed;transform:none!important}.trieoh-button--loading:after{content:"";position:absolute;top:0;left:-150%;width:150%;height:100%;background:linear-gradient(120deg,transparent 0%,color-mix(in oklab,var(--trieoh-button-color) 40%,white 15%) 40%,transparent 80%);animation:trieoh-shine 1.5s infinite}@keyframes trieoh-shine{0%{left:-150%}to{left:150%}}.trieoh-button--logout{border:none;background:none;cursor:pointer;--trieoh-button-color: oklch(.628 .2577 29.23);display:flex;align-items:end;gap:.25rem;font-size:var(--trieoh-text-base);font-weight:500;color:var(--trieoh-button-color);transition:transform .2s}.trieoh-button--logout:hover{transform:scale(1.05)}.trieoh-button--logout:active{transform:scale(.98)}.trieoh-avacard{display:flex;flex-direction:column;align-items:center}.trieoh-avacard__container{display:flex;justify-content:center;align-items:center;padding:.5rem;background-color:#d9d9d94d;border-radius:var(--trieoh-radius-full);margin-bottom:.625rem}.trieoh-avacard__content{width:64px;height:64px;padding:.625rem;background-color:var(--trieoh-neutral1);border-radius:var(--trieoh-radius-full);box-shadow:0 .25rem 1rem #00000040}.trieoh-avacard__title{text-align:center;font-size:var(--trieoh-text-xl);font-weight:500;margin:0}.trieoh-avacard__sub-title{text-align:center;font-size:.875rem;font-weight:300;opacity:.6}.trieoh-card{display:flex;flex-direction:column;width:100%;max-width:30rem;min-width:15rem;max-height:max(75dvh,32rem);overflow:hidden;gap:1.25rem;align-items:center;background-color:var(--trieoh-neutral1);color:var(--trieoh-neutral2);padding:1.25rem 1.5rem;box-shadow:0 .25rem .25rem #00000040;transition:transform .15s ease}.trieoh-card--full-rounded{border-radius:.25rem}.trieoh-card__fields{width:100%;display:flex;flex-direction:column;gap:.625rem;flex:1 1 auto;overflow-y:auto;margin-bottom:.5rem}.trieoh-card__divider{display:flex;align-items:center;gap:.625rem;width:100%;font-size:var(--trieoh-text-base);font-weight:600;opacity:.6}.trieoh-card__divider hr{flex:1}.trieoh-card__other{font-size:var(--trieoh-text-sm);font-weight:600}.trieoh-card__other span{cursor:pointer;color:var(--trieoh-secondary);transition:color .2s}.trieoh-card__other span:hover{color:var(--trieoh-primary)}.trieoh-copyright{font-size:var(--trieoh-text-xl);font-weight:500}.trieoh-copyright--xs{font-size:var(--trieoh-text-sm)}.trieoh-copyright--sm{font-size:var(--trieoh-text-base)}.trieoh-copyright--md{font-size:var(--trieoh-text-xl)}.trieoh-copyright--lg{font-size:var(--trieoh-text-2xl)}.trieoh-copyright--xl{font-size:var(--trieoh-text-3xl)}.trieoh-copyright--2xl{font-size:var(--trieoh-text-6xl)}.trieoh-sessions{width:100%;min-width:20rem;margin:.5rem;container-type:inline-size;background-color:var(--trieoh-neutral1);color:var(--trieoh-neutral2);padding:1.5rem .5rem;border-radius:.5rem}.trieoh-sessions__header{width:100%;display:flex;flex-wrap:wrap;align-items:center;justify-content:center;text-align:center;gap:1rem;box-sizing:border-box;padding:0 .75rem}.trieoh-sessions__header div{flex:0 1 auto;max-width:25rem}.trieoh-sessions__header div h3{font-weight:600;font-size:var(--trieoh-text-2xl);margin:0;margin-bottom:.25rem}.trieoh-sessions__header div p{font-weight:200;font-size:var(--trieoh-text-base);margin:0}.trieoh-sessions__header button{max-width:14rem;padding:1rem 0;height:auto;font-size:var(--trieoh-text-base)}.trieoh-sessions__content{margin-top:1rem}.trieoh-sessions__empty{display:block;border-top:1px solid rgba(0,0,0,.3);padding:1.25rem .75rem;text-align:center;font-weight:600}.trieoh-session{border-top:1px solid rgba(0,0,0,.3);padding:1.25rem .75rem;color:var(--trieoh-neutral2)}.trieoh-session__content{position:relative;display:flex;flex-direction:column;align-items:center;gap:.5rem;flex:1;text-align:center}.trieoh-session__info{display:flex;flex-direction:column;min-width:0}.trieoh-session__meta{display:inline-flex;flex-direction:column;font-size:var(--trieoh-text-sm);font-weight:200}.trieoh-session h3{font-size:var(--trieoh-text-base);font-weight:600;margin:0}.trieoh-session span strong{color:var(--trieoh-primary);font-weight:400}.trieoh-session__content svg:last-child{position:absolute;top:0;right:0;cursor:pointer;opacity:.6;transition:opacity .2s,transform .15s}.trieoh-session__content svg:last-child:hover{opacity:1;transform:scale(1.05)}.trieoh-session__content svg:last-child:active{transform:scale(.95)}@container (min-width: 640px){.trieoh-sessions__header{justify-content:space-between;text-align:left;gap:2rem}.trieoh-session{flex-direction:row;text-align:left}.trieoh-session__content{flex-direction:row;align-items:center;gap:1rem;text-align:left}.trieoh-session__meta{flex-direction:row;gap:.5rem;align-items:center}}
|
|
3
|
-
`);function R({name:e,label:t,placeholder:r,type:o="text",value:s,onValueChange:i,onBlur:n,autoComplete:a,rulesStatus:u=[],submitted:d=false,inputRef:f}){let[m,g]=useState(false),p=u.some(h=>!h.passed);return jsxs("div",{className:"trieoh trieoh-input",children:[jsx("label",{htmlFor:e,className:"trieoh-input__label",children:t}),jsxs("div",{className:(p&&d?"trieoh-input__container--error ":"")+"trieoh-input__container",children:[jsx("input",{type:m?"text":o,name:e,id:e,placeholder:r,value:s,onChange:h=>i&&i(h.target.value),onBlur:n,autoComplete:a,"aria-invalid":p&&d,ref:f,className:"trieoh-input__container-field"}),o==="password"&&(m?jsx(RiEyeCloseLine,{className:"trieoh-input__container-icon",size:24,onClick:()=>g(false)}):jsx(RiEyeLine,{className:"trieoh-input__container-icon",size:24,onClick:()=>g(true)}))]}),jsx("div",{className:"trieoh-input__hint",children:u.map((h,b)=>{let w=["hint-part",h.passed?"passed":"",!h.passed&&d?"failed-on-submit":""].filter(Boolean).join(" ");return jsx("p",{className:w,children:h.message},h.id??b)})})]})}function B({label:e,onSubmit:t,loading:r}){return jsx("button",{type:"submit",onClick:t,disabled:r,className:`trieoh trieoh-button trieoh-button--all-rounded
|
|
4
|
-
${r?"trieoh-button--loading":""}`,children:e})}function N({mainText:e,subText:t}){return jsxs("div",{className:"trieoh trieoh-avacard",children:[jsx("div",{className:"trieoh-avacard__container",children:jsx(GoPerson,{className:"trieoh-avacard__content",size:70})}),jsx("h3",{className:"trieoh-avacard__title",children:e}),jsx("span",{className:"trieoh-avacard__sub-title",children:t})]})}function E(e,t){return e.map(r=>({id:r.id,message:r.message,passed:!!r.test(t)}))}function ut({onSuccess:e,onFailed:t,signUpRedirect:r,forgotPasswordRedirect:o,emailRules:s}){let[i,n]=useState(""),[a,u]=useState(""),[d,f]=useState(false),[m,g]=useState(false),p=useRef(null),h=useRef(null),{auth:b}=T(),w={email:s||[{message:"Digite um e-mail v\xE1lido, ex: exemplo@dominio.com",test:D=>/\S+@\S+\.\S+/.test(D)}],password:[]},x=E(w.email,i),I=E(w.password,a);return jsxs("form",{className:"trieoh trieoh-card trieoh-card--full-rounded",children:[jsx(N,{mainText:"Fa\xE7a login na sua conta",subText:"Insira seus dados para fazer login"}),jsxs("div",{className:"trieoh-card__fields",children:[jsx(R,{label:"Email",name:"email",placeholder:"teste@gmail.com",autoComplete:"email",type:"email",value:i,onValueChange:n,inputRef:p,rulesStatus:x,submitted:d}),jsx(R,{label:"Senha",name:"password",placeholder:"**********",autoComplete:"current-password",type:"password",value:a,onValueChange:u,inputRef:h,rulesStatus:I,submitted:d})]}),jsx(B,{label:"Entrar",onSubmit:async D=>{D.preventDefault(),f(true);let $=x.some(v=>!v.passed),re=I.some(v=>!v.passed);if($){p.current?.focus();return}if(re){h.current?.focus();return}g(true);let J=await b.login(i,a);J.success?e&&await e(J.message):t&&await t(J.message,J.trace),g(false);},loading:m}),o&&jsx("span",{className:"trieoh-card__other",style:{textAlign:"center",cursor:"pointer"},children:jsx("span",{onClick:o,children:"Esqueceu sua senha?"})}),r&&jsxs(Fragment,{children:[jsxs("div",{className:"trieoh-card__divider",children:[jsx("hr",{}),"OU",jsx("hr",{})]}),jsxs("span",{className:"trieoh-card__other",children:["Ainda n\xE3o possui uma conta? ",jsx("span",{onClick:r,children:"Cadastra-se"})]})]})]})}function mt({onSuccess:e,onFailed:t,loginRedirect:r,emailRules:o,passwordRules:s}){let[i,n]=useState(""),[a,u]=useState(""),[d,f]=useState(""),[m,g]=useState(false),[p,h]=useState(false),b=useRef(null),w=useRef(null),x=useRef(null),{auth:I}=T(),P={email:o||[{message:"Digite um e-mail v\xE1lido, ex: exemplo@dominio.com",test:v=>/\S+@\S+\.\S+/.test(v)}],password:s||[{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===a}]},D=E(P.email,i),$=E(P.password,a),re=E(P.confirmPassword,d);return jsxs("form",{className:"trieoh trieoh-card trieoh-card--full-rounded",children:[jsx(N,{mainText:"Crie sua conta",subText:"Insira seus dados para come\xE7ar"}),jsxs("div",{className:"trieoh-card__fields",children:[jsx(R,{label:"Email",name:"email",placeholder:"teste@gmail.com",autoComplete:"email",type:"email",value:i,onValueChange:n,inputRef:b,rulesStatus:D,submitted:m}),jsx(R,{label:"Senha",name:"password",placeholder:"**********",autoComplete:"new-password",type:"password",value:a,onValueChange:u,inputRef:w,rulesStatus:$,submitted:m}),jsx(R,{label:"Confirme a Senha",name:"confirm-password",placeholder:"**********",autoComplete:"new-password",type:"password",value:d,onValueChange:f,inputRef:x,rulesStatus:re,submitted:m})]}),jsx(B,{label:"Criar Conta",onSubmit:async v=>{v.preventDefault(),g(true);let Ke=D.some(V=>!V.passed),Ye=$.some(V=>!V.passed),je=re.some(V=>!V.passed);if(Ke){b.current?.focus();return}if(Ye){w.current?.focus();return}if(je){x.current?.focus();return}h(true);let oe=await I.register(i,a);oe.success?e&&await e(oe.message):t&&await t(oe.message,oe.trace),h(false);},loading:p}),r&&jsxs(Fragment,{children:[jsxs("div",{className:"trieoh-card__divider",children:[jsx("hr",{}),"OU",jsx("hr",{})]}),jsxs("span",{className:"trieoh-card__other",children:["J\xE1 possui uma conta? ",jsx("span",{onClick:r,children:"Entre"})]})]})]})}function ht({size:e}){let t=e?`trieoh-copyright--${e}`:"";return jsxs("span",{className:`trieoh trieoh-copyright ${t}`,children:["\xA9 ",new Date().getFullYear()," TrieOH"]})}function _t({onSuccess:e,onFailed:t,forceLogout:r}){let{auth:o}=T(),[s,i]=useState(false);return jsxs("button",{onClick:async a=>{if(a.preventDefault(),s)return;i(true);let u=await o.logout({forceLogout:r});u.success?e&&await e(u.message):t&&await t(u.message,u.trace),i(false);},type:"button",disabled:s,className:"trieoh trieoh-button--logout",children:[jsx(ImExit,{size:24})," ",jsx("span",{children:"Log out"})]})}var Me={mobile:FaMobileAlt,tablet:FaTabletAlt,desktop:FaDesktop};function ze(e){let{device:t,os:r,browser:o}=UAParser(e);return {deviceType:t.type??"desktop",os:r.name,browser:o.name}}function qe(e){let t=ze(e);return {device:Rt(t.deviceType),os:t.os,browser:t.browser}}function Rt(e){if(!e)return "desktop";switch(e){case "mobile":return "mobile";case "tablet":return "tablet";default:return "desktop"}}function $e(e){let t=Date.now()-new Date(e).getTime(),r=Math.floor(t/1e3),o=Math.floor(r/60),s=Math.floor(o/60),i=Math.floor(s/24),n=Math.floor(i/7);return r<60?"agora mesmo":o<60?`${o} minutos atr\xE1s`:s<24?`${s} horas atr\xE1s`:i<7?`${i} dias atr\xE1s`:`${n} semanas atr\xE1s`}function Re({is_current:e,session_id:t,user_agent:r,issued_at:o,user_ip:s,onClick:i}){let n=qe(r),a=Me[n.device];return jsx("div",{className:"trieoh-session",children:jsxs("div",{className:"trieoh-session__content",children:[jsx(a,{size:40}),jsxs("div",{className:"trieoh-session__info",children:[jsxs("h3",{children:[n.browser," - ",n.os]}),jsxs("span",{className:"trieoh-session__meta",children:[e&&jsx("strong",{children:"\u2022 Sess\xE3o Atual \u2022"}),jsx("span",{children:`${s} - ${$e(o)}`})]})]}),!e&&jsx(FaTrashAlt,{size:20,color:"red",onClick:u=>i(u,t)})]})})}function At({revokeAll:e=false,onSuccess:t}){let{auth:r}=T(),[o,s]=useState(false),[i,n]=useState([]),a=async()=>{let f=await r.sessions();if(f.success){let m=r.profile()?.session_id,g=f.data.sort((p,h)=>p.session_id===m?-1:h.session_id===m?1:0);n(g);}};useEffect(()=>{a();},[]);let u=async(f,m)=>{f.preventDefault();let g=i.find(p=>p.session_id===m);if(g){n(i.filter(p=>p.session_id!==m));try{(await r.revokeASession(m)).success||n(h=>[...h,g]);}catch{n(p=>[...p,g]);}}};return jsxs("div",{className:"trieoh trieoh-sessions",children:[jsxs("div",{className:"trieoh-sessions__header",children:[jsxs("div",{children:[jsx("h3",{children:"Navegadores e Dispositivos"}),jsx("p",{children:"Esses navegadores e dispositivos est\xE3o atualmente conectados \xE0 sua conta. Remova quaisquer dispositivos n\xE3o autorizados."})]}),jsx("button",{type:"submit",onClick:async f=>{if(f.preventDefault(),o)return;s(true);let m=await r.revokeSessions(e),g=r.profile()?.session_id;m.success&&(n(e?[]:i.filter(p=>p.session_id===g)),t&&t(m.message)),s(false);},disabled:o,className:`trieoh trieoh-button trieoh-button--all-rounded
|
|
5
|
-
${o?"trieoh-button--loading":""}`,children:"Revogar todas as sess\xF5es"})]}),jsx("div",{className:"trieoh-sessions__content",children:i.length>0?i.map(f=>jsx(Re,{...f,is_current:r.profile()?.session_id===f.session_id,onClick:u},f.session_id)):jsx("span",{className:"trieoh-sessions__empty",children:"Nenhuma Sess\xE3o Dispon\xEDvel"})})]})}function Ve({onSuccess:e,onFailed:t,loginRedirect:r,emailRules:o}){let[s,i]=useState(""),[n,a]=useState(false),[u,d]=useState(false),f=useRef(null),{auth:m}=T(),p=E({email:o||[{message:"Digite um e-mail v\xE1lido, ex: exemplo@dominio.com",test:b=>/\S+@\S+\.\S+/.test(b)}]}.email,s);return jsxs("form",{className:"trieoh trieoh-card trieoh-card--full-rounded",children:[jsx(N,{mainText:"Esqueci a senha",subText:"Insira seu e-mail para receber um link de redefini\xE7\xE3o."}),jsx("div",{className:"trieoh-card__fields",children:jsx(R,{label:"Email",name:"email",placeholder:"teste@gmail.com",autoComplete:"email",type:"email",value:s,onValueChange:i,inputRef:f,rulesStatus:p,submitted:n})}),jsx(B,{label:u?"Enviando...":"Enviar link de redefini\xE7\xE3o",onSubmit:async b=>{if(b.preventDefault(),a(true),p.some(I=>!I.passed)){f.current?.focus();return}d(true);let x=await m.sendForgotPassword(s);x.success?e&&await e(x.message):t&&await t(x.message,x.trace),d(false);},loading:u}),r&&jsxs(Fragment,{children:[jsxs("div",{className:"trieoh-card__divider",children:[jsx("hr",{}),"OU",jsx("hr",{})]}),jsxs("span",{className:"trieoh-card__other",children:["Lembrou-se da sua senha? ",jsx("span",{onClick:r,children:"Login"})]})]})]})}export{wr as AuthProvider,R as BasicInputField,_t as BasicLogoutButton,ht as Copyright,Ve as ForgotPassword,At as Sessions,ut as SignIn,mt as SignUp,T as useAuth};//# sourceMappingURL=react.js.map
|
|
1
|
+
import {createContext,useRef,useSyncExternalStore,useEffect,useCallback,useMemo,useContext,useState}from'react';import {logger,createDefaultFetchClient,simpleFetch}from'@trieoh/envoy-fetch-ts';import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {RiEyeCloseLine,RiEyeLine}from'react-icons/ri';import {GoPerson}from'react-icons/go';import {ImExit}from'react-icons/im';import {FaDesktop,FaTabletAlt,FaMobileAlt,FaTrashAlt}from'react-icons/fa';import {UAParser}from'ua-parser-js';import {FiCheck,FiInfo}from'react-icons/fi';function xe(e,t){if(t.startsWith("http"))return t;let r=e.replace(/\/$/,""),o=t.replace(/^\//,"");return `${r}/${o}`}var Y={isAuthenticated:false,isInitializing:true},be=new Set,De=()=>be.forEach(e=>e()),b={subscribe:e=>(be.add(e),()=>be.delete(e)),getSnapshot:()=>Y,getServerSnapshot:()=>Y,set:e=>{Y={...Y,...e},De();},reset:()=>{Y={isAuthenticated:false,isInitializing:false},De();}};typeof window<"u"&&window.addEventListener("storage",e=>{if(e.key==="trieoh_access_expiry")if(!e.newValue)b.reset();else {let t=parseInt(e.newValue,10),r=!isNaN(t)&&t>Date.now();b.set({isAuthenticated:r,isInitializing:false});}});var I={getItem:e=>typeof window<"u"?localStorage.getItem(e):null,setItem:(e,t)=>{typeof window<"u"&&localStorage.setItem(e,t);},removeItem:e=>{typeof window<"u"&&localStorage.removeItem(e);}},G={getItem:e=>typeof window<"u"?sessionStorage.getItem(e):null,setItem:(e,t)=>{typeof window<"u"&&sessionStorage.setItem(e,t);},removeItem:e=>{typeof window<"u"&&sessionStorage.removeItem(e);}},O={get:e=>{if(typeof window>"u")return null;let t=e+"=",r=document.cookie.split(";");for(let o=0;o<r.length;o++){let i=r[o];for(;i.charAt(0)===" ";)i=i.substring(1,i.length);if(i.indexOf(t)===0)return i.substring(t.length,i.length)}return null},set:(e,t,r={})=>{if(typeof window>"u")return;let{expires:o,path:i="/",domain:s,secure:n=window.location.protocol==="https:",sameSite:l=n?"None":"Lax"}=r,a=window.location.hostname==="localhost",d=[`${e}=${t}`,s&&!a?`Domain=${s}`:"",`Path=${i}`,`SameSite=${l}`,n?"Secure":"",o?`expires=${o}`:""];document.cookie=d.filter(Boolean).join("; ");},remove:(e,t)=>{O.set(e,"",{expires:"Thu, 01 Jan 1970 00:00:00 GMT",domain:t});}};var se="trieoh_access_token",F={getAccessToken:()=>G.getItem(se),setAccessToken:e=>{e?G.setItem(se,e):G.removeItem(se);},clear:()=>{G.removeItem(se);}};var V=null,ye="trieoh_access_expiry",le="trieoh_refresh_expiry",ae="trieoh_refresh_domain";function Oe(e){if(typeof window>"u")return null;let t=window.location.hostname;if(e)try{let r=e;return r.startsWith("http")&&(r=new URL(r).hostname),r}catch{return e}return t}function Me(e){try{let t=e.split(".")[1];return JSON.parse(atob(t))}catch{return null}}function X(e){let{access_token_string:t,refresh_token_string:r,access_expires_at:o,refresh_expires_at:i}=e,s=Me(t);if(!s){logger.error("Failed to decode tokens");return}F.setAccessToken(t);let n=new Date(i).getTime(),l=new Date(o).getTime(),a=Oe(e.domain);O.set("refresh_token",r,{expires:new Date(n).toUTCString(),domain:a}),V={access_data:s,refresh_expiry_date:n},I.setItem(ye,String(l)),I.setItem(le,String(n)),a?I.setItem(ae,a):I.removeItem(ae),b.set({isAuthenticated:true,isInitializing:false}),logger.log("Auth session saved");}function Q(){if(V)return V;let e=F.getAccessToken();if(!e)return null;let t=Me(e);if(!t||t.exp*1e3<=Date.now())return null;let r=I.getItem(le);return r?(V={access_data:t,refresh_expiry_date:parseInt(r,10)},V):null}function Be(e,t){try{let r=I.getItem(e);if(!r)return !0;let o=parseInt(r,10);return isNaN(o)?!0:o-Date.now()<=t*1e3}catch(r){return logger.warn("Error reading expiry:",r),true}}var Se=(e=30)=>Be(ye,e),ce=(e=10)=>Be(le,e);function q(){V=null,F.clear(),I.removeItem(ye),I.removeItem(le);let e=I.getItem(ae)||Oe();O.remove("refresh_token",e),I.removeItem(ae),b.reset(),logger.log("Auth tokens and claims cleared");}function Fe(){let e=Q();return e?e.access_data.sub:null}function it(){let e=typeof window>"u",t=typeof import.meta<"u"&&import.meta.env?import.meta.env:{},r=typeof process<"u"?process.env:{},o=t.VITE_TRIEOH_AUTH_PROJECT_ID||r.NEXT_PUBLIC_TRIEOH_AUTH_PROJECT_ID||r.PUBLIC_TRIEOH_AUTH_PROJECT_ID||"",i=e&&r.TRIEOH_AUTH_API_KEY||"";return {PROJECT_ID:o,API_KEY:i,BASE_URL:"https://api.trieauth.trieoh.com"}}var ue=null,_e={};function Ue(e){_e={..._e,...e},ue=null;}function Re(){return ue||(ue={...it(),..._e}),ue}var y={get PROJECT_ID(){return Re().PROJECT_ID},get BASE_URL(){return Re().BASE_URL}};var me=class{constructor(t){this.isRefreshing=false;this.refreshPromise=null;this.baseURL=t?.baseURL||y.BASE_URL,this.authBaseURL=t?.authBaseURL||this.baseURL,this.onTokenRefreshed=t?.onTokenRefreshed,this.onRefreshFailed=t?.onRefreshFailed;}async refreshToken(){return this.isRefreshing&&this.refreshPromise?this.refreshPromise:(this.isRefreshing=true,this.refreshPromise=(async()=>{try{let t=await simpleFetch(xe(this.authBaseURL,"/auth/refresh"),{method:"POST",credentials:"include"});if(t.code!==200||!t.data)throw t.code!==503&&q(),new Error(t.message||"Failed to refresh token");X(t.data);let r=Q();r&&this.onTokenRefreshed?.(r),logger.log("Token refreshed successfully");}catch(t){throw logger.warn("Failed to refresh token:",t),q(),this.onRefreshFailed?.(t),t}finally{this.isRefreshing=false,this.refreshPromise=null;}})(),this.refreshPromise)}async beforeRequest(){if(ce()){q();return}let t=!!F.getAccessToken(),r=!!O.get("refresh_token");if(!t&&r||t&&Se(30))try{await this.refreshToken();}catch(o){logger.warn("Proactive refresh failed:",o);}}async fetch(t,r){let o=r?.requiresAuth!==false,i=t.includes("/auth/refresh");o&&!i&&!r?.skipRefresh&&await this.beforeRequest();let s=xe(this.baseURL,t),n=async()=>{let a=F.getAccessToken(),d=new Headers(r?.headers);return o&&a&&d.set("Authorization",`Bearer ${a}`),d.has("Content-Type")||d.set("Content-Type","application/json"),fetch(s,{...r,headers:d,credentials:"include"})},l=await n();if(l.status===401&&o&&!i&&Se(30)){logger.log("401 detected and token is expiring/expired, attempting refresh...");try{await this.refreshToken(),l=await n();}catch{logger.error("Retry failed after refresh error");}}return l}};function U(e){if(!e)return;let{requiresAuth:t,skipRefresh:r,...o}=e,i={};return t!==void 0&&(i.requiresAuth=t),r!==void 0&&(i.skipRefresh=r),{...o,adapterInit:{...o.adapterInit,...i}}}var de=class{constructor(t,r,o,i){this.interceptor=new me({baseURL:t,authBaseURL:r,onTokenRefreshed:o}),this.client=createDefaultFetchClient({...i,adapter:this.interceptor.fetch.bind(this.interceptor)});}request(t,r){return this.client.request(t,U(r))}get(t,r){return this.client.get(t,U(r))}post(t,r,o){return this.client.post(t,r,U(o))}put(t,r,o){return this.client.put(t,r,U(o))}patch(t,r,o){return this.client.patch(t,r,U(o))}delete(t,r,o){return this.client.delete(t,r,U(o))}query(t,r){return this.client.query(t,U(r))}};var $=()=>{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 He=(e,t)=>({login:async(r,o)=>{y.PROJECT_ID&&$();let i=`/auth/login${y.PROJECT_ID?`?project_id=${y.PROJECT_ID}`:""}`,s=await e.post(i,{email:r,password:o},{requiresAuth:false});return s.success&&(X(s.data),t?.onLogin?.(s)),s},register:async(r,o)=>{let i={requiresAuth:false},s=`/auth/register${y.PROJECT_ID?`?project_id=${y.PROJECT_ID}`:""}`;y.PROJECT_ID&&$();let n=await e.post(s,{email:r,password:o},i);return n.success&&t?.onRegister?.(n),n},logout:async r=>{let o=`/auth/logout${y.PROJECT_ID?`?project_id=${y.PROJECT_ID}`:""}`,i=await e.post(o);return (i.success||r?.forceLogout)&&q(),i},refresh:async()=>{let r=await e.post("/auth/refresh",void 0,{skipRefresh:true});return r.success&&(X(r.data),t?.onRefresh?.(r)),r},sessions:async()=>e.get("/sessions"),currentSession:async()=>e.get("/sessions/me"),revokeASession:async r=>e.delete(`/sessions/${r}`),revokeSessions:async(r=false)=>{let o=r?"/sessions":"/sessions/others";return e.delete(o)},profile:()=>Fe(),sendForgotPassword:async r=>{let o={requiresAuth:false};return y.PROJECT_ID?($(),e.post("/account/forgot-password",{email:r,project_id:y.PROJECT_ID},o)):e.post("/account/forgot-password",{email:r},o)},resetPassword:async(r,o)=>{let i=await e.post(`/account/reset-password?token=${r}`,{new_password:o},{requiresAuth:false});return i.success&&t?.onResetPassword?.(i),i},verifyEmail:async r=>{let o=`/account/verify?token=${r}`,i=await e.post(o);return i.success&&t?.onVerify?.(i),i},resendVerifyEmail:async()=>e.post("/account/verify/resend"),health:async()=>e.get("/health",{requiresAuth:false}),authHealth:async()=>e.get("/protected/health")});var Ve=createContext(null);function zr({children:e,baseURL:t,projectId:r,isProjectMode:o=true,fallback:i,waitSession:s=true,clientConfig:n,onLogin:l,onResetPassword:a,onRegister:d,onVerify:h,onRefresh:f}){let g=useRef(false),{isAuthenticated:p,isInitializing:c}=useSyncExternalStore(b.subscribe,b.getSnapshot,b.getServerSnapshot);useEffect(()=>{Ue({...r?{PROJECT_ID:r}:{},...t?{BASE_URL:t}:{}});},[r,t]);let R=useCallback(D=>{b.set({isAuthenticated:!!D.access_data,isInitializing:false}),f?.();},[f]),_=useMemo(()=>new de(t,void 0,R,n),[t,R,n]),x=useMemo(()=>He(_,{onLogin:l,onResetPassword:a,onRegister:d,onVerify:h,onRefresh:f}),[_,l,a,d,h,f]);useEffect(()=>{o&&$(),(async()=>{if(g.current)return;if(g.current=true,Q()){b.set({isAuthenticated:true,isInitializing:false});return}if(!!!O.get("refresh_token")||ce()){b.reset(),b.set({isInitializing:false});return}logger.log("No cached claims, attempting silent refresh...");try{(await x.refresh()).success?(b.set({isAuthenticated:!0,isInitializing:!1}),logger.log("Session restored.")):(b.reset(),logger.warn("No active session."));}catch{b.reset(),logger.warn("Could not restore session (offline?).");}finally{b.set({isInitializing:false});}})();},[x,o]);let A=useMemo(()=>({auth:x,isAuthenticated:p,isInitializing:c,isProjectMode:o}),[x,p,c,o]);return s&&c?i??null:jsx(Ve.Provider,{value:A,children:e})}function S(){let e=useContext(Ve);if(!e)throw new Error("useAuth must be used inside <AuthProvider>");return e}function ke(e,{insertAt:t}={}){if(typeof document>"u")return;let r=document.head||document.getElementsByTagName("head")[0],o=document.createElement("style");o.type="text/css",t==="top"&&r.firstChild?r.insertBefore(o,r.firstChild):r.appendChild(o),o.styleSheet?o.styleSheet.cssText=e:o.appendChild(document.createTextNode(e));}ke(`/*! 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 E({name:e,label:t,placeholder:r,type:o="text",value:i,onValueChange:s,onBlur:n,autoComplete:l,rulesStatus:a=[],submitted:d=false,inputRef:h}){let[f,g]=useState(false),p=a.some(c=>!c.passed);return jsxs("div",{className:"font-inter relative w-full flex flex-col gap-1 text-trieoh-neutral2",children:[jsx("label",{htmlFor:e,className:"text-[1rem] font-semibold",children:t}),jsxs("div",{className:`flex justify-between items-center px-[0.625rem] py-[0.0625rem] gap-[0.625rem] border-b-2 border-trieoh-neutral2 ${p&&d?"!border-[#e53935]":""}`,children:[jsx("input",{type:f?"text":o,name:e,id:e,placeholder:r,value:i,onChange:c=>s&&s(c.target.value),onBlur:n,autoComplete:l,"aria-invalid":p&&d,ref:h,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?jsx(RiEyeCloseLine,{className:"cursor-pointer shrink-0 select-none",size:24,onClick:()=>g(false)}):jsx(RiEyeLine,{className:"cursor-pointer shrink-0 select-none",size:24,onClick:()=>g(true)}))]}),jsx("div",{className:"text-[0.75rem] text-[#6b7280] transition-opacity duration-200 ease-in-out",children:a.map((c,R)=>{let _=["transition-[color,text-decoration,opacity] duration-[120ms] ease opacity-95 m-[0.125rem]",c.passed?"line-through opacity-60 text-[#10b981]":"",!c.passed&&d?"text-[#e53935] font-semibold opacity-100":""].filter(Boolean).join(" ");return jsx("p",{className:_,children:c.message},c.id??R)})})]})}function k({label:e,onSubmit:t,loading:r}){return jsx("button",{type:"submit",onClick:t,disabled:r,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 ${r?"trieoh-button-loading":""}`,children:e})}function T({mainText:e,subText:t}){return jsxs("div",{className:"font-inter flex flex-col items-center",children:[jsx("div",{className:"flex justify-center items-center p-2 bg-[oklch(0.8853_0_0/30%)] rounded-trieoh-full mb-[0.625rem]",children:jsx(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})}),jsx("h3",{className:"text-center text-trieoh-xl font-medium m-0",children:e}),jsx("span",{className:"text-center text-[0.875rem] font-light opacity-60",children:t})]})}function C(e,t){return e.map(r=>({id:r.id,message:r.message,passed:!!r.test(t)}))}function xt({onSuccess:e,onFailed:t,signUpRedirect:r,forgotPasswordRedirect:o,emailRules:i}){let[s,n]=useState(""),[l,a]=useState(""),[d,h]=useState(false),[f,g]=useState(false),p=useRef(null),c=useRef(null),{auth:R}=S(),_={email:i||[{message:"Digite um e-mail v\xE1lido, ex: exemplo@dominio.com",test:w=>/\S+@\S+\.\S+/.test(w)}],password:[]},x=C(_.email,s),A=C(_.password,l);return 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:[jsx(T,{mainText:"Fa\xE7a login na sua conta",subText:"Insira seus dados para fazer login"}),jsxs("div",{className:"w-full flex flex-col gap-[0.625rem] flex-[1_1_auto] overflow-y-auto mb-2",children:[jsx(E,{label:"Email",name:"email",placeholder:"teste@gmail.com",autoComplete:"email",type:"email",value:s,onValueChange:n,inputRef:p,rulesStatus:x,submitted:d}),jsx(E,{label:"Senha",name:"password",placeholder:"**********",autoComplete:"current-password",type:"password",value:l,onValueChange:a,inputRef:c,rulesStatus:A,submitted:d})]}),jsx(k,{label:"Entrar",onSubmit:async w=>{w.preventDefault(),h(true);let B=x.some(v=>!v.passed),z=A.some(v=>!v.passed);if(B){p.current?.focus();return}if(z){c.current?.focus();return}g(true);let N=await R.login(s,l);N.success?e&&await e(N.message):t&&await t(N.message,N.trace),g(false);},loading:f}),o&&jsx("span",{className:"text-trieoh-sm font-semibold text-center cursor-pointer",children:jsx("span",{className:"cursor-pointer text-trieoh-secondary transition-colors duration-200 hover:text-trieoh-primary",onClick:o,children:"Esqueceu sua senha?"})}),r&&jsxs(Fragment,{children:[jsxs("div",{className:"flex items-center gap-[0.625rem] w-full text-trieoh-base font-semibold opacity-60",children:[jsx("hr",{className:"flex-1"}),"OU",jsx("hr",{className:"flex-1"})]}),jsxs("span",{className:"text-trieoh-sm font-semibold",children:["Ainda n\xE3o possui uma conta? ",jsx("span",{className:"cursor-pointer text-trieoh-secondary transition-colors duration-200 hover:text-trieoh-primary",onClick:r,children:"Cadastra-se"})]})]})]})}function yt({onSuccess:e,onFailed:t,loginRedirect:r,emailRules:o,passwordRules:i}){let[s,n]=useState(""),[l,a]=useState(""),[d,h]=useState(""),[f,g]=useState(false),[p,c]=useState(false),R=useRef(null),_=useRef(null),x=useRef(null),{auth:A}=S(),D={email:o||[{message:"Digite um e-mail v\xE1lido, ex: exemplo@dominio.com",test:v=>/\S+@\S+\.\S+/.test(v)}],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===l}]},w=C(D.email,s),B=C(D.password,l),z=C(D.confirmPassword,d);return 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:[jsx(T,{mainText:"Crie sua conta",subText:"Insira seus dados para come\xE7ar"}),jsxs("div",{className:"w-full flex flex-col gap-[0.625rem] flex-[1_1_auto] overflow-y-auto mb-2",children:[jsx(E,{label:"Email",name:"email",placeholder:"teste@gmail.com",autoComplete:"email",type:"email",value:s,onValueChange:n,inputRef:R,rulesStatus:w,submitted:f}),jsx(E,{label:"Senha",name:"password",placeholder:"**********",autoComplete:"new-password",type:"password",value:l,onValueChange:a,inputRef:_,rulesStatus:B,submitted:f}),jsx(E,{label:"Confirme a Senha",name:"confirm-password",placeholder:"**********",autoComplete:"new-password",type:"password",value:d,onValueChange:h,inputRef:x,rulesStatus:z,submitted:f})]}),jsx(k,{label:"Criar Conta",onSubmit:async v=>{v.preventDefault(),g(true);let tt=w.some(K=>!K.passed),rt=B.some(K=>!K.passed),ot=z.some(K=>!K.passed);if(tt){R.current?.focus();return}if(rt){_.current?.focus();return}if(ot){x.current?.focus();return}c(true);let ie=await A.register(s,l);ie.success?e&&await e(ie.message):t&&await t(ie.message,ie.trace),c(false);},loading:p}),r&&jsxs(Fragment,{children:[jsxs("div",{className:"flex items-center gap-[0.625rem] w-full text-trieoh-base font-semibold opacity-60",children:[jsx("hr",{className:"flex-1"}),"OU",jsx("hr",{className:"flex-1"})]}),jsxs("span",{className:"text-trieoh-sm font-semibold",children:["J\xE1 possui uma conta? ",jsx("span",{className:"cursor-pointer text-trieoh-secondary transition-colors duration-200 hover:text-trieoh-primary",onClick:r,children:"Entre"})]})]})]})}var Rt={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 _t({size:e}){let t=e?Rt[e]:"text-trieoh-xl";return jsxs("span",{className:`font-inter font-medium ${t}`,children:["\xA9 ",new Date().getFullYear()," TrieOH"]})}function Ct({onSuccess:e,onFailed:t,forceLogout:r}){let{auth:o}=S(),[i,s]=useState(false);return jsxs("button",{onClick:async l=>{if(l.preventDefault(),i)return;s(true);let a=await o.logout({forceLogout:r});a.success?e&&await e(a.message):t&&await t(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:[jsx(ImExit,{size:24})," ",jsx("span",{children:"Log out"})]})}var je={mobile:FaMobileAlt,tablet:FaTabletAlt,desktop:FaDesktop};function Ke(e){let{device:t,os:r,browser:o}=UAParser(e);return {deviceType:t.type??"desktop",os:r.name,browser:o.name}}function Ye(e){let t=Ke(e);return {device:Dt(t.deviceType),os:t.os,browser:t.browser}}function Dt(e){if(!e)return "desktop";switch(e){case "mobile":return "mobile";case "tablet":return "tablet";default:return "desktop"}}function Ge(e){let t=Date.now()-new Date(e).getTime(),r=Math.floor(t/1e3),o=Math.floor(r/60),i=Math.floor(o/60),s=Math.floor(i/24),n=Math.floor(s/7);return r<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 Ce({is_current:e,session_id:t,user_agent:r,issued_at:o,user_ip:i,onClick:s}){let n=Ye(r),l=je[n.device];return jsx("div",{className:"border-t border-[rgba(0,0,0,0.3)] p-[1.25rem_0.75rem] text-trieoh-neutral2",children: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:[jsx(l,{size:40}),jsxs("div",{className:"flex flex-col min-w-0",children:[jsxs("h3",{className:"text-trieoh-base font-semibold m-0",children:[n.browser," - ",n.os]}),jsxs("span",{className:"inline-flex flex-col text-trieoh-sm font-extralight @[640px]:flex-row @[640px]:gap-2 @[640px]:items-center",children:[e&&jsx("strong",{className:"text-trieoh-primary font-normal",children:"\u2022 Sess\xE3o Atual \u2022"}),jsx("span",{children:`${i} - ${Ge(o)}`})]})]}),!e&&jsx(FaTrashAlt,{size:20,color:"red",onClick:a=>s(a,t),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 Bt({revokeAll:e=false,onSuccess:t}){let{auth:r}=S(),[o,i]=useState(false),[s,n]=useState([]),l=async()=>{let h=await r.sessions();if(h.success){let f=r.profile()?.session_id,g=h.data.sort((p,c)=>p.session_id===f?-1:c.session_id===f?1:0);n(g);}};useEffect(()=>{l();},[]);let a=async(h,f)=>{h.preventDefault();let g=s.find(p=>p.session_id===f);if(g){n(s.filter(p=>p.session_id!==f));try{(await r.revokeASession(f)).success||n(c=>[...c,g]);}catch{n(p=>[...p,g]);}}};return 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:[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:[jsxs("div",{className:"flex-[0_1_auto] max-w-[25rem]",children:[jsx("h3",{className:"font-semibold text-trieoh-2xl m-0 mb-1",children:"Navegadores e Dispositivos"}),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."})]}),jsx("button",{type:"submit",onClick:async h=>{if(h.preventDefault(),o)return;i(true);let f=await r.revokeSessions(e),g=r.profile()?.session_id;f.success&&(n(e?[]:s.filter(p=>p.session_id===g)),t&&t(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"})]}),jsx("div",{className:"mt-4",children:s.length>0?s.map(h=>jsx(Ce,{...h,is_current:r.profile()?.session_id===h.session_id,onClick:a},h.session_id)):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 Qe({onSuccess:e,onFailed:t,loginRedirect:r,emailRules:o}){let[i,s]=useState(""),[n,l]=useState(false),[a,d]=useState(false),h=useRef(null),{auth:f}=S(),p=C({email:o||[{message:"Digite um e-mail v\xE1lido, ex: exemplo@dominio.com",test:R=>/\S+@\S+\.\S+/.test(R)}]}.email,i);return 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:[jsx(T,{mainText:"Esqueci a senha",subText:"Insira seu e-mail para receber um link de redefini\xE7\xE3o."}),jsx("div",{className:"w-full flex flex-col gap-[0.625rem] flex-[1_1_auto] overflow-y-auto mb-2",children:jsx(E,{label:"Email",name:"email",placeholder:"teste@gmail.com",autoComplete:"email",type:"email",value:i,onValueChange:s,inputRef:h,rulesStatus:p,submitted:n})}),jsx(k,{label:a?"Enviando...":"Enviar link de redefini\xE7\xE3o",onSubmit:async R=>{if(R.preventDefault(),l(true),p.some(A=>!A.passed)){h.current?.focus();return}d(true);let x=await f.sendForgotPassword(i);x.success?e&&await e(x.message):t&&await t(x.message,x.trace),d(false);},loading:a}),r&&jsxs(Fragment,{children:[jsxs("div",{className:"flex items-center gap-[0.625rem] w-full text-trieoh-base font-semibold opacity-60",children:[jsx("hr",{className:"flex-1"}),"OU",jsx("hr",{className:"flex-1"})]}),jsxs("span",{className:"text-trieoh-sm font-semibold",children:["Lembrou-se da sua senha? ",jsx("span",{className:"cursor-pointer text-trieoh-secondary transition-colors duration-200 hover:text-trieoh-primary",onClick:r,children:"Login"})]})]})]})}function Ht({token:e,onSuccess:t,onFailed:r,loginRedirect:o,passwordRules:i}){let[s,n]=useState(""),[l,a]=useState(""),[d,h]=useState(false),[f,g]=useState(false),p=useRef(null),c=useRef(null),{auth:R}=S(),_={password:i||[{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===s}]},x=C(_.password,s),A=C(_.confirmPassword,l);return 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:[jsx(T,{mainText:"Redefinir Senha",subText:"Crie uma nova senha para sua conta"}),jsxs("div",{className:"w-full flex flex-col gap-[0.625rem] flex-[1_1_auto] overflow-y-auto mb-2",children:[jsx(E,{label:"Nova Senha",name:"password",placeholder:"**********",autoComplete:"new-password",type:"password",value:s,onValueChange:n,inputRef:p,rulesStatus:x,submitted:d}),jsx(E,{label:"Confirme a Nova Senha",name:"confirm-password",placeholder:"**********",autoComplete:"new-password",type:"password",value:l,onValueChange:a,inputRef:c,rulesStatus:A,submitted:d})]}),jsx(k,{label:"Redefinir Senha",onSubmit:async w=>{w.preventDefault(),h(true);let B=x.some(v=>!v.passed),z=A.some(v=>!v.passed);if(B){p.current?.focus();return}if(z){c.current?.focus();return}g(true);let N=await R.resetPassword(e,s);N.success?t&&await t(N.message):r&&await r(N.message,N.trace),g(false);},loading:f}),o&&jsxs("span",{className:"text-trieoh-sm font-semibold",children:["Lembrou-se da sua senha? ",jsx("span",{className:"cursor-pointer text-trieoh-secondary transition-colors duration-200 hover:text-trieoh-primary",onClick:o,children:"Login"})]})]})}function Jt(e,t,r){let[o,i]=useState(true),[s,n]=useState("verifying"),[l,a]=useState("Verificando seu e-mail..."),{auth:d}=S(),h=useRef(false),f=async()=>{if(!h.current){h.current=true,i(true),n("verifying");try{if(d.profile()?.is_verified){n("already_verified"),a("Seu e-mail j\xE1 est\xE1 verificado."),i(!1);return}let c=await d.verifyEmail(e);c.success?(await d.refresh(),n("success"),a(c.message||"E-mail verificado com sucesso!"),t&&await t(c.message)):(n("error"),a(c.message||"Falha na verifica\xE7\xE3o do e-mail."),r&&await r(c.message,c.trace));}catch{n("error"),a("Ocorreu um erro inesperado durante a verifica\xE7\xE3o.");}finally{i(false);}}};return useEffect(()=>{e&&!h.current&&f();},[e]),{loading:o,status:s,message:l,onRetry:p=>{p.preventDefault(),h.current=false,f();},setStatus:n,setLoading:i,setMessage:a}}function jt({token:e,onSuccess:t,onFailed:r}){let{loading:o,status:i,message:s,onRetry:n}=Jt(e,t,r);return 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: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:[jsx(T,{mainText:i==="verifying"?"Verificando...":i==="error"?"Ops! Falha na verifica\xE7\xE3o":"Tudo pronto!",subText:s}),i==="verifying"&&jsx("div",{className:"w-full flex justify-center py-4",children:jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-trieoh-secondary"})}),i==="error"&&jsx("div",{className:"w-full flex flex-col gap-6 items-center",children:jsx("div",{className:"w-full mt-2",children:jsx(k,{label:"Tentar novamente",onSubmit:n,loading:o})})}),(i==="success"||i==="already_verified")&&jsxs("div",{className:"w-full flex flex-col gap-4 items-center",children:[jsx("div",{className:"w-16 h-16 flex items-center justify-center rounded-full bg-trieoh-secondary/10 text-trieoh-secondary",children:i==="success"?jsx(FiCheck,{size:40}):jsx(FiInfo,{size:40})}),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 Kt({onSuccess:e,onFailed:t}){let[r,o]=useState(false),[i,s]=useState(false),{auth:n}=S();return 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:[jsx(T,{mainText:"Reenviar Verifica\xE7\xE3o",subText:"N\xE3o recebeu o e-mail de verifica\xE7\xE3o? Clique no bot\xE3o abaixo para reenviar."}),jsx(k,{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)):t&&await t(a.message,a.trace),o(false);},loading:r}),i&&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."})]})}export{zr as AuthProvider,E as BasicInputField,Ct as BasicLogoutButton,_t as Copyright,Qe as ForgotPassword,Kt as ResendVerifyEmail,Ht as ResetPassword,Bt as Sessions,xt as SignIn,yt as SignUp,jt as VerifyEmail,S as useAuth};//# sourceMappingURL=react.js.map
|
|
6
3
|
//# sourceMappingURL=react.js.map
|