@trieoh/identityx-sdk-ts 0.12.0 → 0.12.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/index.js +2 -2
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/react.js +2 -2
- package/dist/cjs/react.js.map +1 -1
- package/dist/esm/index.js +2 -2
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/react.js +2 -2
- package/dist/esm/react.js.map +1 -1
- package/package.json +1 -1
package/dist/cjs/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
'use strict';var envoyFetchTs=require('@trieoh/envoy-fetch-ts');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function
|
|
2
|
-
Object.defineProperty(exports,"ApiError",{enumerable:true,get:function(){return envoyFetchTs.FetchClientError}});exports.AuthInterceptor=T;exports.configure
|
|
1
|
+
'use strict';var envoyFetchTs=require('@trieoh/envoy-fetch-ts');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;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},b=new Set,D=()=>b.forEach(t=>t()),O={subscribe:t=>(b.add(t),()=>b.delete(t)),getSnapshot:()=>R,getServerSnapshot:()=>R,set:t=>{R={...R,...t},D();},reset:()=>{R={isAuthenticated:false,isInitializing:false},D();}};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);}},_={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",u=[`${t}=${e}`,l&&!a?`Domain=${l}`:"",`Path=${s}`,`SameSite=${p}`,o?"Secure":"",n?`expires=${n}`:""];document.cookie=u.filter(Boolean).join("; ");},remove:(t,e)=>{m.set(t,"",{expires:"Thu, 01 Jan 1970 00:00:00 GMT",domain:e||void 0});}};function f(t){try{let r=encodeURIComponent(JSON.stringify(t)).split("").reverse().join("");return "tr_"+btoa(r)}catch{return ""}}function g(t){if(!t)return null;try{if(!t.startsWith("tr_"))return null;let e=t.replace(/^tr_/,""),n=atob(e).split("").reverse().join("");return JSON.parse(decodeURIComponent(n))}catch{return null}}var v="trieoh_access_token",h={getAccessToken:()=>g(_.getItem(v)),setAccessToken:t=>{t?_.setItem(v,f(t)):_.removeItem(v);},clear:()=>{_.removeItem(v);}};var k=null,P="trieoh_access_expiry",I="trieoh_refresh_expiry",E="trieoh_refresh_domain";function L(t){if(typeof window>"u")return null;let e=window.location.hostname;if(e==="localhost"||e==="127.0.0.1"||e.includes("localhost"))return null;if(t)try{let n=t;return n.startsWith("http")&&(n=new URL(n).hostname),e===n||e.endsWith("."+n)?n:e}catch{return e}return e}function B(t){try{let e=t.split(".")[1];if(!e)return null;let r=e.replace(/-/g,"+").replace(/_/g,"/");for(;r.length%4;)r+="=";let n=decodeURIComponent(atob(r).split("").map(s=>"%"+("00"+s.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(n)}catch(e){return envoyFetchTs.logger.error("Error decoding JWT:",e),null}}function H(t){let{access_token_string:e,refresh_token_string:r,access_expires_at:n,refresh_expires_at:s}=t,l=B(e);if(!l){envoyFetchTs.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}),k=f({access_data:l,refresh_expiry_date:o}),i.setItem(P,f(p)),i.setItem(I,f(o)),a?i.setItem(E,a):i.removeItem(E),O.set({isAuthenticated:true,isInitializing:false}),envoyFetchTs.logger.log("Auth session saved");}function j(){if(k)return g(k);let t=h.getAccessToken();if(!t)return null;let e=B(t);if(!e||e.exp*1e3<=Date.now())return null;let r=i.getItem(I);if(!r)return null;let n=g(r);if(!n)return null;let s={access_data:e,refresh_expiry_date:n};return k=f(s),s}function J(t,e){try{let r=i.getItem(t);if(!r)return !0;let n=g(r);return n?n-Date.now()<=e*1e3:!0}catch(r){return envoyFetchTs.logger.warn("Error reading expiry:",r),true}}var U=(t=30)=>J(P,t),K=(t=10)=>J(I,t);function y(){k=null,h.clear(),i.removeItem(P),i.removeItem(I);let t=i.getItem(E)||L();m.remove("refresh_token",t),i.removeItem(E),O.reset(),envoyFetchTs.logger.log("Auth tokens and claims cleared");}function $(){let t=typeof window>"u",e=typeof ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.js', document.baseURI).href)) })<"u"&&undefined?undefined:{},r=typeof process<"u"?process.env:{},n=e.VITE_TRIEOH_AUTH_PROJECT_ID||r.NEXT_PUBLIC_TRIEOH_AUTH_PROJECT_ID||r.PUBLIC_TRIEOH_AUTH_PROJECT_ID||"",s=t&&r.TRIEOH_AUTH_API_KEY||"";return {PROJECT_ID:n,API_KEY:s,BASE_URL:"https://api.trieauth.trieoh.com"}}var w=null,q={};function N(t){q={...q,...t},w=null;}function F(){return w||(w={...$(),...q}),w}var Y={get BASE_URL(){return F().BASE_URL}};var T=class{constructor(e){this.isRefreshing=false;this.refreshPromise=null;this.baseURL=e?.baseURL||Y.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 envoyFetchTs.simpleFetch(C(this.authBaseURL,"/auth/refresh"),{method:"POST",credentials:"include"});if(e.code!==200||!e.data)throw e.code!==503&&y(),new Error(e.message||"Failed to refresh token");H(e.data);let r=j();r&&this.onTokenRefreshed?.(r),envoyFetchTs.logger.log("Token refreshed successfully");}catch(e){throw envoyFetchTs.logger.warn("Failed to refresh token:",e),y(),this.onRefreshFailed?.(e),e}finally{this.isRefreshing=false,this.refreshPromise=null;}})(),this.refreshPromise)}async beforeRequest(){if(K()){y();return}let e=!!h.getAccessToken(),r=!!m.get("refresh_token");if(!e&&r||e&&U(30))try{await this.refreshToken();}catch(n){envoyFetchTs.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(),u=new Headers(r?.headers);return n&&a&&u.set("Authorization",`Bearer ${a}`),u.has("Content-Type")||u.set("Content-Type","application/json"),fetch(l,{...r,headers:u,credentials:"include"})},p=await o();if(p.status===401&&n&&!s&&U(30)){envoyFetchTs.logger.log("401 detected and token is expiring/expired, attempting refresh...");try{await this.refreshToken(),p=await o();}catch{envoyFetchTs.logger.error("Retry failed after refresh error");}}return p}},ve=t=>new T(t),Ee=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=envoyFetchTs.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
|
+
Object.defineProperty(exports,"ApiError",{enumerable:true,get:function(){return envoyFetchTs.FetchClientError}});exports.AuthInterceptor=T;exports.configure=N;exports.createAuthInterceptor=ve;exports.createAuthenticatedFetch=Ee;exports.createFetcher=M;exports.createQueryFetcher=Q;//# sourceMappingURL=index.js.map
|
|
3
3
|
//# sourceMappingURL=index.js.map
|
package/dist/cjs/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/url-utils.ts","../../src/store/auth-store.ts","../../src/utils/storage-adapter.ts","../../src/utils/obfuscation-utils.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","obfuscate","data","reversed","deobfuscate","obfuscated","cleanBase64","jsonStr","ACCESS_TOKEN_KEY","tokenStore","token","_obfuscatedClaims","ACCESS_EXPIRY_KEY","REFRESH_EXPIRY_KEY","REFRESH_DOMAIN_KEY","getCookieDomain","returnedDomain","hostname","decodeJwt","payload","base64","jsonPayload","error","logger","saveAuthSession","tokens","access_token_string","refresh_token_string","access_expires_at","refresh_expires_at","claims","refreshExpiry","accessExpiry","getTokenClaims","refreshExpiryStr","sessionData","isExpiringSoon","thresholdSeconds","e","isTokenExpiringSoon","isRefreshSessionExpired","clearAuthTokens","resolveEnv","isServer","viteEnv","safeProcessEnv","resolvedProjectId","resolvedApiKey","memoizedEnv","overrides","configure","config","getEnv","env","AuthInterceptor","res","simpleFetch","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":"qJAAO,SAASA,CAAAA,CAAQC,EAAcC,CAAAA,CAAsB,CAC1D,GAAIA,CAAAA,CAAK,UAAA,CAAW,MAAM,CAAA,CAAG,OAAOA,CAAAA,CAEpC,IAAMC,CAAAA,CAAYF,CAAAA,CAAK,QAAQ,KAAA,CAAO,EAAE,EAClCG,CAAAA,CAAYF,CAAAA,CAAK,OAAA,CAAQ,KAAA,CAAO,EAAE,CAAA,CAExC,OAAO,CAAA,EAAGC,CAAS,IAAIC,CAAS,CAAA,CAClC,CCFA,IAAIC,CAAAA,CAAoB,CACtB,eAAA,CAAiB,KAAA,CACjB,cAAA,CAAgB,IAClB,CAAA,CACMC,CAAAA,CAAa,IAAI,GAAA,CAEjBC,CAAAA,CAAS,IAAMD,CAAAA,CAAW,OAAA,CAASE,CAAAA,EAAMA,CAAAA,EAAG,CAAA,CAErCC,EAAY,CACvB,SAAA,CAAYC,IACVJ,CAAAA,CAAW,GAAA,CAAII,CAAE,CAAA,CACV,IAAMJ,CAAAA,CAAW,MAAA,CAAOI,CAAE,CAAA,CAAA,CAEnC,YAAa,IAAML,CAAAA,CACnB,kBAAmB,IAAMA,CAAAA,CACzB,IAAMM,CAAAA,EAAg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KA,CAAG,CAAA,CAC7B,GAAA,CAAKA,EAAI,GAAA,CAAI,IAAA,CAAKA,CAAG,CAAA,CACrB,IAAA,CAAMA,CAAAA,CAAI,KAAK,IAAA,CAAKA,CAAG,CAAA,CACvB,GAAA,CAAKA,CAAAA,CAAI,GAAA,CAAI,KAAKA,CAAG,CAAA,CACrB,MAAOA,CAAAA,CAAI,KAAA,CAAM,KAAKA,CAAG,CAAA,CACzB,MAAA,CAAQA,CAAAA,CAAI,MAAA,CAAO,IAAA,CAAKA,CAAG,CAAA,CAC3B,KAAA,CAAOA,EAAI,KAAA,CAAM,IAAA,CAAKA,CAAG,CAC3B,CACF,CAEO,SAASC,CAAAA,CAAmBjC,CAAAA,CAIhC,CACD,IAAMgC,CAAAA,CAAM,IAAIR,CAAAA,CACdxB,CAAAA,EAAQ,QACRA,CAAAA,EAAQ,WAAA,CACR,MAAA,CACAA,CAAAA,EAAQ,YACV,CAAA,CAEA,OAAO,CAAQhF,CAAAA,CAAcuB,CAAAA,GAC3ByF,CAAAA,CAAI,KAAA,CAAahH,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: domain || undefined,\n });\n },\n};\n","export function obfuscate(data: unknown): string {\n try {\n const jsonStr = encodeURIComponent(JSON.stringify(data));\n const reversed = jsonStr.split(\"\").reverse().join(\"\");\n return \"tr_\" + btoa(reversed);\n } catch {\n return \"\";\n }\n}\n\nexport function deobfuscate<T>(obfuscated: string | null): T | null {\n if (!obfuscated) return null;\n try {\n if (!obfuscated.startsWith(\"tr_\")) return null;\n const cleanBase64 = obfuscated.replace(/^tr_/, \"\");\n const reversed = atob(cleanBase64);\n const jsonStr = reversed.split(\"\").reverse().join(\"\");\n return JSON.parse(decodeURIComponent(jsonStr));\n } catch {\n return null;\n }\n}\n","import { sessionBrowserStorage } from \"../utils/storage-adapter\";\nimport { obfuscate, deobfuscate } from \"../utils/obfuscation-utils\";\n\nconst ACCESS_TOKEN_KEY = \"trieoh_access_token\";\n\nexport const tokenStore = {\n getAccessToken: () => deobfuscate<string>(sessionBrowserStorage.getItem(ACCESS_TOKEN_KEY)),\n setAccessToken: (token: string | null) => {\n if (token) sessionBrowserStorage.setItem(ACCESS_TOKEN_KEY, obfuscate(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\";\nimport { obfuscate, deobfuscate } from \"./obfuscation-utils\";\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 _obfuscatedClaims: string | null = null;\nconst ACCESS_EXPIRY_KEY = \"trieoh_access_expiry\";\nconst REFRESH_EXPIRY_KEY = \"trieoh_refresh_expiry\";\nconst REFRESH_DOMAIN_KEY = \"trieoh_refresh_domain\";\n\nexport function getCookieDomain(returnedDomain?: string) {\n if (typeof window === \"undefined\") return null;\n const hostname = window.location.hostname;\n const isLocalhost = hostname === \"localhost\" || hostname === \"127.0.0.1\" || hostname.includes(\"localhost\");\n if (isLocalhost) return null;\n\n if (returnedDomain) {\n try {\n let domain = returnedDomain;\n if (domain.startsWith(\"http\")) domain = new URL(domain).hostname;\n if (hostname === domain || hostname.endsWith(\".\" + domain)) return domain;\n return hostname;\n } catch { return hostname; }\n }\n\n return hostname;\n}\n\nexport function decodeJwt<T>(token: string): T | null {\n try {\n const payload = token.split(\".\")[1];\n if (!payload) return null;\n\n let base64 = payload.replace(/-/g, \"+\").replace(/_/g, \"/\");\n while (base64.length % 4) {\n base64 += \"=\";\n }\n\n const jsonPayload = decodeURIComponent(\n atob(base64)\n .split(\"\")\n .map((c) => \"%\" + (\"00\" + c.charCodeAt(0).toString(16)).slice(-2))\n .join(\"\")\n );\n\n return JSON.parse(jsonPayload);\n } catch (error) {\n logger.error(\"Error decoding JWT:\", error);\n return null;\n }\n}\n\nexport function saveAuthSession(tokens: AuthTokens): void {\n const {\n access_token_string,\n refresh_token_string,\n access_expires_at,\n refresh_expires_at,\n } = tokens;\n\n const claims = decodeJwt<TokenClaims>(access_token_string);\n\n if (!claims) {\n logger.error(\"Failed to decode tokens\");\n return;\n }\n\n tokenStore.setAccessToken(access_token_string);\n\n const refreshExpiry = new Date(refresh_expires_at).getTime();\n const accessExpiry = new Date(access_expires_at).getTime();\n const domain = getCookieDomain(tokens.domain);\n\n cookieStorage.set(\"refresh_token\", refresh_token_string, {\n expires: new Date(refreshExpiry).toUTCString(),\n domain\n });\n\n const sessionData: AuthTokenClaims = {\n access_data: claims,\n refresh_expiry_date: refreshExpiry,\n };\n\n _obfuscatedClaims = obfuscate(sessionData);\n\n browserStorage.setItem(ACCESS_EXPIRY_KEY, obfuscate(accessExpiry));\n browserStorage.setItem(REFRESH_EXPIRY_KEY, obfuscate(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 (_obfuscatedClaims) return deobfuscate<AuthTokenClaims>(_obfuscatedClaims);\n\n const token = tokenStore.getAccessToken();\n if (!token) return null;\n\n const claims = decodeJwt<TokenClaims>(token);\n if (!claims) return null;\n\n // Check if token is expired\n if (claims.exp * 1000 <= Date.now()) return null;\n\n const refreshExpiryStr = browserStorage.getItem(REFRESH_EXPIRY_KEY);\n if (!refreshExpiryStr) return null;\n\n const refreshExpiry = deobfuscate<number>(refreshExpiryStr);\n if (!refreshExpiry) return null;\n\n const sessionData = {\n access_data: claims,\n refresh_expiry_date: refreshExpiry,\n };\n\n _obfuscatedClaims = obfuscate(sessionData);\n\n return sessionData;\n}\n\nfunction isExpiringSoon(key: string, thresholdSeconds: number): boolean {\n try {\n const obfuscated = browserStorage.getItem(key);\n if (!obfuscated) return true;\n const expiry = deobfuscate<number>(obfuscated);\n if (!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 obfuscated = browserStorage.getItem(ACCESS_EXPIRY_KEY);\n if (!obfuscated) return false;\n const accessExpiryTimestamp = deobfuscate<number>(obfuscated);\n if (!accessExpiryTimestamp) return false;\n return accessExpiryTimestamp > Date.now();\n}\n\nexport function clearAuthTokens(): void {\n _obfuscatedClaims = 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"]}
|
|
1
|
+
{"version":3,"sources":["../../src/utils/url-utils.ts","../../src/store/auth-store.ts","../../src/utils/storage-adapter.ts","../../src/utils/obfuscation-utils.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","browserStorage","key","value","sessionBrowserStorage","cookieStorage","name","nameEQ","ca","i","c","options","expires","domain","secure","sameSite","isLocalhost","cookieParts","obfuscate","data","reversed","deobfuscate","obfuscated","cleanBase64","jsonStr","ACCESS_TOKEN_KEY","tokenStore","token","_obfuscatedClaims","ACCESS_EXPIRY_KEY","REFRESH_EXPIRY_KEY","REFRESH_DOMAIN_KEY","getCookieDomain","returnedDomain","hostname","decodeJwt","payload","base64","jsonPayload","error","logger","saveAuthSession","tokens","access_token_string","refresh_token_string","access_expires_at","refresh_expires_at","claims","refreshExpiry","accessExpiry","getTokenClaims","refreshExpiryStr","sessionData","isExpiringSoon","thresholdSeconds","expiry","e","isTokenExpiringSoon","isRefreshSessionExpired","clearAuthTokens","resolveEnv","isServer","viteEnv","safeProcessEnv","resolvedProjectId","resolvedApiKey","memoizedEnv","overrides","configure","config","getEnv","env","AuthInterceptor","res","simpleFetch","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":"qJAAO,SAASA,CAAAA,CAAQC,EAAcC,CAAAA,CAAsB,CAC1D,GAAIA,CAAAA,CAAK,UAAA,CAAW,MAAM,CAAA,CAAG,OAAOA,EAEpC,IAAMC,CAAAA,CAAYF,EAAK,OAAA,CAAQ,KAAA,CAAO,EAAE,CAAA,CAClCG,CAAAA,CAAYF,CAAAA,CAAK,OAAA,CAAQ,KAA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AAI,GAAA,CAAI,IAAA,CAAKA,CAAG,CAAA,CACrB,KAAA,CAAOA,EAAI,KAAA,CAAM,IAAA,CAAKA,CAAG,CAAA,CACzB,MAAA,CAAQA,CAAAA,CAAI,MAAA,CAAO,IAAA,CAAKA,CAAG,EAC3B,KAAA,CAAOA,CAAAA,CAAI,MAAM,IAAA,CAAKA,CAAG,CAC3B,CACF,CAEO,SAASC,CAAAA,CAAmBjC,CAAAA,CAIhC,CACD,IAAMgC,CAAAA,CAAM,IAAIR,EACdxB,CAAAA,EAAQ,OAAA,CACRA,GAAQ,WAAA,CACR,MAAA,CACAA,CAAAA,EAAQ,YACV,CAAA,CAEA,OAAO,CAAQ9E,CAAAA,CAAcoB,CAAAA,GAC3B0F,EAAI,KAAA,CAAa9G,CAAAA,CAAMoB,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\n// if (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: domain || undefined,\n });\n },\n};\n","export function obfuscate(data: unknown): string {\n try {\n const jsonStr = encodeURIComponent(JSON.stringify(data));\n const reversed = jsonStr.split(\"\").reverse().join(\"\");\n return \"tr_\" + btoa(reversed);\n } catch {\n return \"\";\n }\n}\n\nexport function deobfuscate<T>(obfuscated: string | null): T | null {\n if (!obfuscated) return null;\n try {\n if (!obfuscated.startsWith(\"tr_\")) return null;\n const cleanBase64 = obfuscated.replace(/^tr_/, \"\");\n const reversed = atob(cleanBase64);\n const jsonStr = reversed.split(\"\").reverse().join(\"\");\n return JSON.parse(decodeURIComponent(jsonStr));\n } catch {\n return null;\n }\n}\n","import { sessionBrowserStorage } from \"../utils/storage-adapter\";\nimport { obfuscate, deobfuscate } from \"../utils/obfuscation-utils\";\n\nconst ACCESS_TOKEN_KEY = \"trieoh_access_token\";\n\nexport const tokenStore = {\n getAccessToken: () => deobfuscate<string>(sessionBrowserStorage.getItem(ACCESS_TOKEN_KEY)),\n setAccessToken: (token: string | null) => {\n if (token) sessionBrowserStorage.setItem(ACCESS_TOKEN_KEY, obfuscate(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\";\nimport { obfuscate, deobfuscate } from \"./obfuscation-utils\";\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 _obfuscatedClaims: string | null = null;\nconst ACCESS_EXPIRY_KEY = \"trieoh_access_expiry\";\nconst REFRESH_EXPIRY_KEY = \"trieoh_refresh_expiry\";\nconst REFRESH_DOMAIN_KEY = \"trieoh_refresh_domain\";\n\nexport function getCookieDomain(returnedDomain?: string) {\n if (typeof window === \"undefined\") return null;\n const hostname = window.location.hostname;\n const isLocalhost = hostname === \"localhost\" || hostname === \"127.0.0.1\" || hostname.includes(\"localhost\");\n if (isLocalhost) return null;\n\n if (returnedDomain) {\n try {\n let domain = returnedDomain;\n if (domain.startsWith(\"http\")) domain = new URL(domain).hostname;\n if (hostname === domain || hostname.endsWith(\".\" + domain)) return domain;\n return hostname;\n } catch { return hostname; }\n }\n\n return hostname;\n}\n\nexport function decodeJwt<T>(token: string): T | null {\n try {\n const payload = token.split(\".\")[1];\n if (!payload) return null;\n\n let base64 = payload.replace(/-/g, \"+\").replace(/_/g, \"/\");\n while (base64.length % 4) {\n base64 += \"=\";\n }\n\n const jsonPayload = decodeURIComponent(\n atob(base64)\n .split(\"\")\n .map((c) => \"%\" + (\"00\" + c.charCodeAt(0).toString(16)).slice(-2))\n .join(\"\")\n );\n\n return JSON.parse(jsonPayload);\n } catch (error) {\n logger.error(\"Error decoding JWT:\", error);\n return null;\n }\n}\n\nexport function saveAuthSession(tokens: AuthTokens): void {\n const {\n access_token_string,\n refresh_token_string,\n access_expires_at,\n refresh_expires_at,\n } = tokens;\n\n const claims = decodeJwt<TokenClaims>(access_token_string);\n\n if (!claims) {\n logger.error(\"Failed to decode tokens\");\n return;\n }\n\n tokenStore.setAccessToken(access_token_string);\n\n const refreshExpiry = new Date(refresh_expires_at).getTime();\n const accessExpiry = new Date(access_expires_at).getTime();\n const domain = getCookieDomain(tokens.domain);\n\n cookieStorage.set(\"refresh_token\", refresh_token_string, {\n expires: new Date(refreshExpiry).toUTCString(),\n domain\n });\n\n const sessionData: AuthTokenClaims = {\n access_data: claims,\n refresh_expiry_date: refreshExpiry,\n };\n\n _obfuscatedClaims = obfuscate(sessionData);\n\n browserStorage.setItem(ACCESS_EXPIRY_KEY, obfuscate(accessExpiry));\n browserStorage.setItem(REFRESH_EXPIRY_KEY, obfuscate(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 (_obfuscatedClaims) return deobfuscate<AuthTokenClaims>(_obfuscatedClaims);\n\n const token = tokenStore.getAccessToken();\n if (!token) return null;\n\n const claims = decodeJwt<TokenClaims>(token);\n if (!claims) return null;\n\n // Check if token is expired\n if (claims.exp * 1000 <= Date.now()) return null;\n\n const refreshExpiryStr = browserStorage.getItem(REFRESH_EXPIRY_KEY);\n if (!refreshExpiryStr) return null;\n\n const refreshExpiry = deobfuscate<number>(refreshExpiryStr);\n if (!refreshExpiry) return null;\n\n const sessionData = {\n access_data: claims,\n refresh_expiry_date: refreshExpiry,\n };\n\n _obfuscatedClaims = obfuscate(sessionData);\n\n return sessionData;\n}\n\nfunction isExpiringSoon(key: string, thresholdSeconds: number): boolean {\n try {\n const obfuscated = browserStorage.getItem(key);\n if (!obfuscated) return true;\n const expiry = deobfuscate<number>(obfuscated);\n if (!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 obfuscated = browserStorage.getItem(ACCESS_EXPIRY_KEY);\n if (!obfuscated) return false;\n const accessExpiryTimestamp = deobfuscate<number>(obfuscated);\n if (!accessExpiryTimestamp) return false;\n return accessExpiryTimestamp > Date.now();\n}\n\nexport function clearAuthTokens(): void {\n _obfuscatedClaims = 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/cjs/react.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
'use strict';var react=require('react'),envoyFetchTs=require('@trieoh/envoy-fetch-ts'),jsxRuntime=require('react/jsx-runtime'),ri=require('react-icons/ri'),go=require('react-icons/go'),im=require('react-icons/im'),fa=require('react-icons/fa'),uaParserJs=require('ua-parser-js'),fi=require('react-icons/fi');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function be(e,t){if(t.startsWith("http"))return t;let r=e.replace(/\/$/,""),o=t.replace(/^\//,"");return `${r}/${o}`}var Y={isAuthenticated:false,isInitializing:true},ye=new Set,Oe=()=>ye.forEach(e=>e()),x={subscribe:e=>(ye.add(e),()=>ye.delete(e)),getSnapshot:()=>Y,getServerSnapshot:()=>Y,set:e=>{Y={...Y,...e},Oe();},reset:()=>{Y={isAuthenticated:false,isInitializing:false},Oe();}};typeof window<"u"&&window.addEventListener("storage",e=>{if(e.key==="trieoh_access_expiry")if(!e.newValue)x.reset();else {let t=parseInt(e.newValue,10),r=!isNaN(t)&&t>Date.now();x.set({isAuthenticated:r,isInitializing:false});}});var A={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);}},W={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);}},D={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",m=[`${e}=${t}`,s&&!a?`Domain=${s}`:"",`Path=${i}`,`SameSite=${l}`,n?"Secure":"",o?`expires=${o}`:""];document.cookie=m.filter(Boolean).join("; ");},remove:(e,t)=>{D.set(e,"",{expires:"Thu, 01 Jan 1970 00:00:00 GMT",domain:t||void 0});}};function B(e){try{let r=encodeURIComponent(JSON.stringify(e)).split("").reverse().join("");return "tr_"+btoa(r)}catch{return ""}}function V(e){if(!e)return null;try{if(!e.startsWith("tr_"))return null;let t=e.replace(/^tr_/,""),o=atob(t).split("").reverse().join("");return JSON.parse(decodeURIComponent(o))}catch{return null}}var ae="trieoh_access_token",F={getAccessToken:()=>V(W.getItem(ae)),setAccessToken:e=>{e?W.setItem(ae,B(e)):W.removeItem(ae);},clear:()=>{W.removeItem(ae);}};var G=null,Se="trieoh_access_expiry",ce="trieoh_refresh_expiry",le="trieoh_refresh_domain";function Me(e){if(typeof window>"u")return null;let t=window.location.hostname;if(t==="localhost"||t==="127.0.0.1"||t.includes("localhost"))return null;if(e)try{let o=e;return o.startsWith("http")&&(o=new URL(o).hostname),t===o||t.endsWith("."+o)?o:t}catch{return t}return t}function Be(e){try{let t=e.split(".")[1];if(!t)return null;let r=t.replace(/-/g,"+").replace(/_/g,"/");for(;r.length%4;)r+="=";let o=decodeURIComponent(atob(r).split("").map(i=>"%"+("00"+i.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(o)}catch(t){return envoyFetchTs.logger.error("Error decoding JWT:",t),null}}function Q(e){let{access_token_string:t,refresh_token_string:r,access_expires_at:o,refresh_expires_at:i}=e,s=Be(t);if(!s){envoyFetchTs.logger.error("Failed to decode tokens");return}F.setAccessToken(t);let n=new Date(i).getTime(),l=new Date(o).getTime(),a=Me(e.domain);D.set("refresh_token",r,{expires:new Date(n).toUTCString(),domain:a}),G=B({access_data:s,refresh_expiry_date:n}),A.setItem(Se,B(l)),A.setItem(ce,B(n)),a?A.setItem(le,a):A.removeItem(le),x.set({isAuthenticated:true,isInitializing:false}),envoyFetchTs.logger.log("Auth session saved");}function Z(){if(G)return V(G);let e=F.getAccessToken();if(!e)return null;let t=Be(e);if(!t||t.exp*1e3<=Date.now())return null;let r=A.getItem(ce);if(!r)return null;let o=V(r);if(!o)return null;let i={access_data:t,refresh_expiry_date:o};return G=B(i),i}function Fe(e,t){try{let r=A.getItem(e);if(!r)return !0;let o=V(r);return o?o-Date.now()<=t*1e3:!0}catch(r){return envoyFetchTs.logger.warn("Error reading expiry:",r),true}}var Re=(e=30)=>Fe(Se,e),ue=(e=10)=>Fe(ce,e);function q(){G=null,F.clear(),A.removeItem(Se),A.removeItem(ce);let e=A.getItem(le)||Me();D.remove("refresh_token",e),A.removeItem(le),x.reset(),envoyFetchTs.logger.log("Auth tokens and claims cleared");}function Ue(){let e=Z();return e?e.access_data.sub:null}function st(){let e=typeof window>"u",t=typeof ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('react.js', document.baseURI).href)) })<"u"&&undefined?undefined:{},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 me=null,ke={};function He(e){ke={...ke,...e},me=null;}function _e(){return me||(me={...st(),...ke}),me}var b={get PROJECT_ID(){return _e().PROJECT_ID},get BASE_URL(){return _e().BASE_URL}};var de=class{constructor(t){this.isRefreshing=false;this.refreshPromise=null;this.baseURL=t?.baseURL||b.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 envoyFetchTs.simpleFetch(be(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");Q(t.data);let r=Z();r&&this.onTokenRefreshed?.(r),envoyFetchTs.logger.log("Token refreshed successfully");}catch(t){throw envoyFetchTs.logger.warn("Failed to refresh token:",t),q(),this.onRefreshFailed?.(t),t}finally{this.isRefreshing=false,this.refreshPromise=null;}})(),this.refreshPromise)}async beforeRequest(){if(ue()){q();return}let t=!!F.getAccessToken(),r=!!D.get("refresh_token");if(!t&&r||t&&Re(30))try{await this.refreshToken();}catch(o){envoyFetchTs.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=be(this.baseURL,t),n=async()=>{let a=F.getAccessToken(),m=new Headers(r?.headers);return o&&a&&m.set("Authorization",`Bearer ${a}`),m.has("Content-Type")||m.set("Content-Type","application/json"),fetch(s,{...r,headers:m,credentials:"include"})},l=await n();if(l.status===401&&o&&!i&&Re(30)){envoyFetchTs.logger.log("401 detected and token is expiring/expired, attempting refresh...");try{await this.refreshToken(),l=await n();}catch{envoyFetchTs.logger.error("Retry failed after refresh error");}}return l}};function 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 pe=class{constructor(t,r,o,i){this.interceptor=new de({baseURL:t,authBaseURL:r,onTokenRefreshed:o}),this.client=envoyFetchTs.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 j=()=>{if(!b.PROJECT_ID||b.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 ze=(e,t)=>({login:async(r,o)=>{b.PROJECT_ID&&j();let i=`/auth/login${b.PROJECT_ID?`?project_id=${b.PROJECT_ID}`:""}`,s=await e.post(i,{email:r,password:o},{requiresAuth:false});return s.success&&(Q(s.data),t?.onLogin?.(s)),s},register:async(r,o)=>{let i={requiresAuth:false},s=`/auth/register${b.PROJECT_ID?`?project_id=${b.PROJECT_ID}`:""}`;b.PROJECT_ID&&j();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${b.PROJECT_ID?`?project_id=${b.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&&(Q(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:()=>Ue(),sendForgotPassword:async r=>{let o={requiresAuth:false};return b.PROJECT_ID?(j(),e.post("/account/forgot-password",{email:r,project_id:b.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 qe=react.createContext(null);function Jr({children:e,baseURL:t,projectId:r,isProjectMode:o=true,fallback:i,waitSession:s=true,clientConfig:n,onLogin:l,onResetPassword:a,onRegister:m,onVerify:f,onRefresh:p}){let h=react.useRef(false),{isAuthenticated:d,isInitializing:c}=react.useSyncExternalStore(x.subscribe,x.getSnapshot,x.getServerSnapshot);react.useEffect(()=>{He({...r?{PROJECT_ID:r}:{},...t?{BASE_URL:t}:{}});},[r,t]);let S=react.useCallback(L=>{x.set({isAuthenticated:!!L.access_data,isInitializing:false}),p?.();},[p]),R=react.useMemo(()=>new pe(t,void 0,S,n),[t,S,n]),w=react.useMemo(()=>ze(R,{onLogin:l,onResetPassword:a,onRegister:m,onVerify:f,onRefresh:p}),[R,l,a,m,f,p]);react.useEffect(()=>{o&&j(),(async()=>{if(h.current)return;if(h.current=true,Z()){x.set({isAuthenticated:true,isInitializing:false});return}if(!!!D.get("refresh_token")||ue()){x.reset(),x.set({isInitializing:false});return}envoyFetchTs.logger.log("No cached claims, attempting silent refresh...");try{(await w.refresh()).success?(x.set({isAuthenticated:!0,isInitializing:!1}),envoyFetchTs.logger.log("Session restored.")):(x.reset(),envoyFetchTs.logger.warn("No active session."));}catch{x.reset(),envoyFetchTs.logger.warn("Could not restore session (offline?).");}finally{x.set({isInitializing:false});}})();},[w,o]);let C=react.useMemo(()=>({auth:w,isAuthenticated:d,isInitializing:c,isProjectMode:o}),[w,d,c,o]);return s&&c?i??null:jsxRuntime.jsx(qe.Provider,{value:C,children:e})}function y(){let e=react.useContext(qe);if(!e)throw new Error("useAuth must be used inside <AuthProvider>");return e}function Te(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));}Te(`/*! tailwindcss v4.3.0 | MIT License | https://tailwindcss.com */@layer properties;@layer theme,base,components,utilities;@layer theme{:root,:host{--font-sans: ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";--font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;--spacing: .25rem;--font-weight-extralight: 200;--font-weight-light: 300;--font-weight-normal: 400;--font-weight-medium: 500;--font-weight-semibold: 600;--radius-lg: .5rem;--ease-in-out: cubic-bezier(.4, 0, .2, 1);--animate-spin: spin 1s linear infinite;--default-transition-duration: .15s;--default-transition-timing-function: cubic-bezier(.4, 0, .2, 1);--default-font-family: var(--font-sans);--default-mono-font-family: var(--font-mono);--color-trieoh-primary: oklch(.1139 .0789 264.05);--color-trieoh-secondary: oklch(.7975 .1018 262.7);--color-trieoh-neutral1: oklch(.9702 0 0);--color-trieoh-neutral2: oklch(.1944 .0051 248.09);--radius-trieoh-full: 50%;--font-inter: "Inter", sans-serif}}@layer base{*,:after,:before,::backdrop,::file-selector-button{box-sizing:border-box;margin:0;padding:0;border:0 solid}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;tab-size:4;font-family:var(--default-font-family, ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings, normal);font-variation-settings:var(--default-font-variation-settings, normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings, normal);font-variation-settings:var(--default-mono-font-variation-settings, normal);font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea,::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;border-radius:0;background-color:transparent;opacity:1}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not (-webkit-appearance: -apple-pay-button)) or (contain-intrinsic-size: 1px){::placeholder{color:currentcolor;@supports (color: color-mix(in lab,red,red)){color:color-mix(in oklab,currentcolor 50%,transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit,::-webkit-datetime-edit-year-field,::-webkit-datetime-edit-month-field,::-webkit-datetime-edit-day-field,::-webkit-datetime-edit-hour-field,::-webkit-datetime-edit-minute-field,::-webkit-datetime-edit-second-field,::-webkit-datetime-edit-millisecond-field,::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]),::file-selector-button{appearance:button}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}}@layer utilities{.\\@container{container-type:inline-size}.trieoh-button-loading{&:after{content:"";position:absolute;top:0;left:-150%;width:150%;height:100%;background:linear-gradient(120deg,transparent 0%,var(--trieoh-neutral2) 40%,transparent 80%);@supports (color: color-mix(in lab,red,red)){background:linear-gradient(120deg,transparent 0%,color-mix(in oklab,var(--trieoh-neutral2) 40%,white 15%) 40%,transparent 80%)}animation:trieoh-shine 1.5s infinite}}.absolute{position:absolute}.relative{position:relative}.top-0{top:calc(var(--spacing) * 0)}.right-0{right:calc(var(--spacing) * 0)}.m-0{margin:calc(var(--spacing) * 0)}.m-2{margin:calc(var(--spacing) * 2)}.m-\\[0\\.125rem\\]{margin:.125rem}.mt-2{margin-top:calc(var(--spacing) * 2)}.mt-4{margin-top:calc(var(--spacing) * 4)}.mb-1{margin-bottom:calc(var(--spacing) * 1)}.mb-2{margin-bottom:calc(var(--spacing) * 2)}.mb-\\[0\\.625rem\\]{margin-bottom:.625rem}.box-border{box-sizing:border-box}.block{display:block}.contents{display:contents}.flex{display:flex}.inline-block{display:inline-block}.inline-flex{display:inline-flex}.h-12{height:calc(var(--spacing) * 12)}.h-16{height:calc(var(--spacing) * 16)}.h-\\[3\\.25rem\\]{height:3.25rem}.h-\\[64px\\]{height:64px}.h-auto{height:auto}.h-full{height:100%}.max-h-\\[max\\(75dvh\\,32rem\\)\\]{max-height:max(75dvh,32rem)}.min-h-screen{min-height:100vh}.w-12{width:calc(var(--spacing) * 12)}.w-16{width:calc(var(--spacing) * 16)}.w-\\[64px\\]{width:64px}.w-full{width:100%}.max-w-\\[14rem\\]{max-width:14rem}.max-w-\\[25rem\\]{max-width:25rem}.max-w-\\[30rem\\]{max-width:30rem}.min-w-0{min-width:calc(var(--spacing) * 0)}.min-w-\\[10rem\\]{min-width:10rem}.min-w-\\[15rem\\]{min-width:15rem}.min-w-\\[20rem\\]{min-width:20rem}.flex-1{flex:1}.flex-\\[0_1_auto\\]{flex:0 1 auto}.flex-\\[1_1_auto\\]{flex:1 1 auto}.shrink-0{flex-shrink:0}.animate-spin{animation:var(--animate-spin)}.cursor-pointer{cursor:pointer}.appearance-none{appearance:none}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-center{align-items:center}.items-end{align-items:flex-end}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.gap-1{gap:calc(var(--spacing) * 1)}.gap-2{gap:calc(var(--spacing) * 2)}.gap-4{gap:calc(var(--spacing) * 4)}.gap-5{gap:calc(var(--spacing) * 5)}.gap-6{gap:calc(var(--spacing) * 6)}.gap-8{gap:calc(var(--spacing) * 8)}.gap-\\[0\\.625rem\\]{gap:.625rem}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.rounded-\\[0\\.25rem\\]{border-radius:.25rem}.rounded-full{border-radius:calc(infinity * 1px)}.rounded-lg{border-radius:var(--radius-lg)}.rounded-trieoh-full{border-radius:var(--radius-trieoh-full)}.border-2{border-style:var(--tw-border-style);border-width:2px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-b-2{border-bottom-style:var(--tw-border-style);border-bottom-width:2px}.border-none{--tw-border-style: none;border-style:none}.\\!border-\\[\\#e53935\\]{border-color:#e53935!important}.border-\\[rgba\\(0\\,0\\,0\\,0\\.3\\)\\]{border-color:#0000004d}.border-trieoh-neutral2{border-color:var(--color-trieoh-neutral2)}.border-trieoh-secondary{border-color:var(--color-trieoh-secondary)}.bg-\\[oklch\\(0\\.8853_0_0\\/30\\%\\)\\]{background-color:#d9d9d94d}.bg-transparent{background-color:transparent}.bg-trieoh-neutral1{background-color:var(--color-trieoh-neutral1)}.bg-trieoh-secondary\\/10{background-color:color-mix(in srgb,oklch(.7975 .1018 262.7) 10%,transparent);@supports (color: color-mix(in lab,red,red)){background-color:color-mix(in oklab,var(--color-trieoh-secondary) 10%,transparent)}}.p-2{padding:calc(var(--spacing) * 2)}.p-6{padding:calc(var(--spacing) * 6)}.p-\\[0\\.625rem\\]{padding:.625rem}.p-\\[1\\.5rem_0\\.5rem\\]{padding:1.5rem .5rem}.p-\\[1\\.25rem_0\\.75rem\\]{padding:1.25rem .75rem}.p-\\[1\\.25rem_1\\.5rem\\]{padding:1.25rem 1.5rem}.p-\\[1rem_0\\]{padding:1rem 0}.px-\\[0\\.75rem\\]{padding-inline:.75rem}.px-\\[0\\.625rem\\]{padding-inline:.625rem}.px-\\[1\\.5rem\\]{padding-inline:1.5rem}.py-4{padding-block:calc(var(--spacing) * 4)}.py-\\[0\\.125rem\\]{padding-block:.125rem}.py-\\[0\\.0625rem\\]{padding-block:.0625rem}.text-center{text-align:center}.font-inter{font-family:var(--font-inter)}.text-\\[0\\.75rem\\]{font-size:.75rem}.text-\\[0\\.875rem\\]{font-size:.875rem}.text-\\[1rem\\]{font-size:1rem}.font-extralight{--tw-font-weight: var(--font-weight-extralight);font-weight:var(--font-weight-extralight)}.font-light{--tw-font-weight: var(--font-weight-light);font-weight:var(--font-weight-light)}.font-medium{--tw-font-weight: var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-normal{--tw-font-weight: var(--font-weight-normal);font-weight:var(--font-weight-normal)}.font-semibold{--tw-font-weight: var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.text-\\[\\#6b7280\\]{color:#6b7280}.text-\\[\\#10b981\\]{color:#10b981}.text-\\[\\#e53935\\]{color:#e53935}.text-\\[oklch\\(0\\.628_0\\.2577_29\\.23\\)\\]{color:red}.text-trieoh-neutral2{color:var(--color-trieoh-neutral2)}.text-trieoh-primary{color:var(--color-trieoh-primary)}.text-trieoh-secondary{color:var(--color-trieoh-secondary)}.line-through{text-decoration-line:line-through}.opacity-50{opacity:50%}.opacity-60{opacity:60%}.opacity-95{opacity:95%}.opacity-100{opacity:100%}.\\!shadow-none{--tw-shadow: 0 0 #0000 !important;box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)!important}.shadow-\\[0_0\\.25rem_0\\.25rem_0_rgba\\(0\\,0\\,0\\,0\\.25\\)\\]{--tw-shadow: 0 .25rem .25rem 0 var(--tw-shadow-color, rgba(0,0,0,.25));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-\\[0_0\\.25rem_1rem_rgba\\(0\\,0\\,0\\,0\\.25\\)\\]{--tw-shadow: 0 .25rem 1rem var(--tw-shadow-color, rgba(0,0,0,.25));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.transition-\\[color\\,text-decoration\\,opacity\\]{transition-property:color,text-decoration,opacity;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-\\[opacity\\,transform\\]{transition-property:opacity,transform;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-opacity{transition-property:opacity;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-transform{transition-property:transform,translate,scale,rotate;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.duration-150{--tw-duration: .15s;transition-duration:.15s}.duration-200{--tw-duration: .2s;transition-duration:.2s}.duration-500{--tw-duration: .5s;transition-duration:.5s}.duration-\\[120ms\\]{--tw-duration: .12s;transition-duration:.12s}.ease-in-out{--tw-ease: var(--ease-in-out);transition-timing-function:var(--ease-in-out)}.outline-none{--tw-outline-style: none;outline-style:none}.select-none{-webkit-user-select:none;user-select:none}.hover\\:scale-\\[1\\.02\\]{&:hover{@media(hover:hover){scale:1.02}}}.hover\\:scale-\\[1\\.05\\]{&:hover{@media(hover:hover){scale:1.05}}}.hover\\:text-trieoh-primary{&:hover{@media(hover:hover){color:var(--color-trieoh-primary)}}}.hover\\:opacity-100{&:hover{@media(hover:hover){opacity:100%}}}.active\\:scale-\\[0\\.95\\]{&:active{scale:.95}}.active\\:scale-\\[0\\.98\\]{&:active{scale:.98}}.active\\:scale-\\[0\\.99\\]{&:active{scale:.99}}.disabled\\:\\!transform-none{&:disabled{transform:none!important}}.disabled\\:cursor-not-allowed{&:disabled{cursor:not-allowed}}.disabled\\:opacity-60{&:disabled{opacity:60%}}.\\@\\[640px\\]\\:flex-row{@container (width >= 640px){flex-direction:row}}.\\@\\[640px\\]\\:items-center{@container (width >= 640px){align-items:center}}.\\@\\[640px\\]\\:justify-between{@container (width >= 640px){justify-content:space-between}}.\\@\\[640px\\]\\:gap-2{@container (width >= 640px){gap:calc(var(--spacing) * 2)}}.\\@\\[640px\\]\\:gap-4{@container (width >= 640px){gap:calc(var(--spacing) * 4)}}.\\@\\[640px\\]\\:gap-8{@container (width >= 640px){gap:calc(var(--spacing) * 8)}}.\\@\\[640px\\]\\:text-left{@container (width >= 640px){text-align:left}}}@import url(https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap);@property --tw-border-style{syntax: "*"; inherits: false; initial-value: solid;}@property --tw-font-weight{syntax: "*"; inherits: false;}@property --tw-shadow{syntax: "*"; inherits: false; initial-value: 0 0 #0000;}@property --tw-shadow-color{syntax: "*"; inherits: false;}@property --tw-shadow-alpha{syntax: "<percentage>"; inherits: false; initial-value: 100%;}@property --tw-inset-shadow{syntax: "*"; inherits: false; initial-value: 0 0 #0000;}@property --tw-inset-shadow-color{syntax: "*"; inherits: false;}@property --tw-inset-shadow-alpha{syntax: "<percentage>"; inherits: false; initial-value: 100%;}@property --tw-ring-color{syntax: "*"; inherits: false;}@property --tw-ring-shadow{syntax: "*"; inherits: false; initial-value: 0 0 #0000;}@property --tw-inset-ring-color{syntax: "*"; inherits: false;}@property --tw-inset-ring-shadow{syntax: "*"; inherits: false; initial-value: 0 0 #0000;}@property --tw-ring-inset{syntax: "*"; inherits: false;}@property --tw-ring-offset-width{syntax: "<length>"; inherits: false; initial-value: 0px;}@property --tw-ring-offset-color{syntax: "*"; inherits: false; initial-value: #fff;}@property --tw-ring-offset-shadow{syntax: "*"; inherits: false; initial-value: 0 0 #0000;}@property --tw-duration{syntax: "*"; inherits: false;}@property --tw-ease{syntax: "*"; inherits: false;}@keyframes spin{to{transform:rotate(360deg)}}@keyframes trieoh-shine{0%{left:-150%}to{left:150%}}@layer properties{@supports ((-webkit-hyphens: none) and (not (margin-trim: inline))) or ((-moz-orient: inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-border-style: solid;--tw-font-weight: initial;--tw-shadow: 0 0 #0000;--tw-shadow-color: initial;--tw-shadow-alpha: 100%;--tw-inset-shadow: 0 0 #0000;--tw-inset-shadow-color: initial;--tw-inset-shadow-alpha: 100%;--tw-ring-color: initial;--tw-ring-shadow: 0 0 #0000;--tw-inset-ring-color: initial;--tw-inset-ring-shadow: 0 0 #0000;--tw-ring-inset: initial;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-offset-shadow: 0 0 #0000;--tw-duration: initial;--tw-ease: initial}}}
|
|
2
|
-
`);function _({name:e,label:t,placeholder:r,type:o="text",value:i,onValueChange:s,onBlur:n,autoComplete:l,rulesStatus:a=[],submitted:m=false,inputRef:f}){let[p,h]=react.useState(false),d=a.some(c=>!c.passed);return jsxRuntime.jsxs("div",{className:"font-inter relative w-full flex flex-col gap-1 text-trieoh-neutral2",children:[jsxRuntime.jsx("label",{htmlFor:e,className:"text-[1rem] font-semibold",children:t}),jsxRuntime.jsxs("div",{className:`flex justify-between items-center px-[0.625rem] py-[0.0625rem] gap-[0.625rem] border-b-2 border-trieoh-neutral2 ${d&&m?"!border-[#e53935]":""}`,children:[jsxRuntime.jsx("input",{type:p?"text":o,name:e,id:e,placeholder:r,value:i,onChange:c=>s&&s(c.target.value),onBlur:n,autoComplete:l,"aria-invalid":d&&m,ref:f,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"&&(p?jsxRuntime.jsx(ri.RiEyeCloseLine,{className:"cursor-pointer shrink-0 select-none",size:24,onClick:()=>h(false)}):jsxRuntime.jsx(ri.RiEyeLine,{className:"cursor-pointer shrink-0 select-none",size:24,onClick:()=>h(true)}))]}),jsxRuntime.jsx("div",{className:"text-[0.75rem] text-[#6b7280] transition-opacity duration-200 ease-in-out",children:a.map((c,S)=>{let R=["transition-[color,text-decoration,opacity] duration-[120ms] ease opacity-95 m-[0.125rem]",c.passed?"line-through opacity-60 text-[#10b981]":"",!c.passed&&m?"text-[#e53935] font-semibold opacity-100":""].filter(Boolean).join(" ");return jsxRuntime.jsx("p",{className:R,children:c.message},c.id??S)})})]})}function k({label:e,onSubmit:t,loading:r}){return jsxRuntime.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 E({mainText:e,subText:t}){return jsxRuntime.jsxs("div",{className:"font-inter flex flex-col items-center",children:[jsxRuntime.jsx("div",{className:"flex justify-center items-center p-2 bg-[oklch(0.8853_0_0/30%)] rounded-trieoh-full mb-[0.625rem]",children:jsxRuntime.jsx(go.GoPerson,{className:"w-[64px] h-[64px] p-[0.625rem] bg-trieoh-neutral1 rounded-trieoh-full shadow-[0_0.25rem_1rem_rgba(0,0,0,0.25)]",size:70})}),jsxRuntime.jsx("h3",{className:"text-center text-trieoh-xl font-medium m-0",children:e}),jsxRuntime.jsx("span",{className:"text-center text-[0.875rem] font-light opacity-60",children:t})]})}function T(e,t){return e.map(r=>({id:r.id,message:r.message,passed:!!r.test(t)}))}function bt({onSuccess:e,onFailed:t,signUpRedirect:r,forgotPasswordRedirect:o,emailRules:i}){let[s,n]=react.useState(""),[l,a]=react.useState(""),[m,f]=react.useState(false),[p,h]=react.useState(false),d=react.useRef(null),c=react.useRef(null),{auth:S}=y(),R={email:i||[{message:"Digite um e-mail v\xE1lido, ex: exemplo@dominio.com",test:v=>/\S+@\S+\.\S+/.test(v)}],password:[]},w=T(R.email,s),C=T(R.password,l);return jsxRuntime.jsxs("form",{className:"font-inter flex flex-col w-full max-w-[30rem] min-w-[15rem] max-h-[max(75dvh,32rem)] overflow-hidden gap-5 items-center bg-trieoh-neutral1 text-trieoh-neutral2 p-[1.25rem_1.5rem] shadow-[0_0.25rem_0.25rem_0_rgba(0,0,0,0.25)] transition-transform duration-150 ease-in-out rounded-[0.25rem]",children:[jsxRuntime.jsx(E,{mainText:"Fa\xE7a login na sua conta",subText:"Insira seus dados para fazer login"}),jsxRuntime.jsxs("div",{className:"w-full flex flex-col gap-[0.625rem] flex-[1_1_auto] overflow-y-auto mb-2",children:[jsxRuntime.jsx(_,{label:"Email",name:"email",placeholder:"teste@gmail.com",autoComplete:"email",type:"email",value:s,onValueChange:n,inputRef:d,rulesStatus:w,submitted:m}),jsxRuntime.jsx(_,{label:"Senha",name:"password",placeholder:"**********",autoComplete:"current-password",type:"password",value:l,onValueChange:a,inputRef:c,rulesStatus:C,submitted:m})]}),jsxRuntime.jsx(k,{label:"Entrar",onSubmit:async v=>{v.preventDefault(),f(true);let M=w.some(g=>!g.passed),z=C.some(g=>!g.passed);if(M){d.current?.focus();return}if(z){c.current?.focus();return}h(true);let P=await S.login(s,l);P.success?e&&await e(P.message):t&&await t(P.message,P.trace),h(false);},loading:p}),o&&jsxRuntime.jsx("span",{className:"text-trieoh-sm font-semibold text-center cursor-pointer",children:jsxRuntime.jsx("span",{className:"cursor-pointer text-trieoh-secondary transition-colors duration-200 hover:text-trieoh-primary",onClick:o,children:"Esqueceu sua senha?"})}),r&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-[0.625rem] w-full text-trieoh-base font-semibold opacity-60",children:[jsxRuntime.jsx("hr",{className:"flex-1"}),"OU",jsxRuntime.jsx("hr",{className:"flex-1"})]}),jsxRuntime.jsxs("span",{className:"text-trieoh-sm font-semibold",children:["Ainda n\xE3o possui uma conta? ",jsxRuntime.jsx("span",{className:"cursor-pointer text-trieoh-secondary transition-colors duration-200 hover:text-trieoh-primary",onClick:r,children:"Cadastra-se"})]})]})]})}function St({onSuccess:e,onFailed:t,loginRedirect:r,emailRules:o,passwordRules:i}){let[s,n]=react.useState(""),[l,a]=react.useState(""),[m,f]=react.useState(""),[p,h]=react.useState(false),[d,c]=react.useState(false),S=react.useRef(null),R=react.useRef(null),w=react.useRef(null),{auth:C}=y(),L={email:o||[{message:"Digite um e-mail v\xE1lido, ex: exemplo@dominio.com",test:g=>/\S+@\S+\.\S+/.test(g)}],password:i||[{message:"M\xEDnimo de 8 caracteres.",test:g=>g.length>=8},{message:"Deve conter uma letra mai\xFAscula.",test:g=>/[A-Z]/.test(g)},{message:"Inclua pelo menos um caractere especial, ex: ! @ # $ % & * . ,",test:g=>/[!@#$%^&*(),.?":{}|<>_\-+=~`;/\\[\]]/.test(g)},{message:"Deve conter um n\xFAmero.",test:g=>/\d/.test(g)}],confirmPassword:[{message:"Senhas n\xE3o conferem.",test:g=>g===l}]},v=T(L.email,s),M=T(L.password,l),z=T(L.confirmPassword,m);return jsxRuntime.jsxs("form",{className:"font-inter flex flex-col w-full max-w-[30rem] min-w-[15rem] max-h-[max(75dvh,32rem)] overflow-hidden gap-5 items-center bg-trieoh-neutral1 text-trieoh-neutral2 p-[1.25rem_1.5rem] shadow-[0_0.25rem_0.25rem_0_rgba(0,0,0,0.25)] transition-transform duration-150 ease-in-out rounded-[0.25rem]",children:[jsxRuntime.jsx(E,{mainText:"Crie sua conta",subText:"Insira seus dados para come\xE7ar"}),jsxRuntime.jsxs("div",{className:"w-full flex flex-col gap-[0.625rem] flex-[1_1_auto] overflow-y-auto mb-2",children:[jsxRuntime.jsx(_,{label:"Email",name:"email",placeholder:"teste@gmail.com",autoComplete:"email",type:"email",value:s,onValueChange:n,inputRef:S,rulesStatus:v,submitted:p}),jsxRuntime.jsx(_,{label:"Senha",name:"password",placeholder:"**********",autoComplete:"new-password",type:"password",value:l,onValueChange:a,inputRef:R,rulesStatus:M,submitted:p}),jsxRuntime.jsx(_,{label:"Confirme a Senha",name:"confirm-password",placeholder:"**********",autoComplete:"new-password",type:"password",value:m,onValueChange:f,inputRef:w,rulesStatus:z,submitted:p})]}),jsxRuntime.jsx(k,{label:"Criar Conta",onSubmit:async g=>{g.preventDefault(),h(true);let rt=v.some(K=>!K.passed),ot=M.some(K=>!K.passed),it=z.some(K=>!K.passed);if(rt){S.current?.focus();return}if(ot){R.current?.focus();return}if(it){w.current?.focus();return}c(true);let ne=await C.register(s,l);ne.success?e&&await e(ne.message):t&&await t(ne.message,ne.trace),c(false);},loading:d}),r&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-[0.625rem] w-full text-trieoh-base font-semibold opacity-60",children:[jsxRuntime.jsx("hr",{className:"flex-1"}),"OU",jsxRuntime.jsx("hr",{className:"flex-1"})]}),jsxRuntime.jsxs("span",{className:"text-trieoh-sm font-semibold",children:["J\xE1 possui uma conta? ",jsxRuntime.jsx("span",{className:"cursor-pointer text-trieoh-secondary transition-colors duration-200 hover:text-trieoh-primary",onClick:r,children:"Entre"})]})]})]})}var _t={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 kt({size:e}){let t=e?_t[e]:"text-trieoh-xl";return jsxRuntime.jsxs("span",{className:`font-inter font-medium ${t}`,children:["\xA9 ",new Date().getFullYear()," TrieOH"]})}function At({onSuccess:e,onFailed:t,forceLogout:r}){let{auth:o}=y(),[i,s]=react.useState(false);return jsxRuntime.jsxs("button",{onClick:async l=>{if(l.preventDefault(),i)return;s(true);let a=await o.logout({forceLogout: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:[jsxRuntime.jsx(im.ImExit,{size:24})," ",jsxRuntime.jsx("span",{children:"Log out"})]})}var Ke={mobile:fa.FaMobileAlt,tablet:fa.FaTabletAlt,desktop:fa.FaDesktop};function Ye(e){let{device:t,os:r,browser:o}=uaParserJs.UAParser(e);return {deviceType:t.type??"desktop",os:r.name,browser:o.name}}function We(e){let t=Ye(e);return {device:Ot(t.deviceType),os:t.os,browser:t.browser}}function Ot(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 Ae({is_current:e,session_id:t,user_agent:r,issued_at:o,user_ip:i,onClick:s}){let n=We(r),l=Ke[n.device];return jsxRuntime.jsx("div",{className:"border-t border-[rgba(0,0,0,0.3)] p-[1.25rem_0.75rem] text-trieoh-neutral2",children:jsxRuntime.jsxs("div",{className:"relative flex flex-col items-center gap-2 flex-1 text-center @[640px]:flex-row @[640px]:items-center @[640px]:gap-4 @[640px]:text-left",children:[jsxRuntime.jsx(l,{size:40}),jsxRuntime.jsxs("div",{className:"flex flex-col min-w-0",children:[jsxRuntime.jsxs("h3",{className:"text-trieoh-base font-semibold m-0",children:[n.browser," - ",n.os]}),jsxRuntime.jsxs("span",{className:"inline-flex flex-col text-trieoh-sm font-extralight @[640px]:flex-row @[640px]:gap-2 @[640px]:items-center",children:[e&&jsxRuntime.jsx("strong",{className:"text-trieoh-primary font-normal",children:"\u2022 Sess\xE3o Atual \u2022"}),jsxRuntime.jsx("span",{children:`${i} - ${Ge(o)}`})]})]}),!e&&jsxRuntime.jsx(fa.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 Ft({revokeAll:e=false,onSuccess:t}){let{auth:r}=y(),[o,i]=react.useState(false),[s,n]=react.useState([]),l=async()=>{let f=await r.sessions();if(f.success){let p=r.profile()?.session_id,h=f.data.sort((d,c)=>d.session_id===p?-1:c.session_id===p?1:0);n(h);}};react.useEffect(()=>{l();},[]);let a=async(f,p)=>{f.preventDefault();let h=s.find(d=>d.session_id===p);if(h){n(s.filter(d=>d.session_id!==p));try{(await r.revokeASession(p)).success||n(c=>[...c,h]);}catch{n(d=>[...d,h]);}}};return jsxRuntime.jsxs("div",{className:"font-inter w-full min-w-[20rem] m-2 @container bg-trieoh-neutral1 text-trieoh-neutral2 p-[1.5rem_0.5rem] rounded-lg",children:[jsxRuntime.jsxs("div",{className:"w-full flex flex-wrap items-center justify-center text-center gap-4 box-border px-[0.75rem] @[640px]:justify-between @[640px]:text-left @[640px]:gap-8",children:[jsxRuntime.jsxs("div",{className:"flex-[0_1_auto] max-w-[25rem]",children:[jsxRuntime.jsx("h3",{className:"font-semibold text-trieoh-2xl m-0 mb-1",children:"Navegadores e Dispositivos"}),jsxRuntime.jsx("p",{className:"font-extralight text-trieoh-base m-0",children:"Esses navegadores e dispositivos est\xE3o atualmente conectados \xE0 sua conta. Remova quaisquer dispositivos n\xE3o autorizados."})]}),jsxRuntime.jsx("button",{type:"submit",onClick:async f=>{if(f.preventDefault(),o)return;i(true);let p=await r.revokeSessions(e),h=r.profile()?.session_id;p.success&&(n(e?[]:s.filter(d=>d.session_id===h)),t&&t(p.message)),i(false);},disabled:o,className:`font-inter w-full max-w-[14rem] p-[1rem_0] h-auto text-trieoh-base font-semibold outline-none bg-transparent relative overflow-hidden shrink-0 border-2 border-trieoh-neutral2 text-trieoh-neutral2 cursor-pointer transition-transform duration-500 rounded-[0.25rem] hover:scale-[1.02] active:scale-[0.99] disabled:opacity-60 disabled:cursor-not-allowed disabled:!transform-none ${o?"trieoh-button-loading":""}`,children:"Revogar todas as sess\xF5es"})]}),jsxRuntime.jsx("div",{className:"mt-4",children:s.length>0?s.map(f=>jsxRuntime.jsx(Ae,{...f,is_current:r.profile()?.session_id===f.session_id,onClick:a},f.session_id)):jsxRuntime.jsx("span",{className:"block border-t border-[rgba(0,0,0,0.3)] p-[1.25rem_0.75rem] text-center font-semibold",children:"Nenhuma Sess\xE3o Dispon\xEDvel"})})]})}function Qe({onSuccess:e,onFailed:t,loginRedirect:r,emailRules:o}){let[i,s]=react.useState(""),[n,l]=react.useState(false),[a,m]=react.useState(false),f=react.useRef(null),{auth:p}=y(),d=T({email:o||[{message:"Digite um e-mail v\xE1lido, ex: exemplo@dominio.com",test:S=>/\S+@\S+\.\S+/.test(S)}]}.email,i);return jsxRuntime.jsxs("form",{className:"font-inter flex flex-col w-full max-w-[30rem] min-w-[15rem] max-h-[max(75dvh,32rem)] overflow-hidden gap-5 items-center bg-trieoh-neutral1 text-trieoh-neutral2 p-[1.25rem_1.5rem] shadow-[0_0.25rem_0.25rem_0_rgba(0,0,0,0.25)] transition-transform duration-150 ease-in-out rounded-[0.25rem]",children:[jsxRuntime.jsx(E,{mainText:"Esqueci a senha",subText:"Insira seu e-mail para receber um link de redefini\xE7\xE3o."}),jsxRuntime.jsx("div",{className:"w-full flex flex-col gap-[0.625rem] flex-[1_1_auto] overflow-y-auto mb-2",children:jsxRuntime.jsx(_,{label:"Email",name:"email",placeholder:"teste@gmail.com",autoComplete:"email",type:"email",value:i,onValueChange:s,inputRef:f,rulesStatus:d,submitted:n})}),jsxRuntime.jsx(k,{label:a?"Enviando...":"Enviar link de redefini\xE7\xE3o",onSubmit:async S=>{if(S.preventDefault(),l(true),d.some(C=>!C.passed)){f.current?.focus();return}m(true);let w=await p.sendForgotPassword(i);w.success?e&&await e(w.message):t&&await t(w.message,w.trace),m(false);},loading:a}),r&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-[0.625rem] w-full text-trieoh-base font-semibold opacity-60",children:[jsxRuntime.jsx("hr",{className:"flex-1"}),"OU",jsxRuntime.jsx("hr",{className:"flex-1"})]}),jsxRuntime.jsxs("span",{className:"text-trieoh-sm font-semibold",children:["Lembrou-se da sua senha? ",jsxRuntime.jsx("span",{className:"cursor-pointer text-trieoh-secondary transition-colors duration-200 hover:text-trieoh-primary",onClick:r,children:"Login"})]})]})]})}function zt({token:e,onSuccess:t,onFailed:r,loginRedirect:o,passwordRules:i}){let[s,n]=react.useState(""),[l,a]=react.useState(""),[m,f]=react.useState(false),[p,h]=react.useState(false),d=react.useRef(null),c=react.useRef(null),{auth:S}=y(),R={password:i||[{message:"M\xEDnimo de 8 caracteres.",test:v=>v.length>=8},{message:"Deve conter uma letra mai\xFAscula.",test:v=>/[A-Z]/.test(v)},{message:"Inclua pelo menos um caractere especial, ex: ! @ # $ % & * . ,",test:v=>/[!@#$%^&*(),.?":{}|<>_\-+=~`;/\\[\]]/.test(v)},{message:"Deve conter um n\xFAmero.",test:v=>/\d/.test(v)}],confirmPassword:[{message:"Senhas n\xE3o conferem.",test:v=>v===s}]},w=T(R.password,s),C=T(R.confirmPassword,l);return jsxRuntime.jsxs("form",{className:"font-inter flex flex-col w-full max-w-[30rem] min-w-[15rem] max-h-[max(75dvh,32rem)] overflow-hidden gap-5 items-center bg-trieoh-neutral1 text-trieoh-neutral2 p-[1.25rem_1.5rem] shadow-[0_0.25rem_0.25rem_0_rgba(0,0,0,0.25)] transition-transform duration-150 ease-in-out rounded-[0.25rem]",children:[jsxRuntime.jsx(E,{mainText:"Redefinir Senha",subText:"Crie uma nova senha para sua conta"}),jsxRuntime.jsxs("div",{className:"w-full flex flex-col gap-[0.625rem] flex-[1_1_auto] overflow-y-auto mb-2",children:[jsxRuntime.jsx(_,{label:"Nova Senha",name:"password",placeholder:"**********",autoComplete:"new-password",type:"password",value:s,onValueChange:n,inputRef:d,rulesStatus:w,submitted:m}),jsxRuntime.jsx(_,{label:"Confirme a Nova Senha",name:"confirm-password",placeholder:"**********",autoComplete:"new-password",type:"password",value:l,onValueChange:a,inputRef:c,rulesStatus:C,submitted:m})]}),jsxRuntime.jsx(k,{label:"Redefinir Senha",onSubmit:async v=>{v.preventDefault(),f(true);let M=w.some(g=>!g.passed),z=C.some(g=>!g.passed);if(M){d.current?.focus();return}if(z){c.current?.focus();return}h(true);let P=await S.resetPassword(e,s);P.success?t&&await t(P.message):r&&await r(P.message,P.trace),h(false);},loading:p}),o&&jsxRuntime.jsxs("span",{className:"text-trieoh-sm font-semibold",children:["Lembrou-se da sua senha? ",jsxRuntime.jsx("span",{className:"cursor-pointer text-trieoh-secondary transition-colors duration-200 hover:text-trieoh-primary",onClick:o,children:"Login"})]})]})}function Jt(e,t,r){let[o,i]=react.useState(true),[s,n]=react.useState("verifying"),[l,a]=react.useState("Verificando seu e-mail..."),{auth:m}=y(),f=react.useRef(false),p=async()=>{if(!f.current){f.current=true,i(true),n("verifying");try{if(m.profile()?.is_verified){n("already_verified"),a("Seu e-mail j\xE1 est\xE1 verificado."),i(!1);return}let c=await m.verifyEmail(e);c.success?(await m.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 react.useEffect(()=>{e&&!f.current&&p();},[e]),{loading:o,status:s,message:l,onRetry:d=>{d.preventDefault(),f.current=false,p();},setStatus:n,setLoading:i,setMessage:a}}function Kt({token:e,onSuccess:t,onFailed:r}){let{loading:o,status:i,message:s,onRetry:n}=Jt(e,t,r);return jsxRuntime.jsx("div",{className:"font-inter flex flex-col w-full h-full min-h-screen items-center justify-center bg-trieoh-neutral1 text-trieoh-neutral2 p-6",children:jsxRuntime.jsxs("div",{className:"w-full max-w-[30rem] flex flex-col gap-8 items-center bg-trieoh-neutral1 text-trieoh-neutral2 p-[1.25rem_1.5rem] shadow-[0_0.25rem_0.25rem_0_rgba(0,0,0,0.25)] rounded-[0.25rem]",children:[jsxRuntime.jsx(E,{mainText:i==="verifying"?"Verificando...":i==="error"?"Ops! Falha na verifica\xE7\xE3o":"Tudo pronto!",subText:s}),i==="verifying"&&jsxRuntime.jsx("div",{className:"w-full flex justify-center py-4",children:jsxRuntime.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-trieoh-secondary"})}),i==="error"&&jsxRuntime.jsx("div",{className:"w-full flex flex-col gap-6 items-center",children:jsxRuntime.jsx("div",{className:"w-full mt-2",children:jsxRuntime.jsx(k,{label:"Tentar novamente",onSubmit:n,loading:o})})}),(i==="success"||i==="already_verified")&&jsxRuntime.jsxs("div",{className:"w-full flex flex-col gap-4 items-center",children:[jsxRuntime.jsx("div",{className:"w-16 h-16 flex items-center justify-center rounded-full bg-trieoh-secondary/10 text-trieoh-secondary",children:i==="success"?jsxRuntime.jsx(fi.FiCheck,{size:40}):jsxRuntime.jsx(fi.FiInfo,{size:40})}),jsxRuntime.jsx("p",{className:"text-trieoh-sm font-semibold opacity-50 text-center",children:"Voc\xEA j\xE1 pode fechar esta janela ou continuar navegando em sua conta."})]})]})})}function Yt({onSuccess:e,onFailed:t}){let[r,o]=react.useState(false),[i,s]=react.useState(false),{auth:n}=y();return jsxRuntime.jsxs("div",{className:"font-inter flex flex-col w-full max-w-[30rem] min-w-[15rem] max-h-[max(75dvh,32rem)] overflow-hidden gap-5 items-center bg-trieoh-neutral1 text-trieoh-neutral2 p-[1.25rem_1.5rem] shadow-[0_0.25rem_0.25rem_0_rgba(0,0,0,0.25)] transition-transform duration-150 ease-in-out rounded-[0.25rem]",children:[jsxRuntime.jsx(E,{mainText:"Reenviar Verifica\xE7\xE3o",subText:"N\xE3o recebeu o e-mail de verifica\xE7\xE3o? Clique no bot\xE3o abaixo para reenviar."}),jsxRuntime.jsx(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&&jsxRuntime.jsx("p",{className:"text-trieoh-sm font-semibold text-trieoh-secondary",children:"Um novo link de verifica\xE7\xE3o foi enviado para seu e-mail."})]})}exports.AuthProvider=Jr;exports.BasicInputField=_;exports.BasicLogoutButton=At;exports.Copyright=kt;exports.ForgotPassword=Qe;exports.ResendVerifyEmail=Yt;exports.ResetPassword=zt;exports.Sessions=Ft;exports.SignIn=bt;exports.SignUp=St;exports.VerifyEmail=Kt;exports.useAuth=y;//# sourceMappingURL=react.js.map
|
|
1
|
+
'use strict';var react=require('react'),envoyFetchTs=require('@trieoh/envoy-fetch-ts'),jsxRuntime=require('react/jsx-runtime'),ri=require('react-icons/ri'),go=require('react-icons/go'),im=require('react-icons/im'),fa=require('react-icons/fa'),uaParserJs=require('ua-parser-js'),fi=require('react-icons/fi');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function be(e,t){if(t.startsWith("http"))return t;let r=e.replace(/\/$/,""),o=t.replace(/^\//,"");return `${r}/${o}`}var Y={isAuthenticated:false,isInitializing:true},ye=new Set,Oe=()=>ye.forEach(e=>e()),S={subscribe:e=>(ye.add(e),()=>ye.delete(e)),getSnapshot:()=>Y,getServerSnapshot:()=>Y,set:e=>{Y={...Y,...e},Oe();},reset:()=>{Y={isAuthenticated:false,isInitializing:false},Oe();}};var A={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);}},W={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);}},D={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",m=[`${e}=${t}`,s&&!a?`Domain=${s}`:"",`Path=${i}`,`SameSite=${l}`,n?"Secure":"",o?`expires=${o}`:""];document.cookie=m.filter(Boolean).join("; ");},remove:(e,t)=>{D.set(e,"",{expires:"Thu, 01 Jan 1970 00:00:00 GMT",domain:t||void 0});}};function B(e){try{let r=encodeURIComponent(JSON.stringify(e)).split("").reverse().join("");return "tr_"+btoa(r)}catch{return ""}}function q(e){if(!e)return null;try{if(!e.startsWith("tr_"))return null;let t=e.replace(/^tr_/,""),o=atob(t).split("").reverse().join("");return JSON.parse(decodeURIComponent(o))}catch{return null}}var ae="trieoh_access_token",F={getAccessToken:()=>q(W.getItem(ae)),setAccessToken:e=>{e?W.setItem(ae,B(e)):W.removeItem(ae);},clear:()=>{W.removeItem(ae);}};var G=null,Se="trieoh_access_expiry",ce="trieoh_refresh_expiry",le="trieoh_refresh_domain";function Me(e){if(typeof window>"u")return null;let t=window.location.hostname;if(t==="localhost"||t==="127.0.0.1"||t.includes("localhost"))return null;if(e)try{let o=e;return o.startsWith("http")&&(o=new URL(o).hostname),t===o||t.endsWith("."+o)?o:t}catch{return t}return t}function Be(e){try{let t=e.split(".")[1];if(!t)return null;let r=t.replace(/-/g,"+").replace(/_/g,"/");for(;r.length%4;)r+="=";let o=decodeURIComponent(atob(r).split("").map(i=>"%"+("00"+i.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(o)}catch(t){return envoyFetchTs.logger.error("Error decoding JWT:",t),null}}function Q(e){let{access_token_string:t,refresh_token_string:r,access_expires_at:o,refresh_expires_at:i}=e,s=Be(t);if(!s){envoyFetchTs.logger.error("Failed to decode tokens");return}F.setAccessToken(t);let n=new Date(i).getTime(),l=new Date(o).getTime(),a=Me(e.domain);D.set("refresh_token",r,{expires:new Date(n).toUTCString(),domain:a}),G=B({access_data:s,refresh_expiry_date:n}),A.setItem(Se,B(l)),A.setItem(ce,B(n)),a?A.setItem(le,a):A.removeItem(le),S.set({isAuthenticated:true,isInitializing:false}),envoyFetchTs.logger.log("Auth session saved");}function Z(){if(G)return q(G);let e=F.getAccessToken();if(!e)return null;let t=Be(e);if(!t||t.exp*1e3<=Date.now())return null;let r=A.getItem(ce);if(!r)return null;let o=q(r);if(!o)return null;let i={access_data:t,refresh_expiry_date:o};return G=B(i),i}function Fe(e,t){try{let r=A.getItem(e);if(!r)return !0;let o=q(r);return o?o-Date.now()<=t*1e3:!0}catch(r){return envoyFetchTs.logger.warn("Error reading expiry:",r),true}}var Re=(e=30)=>Fe(Se,e),ue=(e=10)=>Fe(ce,e);function V(){G=null,F.clear(),A.removeItem(Se),A.removeItem(ce);let e=A.getItem(le)||Me();D.remove("refresh_token",e),A.removeItem(le),S.reset(),envoyFetchTs.logger.log("Auth tokens and claims cleared");}function Ue(){let e=Z();return e?e.access_data.sub:null}function st(){let e=typeof window>"u",t=typeof ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('react.js', document.baseURI).href)) })<"u"&&undefined?undefined:{},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 me=null,ke={};function He(e){ke={...ke,...e},me=null;}function _e(){return me||(me={...st(),...ke}),me}var x={get PROJECT_ID(){return _e().PROJECT_ID},get BASE_URL(){return _e().BASE_URL}};var de=class{constructor(t){this.isRefreshing=false;this.refreshPromise=null;this.baseURL=t?.baseURL||x.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 envoyFetchTs.simpleFetch(be(this.authBaseURL,"/auth/refresh"),{method:"POST",credentials:"include"});if(t.code!==200||!t.data)throw t.code!==503&&V(),new Error(t.message||"Failed to refresh token");Q(t.data);let r=Z();r&&this.onTokenRefreshed?.(r),envoyFetchTs.logger.log("Token refreshed successfully");}catch(t){throw envoyFetchTs.logger.warn("Failed to refresh token:",t),V(),this.onRefreshFailed?.(t),t}finally{this.isRefreshing=false,this.refreshPromise=null;}})(),this.refreshPromise)}async beforeRequest(){if(ue()){V();return}let t=!!F.getAccessToken(),r=!!D.get("refresh_token");if(!t&&r||t&&Re(30))try{await this.refreshToken();}catch(o){envoyFetchTs.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=be(this.baseURL,t),n=async()=>{let a=F.getAccessToken(),m=new Headers(r?.headers);return o&&a&&m.set("Authorization",`Bearer ${a}`),m.has("Content-Type")||m.set("Content-Type","application/json"),fetch(s,{...r,headers:m,credentials:"include"})},l=await n();if(l.status===401&&o&&!i&&Re(30)){envoyFetchTs.logger.log("401 detected and token is expiring/expired, attempting refresh...");try{await this.refreshToken(),l=await n();}catch{envoyFetchTs.logger.error("Retry failed after refresh error");}}return l}};function 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 pe=class{constructor(t,r,o,i){this.interceptor=new de({baseURL:t,authBaseURL:r,onTokenRefreshed:o}),this.client=envoyFetchTs.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 j=()=>{if(!x.PROJECT_ID||x.PROJECT_ID.trim()==="")throw new Error("[TRIEOH SDK] Project ID is missing. Please set PUBLIC_TRIEOH_AUTH_PROJECT_ID, NEXT_PUBLIC_TRIEOH_AUTH_PROJECT_ID or VITE_TRIEOH_AUTH_PROJECT_ID.")};var ze=(e,t)=>({login:async(r,o)=>{x.PROJECT_ID&&j();let i=`/auth/login${x.PROJECT_ID?`?project_id=${x.PROJECT_ID}`:""}`,s=await e.post(i,{email:r,password:o},{requiresAuth:false});return s.success&&(Q(s.data),t?.onLogin?.(s)),s},register:async(r,o)=>{let i={requiresAuth:false},s=`/auth/register${x.PROJECT_ID?`?project_id=${x.PROJECT_ID}`:""}`;x.PROJECT_ID&&j();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${x.PROJECT_ID?`?project_id=${x.PROJECT_ID}`:""}`,i=await e.post(o);return (i.success||r?.forceLogout)&&V(),i},refresh:async()=>{let r=await e.post("/auth/refresh",void 0,{skipRefresh:true});return r.success&&(Q(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:()=>Ue(),sendForgotPassword:async r=>{let o={requiresAuth:false};return x.PROJECT_ID?(j(),e.post("/account/forgot-password",{email:r,project_id:x.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=react.createContext(null);function Jr({children:e,baseURL:t,projectId:r,isProjectMode:o=true,fallback:i,waitSession:s=true,clientConfig:n,onLogin:l,onResetPassword:a,onRegister:m,onVerify:f,onRefresh:p}){let h=react.useRef(false),{isAuthenticated:d,isInitializing:c}=react.useSyncExternalStore(S.subscribe,S.getSnapshot,S.getServerSnapshot);react.useEffect(()=>{He({...r?{PROJECT_ID:r}:{},...t?{BASE_URL:t}:{}});},[r,t]);let y=react.useCallback(L=>{S.set({isAuthenticated:!!L.access_data,isInitializing:false}),p?.();},[p]),R=react.useMemo(()=>new pe(t,void 0,y,n),[t,y,n]),w=react.useMemo(()=>ze(R,{onLogin:l,onResetPassword:a,onRegister:m,onVerify:f,onRefresh:p}),[R,l,a,m,f,p]);react.useEffect(()=>{o&&j(),(async()=>{if(h.current)return;if(h.current=true,Z()){S.set({isAuthenticated:true,isInitializing:false});return}if(!!!D.get("refresh_token")||ue()){S.reset(),S.set({isInitializing:false});return}envoyFetchTs.logger.log("No cached claims, attempting silent refresh...");try{(await w.refresh()).success?(S.set({isAuthenticated:!0,isInitializing:!1}),envoyFetchTs.logger.log("Session restored.")):(S.reset(),envoyFetchTs.logger.warn("No active session."));}catch{S.reset(),envoyFetchTs.logger.warn("Could not restore session (offline?).");}finally{S.set({isInitializing:false});}})();},[w,o]);let C=react.useMemo(()=>({auth:w,isAuthenticated:d,isInitializing:c,isProjectMode:o}),[w,d,c,o]);return s&&c?i??null:jsxRuntime.jsx(Ve.Provider,{value:C,children:e})}function b(){let e=react.useContext(Ve);if(!e)throw new Error("useAuth must be used inside <AuthProvider>");return e}function Te(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));}Te(`/*! tailwindcss v4.3.0 | MIT License | https://tailwindcss.com */@layer properties;@layer theme,base,components,utilities;@layer theme{:root,:host{--font-sans: ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";--font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;--spacing: .25rem;--font-weight-extralight: 200;--font-weight-light: 300;--font-weight-normal: 400;--font-weight-medium: 500;--font-weight-semibold: 600;--radius-lg: .5rem;--ease-in-out: cubic-bezier(.4, 0, .2, 1);--animate-spin: spin 1s linear infinite;--default-transition-duration: .15s;--default-transition-timing-function: cubic-bezier(.4, 0, .2, 1);--default-font-family: var(--font-sans);--default-mono-font-family: var(--font-mono);--color-trieoh-primary: oklch(.1139 .0789 264.05);--color-trieoh-secondary: oklch(.7975 .1018 262.7);--color-trieoh-neutral1: oklch(.9702 0 0);--color-trieoh-neutral2: oklch(.1944 .0051 248.09);--radius-trieoh-full: 50%;--font-inter: "Inter", sans-serif}}@layer base{*,:after,:before,::backdrop,::file-selector-button{box-sizing:border-box;margin:0;padding:0;border:0 solid}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;tab-size:4;font-family:var(--default-font-family, ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings, normal);font-variation-settings:var(--default-font-variation-settings, normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings, normal);font-variation-settings:var(--default-mono-font-variation-settings, normal);font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea,::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;border-radius:0;background-color:transparent;opacity:1}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not (-webkit-appearance: -apple-pay-button)) or (contain-intrinsic-size: 1px){::placeholder{color:currentcolor;@supports (color: color-mix(in lab,red,red)){color:color-mix(in oklab,currentcolor 50%,transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit,::-webkit-datetime-edit-year-field,::-webkit-datetime-edit-month-field,::-webkit-datetime-edit-day-field,::-webkit-datetime-edit-hour-field,::-webkit-datetime-edit-minute-field,::-webkit-datetime-edit-second-field,::-webkit-datetime-edit-millisecond-field,::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]),::file-selector-button{appearance:button}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}}@layer utilities{.\\@container{container-type:inline-size}.trieoh-button-loading{&:after{content:"";position:absolute;top:0;left:-150%;width:150%;height:100%;background:linear-gradient(120deg,transparent 0%,var(--trieoh-neutral2) 40%,transparent 80%);@supports (color: color-mix(in lab,red,red)){background:linear-gradient(120deg,transparent 0%,color-mix(in oklab,var(--trieoh-neutral2) 40%,white 15%) 40%,transparent 80%)}animation:trieoh-shine 1.5s infinite}}.absolute{position:absolute}.relative{position:relative}.top-0{top:calc(var(--spacing) * 0)}.right-0{right:calc(var(--spacing) * 0)}.m-0{margin:calc(var(--spacing) * 0)}.m-2{margin:calc(var(--spacing) * 2)}.m-\\[0\\.125rem\\]{margin:.125rem}.mt-2{margin-top:calc(var(--spacing) * 2)}.mt-4{margin-top:calc(var(--spacing) * 4)}.mb-1{margin-bottom:calc(var(--spacing) * 1)}.mb-2{margin-bottom:calc(var(--spacing) * 2)}.mb-\\[0\\.625rem\\]{margin-bottom:.625rem}.box-border{box-sizing:border-box}.block{display:block}.contents{display:contents}.flex{display:flex}.inline-block{display:inline-block}.inline-flex{display:inline-flex}.h-12{height:calc(var(--spacing) * 12)}.h-16{height:calc(var(--spacing) * 16)}.h-\\[3\\.25rem\\]{height:3.25rem}.h-\\[64px\\]{height:64px}.h-auto{height:auto}.h-full{height:100%}.max-h-\\[max\\(75dvh\\,32rem\\)\\]{max-height:max(75dvh,32rem)}.min-h-screen{min-height:100vh}.w-12{width:calc(var(--spacing) * 12)}.w-16{width:calc(var(--spacing) * 16)}.w-\\[64px\\]{width:64px}.w-full{width:100%}.max-w-\\[14rem\\]{max-width:14rem}.max-w-\\[25rem\\]{max-width:25rem}.max-w-\\[30rem\\]{max-width:30rem}.min-w-0{min-width:calc(var(--spacing) * 0)}.min-w-\\[10rem\\]{min-width:10rem}.min-w-\\[15rem\\]{min-width:15rem}.min-w-\\[20rem\\]{min-width:20rem}.flex-1{flex:1}.flex-\\[0_1_auto\\]{flex:0 1 auto}.flex-\\[1_1_auto\\]{flex:1 1 auto}.shrink-0{flex-shrink:0}.animate-spin{animation:var(--animate-spin)}.cursor-pointer{cursor:pointer}.appearance-none{appearance:none}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-center{align-items:center}.items-end{align-items:flex-end}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.gap-1{gap:calc(var(--spacing) * 1)}.gap-2{gap:calc(var(--spacing) * 2)}.gap-4{gap:calc(var(--spacing) * 4)}.gap-5{gap:calc(var(--spacing) * 5)}.gap-6{gap:calc(var(--spacing) * 6)}.gap-8{gap:calc(var(--spacing) * 8)}.gap-\\[0\\.625rem\\]{gap:.625rem}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.rounded-\\[0\\.25rem\\]{border-radius:.25rem}.rounded-full{border-radius:calc(infinity * 1px)}.rounded-lg{border-radius:var(--radius-lg)}.rounded-trieoh-full{border-radius:var(--radius-trieoh-full)}.border-2{border-style:var(--tw-border-style);border-width:2px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-b-2{border-bottom-style:var(--tw-border-style);border-bottom-width:2px}.border-none{--tw-border-style: none;border-style:none}.\\!border-\\[\\#e53935\\]{border-color:#e53935!important}.border-\\[rgba\\(0\\,0\\,0\\,0\\.3\\)\\]{border-color:#0000004d}.border-trieoh-neutral2{border-color:var(--color-trieoh-neutral2)}.border-trieoh-secondary{border-color:var(--color-trieoh-secondary)}.bg-\\[oklch\\(0\\.8853_0_0\\/30\\%\\)\\]{background-color:#d9d9d94d}.bg-transparent{background-color:transparent}.bg-trieoh-neutral1{background-color:var(--color-trieoh-neutral1)}.bg-trieoh-secondary\\/10{background-color:color-mix(in srgb,oklch(.7975 .1018 262.7) 10%,transparent);@supports (color: color-mix(in lab,red,red)){background-color:color-mix(in oklab,var(--color-trieoh-secondary) 10%,transparent)}}.p-2{padding:calc(var(--spacing) * 2)}.p-6{padding:calc(var(--spacing) * 6)}.p-\\[0\\.625rem\\]{padding:.625rem}.p-\\[1\\.5rem_0\\.5rem\\]{padding:1.5rem .5rem}.p-\\[1\\.25rem_0\\.75rem\\]{padding:1.25rem .75rem}.p-\\[1\\.25rem_1\\.5rem\\]{padding:1.25rem 1.5rem}.p-\\[1rem_0\\]{padding:1rem 0}.px-\\[0\\.75rem\\]{padding-inline:.75rem}.px-\\[0\\.625rem\\]{padding-inline:.625rem}.px-\\[1\\.5rem\\]{padding-inline:1.5rem}.py-4{padding-block:calc(var(--spacing) * 4)}.py-\\[0\\.125rem\\]{padding-block:.125rem}.py-\\[0\\.0625rem\\]{padding-block:.0625rem}.text-center{text-align:center}.font-inter{font-family:var(--font-inter)}.text-\\[0\\.75rem\\]{font-size:.75rem}.text-\\[0\\.875rem\\]{font-size:.875rem}.text-\\[1rem\\]{font-size:1rem}.font-extralight{--tw-font-weight: var(--font-weight-extralight);font-weight:var(--font-weight-extralight)}.font-light{--tw-font-weight: var(--font-weight-light);font-weight:var(--font-weight-light)}.font-medium{--tw-font-weight: var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-normal{--tw-font-weight: var(--font-weight-normal);font-weight:var(--font-weight-normal)}.font-semibold{--tw-font-weight: var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.text-\\[\\#6b7280\\]{color:#6b7280}.text-\\[\\#10b981\\]{color:#10b981}.text-\\[\\#e53935\\]{color:#e53935}.text-\\[oklch\\(0\\.628_0\\.2577_29\\.23\\)\\]{color:red}.text-trieoh-neutral2{color:var(--color-trieoh-neutral2)}.text-trieoh-primary{color:var(--color-trieoh-primary)}.text-trieoh-secondary{color:var(--color-trieoh-secondary)}.line-through{text-decoration-line:line-through}.opacity-50{opacity:50%}.opacity-60{opacity:60%}.opacity-95{opacity:95%}.opacity-100{opacity:100%}.\\!shadow-none{--tw-shadow: 0 0 #0000 !important;box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)!important}.shadow-\\[0_0\\.25rem_0\\.25rem_0_rgba\\(0\\,0\\,0\\,0\\.25\\)\\]{--tw-shadow: 0 .25rem .25rem 0 var(--tw-shadow-color, rgba(0,0,0,.25));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-\\[0_0\\.25rem_1rem_rgba\\(0\\,0\\,0\\,0\\.25\\)\\]{--tw-shadow: 0 .25rem 1rem var(--tw-shadow-color, rgba(0,0,0,.25));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.transition-\\[color\\,text-decoration\\,opacity\\]{transition-property:color,text-decoration,opacity;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-\\[opacity\\,transform\\]{transition-property:opacity,transform;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-opacity{transition-property:opacity;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.transition-transform{transition-property:transform,translate,scale,rotate;transition-timing-function:var(--tw-ease, var(--default-transition-timing-function));transition-duration:var(--tw-duration, var(--default-transition-duration))}.duration-150{--tw-duration: .15s;transition-duration:.15s}.duration-200{--tw-duration: .2s;transition-duration:.2s}.duration-500{--tw-duration: .5s;transition-duration:.5s}.duration-\\[120ms\\]{--tw-duration: .12s;transition-duration:.12s}.ease-in-out{--tw-ease: var(--ease-in-out);transition-timing-function:var(--ease-in-out)}.outline-none{--tw-outline-style: none;outline-style:none}.select-none{-webkit-user-select:none;user-select:none}.hover\\:scale-\\[1\\.02\\]{&:hover{@media(hover:hover){scale:1.02}}}.hover\\:scale-\\[1\\.05\\]{&:hover{@media(hover:hover){scale:1.05}}}.hover\\:text-trieoh-primary{&:hover{@media(hover:hover){color:var(--color-trieoh-primary)}}}.hover\\:opacity-100{&:hover{@media(hover:hover){opacity:100%}}}.active\\:scale-\\[0\\.95\\]{&:active{scale:.95}}.active\\:scale-\\[0\\.98\\]{&:active{scale:.98}}.active\\:scale-\\[0\\.99\\]{&:active{scale:.99}}.disabled\\:\\!transform-none{&:disabled{transform:none!important}}.disabled\\:cursor-not-allowed{&:disabled{cursor:not-allowed}}.disabled\\:opacity-60{&:disabled{opacity:60%}}.\\@\\[640px\\]\\:flex-row{@container (width >= 640px){flex-direction:row}}.\\@\\[640px\\]\\:items-center{@container (width >= 640px){align-items:center}}.\\@\\[640px\\]\\:justify-between{@container (width >= 640px){justify-content:space-between}}.\\@\\[640px\\]\\:gap-2{@container (width >= 640px){gap:calc(var(--spacing) * 2)}}.\\@\\[640px\\]\\:gap-4{@container (width >= 640px){gap:calc(var(--spacing) * 4)}}.\\@\\[640px\\]\\:gap-8{@container (width >= 640px){gap:calc(var(--spacing) * 8)}}.\\@\\[640px\\]\\:text-left{@container (width >= 640px){text-align:left}}}@import url(https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap);@property --tw-border-style{syntax: "*"; inherits: false; initial-value: solid;}@property --tw-font-weight{syntax: "*"; inherits: false;}@property --tw-shadow{syntax: "*"; inherits: false; initial-value: 0 0 #0000;}@property --tw-shadow-color{syntax: "*"; inherits: false;}@property --tw-shadow-alpha{syntax: "<percentage>"; inherits: false; initial-value: 100%;}@property --tw-inset-shadow{syntax: "*"; inherits: false; initial-value: 0 0 #0000;}@property --tw-inset-shadow-color{syntax: "*"; inherits: false;}@property --tw-inset-shadow-alpha{syntax: "<percentage>"; inherits: false; initial-value: 100%;}@property --tw-ring-color{syntax: "*"; inherits: false;}@property --tw-ring-shadow{syntax: "*"; inherits: false; initial-value: 0 0 #0000;}@property --tw-inset-ring-color{syntax: "*"; inherits: false;}@property --tw-inset-ring-shadow{syntax: "*"; inherits: false; initial-value: 0 0 #0000;}@property --tw-ring-inset{syntax: "*"; inherits: false;}@property --tw-ring-offset-width{syntax: "<length>"; inherits: false; initial-value: 0px;}@property --tw-ring-offset-color{syntax: "*"; inherits: false; initial-value: #fff;}@property --tw-ring-offset-shadow{syntax: "*"; inherits: false; initial-value: 0 0 #0000;}@property --tw-duration{syntax: "*"; inherits: false;}@property --tw-ease{syntax: "*"; inherits: false;}@keyframes spin{to{transform:rotate(360deg)}}@keyframes trieoh-shine{0%{left:-150%}to{left:150%}}@layer properties{@supports ((-webkit-hyphens: none) and (not (margin-trim: inline))) or ((-moz-orient: inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-border-style: solid;--tw-font-weight: initial;--tw-shadow: 0 0 #0000;--tw-shadow-color: initial;--tw-shadow-alpha: 100%;--tw-inset-shadow: 0 0 #0000;--tw-inset-shadow-color: initial;--tw-inset-shadow-alpha: 100%;--tw-ring-color: initial;--tw-ring-shadow: 0 0 #0000;--tw-inset-ring-color: initial;--tw-inset-ring-shadow: 0 0 #0000;--tw-ring-inset: initial;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-offset-shadow: 0 0 #0000;--tw-duration: initial;--tw-ease: initial}}}
|
|
2
|
+
`);function _({name:e,label:t,placeholder:r,type:o="text",value:i,onValueChange:s,onBlur:n,autoComplete:l,rulesStatus:a=[],submitted:m=false,inputRef:f}){let[p,h]=react.useState(false),d=a.some(c=>!c.passed);return jsxRuntime.jsxs("div",{className:"font-inter relative w-full flex flex-col gap-1 text-trieoh-neutral2",children:[jsxRuntime.jsx("label",{htmlFor:e,className:"text-[1rem] font-semibold",children:t}),jsxRuntime.jsxs("div",{className:`flex justify-between items-center px-[0.625rem] py-[0.0625rem] gap-[0.625rem] border-b-2 border-trieoh-neutral2 ${d&&m?"!border-[#e53935]":""}`,children:[jsxRuntime.jsx("input",{type:p?"text":o,name:e,id:e,placeholder:r,value:i,onChange:c=>s&&s(c.target.value),onBlur:n,autoComplete:l,"aria-invalid":d&&m,ref:f,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"&&(p?jsxRuntime.jsx(ri.RiEyeCloseLine,{className:"cursor-pointer shrink-0 select-none",size:24,onClick:()=>h(false)}):jsxRuntime.jsx(ri.RiEyeLine,{className:"cursor-pointer shrink-0 select-none",size:24,onClick:()=>h(true)}))]}),jsxRuntime.jsx("div",{className:"text-[0.75rem] text-[#6b7280] transition-opacity duration-200 ease-in-out",children:a.map((c,y)=>{let R=["transition-[color,text-decoration,opacity] duration-[120ms] ease opacity-95 m-[0.125rem]",c.passed?"line-through opacity-60 text-[#10b981]":"",!c.passed&&m?"text-[#e53935] font-semibold opacity-100":""].filter(Boolean).join(" ");return jsxRuntime.jsx("p",{className:R,children:c.message},c.id??y)})})]})}function k({label:e,onSubmit:t,loading:r}){return jsxRuntime.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 E({mainText:e,subText:t}){return jsxRuntime.jsxs("div",{className:"font-inter flex flex-col items-center",children:[jsxRuntime.jsx("div",{className:"flex justify-center items-center p-2 bg-[oklch(0.8853_0_0/30%)] rounded-trieoh-full mb-[0.625rem]",children:jsxRuntime.jsx(go.GoPerson,{className:"w-[64px] h-[64px] p-[0.625rem] bg-trieoh-neutral1 rounded-trieoh-full shadow-[0_0.25rem_1rem_rgba(0,0,0,0.25)]",size:70})}),jsxRuntime.jsx("h3",{className:"text-center text-trieoh-xl font-medium m-0",children:e}),jsxRuntime.jsx("span",{className:"text-center text-[0.875rem] font-light opacity-60",children:t})]})}function T(e,t){return e.map(r=>({id:r.id,message:r.message,passed:!!r.test(t)}))}function bt({onSuccess:e,onFailed:t,signUpRedirect:r,forgotPasswordRedirect:o,emailRules:i}){let[s,n]=react.useState(""),[l,a]=react.useState(""),[m,f]=react.useState(false),[p,h]=react.useState(false),d=react.useRef(null),c=react.useRef(null),{auth:y}=b(),R={email:i||[{message:"Digite um e-mail v\xE1lido, ex: exemplo@dominio.com",test:v=>/\S+@\S+\.\S+/.test(v)}],password:[]},w=T(R.email,s),C=T(R.password,l);return jsxRuntime.jsxs("form",{className:"font-inter flex flex-col w-full max-w-[30rem] min-w-[15rem] max-h-[max(75dvh,32rem)] overflow-hidden gap-5 items-center bg-trieoh-neutral1 text-trieoh-neutral2 p-[1.25rem_1.5rem] shadow-[0_0.25rem_0.25rem_0_rgba(0,0,0,0.25)] transition-transform duration-150 ease-in-out rounded-[0.25rem]",children:[jsxRuntime.jsx(E,{mainText:"Fa\xE7a login na sua conta",subText:"Insira seus dados para fazer login"}),jsxRuntime.jsxs("div",{className:"w-full flex flex-col gap-[0.625rem] flex-[1_1_auto] overflow-y-auto mb-2",children:[jsxRuntime.jsx(_,{label:"Email",name:"email",placeholder:"teste@gmail.com",autoComplete:"email",type:"email",value:s,onValueChange:n,inputRef:d,rulesStatus:w,submitted:m}),jsxRuntime.jsx(_,{label:"Senha",name:"password",placeholder:"**********",autoComplete:"current-password",type:"password",value:l,onValueChange:a,inputRef:c,rulesStatus:C,submitted:m})]}),jsxRuntime.jsx(k,{label:"Entrar",onSubmit:async v=>{v.preventDefault(),f(true);let M=w.some(g=>!g.passed),z=C.some(g=>!g.passed);if(M){d.current?.focus();return}if(z){c.current?.focus();return}h(true);let P=await y.login(s,l);P.success?e&&await e(P.message):t&&await t(P.message,P.trace),h(false);},loading:p}),o&&jsxRuntime.jsx("span",{className:"text-trieoh-sm font-semibold text-center cursor-pointer",children:jsxRuntime.jsx("span",{className:"cursor-pointer text-trieoh-secondary transition-colors duration-200 hover:text-trieoh-primary",onClick:o,children:"Esqueceu sua senha?"})}),r&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-[0.625rem] w-full text-trieoh-base font-semibold opacity-60",children:[jsxRuntime.jsx("hr",{className:"flex-1"}),"OU",jsxRuntime.jsx("hr",{className:"flex-1"})]}),jsxRuntime.jsxs("span",{className:"text-trieoh-sm font-semibold",children:["Ainda n\xE3o possui uma conta? ",jsxRuntime.jsx("span",{className:"cursor-pointer text-trieoh-secondary transition-colors duration-200 hover:text-trieoh-primary",onClick:r,children:"Cadastra-se"})]})]})]})}function St({onSuccess:e,onFailed:t,loginRedirect:r,emailRules:o,passwordRules:i}){let[s,n]=react.useState(""),[l,a]=react.useState(""),[m,f]=react.useState(""),[p,h]=react.useState(false),[d,c]=react.useState(false),y=react.useRef(null),R=react.useRef(null),w=react.useRef(null),{auth:C}=b(),L={email:o||[{message:"Digite um e-mail v\xE1lido, ex: exemplo@dominio.com",test:g=>/\S+@\S+\.\S+/.test(g)}],password:i||[{message:"M\xEDnimo de 8 caracteres.",test:g=>g.length>=8},{message:"Deve conter uma letra mai\xFAscula.",test:g=>/[A-Z]/.test(g)},{message:"Inclua pelo menos um caractere especial, ex: ! @ # $ % & * . ,",test:g=>/[!@#$%^&*(),.?":{}|<>_\-+=~`;/\\[\]]/.test(g)},{message:"Deve conter um n\xFAmero.",test:g=>/\d/.test(g)}],confirmPassword:[{message:"Senhas n\xE3o conferem.",test:g=>g===l}]},v=T(L.email,s),M=T(L.password,l),z=T(L.confirmPassword,m);return jsxRuntime.jsxs("form",{className:"font-inter flex flex-col w-full max-w-[30rem] min-w-[15rem] max-h-[max(75dvh,32rem)] overflow-hidden gap-5 items-center bg-trieoh-neutral1 text-trieoh-neutral2 p-[1.25rem_1.5rem] shadow-[0_0.25rem_0.25rem_0_rgba(0,0,0,0.25)] transition-transform duration-150 ease-in-out rounded-[0.25rem]",children:[jsxRuntime.jsx(E,{mainText:"Crie sua conta",subText:"Insira seus dados para come\xE7ar"}),jsxRuntime.jsxs("div",{className:"w-full flex flex-col gap-[0.625rem] flex-[1_1_auto] overflow-y-auto mb-2",children:[jsxRuntime.jsx(_,{label:"Email",name:"email",placeholder:"teste@gmail.com",autoComplete:"email",type:"email",value:s,onValueChange:n,inputRef:y,rulesStatus:v,submitted:p}),jsxRuntime.jsx(_,{label:"Senha",name:"password",placeholder:"**********",autoComplete:"new-password",type:"password",value:l,onValueChange:a,inputRef:R,rulesStatus:M,submitted:p}),jsxRuntime.jsx(_,{label:"Confirme a Senha",name:"confirm-password",placeholder:"**********",autoComplete:"new-password",type:"password",value:m,onValueChange:f,inputRef:w,rulesStatus:z,submitted:p})]}),jsxRuntime.jsx(k,{label:"Criar Conta",onSubmit:async g=>{g.preventDefault(),h(true);let rt=v.some(K=>!K.passed),ot=M.some(K=>!K.passed),it=z.some(K=>!K.passed);if(rt){y.current?.focus();return}if(ot){R.current?.focus();return}if(it){w.current?.focus();return}c(true);let ne=await C.register(s,l);ne.success?e&&await e(ne.message):t&&await t(ne.message,ne.trace),c(false);},loading:d}),r&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-[0.625rem] w-full text-trieoh-base font-semibold opacity-60",children:[jsxRuntime.jsx("hr",{className:"flex-1"}),"OU",jsxRuntime.jsx("hr",{className:"flex-1"})]}),jsxRuntime.jsxs("span",{className:"text-trieoh-sm font-semibold",children:["J\xE1 possui uma conta? ",jsxRuntime.jsx("span",{className:"cursor-pointer text-trieoh-secondary transition-colors duration-200 hover:text-trieoh-primary",onClick:r,children:"Entre"})]})]})]})}var _t={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 kt({size:e}){let t=e?_t[e]:"text-trieoh-xl";return jsxRuntime.jsxs("span",{className:`font-inter font-medium ${t}`,children:["\xA9 ",new Date().getFullYear()," TrieOH"]})}function At({onSuccess:e,onFailed:t,forceLogout:r}){let{auth:o}=b(),[i,s]=react.useState(false);return jsxRuntime.jsxs("button",{onClick:async l=>{if(l.preventDefault(),i)return;s(true);let a=await o.logout({forceLogout: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:[jsxRuntime.jsx(im.ImExit,{size:24})," ",jsxRuntime.jsx("span",{children:"Log out"})]})}var Ke={mobile:fa.FaMobileAlt,tablet:fa.FaTabletAlt,desktop:fa.FaDesktop};function Ye(e){let{device:t,os:r,browser:o}=uaParserJs.UAParser(e);return {deviceType:t.type??"desktop",os:r.name,browser:o.name}}function We(e){let t=Ye(e);return {device:Ot(t.deviceType),os:t.os,browser:t.browser}}function Ot(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 Ae({is_current:e,session_id:t,user_agent:r,issued_at:o,user_ip:i,onClick:s}){let n=We(r),l=Ke[n.device];return jsxRuntime.jsx("div",{className:"border-t border-[rgba(0,0,0,0.3)] p-[1.25rem_0.75rem] text-trieoh-neutral2",children:jsxRuntime.jsxs("div",{className:"relative flex flex-col items-center gap-2 flex-1 text-center @[640px]:flex-row @[640px]:items-center @[640px]:gap-4 @[640px]:text-left",children:[jsxRuntime.jsx(l,{size:40}),jsxRuntime.jsxs("div",{className:"flex flex-col min-w-0",children:[jsxRuntime.jsxs("h3",{className:"text-trieoh-base font-semibold m-0",children:[n.browser," - ",n.os]}),jsxRuntime.jsxs("span",{className:"inline-flex flex-col text-trieoh-sm font-extralight @[640px]:flex-row @[640px]:gap-2 @[640px]:items-center",children:[e&&jsxRuntime.jsx("strong",{className:"text-trieoh-primary font-normal",children:"\u2022 Sess\xE3o Atual \u2022"}),jsxRuntime.jsx("span",{children:`${i} - ${Ge(o)}`})]})]}),!e&&jsxRuntime.jsx(fa.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 Ft({revokeAll:e=false,onSuccess:t}){let{auth:r}=b(),[o,i]=react.useState(false),[s,n]=react.useState([]),l=async()=>{let f=await r.sessions();if(f.success){let p=r.profile()?.session_id,h=f.data.sort((d,c)=>d.session_id===p?-1:c.session_id===p?1:0);n(h);}};react.useEffect(()=>{l();},[]);let a=async(f,p)=>{f.preventDefault();let h=s.find(d=>d.session_id===p);if(h){n(s.filter(d=>d.session_id!==p));try{(await r.revokeASession(p)).success||n(c=>[...c,h]);}catch{n(d=>[...d,h]);}}};return jsxRuntime.jsxs("div",{className:"font-inter w-full min-w-[20rem] m-2 @container bg-trieoh-neutral1 text-trieoh-neutral2 p-[1.5rem_0.5rem] rounded-lg",children:[jsxRuntime.jsxs("div",{className:"w-full flex flex-wrap items-center justify-center text-center gap-4 box-border px-[0.75rem] @[640px]:justify-between @[640px]:text-left @[640px]:gap-8",children:[jsxRuntime.jsxs("div",{className:"flex-[0_1_auto] max-w-[25rem]",children:[jsxRuntime.jsx("h3",{className:"font-semibold text-trieoh-2xl m-0 mb-1",children:"Navegadores e Dispositivos"}),jsxRuntime.jsx("p",{className:"font-extralight text-trieoh-base m-0",children:"Esses navegadores e dispositivos est\xE3o atualmente conectados \xE0 sua conta. Remova quaisquer dispositivos n\xE3o autorizados."})]}),jsxRuntime.jsx("button",{type:"submit",onClick:async f=>{if(f.preventDefault(),o)return;i(true);let p=await r.revokeSessions(e),h=r.profile()?.session_id;p.success&&(n(e?[]:s.filter(d=>d.session_id===h)),t&&t(p.message)),i(false);},disabled:o,className:`font-inter w-full max-w-[14rem] p-[1rem_0] h-auto text-trieoh-base font-semibold outline-none bg-transparent relative overflow-hidden shrink-0 border-2 border-trieoh-neutral2 text-trieoh-neutral2 cursor-pointer transition-transform duration-500 rounded-[0.25rem] hover:scale-[1.02] active:scale-[0.99] disabled:opacity-60 disabled:cursor-not-allowed disabled:!transform-none ${o?"trieoh-button-loading":""}`,children:"Revogar todas as sess\xF5es"})]}),jsxRuntime.jsx("div",{className:"mt-4",children:s.length>0?s.map(f=>jsxRuntime.jsx(Ae,{...f,is_current:r.profile()?.session_id===f.session_id,onClick:a},f.session_id)):jsxRuntime.jsx("span",{className:"block border-t border-[rgba(0,0,0,0.3)] p-[1.25rem_0.75rem] text-center font-semibold",children:"Nenhuma Sess\xE3o Dispon\xEDvel"})})]})}function Qe({onSuccess:e,onFailed:t,loginRedirect:r,emailRules:o}){let[i,s]=react.useState(""),[n,l]=react.useState(false),[a,m]=react.useState(false),f=react.useRef(null),{auth:p}=b(),d=T({email:o||[{message:"Digite um e-mail v\xE1lido, ex: exemplo@dominio.com",test:y=>/\S+@\S+\.\S+/.test(y)}]}.email,i);return jsxRuntime.jsxs("form",{className:"font-inter flex flex-col w-full max-w-[30rem] min-w-[15rem] max-h-[max(75dvh,32rem)] overflow-hidden gap-5 items-center bg-trieoh-neutral1 text-trieoh-neutral2 p-[1.25rem_1.5rem] shadow-[0_0.25rem_0.25rem_0_rgba(0,0,0,0.25)] transition-transform duration-150 ease-in-out rounded-[0.25rem]",children:[jsxRuntime.jsx(E,{mainText:"Esqueci a senha",subText:"Insira seu e-mail para receber um link de redefini\xE7\xE3o."}),jsxRuntime.jsx("div",{className:"w-full flex flex-col gap-[0.625rem] flex-[1_1_auto] overflow-y-auto mb-2",children:jsxRuntime.jsx(_,{label:"Email",name:"email",placeholder:"teste@gmail.com",autoComplete:"email",type:"email",value:i,onValueChange:s,inputRef:f,rulesStatus:d,submitted:n})}),jsxRuntime.jsx(k,{label:a?"Enviando...":"Enviar link de redefini\xE7\xE3o",onSubmit:async y=>{if(y.preventDefault(),l(true),d.some(C=>!C.passed)){f.current?.focus();return}m(true);let w=await p.sendForgotPassword(i);w.success?e&&await e(w.message):t&&await t(w.message,w.trace),m(false);},loading:a}),r&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-[0.625rem] w-full text-trieoh-base font-semibold opacity-60",children:[jsxRuntime.jsx("hr",{className:"flex-1"}),"OU",jsxRuntime.jsx("hr",{className:"flex-1"})]}),jsxRuntime.jsxs("span",{className:"text-trieoh-sm font-semibold",children:["Lembrou-se da sua senha? ",jsxRuntime.jsx("span",{className:"cursor-pointer text-trieoh-secondary transition-colors duration-200 hover:text-trieoh-primary",onClick:r,children:"Login"})]})]})]})}function zt({token:e,onSuccess:t,onFailed:r,loginRedirect:o,passwordRules:i}){let[s,n]=react.useState(""),[l,a]=react.useState(""),[m,f]=react.useState(false),[p,h]=react.useState(false),d=react.useRef(null),c=react.useRef(null),{auth:y}=b(),R={password:i||[{message:"M\xEDnimo de 8 caracteres.",test:v=>v.length>=8},{message:"Deve conter uma letra mai\xFAscula.",test:v=>/[A-Z]/.test(v)},{message:"Inclua pelo menos um caractere especial, ex: ! @ # $ % & * . ,",test:v=>/[!@#$%^&*(),.?":{}|<>_\-+=~`;/\\[\]]/.test(v)},{message:"Deve conter um n\xFAmero.",test:v=>/\d/.test(v)}],confirmPassword:[{message:"Senhas n\xE3o conferem.",test:v=>v===s}]},w=T(R.password,s),C=T(R.confirmPassword,l);return jsxRuntime.jsxs("form",{className:"font-inter flex flex-col w-full max-w-[30rem] min-w-[15rem] max-h-[max(75dvh,32rem)] overflow-hidden gap-5 items-center bg-trieoh-neutral1 text-trieoh-neutral2 p-[1.25rem_1.5rem] shadow-[0_0.25rem_0.25rem_0_rgba(0,0,0,0.25)] transition-transform duration-150 ease-in-out rounded-[0.25rem]",children:[jsxRuntime.jsx(E,{mainText:"Redefinir Senha",subText:"Crie uma nova senha para sua conta"}),jsxRuntime.jsxs("div",{className:"w-full flex flex-col gap-[0.625rem] flex-[1_1_auto] overflow-y-auto mb-2",children:[jsxRuntime.jsx(_,{label:"Nova Senha",name:"password",placeholder:"**********",autoComplete:"new-password",type:"password",value:s,onValueChange:n,inputRef:d,rulesStatus:w,submitted:m}),jsxRuntime.jsx(_,{label:"Confirme a Nova Senha",name:"confirm-password",placeholder:"**********",autoComplete:"new-password",type:"password",value:l,onValueChange:a,inputRef:c,rulesStatus:C,submitted:m})]}),jsxRuntime.jsx(k,{label:"Redefinir Senha",onSubmit:async v=>{v.preventDefault(),f(true);let M=w.some(g=>!g.passed),z=C.some(g=>!g.passed);if(M){d.current?.focus();return}if(z){c.current?.focus();return}h(true);let P=await y.resetPassword(e,s);P.success?t&&await t(P.message):r&&await r(P.message,P.trace),h(false);},loading:p}),o&&jsxRuntime.jsxs("span",{className:"text-trieoh-sm font-semibold",children:["Lembrou-se da sua senha? ",jsxRuntime.jsx("span",{className:"cursor-pointer text-trieoh-secondary transition-colors duration-200 hover:text-trieoh-primary",onClick:o,children:"Login"})]})]})}function Jt(e,t,r){let[o,i]=react.useState(true),[s,n]=react.useState("verifying"),[l,a]=react.useState("Verificando seu e-mail..."),{auth:m}=b(),f=react.useRef(false),p=async()=>{if(!f.current){f.current=true,i(true),n("verifying");try{if(m.profile()?.is_verified){n("already_verified"),a("Seu e-mail j\xE1 est\xE1 verificado."),i(!1);return}let c=await m.verifyEmail(e);c.success?(await m.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 react.useEffect(()=>{e&&!f.current&&p();},[e]),{loading:o,status:s,message:l,onRetry:d=>{d.preventDefault(),f.current=false,p();},setStatus:n,setLoading:i,setMessage:a}}function Kt({token:e,onSuccess:t,onFailed:r}){let{loading:o,status:i,message:s,onRetry:n}=Jt(e,t,r);return jsxRuntime.jsx("div",{className:"font-inter flex flex-col w-full h-full min-h-screen items-center justify-center bg-trieoh-neutral1 text-trieoh-neutral2 p-6",children:jsxRuntime.jsxs("div",{className:"w-full max-w-[30rem] flex flex-col gap-8 items-center bg-trieoh-neutral1 text-trieoh-neutral2 p-[1.25rem_1.5rem] shadow-[0_0.25rem_0.25rem_0_rgba(0,0,0,0.25)] rounded-[0.25rem]",children:[jsxRuntime.jsx(E,{mainText:i==="verifying"?"Verificando...":i==="error"?"Ops! Falha na verifica\xE7\xE3o":"Tudo pronto!",subText:s}),i==="verifying"&&jsxRuntime.jsx("div",{className:"w-full flex justify-center py-4",children:jsxRuntime.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-trieoh-secondary"})}),i==="error"&&jsxRuntime.jsx("div",{className:"w-full flex flex-col gap-6 items-center",children:jsxRuntime.jsx("div",{className:"w-full mt-2",children:jsxRuntime.jsx(k,{label:"Tentar novamente",onSubmit:n,loading:o})})}),(i==="success"||i==="already_verified")&&jsxRuntime.jsxs("div",{className:"w-full flex flex-col gap-4 items-center",children:[jsxRuntime.jsx("div",{className:"w-16 h-16 flex items-center justify-center rounded-full bg-trieoh-secondary/10 text-trieoh-secondary",children:i==="success"?jsxRuntime.jsx(fi.FiCheck,{size:40}):jsxRuntime.jsx(fi.FiInfo,{size:40})}),jsxRuntime.jsx("p",{className:"text-trieoh-sm font-semibold opacity-50 text-center",children:"Voc\xEA j\xE1 pode fechar esta janela ou continuar navegando em sua conta."})]})]})})}function Yt({onSuccess:e,onFailed:t}){let[r,o]=react.useState(false),[i,s]=react.useState(false),{auth:n}=b();return jsxRuntime.jsxs("div",{className:"font-inter flex flex-col w-full max-w-[30rem] min-w-[15rem] max-h-[max(75dvh,32rem)] overflow-hidden gap-5 items-center bg-trieoh-neutral1 text-trieoh-neutral2 p-[1.25rem_1.5rem] shadow-[0_0.25rem_0.25rem_0_rgba(0,0,0,0.25)] transition-transform duration-150 ease-in-out rounded-[0.25rem]",children:[jsxRuntime.jsx(E,{mainText:"Reenviar Verifica\xE7\xE3o",subText:"N\xE3o recebeu o e-mail de verifica\xE7\xE3o? Clique no bot\xE3o abaixo para reenviar."}),jsxRuntime.jsx(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&&jsxRuntime.jsx("p",{className:"text-trieoh-sm font-semibold text-trieoh-secondary",children:"Um novo link de verifica\xE7\xE3o foi enviado para seu e-mail."})]})}exports.AuthProvider=Jr;exports.BasicInputField=_;exports.BasicLogoutButton=At;exports.Copyright=kt;exports.ForgotPassword=Qe;exports.ResendVerifyEmail=Yt;exports.ResetPassword=zt;exports.Sessions=Ft;exports.SignIn=bt;exports.SignUp=St;exports.VerifyEmail=Kt;exports.useAuth=b;//# sourceMappingURL=react.js.map
|
|
3
3
|
//# sourceMappingURL=react.js.map
|