@trieoh/identityx-sdk-ts 0.11.0 → 0.11.6

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 CHANGED
@@ -1,3 +1,3 @@
1
- 'use strict';var nodeFetchSdk=require('@soramux/node-fetch-sdk');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function w(t,e){if(e.startsWith("http"))return e;let r=t.replace(/\/$/,""),n=e.replace(/^\//,"");return `${r}/${n}`}var g={isAuthenticated:false,isInitializing:true},S=new Set,U=()=>S.forEach(t=>t()),T={subscribe:t=>(S.add(t),()=>S.delete(t)),getSnapshot:()=>g,getServerSnapshot:()=>g,set:t=>{g={...g,...t},U();},reset:()=>{g={isAuthenticated:false,isInitializing:false},U();}};typeof window<"u"&&window.addEventListener("storage",t=>{if(t.key==="trieoh_access_expiry")if(!t.newValue)T.reset();else {let e=parseInt(t.newValue,10),r=!isNaN(e)&&e>Date.now();T.set({isAuthenticated:r,isInitializing:false});}});var o={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);}},R={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);}},l={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:u,secure:h=window.location.protocol==="https:",sameSite:d=h?"None":"Lax"}=r,m=[`${t}=${e}`,u?`Domain=${u}`:"",`Path=${s}`,`SameSite=${d}`,h?"Secure":"",n?`expires=${n}`:""];document.cookie=m.filter(Boolean).join("; ");},remove:(t,e)=>{l.set(t,"",{expires:"Thu, 01 Jan 1970 00:00:00 GMT",domain:e});}};var y="trieoh_access_token",a={getAccessToken:()=>R.getItem(y),setAccessToken:t=>{t?R.setItem(y,t):R.removeItem(y);},clear:()=>{R.removeItem(y);}};var p=null,b="trieoh_access_expiry",v="trieoh_refresh_expiry";function F(){if(typeof window>"u")return null;let t=window.location.hostname;if(t==="localhost")return null;if(t.endsWith("univents.com.br"))return "univents.com.br";if(t.endsWith("identityx.com.br"))return "identityx.com.br";let e=t.split(".");return t.endsWith("trieoh.com")&&e.length>=3?`${e[e.length-3]}.trieoh.com`:t}function C(t){try{let e=t.split(".")[1];return JSON.parse(atob(e))}catch{return null}}function q(t,e){let r=C(t),n=C(e);if(!r||!n){nodeFetchSdk.logger.error("Failed to decode tokens");return}a.setAccessToken(t);let s=n.exp*1e3,u=r.exp*1e3;l.set("refresh_token",e,{expires:new Date(s).toUTCString(),domain:F()}),p={access_data:r,refresh_expiry_date:s},o.setItem(b,String(u)),o.setItem(v,String(s)),T.set({isAuthenticated:true,isInitializing:false}),nodeFetchSdk.logger.log("Auth session saved");}function L(){if(p)return p;let t=a.getAccessToken();if(!t)return null;let e=C(t);if(!e||e.exp*1e3<=Date.now())return null;let r=o.getItem(v);return r?(p={access_data:e,refresh_expiry_date:parseInt(r,10)},p):null}function D(t,e){try{let r=o.getItem(t);if(!r)return !0;let n=parseInt(r,10);return isNaN(n)?!0:n-Date.now()<=e*1e3}catch(r){return nodeFetchSdk.logger.warn("Error reading expiry:",r),true}}var B=(t=30)=>D(b,t),H=(t=10)=>D(v,t);function E(){p=null,a.clear(),o.removeItem(b),o.removeItem(v);let t=F();l.remove("refresh_token",t),T.reset(),nodeFetchSdk.logger.log("Auth tokens and claims cleared");}function N(){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 I=null,P={};function $(t){P={...P,...t},I=null;}function O(){return I||(I={...N(),...P}),I}var J={get BASE_URL(){return O().BASE_URL}};var f=class{constructor(e){this.isRefreshing=false;this.refreshPromise=null;this.baseURL=e?.baseURL||J.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 nodeFetchSdk.simpleFetch(w(this.authBaseURL,"/auth/refresh"),{method:"POST",credentials:"include"});if(e.code!==200||!e.data)throw e.code!==503&&E(),new Error(e.message||"Failed to refresh token");let{access_token:r,refresh_token:n}=e.data;q(r,n);let s=L();s&&this.onTokenRefreshed?.(s),nodeFetchSdk.logger.log("Token refreshed successfully");}catch(e){throw nodeFetchSdk.logger.warn("Failed to refresh token:",e),E(),this.onRefreshFailed?.(e),e}finally{this.isRefreshing=false,this.refreshPromise=null;}})(),this.refreshPromise)}async beforeRequest(){if(H()){E();return}let e=!!a.getAccessToken(),r=!!l.get("refresh_token");if(!e&&r||e&&B(30))try{await this.refreshToken();}catch(n){nodeFetchSdk.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 u=w(this.baseURL,e),h=async()=>{let m=a.getAccessToken(),k=new Headers(r?.headers);return n&&m&&k.set("Authorization",`Bearer ${m}`),k.has("Content-Type")||k.set("Content-Type","application/json"),fetch(u,{...r,headers:k,credentials:"include"})},d=await h();if(d.status===401&&n&&!s){nodeFetchSdk.logger.log("401 detected, attempting one-time retry after refresh...");try{await this.refreshToken(),d=await h();}catch{nodeFetchSdk.logger.error("Retry failed after refresh error");}}return d}},ge=t=>new f(t),Te=t=>{let e=new f(t);return (r,n)=>e.fetch(r,n)};function c(t){if(!t)return;let{requiresAuth:e,skipRefresh:r,...n}=t,s={};return e!==void 0&&(s.requiresAuth=e),r!==void 0&&(s.skipRefresh=r),{...n,adapterInit:{...n.adapterInit,...s}}}var _=class{constructor(e,r,n,s){this.interceptor=new f({baseURL:e,authBaseURL:r,onTokenRefreshed:n}),this.client=nodeFetchSdk.createDefaultFetchClient({...s,adapter:this.interceptor.fetch.bind(this.interceptor)});}request(e,r){return this.client.request(e,c(r))}get(e,r){return this.client.get(e,c(r))}post(e,r,n){return this.client.post(e,r,c(n))}put(e,r,n){return this.client.put(e,r,c(n))}patch(e,r,n){return this.client.patch(e,r,c(n))}delete(e,r,n){return this.client.delete(e,r,c(n))}query(e,r){return this.client.query(e,c(r))}};function j(t){let e=new _(t?.baseURL,t?.authBaseURL,void 0,t?.clientConfig);return {request:e.request.bind(e),get:e.get.bind(e),post:e.post.bind(e),put:e.put.bind(e),patch:e.patch.bind(e),delete:e.delete.bind(e),query:e.query.bind(e)}}function z(t){let e=new _(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 nodeFetchSdk.FetchClientError}});exports.AuthInterceptor=f;exports.configure=$;exports.createAuthInterceptor=ge;exports.createAuthenticatedFetch=Te;exports.createFetcher=j;exports.createQueryFetcher=z;//# sourceMappingURL=index.js.map
1
+ 'use strict';var envoyFetchTs=require('@trieoh/envoy-fetch-ts');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function S(t,e){if(e.startsWith("http"))return e;let r=t.replace(/\/$/,""),n=e.replace(/^\//,"");return `${r}/${n}`}var T={isAuthenticated:false,isInitializing:true},C=new Set,U=()=>C.forEach(t=>t()),R={subscribe:t=>(C.add(t),()=>C.delete(t)),getSnapshot:()=>T,getServerSnapshot:()=>T,set:t=>{T={...T,...t},U();},reset:()=>{T={isAuthenticated:false,isInitializing:false},U();}};typeof window<"u"&&window.addEventListener("storage",t=>{if(t.key==="trieoh_access_expiry")if(!t.newValue)R.reset();else {let e=parseInt(t.newValue,10),r=!isNaN(e)&&e>Date.now();R.set({isAuthenticated:r,isInitializing:false});}});var i={getItem:t=>typeof window<"u"?localStorage.getItem(t):null,setItem:(t,e)=>{typeof window<"u"&&localStorage.setItem(t,e);},removeItem:t=>{typeof window<"u"&&localStorage.removeItem(t);}},A={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);}},d={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:h,secure:a=window.location.protocol==="https:",sameSite:o=a?"None":"Lax"}=r,l=[`${t}=${e}`,h?`Domain=${h}`:"",`Path=${s}`,`SameSite=${o}`,a?"Secure":"",n?`expires=${n}`:""];document.cookie=l.filter(Boolean).join("; ");},remove:(t,e)=>{d.set(t,"",{expires:"Thu, 01 Jan 1970 00:00:00 GMT",domain:e});}};var x="trieoh_access_token",p={getAccessToken:()=>A.getItem(x),setAccessToken:t=>{t?A.setItem(x,t):A.removeItem(x);},clear:()=>{A.removeItem(x);}};var m=null,O="trieoh_access_expiry",I="trieoh_refresh_expiry",y="trieoh_refresh_domain";function F(t){if(typeof window>"u")return null;let e=window.location.hostname;if(e==="localhost")return null;if(t)try{let r=t;return r.startsWith("http")&&(r=new URL(r).hostname),r}catch{return t}return e}function q(t){try{let e=t.split(".")[1];return JSON.parse(atob(e))}catch{return null}}function D(t){let{AccessTokenString:e,RefreshTokenString:r,AccessExpiresAt:n,RefreshExpiresAt:s,Domain:h}=t,a=q(e);if(!a){envoyFetchTs.logger.error("Failed to decode tokens");return}p.setAccessToken(e);let o=new Date(s).getTime(),l=new Date(n).getTime(),c=F(h);d.set("refresh_token",r,{expires:new Date(o).toUTCString(),domain:c}),m={access_data:a,refresh_expiry_date:o},i.setItem(O,String(l)),i.setItem(I,String(o)),c?i.setItem(y,c):i.removeItem(y),R.set({isAuthenticated:true,isInitializing:false}),envoyFetchTs.logger.log("Auth session saved");}function L(){if(m)return m;let t=p.getAccessToken();if(!t)return null;let e=q(t);if(!e||e.exp*1e3<=Date.now())return null;let r=i.getItem(I);return r?(m={access_data:e,refresh_expiry_date:parseInt(r,10)},m):null}function B(t,e){try{let r=i.getItem(t);if(!r)return !0;let n=parseInt(r,10);return isNaN(n)?!0:n-Date.now()<=e*1e3}catch(r){return envoyFetchTs.logger.warn("Error reading expiry:",r),true}}var H=(t=30)=>B(O,t),J=(t=10)=>B(I,t);function v(){m=null,p.clear(),i.removeItem(O),i.removeItem(I);let t=i.getItem(y)||F();d.remove("refresh_token",t),i.removeItem(y),R.reset(),envoyFetchTs.logger.log("Auth tokens and claims cleared");}function N(){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,P={};function Y(t){P={...P,...t},w=null;}function b(){return w||(w={...N(),...P}),w}var K={get BASE_URL(){return b().BASE_URL}};var g=class{constructor(e){this.isRefreshing=false;this.refreshPromise=null;this.baseURL=e?.baseURL||K.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(S(this.authBaseURL,"/auth/refresh"),{method:"POST",credentials:"include"});if(e.code!==200||!e.data)throw e.code!==503&&v(),new Error(e.message||"Failed to refresh token");D(e.data);let r=L();r&&this.onTokenRefreshed?.(r),envoyFetchTs.logger.log("Token refreshed successfully");}catch(e){throw envoyFetchTs.logger.warn("Failed to refresh token:",e),v(),this.onRefreshFailed?.(e),e}finally{this.isRefreshing=false,this.refreshPromise=null;}})(),this.refreshPromise)}async beforeRequest(){if(J()){v();return}let e=!!p.getAccessToken(),r=!!d.get("refresh_token");if(!e&&r||e&&H(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 h=S(this.baseURL,e),a=async()=>{let l=p.getAccessToken(),c=new Headers(r?.headers);return n&&l&&c.set("Authorization",`Bearer ${l}`),c.has("Content-Type")||c.set("Content-Type","application/json"),fetch(h,{...r,headers:c,credentials:"include"})},o=await a();if(o.status===401&&n&&!s){envoyFetchTs.logger.log("401 detected, attempting one-time retry after refresh...");try{await this.refreshToken(),o=await a();}catch{envoyFetchTs.logger.error("Retry failed after refresh error");}}return o}},Te=t=>new g(t),Re=t=>{let e=new g(t);return (r,n)=>e.fetch(r,n)};function f(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 _=class{constructor(e,r,n,s){this.interceptor=new g({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,f(r))}get(e,r){return this.client.get(e,f(r))}post(e,r,n){return this.client.post(e,r,f(n))}put(e,r,n){return this.client.put(e,r,f(n))}patch(e,r,n){return this.client.patch(e,r,f(n))}delete(e,r,n){return this.client.delete(e,r,f(n))}query(e,r){return this.client.query(e,f(r))}};function z(t){let e=new _(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 M(t){let e=new _(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=g;exports.configure=Y;exports.createAuthInterceptor=Te;exports.createAuthenticatedFetch=Re;exports.createFetcher=z;exports.createQueryFetcher=M;//# sourceMappingURL=index.js.map
3
3
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utils/url-utils.ts","../../src/store/auth-store.ts","../../src/utils/storage-adapter.ts","../../src/store/token-store.ts","../../src/utils/token-utils.ts","../../src/core/env.ts","../../src/core/interceptor.ts","../../src/core/api.ts"],"names":["joinUrl","base","path","cleanBase","cleanPath","_state","_listeners","notify","l","authStore","cb","partial","event","expiry","isAuthenticated","browserStorage","key","value","sessionBrowserStorage","cookieStorage","name","nameEQ","ca","i","c","options","expires","domain","secure","sameSite","cookieParts","ACCESS_TOKEN_KEY","tokenStore","token","memoryClaims","ACCESS_EXPIRY_KEY","REFRESH_EXPIRY_KEY","getCookieDomain","hostname","parts","decodeJwt","payload","saveAuthSession","access_token","refresh_token","claims","refreshClaims","logger","refreshExpiry","accessExpiry","getTokenClaims","refreshExpiryStr","isExpiringSoon","thresholdSeconds","expiryStr","e","isTokenExpiringSoon","isRefreshSessionExpired","clearAuthTokens","resolveEnv","isServer","viteEnv","safeProcessEnv","resolvedProjectId","resolvedApiKey","memoizedEnv","overrides","configure","config","getEnv","env","AuthInterceptor","res","simpleFetch","error","hasAccessToken","hasRefreshToken","url","shouldAuth","isRefreshReq","finalUrl","executeFetch","accessToken","headers","response","createAuthInterceptor","createAuthenticatedFetch","interceptor","toFetchOptions","requiresAuth","skipRefresh","rest","interceptorFields","Api","baseURL","authBaseURL","onTokenRefreshed","clientConfig","createDefaultFetchClient","body","createFetcher","api","createQueryFetcher"],"mappings":"sJAAO,SAASA,EAAQC,CAAAA,CAAcC,CAAAA,CAAsB,CAC1D,GAAIA,CAAAA,CAAK,WAAW,MAAM,CAAA,CAAG,OAAOA,CAAAA,CAEpC,IAAMC,EAAYF,CAAAA,CAAK,OAAA,CAAQ,MAAO,EAAE,CAAA,CAClCG,EAAYF,CAAAA,CAAK,OAAA,CAAQ,KAAA,CAAO,EAAE,EAExC,OAAO,CAAA,EAAGC,CAAS,CAAA,CAAA,EAAIC,CAAS,EAClC,CCFA,IAAIC,EAAoB,CACtB,eAAA,CAAiB,MACjB,cAAA,CAAgB,IAClB,EACMC,CAAAA,CAAa,IAAI,IAEjBC,CAAAA,CAAS,IAAMD,CAAAA,CAAW,OAAA,CAASE,GAAMA,CAAAA,EAAG,EAErCC,CAAAA,CAAY,CACvB,UAAYC,CAAAA,GACVJ,CAAAA,CAAW,IAAII,CAAE,CAAA,CACV,IAAMJ,CAAAA,CAAW,MAAA,CAAOI,CAAE,CAAA,CAAA,CAEnC,WAAA,CAAa,IAAML,CAAAA,CACnB,iBAAA,CAAmB,IAAMA,CAAAA,CACzB,IAAMM,CAAAA,EAA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CAAKA,CAAG,CAAA,CAC7B,IAAKA,CAAAA,CAAI,GAAA,CAAI,KAAKA,CAAG,CAAA,CACrB,KAAMA,CAAAA,CAAI,IAAA,CAAK,KAAKA,CAAG,CAAA,CACvB,IAAKA,CAAAA,CAAI,GAAA,CAAI,KAAKA,CAAG,CAAA,CACrB,MAAOA,CAAAA,CAAI,KAAA,CAAM,IAAA,CAAKA,CAAG,EACzB,MAAA,CAAQA,CAAAA,CAAI,OAAO,IAAA,CAAKA,CAAG,EAC3B,KAAA,CAAOA,CAAAA,CAAI,MAAM,IAAA,CAAKA,CAAG,CAC3B,CACF,CAEO,SAASC,CAAAA,CAAmBlC,CAAAA,CAIhC,CACD,IAAMiC,CAAAA,CAAM,IAAIR,CAAAA,CACdzB,CAAAA,EAAQ,QACRA,CAAAA,EAAQ,WAAA,CACR,OACAA,CAAAA,EAAQ,YACV,EAEA,OAAO,CAAQlE,EAAcuB,CAAAA,GAC3B4E,CAAAA,CAAI,MAAanG,CAAAA,CAAMuB,CAAO,CAClC","file":"index.js","sourcesContent":["export function joinUrl(base: string, path: string): string {\n if (path.startsWith(\"http\")) return path;\n \n const cleanBase = base.replace(/\\/$/, \"\");\n const cleanPath = path.replace(/^\\//, \"\");\n \n return `${cleanBase}/${cleanPath}`;\n}\n","type AuthState = {\n isAuthenticated: boolean;\n isInitializing: boolean;\n};\n\nlet _state: AuthState = {\n isAuthenticated: false,\n isInitializing: true,\n};\nconst _listeners = new Set<() => void>();\n\nconst notify = () => _listeners.forEach((l) => l());\n\nexport const authStore = {\n subscribe: (cb: () => void) => {\n _listeners.add(cb);\n return () => _listeners.delete(cb);\n },\n getSnapshot: () => _state,\n getServerSnapshot: () => _state,\n set: (partial: Partial<AuthState>) => {\n _state = { ..._state, ...partial };\n notify();\n },\n reset: () => {\n _state = {\n isAuthenticated: false,\n isInitializing: false,\n };\n notify();\n },\n};\n\n// Sync between tabs\nif (typeof window !== \"undefined\") {\n window.addEventListener(\"storage\", (event) => {\n if (event.key === \"trieoh_access_expiry\") {\n if (!event.newValue) authStore.reset();\n else {\n const expiry = parseInt(event.newValue, 10);\n const isAuthenticated = !isNaN(expiry) && expiry > Date.now();\n authStore.set({ isAuthenticated, isInitializing: false });\n }\n }\n });\n}\n","export interface StorageAdapter {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n removeItem(key: string): void;\n}\n\nexport const browserStorage: StorageAdapter = {\n getItem: (key) => (typeof window !== \"undefined\" ? localStorage.getItem(key) : null),\n setItem: (key, value) => {\n if (typeof window !== \"undefined\") localStorage.setItem(key, value);\n },\n removeItem: (key) => {\n if (typeof window !== \"undefined\") localStorage.removeItem(key);\n },\n};\n\nexport const sessionBrowserStorage: StorageAdapter = {\n getItem: (key) => (typeof window !== \"undefined\" ? sessionStorage.getItem(key) : null),\n setItem: (key, value) => {\n if (typeof window !== \"undefined\") sessionStorage.setItem(key, value);\n },\n removeItem: (key) => {\n if (typeof window !== \"undefined\") sessionStorage.removeItem(key);\n },\n};\n\nexport interface CookieOptions {\n expires?: string;\n path?: string;\n domain?: string | null;\n secure?: boolean;\n sameSite?: \"Lax\" | \"None\" | \"Strict\";\n}\n\nexport const cookieStorage = {\n get: (name: string): string | null => {\n if (typeof window === \"undefined\") return null;\n const nameEQ = name + \"=\";\n const ca = document.cookie.split(\";\");\n for (let i = 0; i < ca.length; i++) {\n let c = ca[i];\n while (c.charAt(0) === \" \") c = c.substring(1, c.length);\n if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);\n }\n return null;\n },\n\n set: (name: string, value: string, options: CookieOptions = {}) => {\n if (typeof window === \"undefined\") return;\n\n const {\n expires,\n path = \"/\",\n domain,\n secure = window.location.protocol === \"https:\",\n sameSite = secure ? \"None\" : \"Lax\",\n } = options;\n\n const cookieParts = [\n `${name}=${value}`,\n domain ? `Domain=${domain}` : \"\",\n `Path=${path}`,\n `SameSite=${sameSite}`,\n secure ? \"Secure\" : \"\",\n expires ? `expires=${expires}` : \"\",\n ];\n\n document.cookie = cookieParts.filter(Boolean).join(\"; \");\n },\n\n remove: (name: string, domain?: string | null) => {\n cookieStorage.set(name, \"\", {\n expires: \"Thu, 01 Jan 1970 00:00:00 GMT\",\n domain,\n });\n },\n};\n","import { sessionBrowserStorage } from \"../utils/storage-adapter\";\n\nconst ACCESS_TOKEN_KEY = \"trieoh_access_token\";\n\nexport const tokenStore = {\n getAccessToken: () => sessionBrowserStorage.getItem(ACCESS_TOKEN_KEY),\n setAccessToken: (token: string | null) => {\n if (token) sessionBrowserStorage.setItem(ACCESS_TOKEN_KEY, token);\n else sessionBrowserStorage.removeItem(ACCESS_TOKEN_KEY);\n },\n clear: () => {\n sessionBrowserStorage.removeItem(ACCESS_TOKEN_KEY);\n }\n};\n","import { authStore } from \"../store/auth-store\";\nimport { tokenStore } from \"../store/token-store\";\nimport { logger } from \"@soramux/node-fetch-sdk\";\nimport { browserStorage, cookieStorage } from \"./storage-adapter\";\n\nexport interface AuthTokens {\n access_token: string;\n refresh_token: string;\n}\n\nexport interface TokenClaims {\n sub: {\n id: string;\n email: string;\n session_id: string;\n user_agent: string;\n user_ip: string;\n project_id: string | null;\n verified_at: string | null;\n is_verified: boolean;\n user_type: \"client\" | \"project\";\n metadata: Record<string, unknown> | null;\n };\n iss: string;\n exp: number;\n iat: number;\n jti: string;\n}\n\nexport interface AuthTokenClaims {\n access_data: TokenClaims;\n refresh_expiry_date: string | number;\n}\n\n// Stored only in memory\nlet memoryClaims: AuthTokenClaims | null = null;\nconst ACCESS_EXPIRY_KEY = \"trieoh_access_expiry\";\nconst REFRESH_EXPIRY_KEY = \"trieoh_refresh_expiry\";\n\nexport function getCookieDomain() {\n if (typeof window === \"undefined\") return null;\n const hostname = window.location.hostname;\n if (hostname === 'localhost') return null;\n if (hostname.endsWith('univents.com.br')) return 'univents.com.br';\n if (hostname.endsWith('identityx.com.br')) return 'identityx.com.br';\n\n const parts = hostname.split('.');\n if (hostname.endsWith('trieoh.com') && parts.length >= 3) {\n const appName = parts[parts.length - 3];\n return `${appName}.trieoh.com`;\n }\n\n return hostname;\n}\n\nexport function decodeJwt<T>(token: string): T | null {\n try {\n const payload = token.split(\".\")[1];\n return JSON.parse(atob(payload));\n } catch {\n return null;\n }\n}\n\nexport function saveAuthSession(\n access_token: string,\n refresh_token: string,\n): void {\n const claims = decodeJwt<TokenClaims>(access_token);\n const refreshClaims = decodeJwt<{ exp: number }>(refresh_token);\n\n if (!claims || !refreshClaims) {\n logger.error(\"Failed to decode tokens\");\n return;\n }\n\n tokenStore.setAccessToken(access_token);\n\n const refreshExpiry = refreshClaims.exp * 1000;\n const accessExpiry = claims.exp * 1000;\n\n cookieStorage.set(\"refresh_token\", refresh_token, {\n expires: new Date(refreshExpiry).toUTCString(),\n domain: getCookieDomain()\n });\n\n memoryClaims = {\n access_data: claims,\n refresh_expiry_date: refreshExpiry,\n };\n\n browserStorage.setItem(ACCESS_EXPIRY_KEY, String(accessExpiry));\n browserStorage.setItem(REFRESH_EXPIRY_KEY, String(refreshExpiry));\n\n authStore.set({\n isAuthenticated: true,\n isInitializing: false,\n });\n\n logger.log(\"Auth session saved\");\n}\n\nexport function getTokenClaims(): AuthTokenClaims | null {\n if (memoryClaims) return memoryClaims;\n\n const token = tokenStore.getAccessToken();\n if (!token) return null;\n\n const claims = decodeJwt<TokenClaims>(token);\n if (!claims) return null;\n\n // Check if token is expired\n if (claims.exp * 1000 <= Date.now()) return null;\n\n const refreshExpiryStr = browserStorage.getItem(REFRESH_EXPIRY_KEY);\n if (!refreshExpiryStr) return null;\n\n memoryClaims = {\n access_data: claims,\n refresh_expiry_date: parseInt(refreshExpiryStr, 10),\n };\n\n return memoryClaims;\n}\n\nfunction isExpiringSoon(key: string, thresholdSeconds: number): boolean {\n try {\n const expiryStr = browserStorage.getItem(key);\n if (!expiryStr) return true;\n const expiry = parseInt(expiryStr, 10);\n if (isNaN(expiry)) return true;\n return (expiry - Date.now()) <= thresholdSeconds * 1000;\n } catch (e) {\n logger.warn(\"Error reading expiry:\", e);\n return true;\n }\n}\n\nexport const isTokenExpiringSoon = (t = 30) => isExpiringSoon(ACCESS_EXPIRY_KEY, t);\nexport const isRefreshSessionExpired = (t = 10) => isExpiringSoon(REFRESH_EXPIRY_KEY, t);\n\nexport function isAuthenticated(): boolean {\n if (!tokenStore.getAccessToken()) return false;\n const expiryStr = browserStorage.getItem(ACCESS_EXPIRY_KEY);\n if (!expiryStr) return false;\n const accessExpiryTimestamp = parseInt(expiryStr, 10);\n return accessExpiryTimestamp > Date.now();\n}\n\nexport function clearAuthTokens(): void {\n memoryClaims = null;\n tokenStore.clear();\n browserStorage.removeItem(ACCESS_EXPIRY_KEY);\n browserStorage.removeItem(REFRESH_EXPIRY_KEY);\n\n const domain = getCookieDomain();\n cookieStorage.remove(\"refresh_token\", domain);\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 \"@soramux/node-fetch-sdk\";\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 const { access_token, refresh_token } = res.data;\n saveAuthSession(access_token, refresh_token);\n\n const claims = getTokenClaims();\n if (claims) this.onTokenRefreshed?.(claims);\n\n logger.log(\"Token refreshed successfully\");\n } catch (error) {\n logger.warn(\"Failed to refresh token:\", error);\n clearAuthTokens();\n this.onRefreshFailed?.(error as Error);\n throw error;\n } finally {\n this.isRefreshing = false;\n this.refreshPromise = null;\n }\n })();\n\n return this.refreshPromise;\n }\n\n async beforeRequest(): Promise<void> {\n if (isRefreshSessionExpired()) {\n clearAuthTokens();\n return;\n }\n\n const hasAccessToken = !!tokenStore.getAccessToken();\n const hasRefreshToken = !!cookieStorage.get(\"refresh_token\");\n\n if ((!hasAccessToken && hasRefreshToken) || (hasAccessToken && isTokenExpiringSoon(30))) {\n try {\n await this.refreshToken();\n } catch (error) {\n logger.warn(\"Proactive refresh failed:\", error);\n }\n }\n }\n\n async fetch(url: string, options?: RequestOptions): Promise<Response> {\n const shouldAuth = options?.requiresAuth !== false;\n const isRefreshReq = url.includes(\"/auth/refresh\");\n\n if (shouldAuth && !isRefreshReq && !options?.skipRefresh) {\n await this.beforeRequest();\n }\n\n const finalUrl = joinUrl(this.baseURL, url);\n\n const executeFetch = async (): Promise<Response> => {\n const accessToken = tokenStore.getAccessToken();\n const headers = new Headers(options?.headers);\n\n if (shouldAuth && accessToken) {\n headers.set(\"Authorization\", `Bearer ${accessToken}`);\n }\n if (!headers.has(\"Content-Type\")) {\n headers.set(\"Content-Type\", \"application/json\");\n }\n\n return fetch(finalUrl, {\n ...options,\n headers,\n credentials: \"include\",\n });\n };\n\n let response = await executeFetch();\n\n if (response.status === 401 && shouldAuth && !isRefreshReq) {\n logger.log(\"401 detected, attempting one-time retry after refresh...\");\n try {\n await this.refreshToken();\n response = await executeFetch();\n } catch (e) {\n logger.error(\"Retry failed after refresh error\");\n }\n }\n\n return response;\n }\n}\n\nexport const createAuthInterceptor = (config?: InterceptorConfig) => new AuthInterceptor(config);\n\nexport const createAuthenticatedFetch = (config?: InterceptorConfig) => {\n const interceptor = new AuthInterceptor(config);\n return (url: string, options?: RequestOptions) => interceptor.fetch(url, options);\n};\n","import { AuthInterceptor, type RequestOptions as InterceptorOptions } from \"./interceptor\";\nimport type { AuthTokenClaims } from \"../utils/token-utils\";\nimport {\n createDefaultFetchClient,\n type DefaultFetchClientConfig,\n type DefaultFetchResult,\n type DefaultSuccessEnvelope,\n type DefaultFailureEnvelope,\n type FetchClient,\n type FetchClientOptions\n} from \"@soramux/node-fetch-sdk\";\n\nexport type { DefaultFetchResult as ApiResponse };\n\nexport interface ApiRequestOptions extends FetchClientOptions {\n requiresAuth?: boolean;\n skipRefresh?: boolean;\n}\n\nfunction toFetchOptions(options?: ApiRequestOptions): FetchClientOptions | undefined {\n if (!options) return undefined;\n\n const { requiresAuth, skipRefresh, ...rest } = options;\n\n const interceptorFields: Partial<InterceptorOptions> = {};\n if (requiresAuth !== undefined) interceptorFields.requiresAuth = requiresAuth;\n if (skipRefresh !== undefined) interceptorFields.skipRefresh = skipRefresh;\n\n return {\n ...rest,\n adapterInit: {\n ...rest.adapterInit,\n ...interceptorFields,\n },\n };\n}\n\nexport class Api {\n readonly interceptor: AuthInterceptor;\n private readonly client: FetchClient<DefaultSuccessEnvelope, DefaultFailureEnvelope>;\n\n constructor(\n baseURL?: string,\n authBaseURL?: string,\n onTokenRefreshed?: (claims: AuthTokenClaims) => void,\n clientConfig?: Omit<DefaultFetchClientConfig, \"adapter\">,\n ) {\n this.interceptor = new AuthInterceptor({\n baseURL,\n authBaseURL,\n onTokenRefreshed,\n });\n\n this.client = createDefaultFetchClient({\n ...clientConfig,\n adapter: this.interceptor.fetch.bind(this.interceptor),\n });\n }\n\n request<T>(path: string, options?: ApiRequestOptions) {\n return this.client.request<T>(path, toFetchOptions(options));\n }\n\n get<T>(path: string, options?: ApiRequestOptions) {\n return this.client.get<T>(path, toFetchOptions(options));\n }\n\n post<T>(path: string, body?: unknown, options?: ApiRequestOptions) {\n return this.client.post<T>(path, body, toFetchOptions(options));\n }\n\n put<T>(path: string, body?: unknown, options?: ApiRequestOptions) {\n return this.client.put<T>(path, body, toFetchOptions(options));\n }\n\n patch<T>(path: string, body?: unknown, options?: ApiRequestOptions) {\n return this.client.patch<T>(path, body, toFetchOptions(options));\n }\n\n delete<T>(path: string, body?: unknown, options?: ApiRequestOptions) {\n return this.client.delete<T>(path, body, toFetchOptions(options));\n }\n\n query<T>(path: string, options?: ApiRequestOptions) {\n return this.client.query<T>(path, toFetchOptions(options));\n }\n}\n\nexport function createFetcher(config?: {\n baseURL?: string;\n authBaseURL?: string;\n clientConfig?: Omit<DefaultFetchClientConfig, \"adapter\">;\n}) {\n const api = new Api(\n config?.baseURL,\n config?.authBaseURL,\n undefined,\n config?.clientConfig,\n );\n\n return {\n request: api.request.bind(api),\n get: api.get.bind(api),\n post: api.post.bind(api),\n put: api.put.bind(api),\n patch: api.patch.bind(api),\n delete: api.delete.bind(api),\n query: api.query.bind(api),\n };\n}\n\nexport function createQueryFetcher(config?: {\n baseURL?: string;\n authBaseURL?: string;\n clientConfig?: Omit<DefaultFetchClientConfig, \"adapter\">;\n}) {\n const api = new Api(\n config?.baseURL,\n config?.authBaseURL,\n undefined,\n config?.clientConfig,\n );\n\n return <TData>(path: string, options?: ApiRequestOptions): Promise<TData> =>\n api.query<TData>(path, options);\n}\n"]}
1
+ {"version":3,"sources":["../../src/utils/url-utils.ts","../../src/store/auth-store.ts","../../src/utils/storage-adapter.ts","../../src/store/token-store.ts","../../src/utils/token-utils.ts","../../src/core/env.ts","../../src/core/interceptor.ts","../../src/core/api.ts"],"names":["joinUrl","base","path","cleanBase","cleanPath","_state","_listeners","notify","l","authStore","cb","partial","event","expiry","isAuthenticated","browserStorage","key","value","sessionBrowserStorage","cookieStorage","name","nameEQ","ca","i","c","options","expires","domain","secure","sameSite","cookieParts","ACCESS_TOKEN_KEY","tokenStore","token","memoryClaims","ACCESS_EXPIRY_KEY","REFRESH_EXPIRY_KEY","REFRESH_DOMAIN_KEY","getCookieDomain","returnedDomain","hostname","decodeJwt","payload","saveAuthSession","tokens","AccessTokenString","RefreshTokenString","AccessExpiresAt","RefreshExpiresAt","Domain","claims","logger","refreshExpiry","accessExpiry","getTokenClaims","refreshExpiryStr","isExpiringSoon","thresholdSeconds","expiryStr","e","isTokenExpiringSoon","isRefreshSessionExpired","clearAuthTokens","resolveEnv","isServer","viteEnv","safeProcessEnv","resolvedProjectId","resolvedApiKey","memoizedEnv","overrides","configure","config","getEnv","env","AuthInterceptor","res","simpleFetch","error","hasAccessToken","hasRefreshToken","url","shouldAuth","isRefreshReq","finalUrl","executeFetch","accessToken","headers","response","createAuthInterceptor","createAuthenticatedFetch","interceptor","toFetchOptions","requiresAuth","skipRefresh","rest","interceptorFields","Api","baseURL","authBaseURL","onTokenRefreshed","clientConfig","createDefaultFetchClient","body","createFetcher","api","createQueryFetcher"],"mappings":"qJAAO,SAASA,EAAQC,CAAAA,CAAcC,CAAAA,CAAsB,CAC1D,GAAIA,CAAAA,CAAK,WAAW,MAAM,CAAA,CAAG,OAAOA,CAAAA,CAEpC,IAAMC,EAAYF,CAAAA,CAAK,OAAA,CAAQ,MAAO,EAAE,CAAA,CAClCG,EAAYF,CAAAA,CAAK,OAAA,CAAQ,MAAO,EAAE,CAAA,CAExC,OAAO,CAAA,EAAGC,CAAS,IAAIC,CAAS,CAAA,CAClC,CCFA,IAAIC,CAAAA,CAAoB,CACtB,eAAA,CAAiB,KAAA,CACjB,eAAgB,IAClB,CAAA,CACMC,EAAa,IAAI,GAAA,CAEjBC,E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AAA,CAAK,MAAA,CAAO,OAAUvB,CAAAA,CAAMqG,CAAAA,CAAMX,EAAenE,CAAO,CAAC,CAClE,CAEA,KAAA,CAASvB,EAAcuB,CAAAA,CAA6B,CAClD,OAAO,IAAA,CAAK,MAAA,CAAO,MAASvB,CAAAA,CAAM0F,CAAAA,CAAenE,CAAO,CAAC,CAC3D,CACF,CAAA,CAEO,SAAS+E,CAAAA,CAAchC,CAAAA,CAI3B,CACD,IAAMiC,CAAAA,CAAM,IAAIR,CAAAA,CACdzB,CAAAA,EAAQ,QACRA,CAAAA,EAAQ,WAAA,CACR,OACAA,CAAAA,EAAQ,YACV,EAEA,OAAO,CACL,QAASiC,CAAAA,CAAI,OAAA,CAAQ,KAAKA,CAAG,CAAA,CAC7B,IAAKA,CAAAA,CAAI,GAAA,CAAI,KAAKA,CAAG,CAAA,CACrB,KAAMA,CAAAA,CAAI,IAAA,CAAK,KAAKA,CAAG,CAAA,CACvB,IAAKA,CAAAA,CAAI,GAAA,CAAI,KAAKA,CAAG,CAAA,CACrB,MAAOA,CAAAA,CAAI,KAAA,CAAM,IAAA,CAAKA,CAAG,EACzB,MAAA,CAAQA,CAAAA,CAAI,OAAO,IAAA,CAAKA,CAAG,EAC3B,KAAA,CAAOA,CAAAA,CAAI,MAAM,IAAA,CAAKA,CAAG,CAC3B,CACF,CAEO,SAASC,CAAAA,CAAmBlC,CAAAA,CAIhC,CACD,IAAMiC,CAAAA,CAAM,IAAIR,CAAAA,CACdzB,CAAAA,EAAQ,QACRA,CAAAA,EAAQ,WAAA,CACR,OACAA,CAAAA,EAAQ,YACV,EAEA,OAAO,CAAQtE,EAAcuB,CAAAA,GAC3BgF,CAAAA,CAAI,MAAavG,CAAAA,CAAMuB,CAAO,CAClC","file":"index.js","sourcesContent":["export function joinUrl(base: string, path: string): string {\n if (path.startsWith(\"http\")) return path;\n \n const cleanBase = base.replace(/\\/$/, \"\");\n const cleanPath = path.replace(/^\\//, \"\");\n \n return `${cleanBase}/${cleanPath}`;\n}\n","type AuthState = {\n isAuthenticated: boolean;\n isInitializing: boolean;\n};\n\nlet _state: AuthState = {\n isAuthenticated: false,\n isInitializing: true,\n};\nconst _listeners = new Set<() => void>();\n\nconst notify = () => _listeners.forEach((l) => l());\n\nexport const authStore = {\n subscribe: (cb: () => void) => {\n _listeners.add(cb);\n return () => _listeners.delete(cb);\n },\n getSnapshot: () => _state,\n getServerSnapshot: () => _state,\n set: (partial: Partial<AuthState>) => {\n _state = { ..._state, ...partial };\n notify();\n },\n reset: () => {\n _state = {\n isAuthenticated: false,\n isInitializing: false,\n };\n notify();\n },\n};\n\n// Sync between tabs\nif (typeof window !== \"undefined\") {\n window.addEventListener(\"storage\", (event) => {\n if (event.key === \"trieoh_access_expiry\") {\n if (!event.newValue) authStore.reset();\n else {\n const expiry = parseInt(event.newValue, 10);\n const isAuthenticated = !isNaN(expiry) && expiry > Date.now();\n authStore.set({ isAuthenticated, isInitializing: false });\n }\n }\n });\n}\n","export interface StorageAdapter {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n removeItem(key: string): void;\n}\n\nexport const browserStorage: StorageAdapter = {\n getItem: (key) => (typeof window !== \"undefined\" ? localStorage.getItem(key) : null),\n setItem: (key, value) => {\n if (typeof window !== \"undefined\") localStorage.setItem(key, value);\n },\n removeItem: (key) => {\n if (typeof window !== \"undefined\") localStorage.removeItem(key);\n },\n};\n\nexport const sessionBrowserStorage: StorageAdapter = {\n getItem: (key) => (typeof window !== \"undefined\" ? sessionStorage.getItem(key) : null),\n setItem: (key, value) => {\n if (typeof window !== \"undefined\") sessionStorage.setItem(key, value);\n },\n removeItem: (key) => {\n if (typeof window !== \"undefined\") sessionStorage.removeItem(key);\n },\n};\n\nexport interface CookieOptions {\n expires?: string;\n path?: string;\n domain?: string | null;\n secure?: boolean;\n sameSite?: \"Lax\" | \"None\" | \"Strict\";\n}\n\nexport const cookieStorage = {\n get: (name: string): string | null => {\n if (typeof window === \"undefined\") return null;\n const nameEQ = name + \"=\";\n const ca = document.cookie.split(\";\");\n for (let i = 0; i < ca.length; i++) {\n let c = ca[i];\n while (c.charAt(0) === \" \") c = c.substring(1, c.length);\n if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);\n }\n return null;\n },\n\n set: (name: string, value: string, options: CookieOptions = {}) => {\n if (typeof window === \"undefined\") return;\n\n const {\n expires,\n path = \"/\",\n domain,\n secure = window.location.protocol === \"https:\",\n sameSite = secure ? \"None\" : \"Lax\",\n } = options;\n\n const cookieParts = [\n `${name}=${value}`,\n domain ? `Domain=${domain}` : \"\",\n `Path=${path}`,\n `SameSite=${sameSite}`,\n secure ? \"Secure\" : \"\",\n expires ? `expires=${expires}` : \"\",\n ];\n\n document.cookie = cookieParts.filter(Boolean).join(\"; \");\n },\n\n remove: (name: string, domain?: string | null) => {\n cookieStorage.set(name, \"\", {\n expires: \"Thu, 01 Jan 1970 00:00:00 GMT\",\n domain,\n });\n },\n};\n","import { sessionBrowserStorage } from \"../utils/storage-adapter\";\n\nconst ACCESS_TOKEN_KEY = \"trieoh_access_token\";\n\nexport const tokenStore = {\n getAccessToken: () => sessionBrowserStorage.getItem(ACCESS_TOKEN_KEY),\n setAccessToken: (token: string | null) => {\n if (token) sessionBrowserStorage.setItem(ACCESS_TOKEN_KEY, token);\n else sessionBrowserStorage.removeItem(ACCESS_TOKEN_KEY);\n },\n clear: () => {\n sessionBrowserStorage.removeItem(ACCESS_TOKEN_KEY);\n }\n};\n","import { authStore } from \"../store/auth-store\";\nimport { tokenStore } from \"../store/token-store\";\nimport { logger } from \"@trieoh/envoy-fetch-ts\";\nimport { browserStorage, cookieStorage } from \"./storage-adapter\";\n\nexport interface AuthTokens {\n AccessTokenString: string;\n RefreshTokenString: string;\n AccessExpiresAt: string;\n RefreshExpiresAt: string;\n Domain: string;\n}\n\nexport interface TokenClaims {\n sub: {\n id: string;\n email: string;\n session_id: string;\n user_agent: string;\n user_ip: string;\n project_id: string | null;\n verified_at: string | null;\n is_verified: boolean;\n user_type: \"client\" | \"project\";\n metadata: Record<string, unknown> | null;\n };\n iss: string;\n exp: number;\n iat: number;\n jti: string;\n}\n\nexport interface AuthTokenClaims {\n access_data: TokenClaims;\n refresh_expiry_date: string | number;\n}\n\n// Stored only in memory\nlet memoryClaims: AuthTokenClaims | null = null;\nconst ACCESS_EXPIRY_KEY = \"trieoh_access_expiry\";\nconst REFRESH_EXPIRY_KEY = \"trieoh_refresh_expiry\";\nconst REFRESH_DOMAIN_KEY = \"trieoh_refresh_domain\";\n\nexport function getCookieDomain(returnedDomain?: string) {\n if (typeof window === \"undefined\") return null;\n const hostname = window.location.hostname;\n\n // Localhost should never have a domain set for cookies to avoid issues\n if (hostname === 'localhost') return null;\n\n if (returnedDomain) {\n try {\n let domain = returnedDomain;\n if (domain.startsWith(\"http\")) domain = new URL(domain).hostname;\n return domain;\n } catch {\n return returnedDomain;\n }\n }\n\n return hostname;\n}\nexport function decodeJwt<T>(token: string): T | null {\n try {\n const payload = token.split(\".\")[1];\n return JSON.parse(atob(payload));\n } catch {\n return null;\n }\n}\n\nexport function saveAuthSession(tokens: AuthTokens): void {\n const {\n AccessTokenString,\n RefreshTokenString,\n AccessExpiresAt,\n RefreshExpiresAt,\n Domain\n } = tokens;\n\n const claims = decodeJwt<TokenClaims>(AccessTokenString);\n\n if (!claims) {\n logger.error(\"Failed to decode tokens\");\n return;\n }\n\n tokenStore.setAccessToken(AccessTokenString);\n\n const refreshExpiry = new Date(RefreshExpiresAt).getTime();\n const accessExpiry = new Date(AccessExpiresAt).getTime();\n const domain = getCookieDomain(Domain);\n\n cookieStorage.set(\"refresh_token\", RefreshTokenString, {\n expires: new Date(refreshExpiry).toUTCString(),\n domain\n });\n\n memoryClaims = {\n access_data: claims,\n refresh_expiry_date: refreshExpiry,\n };\n\n browserStorage.setItem(ACCESS_EXPIRY_KEY, String(accessExpiry));\n browserStorage.setItem(REFRESH_EXPIRY_KEY, String(refreshExpiry));\n if (domain) browserStorage.setItem(REFRESH_DOMAIN_KEY, domain);\n else browserStorage.removeItem(REFRESH_DOMAIN_KEY);\n\n authStore.set({\n isAuthenticated: true,\n isInitializing: false,\n });\n\n logger.log(\"Auth session saved\");\n}\n\nexport function getTokenClaims(): AuthTokenClaims | null {\n if (memoryClaims) return memoryClaims;\n\n const token = tokenStore.getAccessToken();\n if (!token) return null;\n\n const claims = decodeJwt<TokenClaims>(token);\n if (!claims) return null;\n\n // Check if token is expired\n if (claims.exp * 1000 <= Date.now()) return null;\n\n const refreshExpiryStr = browserStorage.getItem(REFRESH_EXPIRY_KEY);\n if (!refreshExpiryStr) return null;\n\n memoryClaims = {\n access_data: claims,\n refresh_expiry_date: parseInt(refreshExpiryStr, 10),\n };\n\n return memoryClaims;\n}\n\nfunction isExpiringSoon(key: string, thresholdSeconds: number): boolean {\n try {\n const expiryStr = browserStorage.getItem(key);\n if (!expiryStr) return true;\n const expiry = parseInt(expiryStr, 10);\n if (isNaN(expiry)) return true;\n return (expiry - Date.now()) <= thresholdSeconds * 1000;\n } catch (e) {\n logger.warn(\"Error reading expiry:\", e);\n return true;\n }\n}\n\nexport const isTokenExpiringSoon = (t = 30) => isExpiringSoon(ACCESS_EXPIRY_KEY, t);\nexport const isRefreshSessionExpired = (t = 10) => isExpiringSoon(REFRESH_EXPIRY_KEY, t);\n\nexport function isAuthenticated(): boolean {\n if (!tokenStore.getAccessToken()) return false;\n const expiryStr = browserStorage.getItem(ACCESS_EXPIRY_KEY);\n if (!expiryStr) return false;\n const accessExpiryTimestamp = parseInt(expiryStr, 10);\n return accessExpiryTimestamp > Date.now();\n}\n\nexport function clearAuthTokens(): void {\n memoryClaims = null;\n tokenStore.clear();\n browserStorage.removeItem(ACCESS_EXPIRY_KEY);\n browserStorage.removeItem(REFRESH_EXPIRY_KEY);\n\n const domain = browserStorage.getItem(REFRESH_DOMAIN_KEY) || getCookieDomain();\n cookieStorage.remove(\"refresh_token\", domain);\n browserStorage.removeItem(REFRESH_DOMAIN_KEY);\n\n authStore.reset();\n\n logger.log(\"Auth tokens and claims cleared\");\n}\n\nexport function getUserInfo() {\n const claims = getTokenClaims();\n if (!claims) return null;\n\n return claims.access_data.sub\n}\n\nexport function decodeJwtExp(token: string): number | null {\n const decoded = decodeJwt<{ exp: number }>(token);\n return decoded?.exp ?? null;\n}\n","export interface TrieOHEnv {\n PROJECT_ID: string;\n API_KEY: string;\n BASE_URL: string;\n}\n\nexport function resolveEnv(): TrieOHEnv {\n const isServer = typeof window === \"undefined\";\n\n const viteEnv = (\n typeof import.meta !== \"undefined\" && import.meta.env\n ? import.meta.env\n : {}\n ) as Partial<ImportMetaEnv>;\n\n const safeProcessEnv: NodeJS.ProcessEnv =\n typeof process !== \"undefined\" ? process.env : {};\n\n const resolvedProjectId =\n viteEnv.VITE_TRIEOH_AUTH_PROJECT_ID ||\n safeProcessEnv.NEXT_PUBLIC_TRIEOH_AUTH_PROJECT_ID ||\n safeProcessEnv.PUBLIC_TRIEOH_AUTH_PROJECT_ID ||\n \"\";\n\n const resolvedApiKey = isServer\n ? (safeProcessEnv.TRIEOH_AUTH_API_KEY || \"\")\n : \"\";\n\n return {\n PROJECT_ID: resolvedProjectId,\n API_KEY: resolvedApiKey,\n BASE_URL: \"https://api.trieauth.trieoh.com\",\n };\n}\nlet memoizedEnv: TrieOHEnv | null = null;\nlet overrides: Partial<TrieOHEnv> = {};\n\n/**\n * Configure the SDK manually. This will override any environment variables.\n */\nexport function configure(config: Partial<TrieOHEnv>) {\n overrides = { ...overrides, ...config };\n memoizedEnv = null; // Reset memoization to apply new config\n}\n\nfunction getEnv(): TrieOHEnv {\n if (!memoizedEnv) {\n const resolved = resolveEnv();\n memoizedEnv = {\n ...resolved,\n ...overrides,\n };\n }\n return memoizedEnv;\n}\nexport const env: TrieOHEnv = {\n get PROJECT_ID() {\n return getEnv().PROJECT_ID;\n },\n get API_KEY() {\n return getEnv().API_KEY;\n },\n get BASE_URL() {\n return getEnv().BASE_URL;\n },\n};\n","import { joinUrl } from \"../utils/url-utils\";\nimport {\n clearAuthTokens,\n isRefreshSessionExpired,\n isTokenExpiringSoon,\n saveAuthSession,\n getTokenClaims,\n type AuthTokenClaims,\n type AuthTokens\n} from \"../utils/token-utils\";\nimport { env } from \"./env\";\nimport { logger, simpleFetch } from \"@trieoh/envoy-fetch-ts\";\nimport { cookieStorage } from \"../utils/storage-adapter\";\nimport { tokenStore } from \"../store/token-store\";\n\nexport interface RequestOptions extends RequestInit {\n requiresAuth?: boolean;\n skipRefresh?: boolean;\n}\n\ninterface InterceptorConfig {\n baseURL?: string;\n authBaseURL?: string;\n onTokenRefreshed?: (claims: AuthTokenClaims) => void;\n onRefreshFailed?: (error: Error) => void;\n}\n\nexport class AuthInterceptor {\n private baseURL: string;\n private authBaseURL: string;\n private isRefreshing = false;\n private refreshPromise: Promise<void> | null = null;\n private onTokenRefreshed?: (claims: AuthTokenClaims) => void;\n private onRefreshFailed?: (error: Error) => void;\n\n constructor(config?: InterceptorConfig) {\n this.baseURL = config?.baseURL || env.BASE_URL;\n this.authBaseURL = config?.authBaseURL || this.baseURL;\n this.onTokenRefreshed = config?.onTokenRefreshed;\n this.onRefreshFailed = config?.onRefreshFailed;\n }\n\n private async refreshToken(): Promise<void> {\n if (this.isRefreshing && this.refreshPromise) return this.refreshPromise;\n\n this.isRefreshing = true;\n this.refreshPromise = (async () => {\n try {\n const res = await simpleFetch<{ code: number; data?: AuthTokens; message?: string }>(\n joinUrl(this.authBaseURL, \"/auth/refresh\"),\n { method: \"POST\", credentials: \"include\" }\n );\n\n if (res.code !== 200 || !res.data) {\n if (res.code !== 503) clearAuthTokens();\n throw new Error(res.message || \"Failed to refresh token\");\n }\n\n saveAuthSession(res.data);\n\n const claims = getTokenClaims();\n if (claims) this.onTokenRefreshed?.(claims);\n\n logger.log(\"Token refreshed successfully\");\n } catch (error) {\n logger.warn(\"Failed to refresh token:\", error);\n clearAuthTokens();\n this.onRefreshFailed?.(error as Error);\n throw error;\n } finally {\n this.isRefreshing = false;\n this.refreshPromise = null;\n }\n })();\n\n return this.refreshPromise;\n }\n\n async beforeRequest(): Promise<void> {\n if (isRefreshSessionExpired()) {\n clearAuthTokens();\n return;\n }\n\n const hasAccessToken = !!tokenStore.getAccessToken();\n const hasRefreshToken = !!cookieStorage.get(\"refresh_token\");\n\n if ((!hasAccessToken && hasRefreshToken) || (hasAccessToken && isTokenExpiringSoon(30))) {\n try {\n await this.refreshToken();\n } catch (error) {\n logger.warn(\"Proactive refresh failed:\", error);\n }\n }\n }\n\n async fetch(url: string, options?: RequestOptions): Promise<Response> {\n const shouldAuth = options?.requiresAuth !== false;\n const isRefreshReq = url.includes(\"/auth/refresh\");\n\n if (shouldAuth && !isRefreshReq && !options?.skipRefresh) {\n await this.beforeRequest();\n }\n\n const finalUrl = joinUrl(this.baseURL, url);\n\n const executeFetch = async (): Promise<Response> => {\n const accessToken = tokenStore.getAccessToken();\n const headers = new Headers(options?.headers);\n\n if (shouldAuth && accessToken) {\n headers.set(\"Authorization\", `Bearer ${accessToken}`);\n }\n if (!headers.has(\"Content-Type\")) {\n headers.set(\"Content-Type\", \"application/json\");\n }\n\n return fetch(finalUrl, {\n ...options,\n headers,\n credentials: \"include\",\n });\n };\n\n let response = await executeFetch();\n\n if (response.status === 401 && shouldAuth && !isRefreshReq) {\n logger.log(\"401 detected, attempting one-time retry after refresh...\");\n try {\n await this.refreshToken();\n response = await executeFetch();\n } catch (e) {\n logger.error(\"Retry failed after refresh error\");\n }\n }\n\n return response;\n }\n}\n\nexport const createAuthInterceptor = (config?: InterceptorConfig) => new AuthInterceptor(config);\n\nexport const createAuthenticatedFetch = (config?: InterceptorConfig) => {\n const interceptor = new AuthInterceptor(config);\n return (url: string, options?: RequestOptions) => interceptor.fetch(url, options);\n};\n","import { AuthInterceptor, type RequestOptions as InterceptorOptions } from \"./interceptor\";\nimport type { AuthTokenClaims } from \"../utils/token-utils\";\nimport {\n createDefaultFetchClient,\n type DefaultFetchClientConfig,\n type DefaultFetchResult,\n type DefaultSuccessEnvelope,\n type DefaultFailureEnvelope,\n type FetchClient,\n type FetchClientOptions\n} from \"@trieoh/envoy-fetch-ts\";\n\nexport type { DefaultFetchResult as ApiResponse };\n\nexport interface ApiRequestOptions extends FetchClientOptions {\n requiresAuth?: boolean;\n skipRefresh?: boolean;\n}\n\nfunction toFetchOptions(options?: ApiRequestOptions): FetchClientOptions | undefined {\n if (!options) return undefined;\n\n const { requiresAuth, skipRefresh, ...rest } = options;\n\n const interceptorFields: Partial<InterceptorOptions> = {};\n if (requiresAuth !== undefined) interceptorFields.requiresAuth = requiresAuth;\n if (skipRefresh !== undefined) interceptorFields.skipRefresh = skipRefresh;\n\n return {\n ...rest,\n adapterInit: {\n ...rest.adapterInit,\n ...interceptorFields,\n },\n };\n}\n\nexport class Api {\n readonly interceptor: AuthInterceptor;\n private readonly client: FetchClient<DefaultSuccessEnvelope, DefaultFailureEnvelope>;\n\n constructor(\n baseURL?: string,\n authBaseURL?: string,\n onTokenRefreshed?: (claims: AuthTokenClaims) => void,\n clientConfig?: Omit<DefaultFetchClientConfig, \"adapter\">,\n ) {\n this.interceptor = new AuthInterceptor({\n baseURL,\n authBaseURL,\n onTokenRefreshed,\n });\n\n this.client = createDefaultFetchClient({\n ...clientConfig,\n adapter: this.interceptor.fetch.bind(this.interceptor),\n });\n }\n\n request<T>(path: string, options?: ApiRequestOptions) {\n return this.client.request<T>(path, toFetchOptions(options));\n }\n\n get<T>(path: string, options?: ApiRequestOptions) {\n return this.client.get<T>(path, toFetchOptions(options));\n }\n\n post<T>(path: string, body?: unknown, options?: ApiRequestOptions) {\n return this.client.post<T>(path, body, toFetchOptions(options));\n }\n\n put<T>(path: string, body?: unknown, options?: ApiRequestOptions) {\n return this.client.put<T>(path, body, toFetchOptions(options));\n }\n\n patch<T>(path: string, body?: unknown, options?: ApiRequestOptions) {\n return this.client.patch<T>(path, body, toFetchOptions(options));\n }\n\n delete<T>(path: string, body?: unknown, options?: ApiRequestOptions) {\n return this.client.delete<T>(path, body, toFetchOptions(options));\n }\n\n query<T>(path: string, options?: ApiRequestOptions) {\n return this.client.query<T>(path, toFetchOptions(options));\n }\n}\n\nexport function createFetcher(config?: {\n baseURL?: string;\n authBaseURL?: string;\n clientConfig?: Omit<DefaultFetchClientConfig, \"adapter\">;\n}) {\n const api = new Api(\n config?.baseURL,\n config?.authBaseURL,\n undefined,\n config?.clientConfig,\n );\n\n return {\n request: api.request.bind(api),\n get: api.get.bind(api),\n post: api.post.bind(api),\n put: api.put.bind(api),\n patch: api.patch.bind(api),\n delete: api.delete.bind(api),\n query: api.query.bind(api),\n };\n}\n\nexport function createQueryFetcher(config?: {\n baseURL?: string;\n authBaseURL?: string;\n clientConfig?: Omit<DefaultFetchClientConfig, \"adapter\">;\n}) {\n const api = new Api(\n config?.baseURL,\n config?.authBaseURL,\n undefined,\n config?.clientConfig,\n );\n\n return <TData>(path: string, options?: ApiRequestOptions): Promise<TData> =>\n api.query<TData>(path, options);\n}\n"]}
package/dist/cjs/react.js CHANGED
@@ -1,6 +1,6 @@
1
- 'use strict';var react=require('react'),nodeFetchSdk=require('@soramux/node-fetch-sdk'),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');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function fe(e,t){if(t.startsWith("http"))return t;let r=e.replace(/\/$/,""),o=t.replace(/^\//,"");return `${r}/${o}`}var V={isAuthenticated:false,isInitializing:true},ge=new Set,Ee=()=>ge.forEach(e=>e()),v={subscribe:e=>(ge.add(e),()=>ge.delete(e)),getSnapshot:()=>V,getServerSnapshot:()=>V,set:e=>{V={...V,...e},Ee();},reset:()=>{V={isAuthenticated:false,isInitializing:false},Ee();}};typeof window<"u"&&window.addEventListener("storage",e=>{if(e.key==="trieoh_access_expiry")if(!e.newValue)v.reset();else {let t=parseInt(e.newValue,10),r=!isNaN(t)&&t>Date.now();v.set({isAuthenticated:r,isInitializing:false});}});var P={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);}},K={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);}},A={get:e=>{if(typeof window>"u")return null;let t=e+"=",r=document.cookie.split(";");for(let o=0;o<r.length;o++){let s=r[o];for(;s.charAt(0)===" ";)s=s.substring(1,s.length);if(s.indexOf(t)===0)return s.substring(t.length,s.length)}return null},set:(e,t,r={})=>{if(typeof window>"u")return;let{expires:o,path:s="/",domain:i,secure:n=window.location.protocol==="https:",sameSite:l=n?"None":"Lax"}=r,c=[`${e}=${t}`,i?`Domain=${i}`:"",`Path=${s}`,`SameSite=${l}`,n?"Secure":"",o?`expires=${o}`:""];document.cookie=c.filter(Boolean).join("; ");},remove:(e,t)=>{A.set(e,"",{expires:"Thu, 01 Jan 1970 00:00:00 GMT",domain:t});}};var oe="trieoh_access_token",D={getAccessToken:()=>K.getItem(oe),setAccessToken:e=>{e?K.setItem(oe,e):K.removeItem(oe);},clear:()=>{K.removeItem(oe);}};var F=null,_e="trieoh_access_expiry",ie="trieoh_refresh_expiry";function Ae(){if(typeof window>"u")return null;let e=window.location.hostname;if(e==="localhost")return null;if(e.endsWith("univents.com.br"))return "univents.com.br";if(e.endsWith("identityx.com.br"))return "identityx.com.br";let t=e.split(".");return e.endsWith("trieoh.com")&&t.length>=3?`${t[t.length-3]}.trieoh.com`:e}function ve(e){try{let t=e.split(".")[1];return JSON.parse(atob(t))}catch{return null}}function Y(e,t){let r=ve(e),o=ve(t);if(!r||!o){nodeFetchSdk.logger.error("Failed to decode tokens");return}D.setAccessToken(e);let s=o.exp*1e3,i=r.exp*1e3;A.set("refresh_token",t,{expires:new Date(s).toUTCString(),domain:Ae()}),F={access_data:r,refresh_expiry_date:s},P.setItem(_e,String(i)),P.setItem(ie,String(s)),v.set({isAuthenticated:true,isInitializing:false}),nodeFetchSdk.logger.log("Auth session saved");}function j(){if(F)return F;let e=D.getAccessToken();if(!e)return null;let t=ve(e);if(!t||t.exp*1e3<=Date.now())return null;let r=P.getItem(ie);return r?(F={access_data:t,refresh_expiry_date:parseInt(r,10)},F):null}function Ce(e,t){try{let r=P.getItem(e);if(!r)return !0;let o=parseInt(r,10);return isNaN(o)?!0:o-Date.now()<=t*1e3}catch(r){return nodeFetchSdk.logger.warn("Error reading expiry:",r),true}}var Ie=(e=30)=>Ce(_e,e),ne=(e=10)=>Ce(ie,e);function U(){F=null,D.clear(),P.removeItem(_e),P.removeItem(ie);let e=Ae();A.remove("refresh_token",e),v.reset(),nodeFetchSdk.logger.log("Auth tokens and claims cleared");}function ke(){let e=j();return e?e.access_data.sub:null}function Ye(){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||"",s=e&&r.TRIEOH_AUTH_API_KEY||"";return {PROJECT_ID:o,API_KEY:s,BASE_URL:"https://api.trieauth.trieoh.com"}}var ae=null,xe={};function Pe(e){xe={...xe,...e},ae=null;}function ye(){return ae||(ae={...Ye(),...xe}),ae}var _={get PROJECT_ID(){return ye().PROJECT_ID},get BASE_URL(){return ye().BASE_URL}};var le=class{constructor(t){this.isRefreshing=false;this.refreshPromise=null;this.baseURL=t?.baseURL||_.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 nodeFetchSdk.simpleFetch(fe(this.authBaseURL,"/auth/refresh"),{method:"POST",credentials:"include"});if(t.code!==200||!t.data)throw t.code!==503&&U(),new Error(t.message||"Failed to refresh token");let{access_token:r,refresh_token:o}=t.data;Y(r,o);let s=j();s&&this.onTokenRefreshed?.(s),nodeFetchSdk.logger.log("Token refreshed successfully");}catch(t){throw nodeFetchSdk.logger.warn("Failed to refresh token:",t),U(),this.onRefreshFailed?.(t),t}finally{this.isRefreshing=false,this.refreshPromise=null;}})(),this.refreshPromise)}async beforeRequest(){if(ne()){U();return}let t=!!D.getAccessToken(),r=!!A.get("refresh_token");if(!t&&r||t&&Ie(30))try{await this.refreshToken();}catch(o){nodeFetchSdk.logger.warn("Proactive refresh failed:",o);}}async fetch(t,r){let o=r?.requiresAuth!==false,s=t.includes("/auth/refresh");o&&!s&&!r?.skipRefresh&&await this.beforeRequest();let i=fe(this.baseURL,t),n=async()=>{let c=D.getAccessToken(),h=new Headers(r?.headers);return o&&c&&h.set("Authorization",`Bearer ${c}`),h.has("Content-Type")||h.set("Content-Type","application/json"),fetch(i,{...r,headers:h,credentials:"include"})},l=await n();if(l.status===401&&o&&!s){nodeFetchSdk.logger.log("401 detected, attempting one-time retry after refresh...");try{await this.refreshToken(),l=await n();}catch{nodeFetchSdk.logger.error("Retry failed after refresh error");}}return l}};function O(e){if(!e)return;let{requiresAuth:t,skipRefresh:r,...o}=e,s={};return t!==void 0&&(s.requiresAuth=t),r!==void 0&&(s.skipRefresh=r),{...o,adapterInit:{...o.adapterInit,...s}}}var ce=class{constructor(t,r,o,s){this.interceptor=new le({baseURL:t,authBaseURL:r,onTokenRefreshed:o}),this.client=nodeFetchSdk.createDefaultFetchClient({...s,adapter:this.interceptor.fetch.bind(this.interceptor)});}request(t,r){return this.client.request(t,O(r))}get(t,r){return this.client.get(t,O(r))}post(t,r,o){return this.client.post(t,r,O(o))}put(t,r,o){return this.client.put(t,r,O(o))}patch(t,r,o){return this.client.patch(t,r,O(o))}delete(t,r,o){return this.client.delete(t,r,O(o))}query(t,r){return this.client.query(t,O(r))}};var z=()=>{if(!_.PROJECT_ID||_.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 De=(e,t)=>({login:async(r,o)=>{_.PROJECT_ID&&z();let s=`/auth/login${_.PROJECT_ID?`?project_id=${_.PROJECT_ID}`:""}`,i=await e.post(s,{email:r,password:o},{requiresAuth:false});return i.success&&(Y(i.data.access_token,i.data.refresh_token),t?.onLogin?.()),i},register:async(r,o)=>{let s={requiresAuth:false},i=`/auth/register${_.PROJECT_ID?`?project_id=${_.PROJECT_ID}`:""}`;_.PROJECT_ID&&z();let n=await e.post(i,{email:r,password:o},s);return n.success&&t?.onRegister?.(),n},logout:async r=>{let o=`/auth/logout${_.PROJECT_ID?`?project_id=${_.PROJECT_ID}`:""}`,s=await e.post(o);return (s.success||r?.forceLogout)&&U(),s},refresh:async()=>{let r=await e.post("/auth/refresh",void 0,{skipRefresh:true});return r.success&&(Y(r.data.access_token,r.data.refresh_token),t?.onRefresh?.()),r},sessions:async()=>e.get("/sessions"),currentSession:async()=>e.get("/sessions/me"),revokeASession:async r=>e.delete(`/sessions/${r}`),revokeSessions:async(r=false)=>{let o=r?"/sessions":"/sessions/others";return e.delete(o)},profile:()=>ke(),sendForgotPassword:async r=>{let o={requiresAuth:false},s=await(async()=>_.PROJECT_ID?(z(),e.post("/account/forgot-password",{email:r,project_id:_.PROJECT_ID},o)):e.post("/account/forgot-password",{email:r},o))();return s.success&&t?.onForgotPassword?.(),s},resetPassword:async(r,o)=>e.post(`/account/reset-password?token=${r}`,{new_password:o},{requiresAuth:false}),verifyEmail:async()=>{let r=await e.get("/account/verify",{requiresAuth:false});return r.success&&t?.onVerify?.(),r},resendVerifyEmail:async()=>e.post("/account/verify/resend"),health:async()=>e.get("/health",{requiresAuth:false}),authHealth:async()=>e.get("/protected/health")});var Le=react.createContext(null);function xr({children:e,baseURL:t,projectId:r,isProjectMode:o=true,fallback:s,waitSession:i=true,clientConfig:n,onLogin:l,onForgotPassword:c,onRegister:h,onVerify:p,onRefresh:u}){let f=react.useRef(false),{isAuthenticated:d,isInitializing:m}=react.useSyncExternalStore(v.subscribe,v.getSnapshot,v.getServerSnapshot);react.useEffect(()=>{Pe({...r?{PROJECT_ID:r}:{},...t?{BASE_URL:t}:{}});},[r,t]);let x=react.useCallback(I=>{v.set({isAuthenticated:!!I.access_data,isInitializing:false}),u?.();},[u]),b=react.useMemo(()=>new ce(t,void 0,x,n),[t,x,n]),y=react.useMemo(()=>De(b,{onLogin:l,onForgotPassword:c,onRegister:h,onVerify:p,onRefresh:u}),[b,l,c,h,p,u]);react.useEffect(()=>{o&&z(),(async()=>{if(f.current)return;if(f.current=true,j()){v.set({isAuthenticated:true,isInitializing:false});return}if(!!!A.get("refresh_token")||ne()){v.reset(),v.set({isInitializing:false});return}nodeFetchSdk.logger.log("No cached claims, attempting silent refresh...");try{(await y.refresh()).success?(v.set({isAuthenticated:!0,isInitializing:!1}),nodeFetchSdk.logger.log("Session restored.")):(v.reset(),nodeFetchSdk.logger.warn("No active session."));}catch{v.reset(),nodeFetchSdk.logger.warn("Could not restore session (offline?).");}finally{v.set({isInitializing:false});}})();},[y,o]);let E=react.useMemo(()=>({auth:y,isAuthenticated:d,isInitializing:m,isProjectMode:o}),[y,d,m,o]);return i&&m?s??null:jsxRuntime.jsx(Le.Provider,{value:E,children:e})}function S(){let e=react.useContext(Le);if(!e)throw new Error("useAuth must be used inside <AuthProvider>");return e}function W(e,{insertAt:t}={}){if(!e||typeof document>"u")return;let r=document.head||document.getElementsByTagName("head")[0],o=document.createElement("style");o.type="text/css",t==="top"&&r.firstChild?r.insertBefore(o,r.firstChild):r.appendChild(o),o.styleSheet?o.styleSheet.cssText=e:o.appendChild(document.createTextNode(e));}W(`@import"https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap";:root{--trieoh-primary: oklch(.1139 .0789 264.05);--trieoh-secondary: oklch(.7975 .1018 262.7);--trieoh-neutral1: oklch(.9702 0 0);--trieoh-neutral2: oklch(.1944 .0051 248.09);--trieoh-radius-full: 50%;--trieoh-text-sm: .75rem;--trieoh-text-base: .875rem;--trieoh-text-xl: 1.25rem;--trieoh-text-2xl: 1.5rem;--trieoh-text-3xl: 1.875rem;--trieoh-text-6xl: 3.75rem}
2
- `);W(`.trieoh{font-family:Inter,sans-serif}.trieoh-input{position:relative;width:100%;display:flex;flex-direction:column;gap:.25rem;color:var(--trieoh-neutral2)}.trieoh-input__label{font-size:1rem;font-weight:600}.trieoh-input__container{display:flex;justify-content:space-between;align-items:center;padding:.0625rem .625rem;gap:.625rem;border-bottom:solid .125rem var(--trieoh-neutral2)}.trieoh-input__container--error{border-color:#e53935!important}.trieoh-input__container-field{min-width:10rem;flex:1;font-size:var(--trieoh-text-base);font-weight:300;color:var(--trieoh-neutral2);-webkit-appearance:none;background:none;outline:none;border:none;box-shadow:none!important;padding:.125rem 0}.trieoh-input__container-icon{cursor:pointer;flex-shrink:0;-webkit-user-select:none;user-select:none}.trieoh-input__hint{font-size:.75rem;color:#6b7280;transition:opacity .2s ease-in-out}.trieoh-input__hint .hint-part{transition:color .12s ease,text-decoration .12s ease,opacity .12s ease;opacity:.95;margin:.125rem}.trieoh-input__hint .hint-part.passed{text-decoration:line-through;opacity:.6;color:#10b981}.trieoh-input__hint .hint-part.failed-on-submit{color:#e53935;font-weight:600;opacity:1}.trieoh-button{--trieoh-button-color: var(--trieoh-neutral2);width:100%;height:3.25rem;font-size:var(--trieoh-text-xl);font-weight:600;color:var(--trieoh-button-color);outline:none;background:none;position:relative;overflow:hidden;min-width:10rem;flex-shrink:0;border:.125rem solid var(--trieoh-button-color);cursor:pointer;padding:0 1.5rem;transition:transform .5s}.trieoh-button--all-rounded{border-radius:.25rem}.trieoh-button:hover{transform:scale(102%)}.trieoh-button:active{transform:scale(99%)}.trieoh-button[disabled],.trieoh-button--logout[disabled]{opacity:.6;cursor:not-allowed;transform:none!important}.trieoh-button--loading:after{content:"";position:absolute;top:0;left:-150%;width:150%;height:100%;background:linear-gradient(120deg,transparent 0%,color-mix(in oklab,var(--trieoh-button-color) 40%,white 15%) 40%,transparent 80%);animation:trieoh-shine 1.5s infinite}@keyframes trieoh-shine{0%{left:-150%}to{left:150%}}.trieoh-button--logout{border:none;background:none;cursor:pointer;--trieoh-button-color: oklch(.628 .2577 29.23);display:flex;align-items:end;gap:.25rem;font-size:var(--trieoh-text-base);font-weight:500;color:var(--trieoh-button-color);transition:transform .2s}.trieoh-button--logout:hover{transform:scale(1.05)}.trieoh-button--logout:active{transform:scale(.98)}.trieoh-avacard{display:flex;flex-direction:column;align-items:center}.trieoh-avacard__container{display:flex;justify-content:center;align-items:center;padding:.5rem;background-color:#d9d9d94d;border-radius:var(--trieoh-radius-full);margin-bottom:.625rem}.trieoh-avacard__content{width:64px;height:64px;padding:.625rem;background-color:var(--trieoh-neutral1);border-radius:var(--trieoh-radius-full);box-shadow:0 .25rem 1rem #00000040}.trieoh-avacard__title{text-align:center;font-size:var(--trieoh-text-xl);font-weight:500;margin:0}.trieoh-avacard__sub-title{text-align:center;font-size:.875rem;font-weight:300;opacity:.6}.trieoh-card{display:flex;flex-direction:column;width:100%;max-width:30rem;min-width:15rem;max-height:max(75dvh,32rem);overflow:hidden;gap:1.25rem;align-items:center;background-color:var(--trieoh-neutral1);color:var(--trieoh-neutral2);padding:1.25rem 1.5rem;box-shadow:0 .25rem .25rem #00000040;transition:transform .15s ease}.trieoh-card--full-rounded{border-radius:.25rem}.trieoh-card__fields{width:100%;display:flex;flex-direction:column;gap:.625rem;flex:1 1 auto;overflow-y:auto;margin-bottom:.5rem}.trieoh-card__divider{display:flex;align-items:center;gap:.625rem;width:100%;font-size:var(--trieoh-text-base);font-weight:600;opacity:.6}.trieoh-card__divider hr{flex:1}.trieoh-card__other{font-size:var(--trieoh-text-sm);font-weight:600}.trieoh-card__other span{cursor:pointer;color:var(--trieoh-secondary);transition:color .2s}.trieoh-card__other span:hover{color:var(--trieoh-primary)}.trieoh-copyright{font-size:var(--trieoh-text-xl);font-weight:500}.trieoh-copyright--xs{font-size:var(--trieoh-text-sm)}.trieoh-copyright--sm{font-size:var(--trieoh-text-base)}.trieoh-copyright--md{font-size:var(--trieoh-text-xl)}.trieoh-copyright--lg{font-size:var(--trieoh-text-2xl)}.trieoh-copyright--xl{font-size:var(--trieoh-text-3xl)}.trieoh-copyright--2xl{font-size:var(--trieoh-text-6xl)}.trieoh-sessions{width:100%;min-width:20rem;margin:.5rem;container-type:inline-size;background-color:var(--trieoh-neutral1);color:var(--trieoh-neutral2);padding:1.5rem .5rem;border-radius:.5rem}.trieoh-sessions__header{width:100%;display:flex;flex-wrap:wrap;align-items:center;justify-content:center;text-align:center;gap:1rem;box-sizing:border-box;padding:0 .75rem}.trieoh-sessions__header div{flex:0 1 auto;max-width:25rem}.trieoh-sessions__header div h3{font-weight:600;font-size:var(--trieoh-text-2xl);margin:0;margin-bottom:.25rem}.trieoh-sessions__header div p{font-weight:200;font-size:var(--trieoh-text-base);margin:0}.trieoh-sessions__header button{max-width:14rem;padding:1rem 0;height:auto;font-size:var(--trieoh-text-base)}.trieoh-sessions__content{margin-top:1rem}.trieoh-sessions__empty{display:block;border-top:1px solid rgba(0,0,0,.3);padding:1.25rem .75rem;text-align:center;font-weight:600}.trieoh-session{border-top:1px solid rgba(0,0,0,.3);padding:1.25rem .75rem;color:var(--trieoh-neutral2)}.trieoh-session__content{position:relative;display:flex;flex-direction:column;align-items:center;gap:.5rem;flex:1;text-align:center}.trieoh-session__info{display:flex;flex-direction:column;min-width:0}.trieoh-session__meta{display:inline-flex;flex-direction:column;font-size:var(--trieoh-text-sm);font-weight:200}.trieoh-session h3{font-size:var(--trieoh-text-base);font-weight:600;margin:0}.trieoh-session span strong{color:var(--trieoh-primary);font-weight:400}.trieoh-session__content svg:last-child{position:absolute;top:0;right:0;cursor:pointer;opacity:.6;transition:opacity .2s,transform .15s}.trieoh-session__content svg:last-child:hover{opacity:1;transform:scale(1.05)}.trieoh-session__content svg:last-child:active{transform:scale(.95)}@container (min-width: 640px){.trieoh-sessions__header{justify-content:space-between;text-align:left;gap:2rem}.trieoh-session{flex-direction:row;text-align:left}.trieoh-session__content{flex-direction:row;align-items:center;gap:1rem;text-align:left}.trieoh-session__meta{flex-direction:row;gap:.5rem;align-items:center}}
3
- `);function w({name:e,label:t,placeholder:r,type:o="text",value:s,onValueChange:i,onBlur:n,autoComplete:l,rulesStatus:c=[],submitted:h=false,inputRef:p}){let[u,f]=react.useState(false),d=c.some(m=>!m.passed);return jsxRuntime.jsxs("div",{className:"trieoh trieoh-input",children:[jsxRuntime.jsx("label",{htmlFor:e,className:"trieoh-input__label",children:t}),jsxRuntime.jsxs("div",{className:(d&&h?"trieoh-input__container--error ":"")+"trieoh-input__container",children:[jsxRuntime.jsx("input",{type:u?"text":o,name:e,id:e,placeholder:r,value:s,onChange:m=>i&&i(m.target.value),onBlur:n,autoComplete:l,"aria-invalid":d&&h,ref:p,className:"trieoh-input__container-field"}),o==="password"&&(u?jsxRuntime.jsx(ri.RiEyeCloseLine,{className:"trieoh-input__container-icon",size:24,onClick:()=>f(false)}):jsxRuntime.jsx(ri.RiEyeLine,{className:"trieoh-input__container-icon",size:24,onClick:()=>f(true)}))]}),jsxRuntime.jsx("div",{className:"trieoh-input__hint",children:c.map((m,x)=>{let b=["hint-part",m.passed?"passed":"",!m.passed&&h?"failed-on-submit":""].filter(Boolean).join(" ");return jsxRuntime.jsx("p",{className:b,children:m.message},m.id??x)})})]})}function L({label:e,onSubmit:t,loading:r}){return jsxRuntime.jsx("button",{type:"submit",onClick:t,disabled:r,className:`trieoh trieoh-button trieoh-button--all-rounded
4
- ${r?"trieoh-button--loading":""}`,children:e})}function N({mainText:e,subText:t}){return jsxRuntime.jsxs("div",{className:"trieoh trieoh-avacard",children:[jsxRuntime.jsx("div",{className:"trieoh-avacard__container",children:jsxRuntime.jsx(go.GoPerson,{className:"trieoh-avacard__content",size:70})}),jsxRuntime.jsx("h3",{className:"trieoh-avacard__title",children:e}),jsxRuntime.jsx("span",{className:"trieoh-avacard__sub-title",children:t})]})}function R(e,t){return e.map(r=>({id:r.id,message:r.message,passed:!!r.test(t)}))}function lt({onSuccess:e,onFailed:t,signUpRedirect:r,forgotPasswordRedirect:o,emailRules:s}){let[i,n]=react.useState(""),[l,c]=react.useState(""),[h,p]=react.useState(false),[u,f]=react.useState(false),d=react.useRef(null),m=react.useRef(null),{auth:x}=S(),b={email:s||[{message:"Digite um e-mail v\xE1lido, ex: exemplo@dominio.com",test:k=>/\S+@\S+\.\S+/.test(k)}],password:[]},y=R(b.email,i),E=R(b.password,l);return jsxRuntime.jsxs("form",{className:"trieoh trieoh-card trieoh-card--full-rounded",children:[jsxRuntime.jsx(N,{mainText:"Fa\xE7a login na sua conta",subText:"Insira seus dados para fazer login"}),jsxRuntime.jsxs("div",{className:"trieoh-card__fields",children:[jsxRuntime.jsx(w,{label:"Email",name:"email",placeholder:"teste@gmail.com",autoComplete:"email",type:"email",value:i,onValueChange:n,inputRef:d,rulesStatus:y,submitted:h}),jsxRuntime.jsx(w,{label:"Senha",name:"password",placeholder:"**********",autoComplete:"current-password",type:"password",value:l,onValueChange:c,inputRef:m,rulesStatus:E,submitted:h})]}),jsxRuntime.jsx(L,{label:"Entrar",onSubmit:async k=>{k.preventDefault(),p(true);let q=y.some(g=>!g.passed),te=E.some(g=>!g.passed);if(q){d.current?.focus();return}if(te){m.current?.focus();return}f(true);let $=await x.login(i,l);$.success?e&&await e($.message):t&&await t($.message,$.trace),f(false);},loading:u}),o&&jsxRuntime.jsx("span",{className:"trieoh-card__other",style:{textAlign:"center",cursor:"pointer"},children:jsxRuntime.jsx("span",{onClick:o,children:"Esqueceu sua senha?"})}),r&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs("div",{className:"trieoh-card__divider",children:[jsxRuntime.jsx("hr",{}),"OU",jsxRuntime.jsx("hr",{})]}),jsxRuntime.jsxs("span",{className:"trieoh-card__other",children:["Ainda n\xE3o possui uma conta? ",jsxRuntime.jsx("span",{onClick:r,children:"Cadastra-se"})]})]})]})}function ut({onSuccess:e,onFailed:t,loginRedirect:r,emailRules:o,passwordRules:s}){let[i,n]=react.useState(""),[l,c]=react.useState(""),[h,p]=react.useState(""),[u,f]=react.useState(false),[d,m]=react.useState(false),x=react.useRef(null),b=react.useRef(null),y=react.useRef(null),{auth:E}=S(),I={email:o||[{message:"Digite um e-mail v\xE1lido, ex: exemplo@dominio.com",test:g=>/\S+@\S+\.\S+/.test(g)}],password:s||[{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}]},k=R(I.email,i),q=R(I.password,l),te=R(I.confirmPassword,h);return jsxRuntime.jsxs("form",{className:"trieoh trieoh-card trieoh-card--full-rounded",children:[jsxRuntime.jsx(N,{mainText:"Crie sua conta",subText:"Insira seus dados para come\xE7ar"}),jsxRuntime.jsxs("div",{className:"trieoh-card__fields",children:[jsxRuntime.jsx(w,{label:"Email",name:"email",placeholder:"teste@gmail.com",autoComplete:"email",type:"email",value:i,onValueChange:n,inputRef:x,rulesStatus:k,submitted:u}),jsxRuntime.jsx(w,{label:"Senha",name:"password",placeholder:"**********",autoComplete:"new-password",type:"password",value:l,onValueChange:c,inputRef:b,rulesStatus:q,submitted:u}),jsxRuntime.jsx(w,{label:"Confirme a Senha",name:"confirm-password",placeholder:"**********",autoComplete:"new-password",type:"password",value:h,onValueChange:p,inputRef:y,rulesStatus:te,submitted:u})]}),jsxRuntime.jsx(L,{label:"Criar Conta",onSubmit:async g=>{g.preventDefault(),f(true);let Je=k.some(J=>!J.passed),Ve=q.some(J=>!J.passed),Ke=te.some(J=>!J.passed);if(Je){x.current?.focus();return}if(Ve){b.current?.focus();return}if(Ke){y.current?.focus();return}m(true);let re=await E.register(i,l);re.success?e&&await e(re.message):t&&await t(re.message,re.trace),m(false);},loading:d}),r&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs("div",{className:"trieoh-card__divider",children:[jsxRuntime.jsx("hr",{}),"OU",jsxRuntime.jsx("hr",{})]}),jsxRuntime.jsxs("span",{className:"trieoh-card__other",children:["J\xE1 possui uma conta? ",jsxRuntime.jsx("span",{onClick:r,children:"Entre"})]})]})]})}function mt({size:e}){let t=e?`trieoh-copyright--${e}`:"";return jsxRuntime.jsxs("span",{className:`trieoh trieoh-copyright ${t}`,children:["\xA9 ",new Date().getFullYear()," TrieOH"]})}function gt({onSuccess:e,onFailed:t,forceLogout:r}){let{auth:o}=S(),[s,i]=react.useState(false);return jsxRuntime.jsxs("button",{onClick:async l=>{if(l.preventDefault(),s)return;i(true);let c=await o.logout({forceLogout:r});c.success?e&&await e(c.message):t&&await t(c.message,c.trace),i(false);},type:"button",disabled:s,className:"trieoh trieoh-button--logout",children:[jsxRuntime.jsx(im.ImExit,{size:24})," ",jsxRuntime.jsx("span",{children:"Log out"})]})}var Ue={mobile:fa.FaMobileAlt,tablet:fa.FaTabletAlt,desktop:fa.FaDesktop};function ze(e){let{device:t,os:r,browser:o}=uaParserJs.UAParser(e);return {deviceType:t.type??"desktop",os:r.name,browser:o.name}}function He(e){let t=ze(e);return {device:wt(t.deviceType),os:t.os,browser:t.browser}}function wt(e){if(!e)return "desktop";switch(e){case "mobile":return "mobile";case "tablet":return "tablet";default:return "desktop"}}function Me(e){let t=Date.now()-new Date(e).getTime(),r=Math.floor(t/1e3),o=Math.floor(r/60),s=Math.floor(o/60),i=Math.floor(s/24),n=Math.floor(i/7);return r<60?"agora mesmo":o<60?`${o} minutos atr\xE1s`:s<24?`${s} horas atr\xE1s`:i<7?`${i} dias atr\xE1s`:`${n} semanas atr\xE1s`}function Se({is_current:e,session_id:t,user_agent:r,issued_at:o,user_ip:s,onClick:i}){let n=He(r),l=Ue[n.device];return jsxRuntime.jsx("div",{className:"trieoh-session",children:jsxRuntime.jsxs("div",{className:"trieoh-session__content",children:[jsxRuntime.jsx(l,{size:40}),jsxRuntime.jsxs("div",{className:"trieoh-session__info",children:[jsxRuntime.jsxs("h3",{children:[n.browser," - ",n.os]}),jsxRuntime.jsxs("span",{className:"trieoh-session__meta",children:[e&&jsxRuntime.jsx("strong",{children:"\u2022 Sess\xE3o Atual \u2022"}),jsxRuntime.jsx("span",{children:`${s} - ${Me(o)}`})]})]}),!e&&jsxRuntime.jsx(fa.FaTrashAlt,{size:20,color:"red",onClick:c=>i(c,t)})]})})}function Tt({revokeAll:e=false,onSuccess:t}){let{auth:r}=S(),[o,s]=react.useState(false),[i,n]=react.useState([]),l=async()=>{let p=await r.sessions();if(p.success){let u=r.profile()?.session_id,f=p.data.sort((d,m)=>d.session_id===u?-1:m.session_id===u?1:0);n(f);}};react.useEffect(()=>{l();},[]);let c=async(p,u)=>{p.preventDefault();let f=i.find(d=>d.session_id===u);if(f){n(i.filter(d=>d.session_id!==u));try{(await r.revokeASession(u)).success||n(m=>[...m,f]);}catch{n(d=>[...d,f]);}}};return jsxRuntime.jsxs("div",{className:"trieoh trieoh-sessions",children:[jsxRuntime.jsxs("div",{className:"trieoh-sessions__header",children:[jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx("h3",{children:"Navegadores e Dispositivos"}),jsxRuntime.jsx("p",{children:"Esses navegadores e dispositivos est\xE3o atualmente conectados \xE0 sua conta. Remova quaisquer dispositivos n\xE3o autorizados."})]}),jsxRuntime.jsx("button",{type:"submit",onClick:async p=>{if(p.preventDefault(),o)return;s(true);let u=await r.revokeSessions(e),f=r.profile()?.session_id;u.success&&(n(e?[]:i.filter(d=>d.session_id===f)),t&&t(u.message)),s(false);},disabled:o,className:`trieoh trieoh-button trieoh-button--all-rounded
5
- ${o?"trieoh-button--loading":""}`,children:"Revogar todas as sess\xF5es"})]}),jsxRuntime.jsx("div",{className:"trieoh-sessions__content",children:i.length>0?i.map(p=>jsxRuntime.jsx(Se,{...p,is_current:r.profile()?.session_id===p.session_id,onClick:c},p.session_id)):jsxRuntime.jsx("span",{className:"trieoh-sessions__empty",children:"Nenhuma Sess\xE3o Dispon\xEDvel"})})]})}function $e({onSuccess:e,onFailed:t,loginRedirect:r,emailRules:o}){let[s,i]=react.useState(""),[n,l]=react.useState(false),[c,h]=react.useState(false),p=react.useRef(null),{auth:u}=S(),d=R({email:o||[{message:"Digite um e-mail v\xE1lido, ex: exemplo@dominio.com",test:x=>/\S+@\S+\.\S+/.test(x)}]}.email,s);return jsxRuntime.jsxs("form",{className:"trieoh trieoh-card trieoh-card--full-rounded",children:[jsxRuntime.jsx(N,{mainText:"Esqueci a senha",subText:"Insira seu e-mail para receber um link de redefini\xE7\xE3o."}),jsxRuntime.jsx("div",{className:"trieoh-card__fields",children:jsxRuntime.jsx(w,{label:"Email",name:"email",placeholder:"teste@gmail.com",autoComplete:"email",type:"email",value:s,onValueChange:i,inputRef:p,rulesStatus:d,submitted:n})}),jsxRuntime.jsx(L,{label:c?"Enviando...":"Enviar link de redefini\xE7\xE3o",onSubmit:async x=>{if(x.preventDefault(),l(true),d.some(E=>!E.passed)){p.current?.focus();return}h(true);let y=await u.sendForgotPassword(s);y.success?e&&await e(y.message):t&&await t(y.message,y.trace),h(false);},loading:c}),r&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs("div",{className:"trieoh-card__divider",children:[jsxRuntime.jsx("hr",{}),"OU",jsxRuntime.jsx("hr",{})]}),jsxRuntime.jsxs("span",{className:"trieoh-card__other",children:["Lembrou-se da sua senha? ",jsxRuntime.jsx("span",{onClick:r,children:"Login"})]})]})]})}exports.AuthProvider=xr;exports.BasicInputField=w;exports.BasicLogoutButton=gt;exports.Copyright=mt;exports.ForgotPassword=$e;exports.Sessions=Tt;exports.SignIn=lt;exports.SignUp=ut;exports.useAuth=S;//# 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');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function ge(e,t){if(t.startsWith("http"))return t;let r=e.replace(/\/$/,""),o=t.replace(/^\//,"");return `${r}/${o}`}var V={isAuthenticated:false,isInitializing:true},ve=new Set,Ee=()=>ve.forEach(e=>e()),v={subscribe:e=>(ve.add(e),()=>ve.delete(e)),getSnapshot:()=>V,getServerSnapshot:()=>V,set:e=>{V={...V,...e},Ee();},reset:()=>{V={isAuthenticated:false,isInitializing:false},Ee();}};typeof window<"u"&&window.addEventListener("storage",e=>{if(e.key==="trieoh_access_expiry")if(!e.newValue)v.reset();else {let t=parseInt(e.newValue,10),r=!isNaN(t)&&t>Date.now();v.set({isAuthenticated:r,isInitializing:false});}});var w={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);}},K={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);}},I={get:e=>{if(typeof window>"u")return null;let t=e+"=",r=document.cookie.split(";");for(let o=0;o<r.length;o++){let s=r[o];for(;s.charAt(0)===" ";)s=s.substring(1,s.length);if(s.indexOf(t)===0)return s.substring(t.length,s.length)}return null},set:(e,t,r={})=>{if(typeof window>"u")return;let{expires:o,path:s="/",domain:i,secure:n=window.location.protocol==="https:",sameSite:a=n?"None":"Lax"}=r,c=[`${e}=${t}`,i?`Domain=${i}`:"",`Path=${s}`,`SameSite=${a}`,n?"Secure":"",o?`expires=${o}`:""];document.cookie=c.filter(Boolean).join("; ");},remove:(e,t)=>{I.set(e,"",{expires:"Thu, 01 Jan 1970 00:00:00 GMT",domain:t});}};var oe="trieoh_access_token",D={getAccessToken:()=>K.getItem(oe),setAccessToken:e=>{e?K.setItem(oe,e):K.removeItem(oe);},clear:()=>{K.removeItem(oe);}};var F=null,_e="trieoh_access_expiry",ne="trieoh_refresh_expiry",ie="trieoh_refresh_domain";function Ae(e){if(typeof window>"u")return null;let t=window.location.hostname;if(t==="localhost")return null;if(e)try{let r=e;return r.startsWith("http")&&(r=new URL(r).hostname),r}catch{return e}return t}function Ie(e){try{let t=e.split(".")[1];return JSON.parse(atob(t))}catch{return null}}function Y(e){let{AccessTokenString:t,RefreshTokenString:r,AccessExpiresAt:o,RefreshExpiresAt:s,Domain:i}=e,n=Ie(t);if(!n){envoyFetchTs.logger.error("Failed to decode tokens");return}D.setAccessToken(t);let a=new Date(s).getTime(),c=new Date(o).getTime(),u=Ae(i);I.set("refresh_token",r,{expires:new Date(a).toUTCString(),domain:u}),F={access_data:n,refresh_expiry_date:a},w.setItem(_e,String(c)),w.setItem(ne,String(a)),u?w.setItem(ie,u):w.removeItem(ie),v.set({isAuthenticated:true,isInitializing:false}),envoyFetchTs.logger.log("Auth session saved");}function j(){if(F)return F;let e=D.getAccessToken();if(!e)return null;let t=Ie(e);if(!t||t.exp*1e3<=Date.now())return null;let r=w.getItem(ne);return r?(F={access_data:t,refresh_expiry_date:parseInt(r,10)},F):null}function Ce(e,t){try{let r=w.getItem(e);if(!r)return !0;let o=parseInt(r,10);return isNaN(o)?!0:o-Date.now()<=t*1e3}catch(r){return envoyFetchTs.logger.warn("Error reading expiry:",r),true}}var ke=(e=30)=>Ce(_e,e),ae=(e=10)=>Ce(ne,e);function U(){F=null,D.clear(),w.removeItem(_e),w.removeItem(ne);let e=w.getItem(ie)||Ae();I.remove("refresh_token",e),w.removeItem(ie),v.reset(),envoyFetchTs.logger.log("Auth tokens and claims cleared");}function Pe(){let e=j();return e?e.access_data.sub:null}function je(){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||"",s=e&&r.TRIEOH_AUTH_API_KEY||"";return {PROJECT_ID:o,API_KEY:s,BASE_URL:"https://api.trieauth.trieoh.com"}}var le=null,xe={};function De(e){xe={...xe,...e},le=null;}function ye(){return le||(le={...je(),...xe}),le}var _={get PROJECT_ID(){return ye().PROJECT_ID},get BASE_URL(){return ye().BASE_URL}};var ce=class{constructor(t){this.isRefreshing=false;this.refreshPromise=null;this.baseURL=t?.baseURL||_.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(ge(this.authBaseURL,"/auth/refresh"),{method:"POST",credentials:"include"});if(t.code!==200||!t.data)throw t.code!==503&&U(),new Error(t.message||"Failed to refresh token");Y(t.data);let r=j();r&&this.onTokenRefreshed?.(r),envoyFetchTs.logger.log("Token refreshed successfully");}catch(t){throw envoyFetchTs.logger.warn("Failed to refresh token:",t),U(),this.onRefreshFailed?.(t),t}finally{this.isRefreshing=false,this.refreshPromise=null;}})(),this.refreshPromise)}async beforeRequest(){if(ae()){U();return}let t=!!D.getAccessToken(),r=!!I.get("refresh_token");if(!t&&r||t&&ke(30))try{await this.refreshToken();}catch(o){envoyFetchTs.logger.warn("Proactive refresh failed:",o);}}async fetch(t,r){let o=r?.requiresAuth!==false,s=t.includes("/auth/refresh");o&&!s&&!r?.skipRefresh&&await this.beforeRequest();let i=ge(this.baseURL,t),n=async()=>{let c=D.getAccessToken(),u=new Headers(r?.headers);return o&&c&&u.set("Authorization",`Bearer ${c}`),u.has("Content-Type")||u.set("Content-Type","application/json"),fetch(i,{...r,headers:u,credentials:"include"})},a=await n();if(a.status===401&&o&&!s){envoyFetchTs.logger.log("401 detected, attempting one-time retry after refresh...");try{await this.refreshToken(),a=await n();}catch{envoyFetchTs.logger.error("Retry failed after refresh error");}}return a}};function O(e){if(!e)return;let{requiresAuth:t,skipRefresh:r,...o}=e,s={};return t!==void 0&&(s.requiresAuth=t),r!==void 0&&(s.skipRefresh=r),{...o,adapterInit:{...o.adapterInit,...s}}}var ue=class{constructor(t,r,o,s){this.interceptor=new ce({baseURL:t,authBaseURL:r,onTokenRefreshed:o}),this.client=envoyFetchTs.createDefaultFetchClient({...s,adapter:this.interceptor.fetch.bind(this.interceptor)});}request(t,r){return this.client.request(t,O(r))}get(t,r){return this.client.get(t,O(r))}post(t,r,o){return this.client.post(t,r,O(o))}put(t,r,o){return this.client.put(t,r,O(o))}patch(t,r,o){return this.client.patch(t,r,O(o))}delete(t,r,o){return this.client.delete(t,r,O(o))}query(t,r){return this.client.query(t,O(r))}};var H=()=>{if(!_.PROJECT_ID||_.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 Oe=(e,t)=>({login:async(r,o)=>{_.PROJECT_ID&&H();let s=`/auth/login${_.PROJECT_ID?`?project_id=${_.PROJECT_ID}`:""}`,i=await e.post(s,{email:r,password:o},{requiresAuth:false});return i.success&&(Y(i.data),t?.onLogin?.()),i},register:async(r,o)=>{let s={requiresAuth:false},i=`/auth/register${_.PROJECT_ID?`?project_id=${_.PROJECT_ID}`:""}`;_.PROJECT_ID&&H();let n=await e.post(i,{email:r,password:o},s);return n.success&&t?.onRegister?.(),n},logout:async r=>{let o=`/auth/logout${_.PROJECT_ID?`?project_id=${_.PROJECT_ID}`:""}`,s=await e.post(o);return (s.success||r?.forceLogout)&&U(),s},refresh:async()=>{let r=await e.post("/auth/refresh",void 0,{skipRefresh:true});return r.success&&(Y(r.data),t?.onRefresh?.()),r},sessions:async()=>e.get("/sessions"),currentSession:async()=>e.get("/sessions/me"),revokeASession:async r=>e.delete(`/sessions/${r}`),revokeSessions:async(r=false)=>{let o=r?"/sessions":"/sessions/others";return e.delete(o)},profile:()=>Pe(),sendForgotPassword:async r=>{let o={requiresAuth:false},s=await(async()=>_.PROJECT_ID?(H(),e.post("/account/forgot-password",{email:r,project_id:_.PROJECT_ID},o)):e.post("/account/forgot-password",{email:r},o))();return s.success&&t?.onForgotPassword?.(),s},resetPassword:async(r,o)=>e.post(`/account/reset-password?token=${r}`,{new_password:o},{requiresAuth:false}),verifyEmail:async()=>{let r=await e.get("/account/verify",{requiresAuth:false});return r.success&&t?.onVerify?.(),r},resendVerifyEmail:async()=>e.post("/account/verify/resend"),health:async()=>e.get("/health",{requiresAuth:false}),authHealth:async()=>e.get("/protected/health")});var Be=react.createContext(null);function br({children:e,baseURL:t,projectId:r,isProjectMode:o=true,fallback:s,waitSession:i=true,clientConfig:n,onLogin:a,onForgotPassword:c,onRegister:u,onVerify:h,onRefresh:d}){let f=react.useRef(false),{isAuthenticated:m,isInitializing:p}=react.useSyncExternalStore(v.subscribe,v.getSnapshot,v.getServerSnapshot);react.useEffect(()=>{De({...r?{PROJECT_ID:r}:{},...t?{BASE_URL:t}:{}});},[r,t]);let x=react.useCallback(k=>{v.set({isAuthenticated:!!k.access_data,isInitializing:false}),d?.();},[d]),b=react.useMemo(()=>new ue(t,void 0,x,n),[t,x,n]),y=react.useMemo(()=>Oe(b,{onLogin:a,onForgotPassword:c,onRegister:u,onVerify:h,onRefresh:d}),[b,a,c,u,h,d]);react.useEffect(()=>{o&&H(),(async()=>{if(f.current)return;if(f.current=true,j()){v.set({isAuthenticated:true,isInitializing:false});return}if(!!!I.get("refresh_token")||ae()){v.reset(),v.set({isInitializing:false});return}envoyFetchTs.logger.log("No cached claims, attempting silent refresh...");try{(await y.refresh()).success?(v.set({isAuthenticated:!0,isInitializing:!1}),envoyFetchTs.logger.log("Session restored.")):(v.reset(),envoyFetchTs.logger.warn("No active session."));}catch{v.reset(),envoyFetchTs.logger.warn("Could not restore session (offline?).");}finally{v.set({isInitializing:false});}})();},[y,o]);let A=react.useMemo(()=>({auth:y,isAuthenticated:m,isInitializing:p,isProjectMode:o}),[y,m,p,o]);return i&&p?s??null:jsxRuntime.jsx(Be.Provider,{value:A,children:e})}function R(){let e=react.useContext(Be);if(!e)throw new Error("useAuth must be used inside <AuthProvider>");return e}function X(e,{insertAt:t}={}){if(!e||typeof document>"u")return;let r=document.head||document.getElementsByTagName("head")[0],o=document.createElement("style");o.type="text/css",t==="top"&&r.firstChild?r.insertBefore(o,r.firstChild):r.appendChild(o),o.styleSheet?o.styleSheet.cssText=e:o.appendChild(document.createTextNode(e));}X(`@import"https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap";:root{--trieoh-primary: oklch(.1139 .0789 264.05);--trieoh-secondary: oklch(.7975 .1018 262.7);--trieoh-neutral1: oklch(.9702 0 0);--trieoh-neutral2: oklch(.1944 .0051 248.09);--trieoh-radius-full: 50%;--trieoh-text-sm: .75rem;--trieoh-text-base: .875rem;--trieoh-text-xl: 1.25rem;--trieoh-text-2xl: 1.5rem;--trieoh-text-3xl: 1.875rem;--trieoh-text-6xl: 3.75rem}
2
+ `);X(`.trieoh{font-family:Inter,sans-serif}.trieoh-input{position:relative;width:100%;display:flex;flex-direction:column;gap:.25rem;color:var(--trieoh-neutral2)}.trieoh-input__label{font-size:1rem;font-weight:600}.trieoh-input__container{display:flex;justify-content:space-between;align-items:center;padding:.0625rem .625rem;gap:.625rem;border-bottom:solid .125rem var(--trieoh-neutral2)}.trieoh-input__container--error{border-color:#e53935!important}.trieoh-input__container-field{min-width:10rem;flex:1;font-size:var(--trieoh-text-base);font-weight:300;color:var(--trieoh-neutral2);-webkit-appearance:none;background:none;outline:none;border:none;box-shadow:none!important;padding:.125rem 0}.trieoh-input__container-icon{cursor:pointer;flex-shrink:0;-webkit-user-select:none;user-select:none}.trieoh-input__hint{font-size:.75rem;color:#6b7280;transition:opacity .2s ease-in-out}.trieoh-input__hint .hint-part{transition:color .12s ease,text-decoration .12s ease,opacity .12s ease;opacity:.95;margin:.125rem}.trieoh-input__hint .hint-part.passed{text-decoration:line-through;opacity:.6;color:#10b981}.trieoh-input__hint .hint-part.failed-on-submit{color:#e53935;font-weight:600;opacity:1}.trieoh-button{--trieoh-button-color: var(--trieoh-neutral2);width:100%;height:3.25rem;font-size:var(--trieoh-text-xl);font-weight:600;color:var(--trieoh-button-color);outline:none;background:none;position:relative;overflow:hidden;min-width:10rem;flex-shrink:0;border:.125rem solid var(--trieoh-button-color);cursor:pointer;padding:0 1.5rem;transition:transform .5s}.trieoh-button--all-rounded{border-radius:.25rem}.trieoh-button:hover{transform:scale(102%)}.trieoh-button:active{transform:scale(99%)}.trieoh-button[disabled],.trieoh-button--logout[disabled]{opacity:.6;cursor:not-allowed;transform:none!important}.trieoh-button--loading:after{content:"";position:absolute;top:0;left:-150%;width:150%;height:100%;background:linear-gradient(120deg,transparent 0%,color-mix(in oklab,var(--trieoh-button-color) 40%,white 15%) 40%,transparent 80%);animation:trieoh-shine 1.5s infinite}@keyframes trieoh-shine{0%{left:-150%}to{left:150%}}.trieoh-button--logout{border:none;background:none;cursor:pointer;--trieoh-button-color: oklch(.628 .2577 29.23);display:flex;align-items:end;gap:.25rem;font-size:var(--trieoh-text-base);font-weight:500;color:var(--trieoh-button-color);transition:transform .2s}.trieoh-button--logout:hover{transform:scale(1.05)}.trieoh-button--logout:active{transform:scale(.98)}.trieoh-avacard{display:flex;flex-direction:column;align-items:center}.trieoh-avacard__container{display:flex;justify-content:center;align-items:center;padding:.5rem;background-color:#d9d9d94d;border-radius:var(--trieoh-radius-full);margin-bottom:.625rem}.trieoh-avacard__content{width:64px;height:64px;padding:.625rem;background-color:var(--trieoh-neutral1);border-radius:var(--trieoh-radius-full);box-shadow:0 .25rem 1rem #00000040}.trieoh-avacard__title{text-align:center;font-size:var(--trieoh-text-xl);font-weight:500;margin:0}.trieoh-avacard__sub-title{text-align:center;font-size:.875rem;font-weight:300;opacity:.6}.trieoh-card{display:flex;flex-direction:column;width:100%;max-width:30rem;min-width:15rem;max-height:max(75dvh,32rem);overflow:hidden;gap:1.25rem;align-items:center;background-color:var(--trieoh-neutral1);color:var(--trieoh-neutral2);padding:1.25rem 1.5rem;box-shadow:0 .25rem .25rem #00000040;transition:transform .15s ease}.trieoh-card--full-rounded{border-radius:.25rem}.trieoh-card__fields{width:100%;display:flex;flex-direction:column;gap:.625rem;flex:1 1 auto;overflow-y:auto;margin-bottom:.5rem}.trieoh-card__divider{display:flex;align-items:center;gap:.625rem;width:100%;font-size:var(--trieoh-text-base);font-weight:600;opacity:.6}.trieoh-card__divider hr{flex:1}.trieoh-card__other{font-size:var(--trieoh-text-sm);font-weight:600}.trieoh-card__other span{cursor:pointer;color:var(--trieoh-secondary);transition:color .2s}.trieoh-card__other span:hover{color:var(--trieoh-primary)}.trieoh-copyright{font-size:var(--trieoh-text-xl);font-weight:500}.trieoh-copyright--xs{font-size:var(--trieoh-text-sm)}.trieoh-copyright--sm{font-size:var(--trieoh-text-base)}.trieoh-copyright--md{font-size:var(--trieoh-text-xl)}.trieoh-copyright--lg{font-size:var(--trieoh-text-2xl)}.trieoh-copyright--xl{font-size:var(--trieoh-text-3xl)}.trieoh-copyright--2xl{font-size:var(--trieoh-text-6xl)}.trieoh-sessions{width:100%;min-width:20rem;margin:.5rem;container-type:inline-size;background-color:var(--trieoh-neutral1);color:var(--trieoh-neutral2);padding:1.5rem .5rem;border-radius:.5rem}.trieoh-sessions__header{width:100%;display:flex;flex-wrap:wrap;align-items:center;justify-content:center;text-align:center;gap:1rem;box-sizing:border-box;padding:0 .75rem}.trieoh-sessions__header div{flex:0 1 auto;max-width:25rem}.trieoh-sessions__header div h3{font-weight:600;font-size:var(--trieoh-text-2xl);margin:0;margin-bottom:.25rem}.trieoh-sessions__header div p{font-weight:200;font-size:var(--trieoh-text-base);margin:0}.trieoh-sessions__header button{max-width:14rem;padding:1rem 0;height:auto;font-size:var(--trieoh-text-base)}.trieoh-sessions__content{margin-top:1rem}.trieoh-sessions__empty{display:block;border-top:1px solid rgba(0,0,0,.3);padding:1.25rem .75rem;text-align:center;font-weight:600}.trieoh-session{border-top:1px solid rgba(0,0,0,.3);padding:1.25rem .75rem;color:var(--trieoh-neutral2)}.trieoh-session__content{position:relative;display:flex;flex-direction:column;align-items:center;gap:.5rem;flex:1;text-align:center}.trieoh-session__info{display:flex;flex-direction:column;min-width:0}.trieoh-session__meta{display:inline-flex;flex-direction:column;font-size:var(--trieoh-text-sm);font-weight:200}.trieoh-session h3{font-size:var(--trieoh-text-base);font-weight:600;margin:0}.trieoh-session span strong{color:var(--trieoh-primary);font-weight:400}.trieoh-session__content svg:last-child{position:absolute;top:0;right:0;cursor:pointer;opacity:.6;transition:opacity .2s,transform .15s}.trieoh-session__content svg:last-child:hover{opacity:1;transform:scale(1.05)}.trieoh-session__content svg:last-child:active{transform:scale(.95)}@container (min-width: 640px){.trieoh-sessions__header{justify-content:space-between;text-align:left;gap:2rem}.trieoh-session{flex-direction:row;text-align:left}.trieoh-session__content{flex-direction:row;align-items:center;gap:1rem;text-align:left}.trieoh-session__meta{flex-direction:row;gap:.5rem;align-items:center}}
3
+ `);function S({name:e,label:t,placeholder:r,type:o="text",value:s,onValueChange:i,onBlur:n,autoComplete:a,rulesStatus:c=[],submitted:u=false,inputRef:h}){let[d,f]=react.useState(false),m=c.some(p=>!p.passed);return jsxRuntime.jsxs("div",{className:"trieoh trieoh-input",children:[jsxRuntime.jsx("label",{htmlFor:e,className:"trieoh-input__label",children:t}),jsxRuntime.jsxs("div",{className:(m&&u?"trieoh-input__container--error ":"")+"trieoh-input__container",children:[jsxRuntime.jsx("input",{type:d?"text":o,name:e,id:e,placeholder:r,value:s,onChange:p=>i&&i(p.target.value),onBlur:n,autoComplete:a,"aria-invalid":m&&u,ref:h,className:"trieoh-input__container-field"}),o==="password"&&(d?jsxRuntime.jsx(ri.RiEyeCloseLine,{className:"trieoh-input__container-icon",size:24,onClick:()=>f(false)}):jsxRuntime.jsx(ri.RiEyeLine,{className:"trieoh-input__container-icon",size:24,onClick:()=>f(true)}))]}),jsxRuntime.jsx("div",{className:"trieoh-input__hint",children:c.map((p,x)=>{let b=["hint-part",p.passed?"passed":"",!p.passed&&u?"failed-on-submit":""].filter(Boolean).join(" ");return jsxRuntime.jsx("p",{className:b,children:p.message},p.id??x)})})]})}function L({label:e,onSubmit:t,loading:r}){return jsxRuntime.jsx("button",{type:"submit",onClick:t,disabled:r,className:`trieoh trieoh-button trieoh-button--all-rounded
4
+ ${r?"trieoh-button--loading":""}`,children:e})}function B({mainText:e,subText:t}){return jsxRuntime.jsxs("div",{className:"trieoh trieoh-avacard",children:[jsxRuntime.jsx("div",{className:"trieoh-avacard__container",children:jsxRuntime.jsx(go.GoPerson,{className:"trieoh-avacard__content",size:70})}),jsxRuntime.jsx("h3",{className:"trieoh-avacard__title",children:e}),jsxRuntime.jsx("span",{className:"trieoh-avacard__sub-title",children:t})]})}function T(e,t){return e.map(r=>({id:r.id,message:r.message,passed:!!r.test(t)}))}function ct({onSuccess:e,onFailed:t,signUpRedirect:r,forgotPasswordRedirect:o,emailRules:s}){let[i,n]=react.useState(""),[a,c]=react.useState(""),[u,h]=react.useState(false),[d,f]=react.useState(false),m=react.useRef(null),p=react.useRef(null),{auth:x}=R(),b={email:s||[{message:"Digite um e-mail v\xE1lido, ex: exemplo@dominio.com",test:P=>/\S+@\S+\.\S+/.test(P)}],password:[]},y=T(b.email,i),A=T(b.password,a);return jsxRuntime.jsxs("form",{className:"trieoh trieoh-card trieoh-card--full-rounded",children:[jsxRuntime.jsx(B,{mainText:"Fa\xE7a login na sua conta",subText:"Insira seus dados para fazer login"}),jsxRuntime.jsxs("div",{className:"trieoh-card__fields",children:[jsxRuntime.jsx(S,{label:"Email",name:"email",placeholder:"teste@gmail.com",autoComplete:"email",type:"email",value:i,onValueChange:n,inputRef:m,rulesStatus:y,submitted:u}),jsxRuntime.jsx(S,{label:"Senha",name:"password",placeholder:"**********",autoComplete:"current-password",type:"password",value:a,onValueChange:c,inputRef:p,rulesStatus:A,submitted:u})]}),jsxRuntime.jsx(L,{label:"Entrar",onSubmit:async P=>{P.preventDefault(),h(true);let q=y.some(g=>!g.passed),te=A.some(g=>!g.passed);if(q){m.current?.focus();return}if(te){p.current?.focus();return}f(true);let $=await x.login(i,a);$.success?e&&await e($.message):t&&await t($.message,$.trace),f(false);},loading:d}),o&&jsxRuntime.jsx("span",{className:"trieoh-card__other",style:{textAlign:"center",cursor:"pointer"},children:jsxRuntime.jsx("span",{onClick:o,children:"Esqueceu sua senha?"})}),r&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs("div",{className:"trieoh-card__divider",children:[jsxRuntime.jsx("hr",{}),"OU",jsxRuntime.jsx("hr",{})]}),jsxRuntime.jsxs("span",{className:"trieoh-card__other",children:["Ainda n\xE3o possui uma conta? ",jsxRuntime.jsx("span",{onClick:r,children:"Cadastra-se"})]})]})]})}function dt({onSuccess:e,onFailed:t,loginRedirect:r,emailRules:o,passwordRules:s}){let[i,n]=react.useState(""),[a,c]=react.useState(""),[u,h]=react.useState(""),[d,f]=react.useState(false),[m,p]=react.useState(false),x=react.useRef(null),b=react.useRef(null),y=react.useRef(null),{auth:A}=R(),k={email:o||[{message:"Digite um e-mail v\xE1lido, ex: exemplo@dominio.com",test:g=>/\S+@\S+\.\S+/.test(g)}],password:s||[{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===a}]},P=T(k.email,i),q=T(k.password,a),te=T(k.confirmPassword,u);return jsxRuntime.jsxs("form",{className:"trieoh trieoh-card trieoh-card--full-rounded",children:[jsxRuntime.jsx(B,{mainText:"Crie sua conta",subText:"Insira seus dados para come\xE7ar"}),jsxRuntime.jsxs("div",{className:"trieoh-card__fields",children:[jsxRuntime.jsx(S,{label:"Email",name:"email",placeholder:"teste@gmail.com",autoComplete:"email",type:"email",value:i,onValueChange:n,inputRef:x,rulesStatus:P,submitted:d}),jsxRuntime.jsx(S,{label:"Senha",name:"password",placeholder:"**********",autoComplete:"new-password",type:"password",value:a,onValueChange:c,inputRef:b,rulesStatus:q,submitted:d}),jsxRuntime.jsx(S,{label:"Confirme a Senha",name:"confirm-password",placeholder:"**********",autoComplete:"new-password",type:"password",value:u,onValueChange:h,inputRef:y,rulesStatus:te,submitted:d})]}),jsxRuntime.jsx(L,{label:"Criar Conta",onSubmit:async g=>{g.preventDefault(),f(true);let Ve=P.some(J=>!J.passed),Ke=q.some(J=>!J.passed),Ye=te.some(J=>!J.passed);if(Ve){x.current?.focus();return}if(Ke){b.current?.focus();return}if(Ye){y.current?.focus();return}p(true);let re=await A.register(i,a);re.success?e&&await e(re.message):t&&await t(re.message,re.trace),p(false);},loading:m}),r&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs("div",{className:"trieoh-card__divider",children:[jsxRuntime.jsx("hr",{}),"OU",jsxRuntime.jsx("hr",{})]}),jsxRuntime.jsxs("span",{className:"trieoh-card__other",children:["J\xE1 possui uma conta? ",jsxRuntime.jsx("span",{onClick:r,children:"Entre"})]})]})]})}function pt({size:e}){let t=e?`trieoh-copyright--${e}`:"";return jsxRuntime.jsxs("span",{className:`trieoh trieoh-copyright ${t}`,children:["\xA9 ",new Date().getFullYear()," TrieOH"]})}function vt({onSuccess:e,onFailed:t,forceLogout:r}){let{auth:o}=R(),[s,i]=react.useState(false);return jsxRuntime.jsxs("button",{onClick:async a=>{if(a.preventDefault(),s)return;i(true);let c=await o.logout({forceLogout:r});c.success?e&&await e(c.message):t&&await t(c.message,c.trace),i(false);},type:"button",disabled:s,className:"trieoh trieoh-button--logout",children:[jsxRuntime.jsx(im.ImExit,{size:24})," ",jsxRuntime.jsx("span",{children:"Log out"})]})}var He={mobile:fa.FaMobileAlt,tablet:fa.FaTabletAlt,desktop:fa.FaDesktop};function Me(e){let{device:t,os:r,browser:o}=uaParserJs.UAParser(e);return {deviceType:t.type??"desktop",os:r.name,browser:o.name}}function ze(e){let t=Me(e);return {device:St(t.deviceType),os:t.os,browser:t.browser}}function St(e){if(!e)return "desktop";switch(e){case "mobile":return "mobile";case "tablet":return "tablet";default:return "desktop"}}function qe(e){let t=Date.now()-new Date(e).getTime(),r=Math.floor(t/1e3),o=Math.floor(r/60),s=Math.floor(o/60),i=Math.floor(s/24),n=Math.floor(i/7);return r<60?"agora mesmo":o<60?`${o} minutos atr\xE1s`:s<24?`${s} horas atr\xE1s`:i<7?`${i} dias atr\xE1s`:`${n} semanas atr\xE1s`}function Se({is_current:e,session_id:t,user_agent:r,issued_at:o,user_ip:s,onClick:i}){let n=ze(r),a=He[n.device];return jsxRuntime.jsx("div",{className:"trieoh-session",children:jsxRuntime.jsxs("div",{className:"trieoh-session__content",children:[jsxRuntime.jsx(a,{size:40}),jsxRuntime.jsxs("div",{className:"trieoh-session__info",children:[jsxRuntime.jsxs("h3",{children:[n.browser," - ",n.os]}),jsxRuntime.jsxs("span",{className:"trieoh-session__meta",children:[e&&jsxRuntime.jsx("strong",{children:"\u2022 Sess\xE3o Atual \u2022"}),jsxRuntime.jsx("span",{children:`${s} - ${qe(o)}`})]})]}),!e&&jsxRuntime.jsx(fa.FaTrashAlt,{size:20,color:"red",onClick:c=>i(c,t)})]})})}function Et({revokeAll:e=false,onSuccess:t}){let{auth:r}=R(),[o,s]=react.useState(false),[i,n]=react.useState([]),a=async()=>{let h=await r.sessions();if(h.success){let d=r.profile()?.session_id,f=h.data.sort((m,p)=>m.session_id===d?-1:p.session_id===d?1:0);n(f);}};react.useEffect(()=>{a();},[]);let c=async(h,d)=>{h.preventDefault();let f=i.find(m=>m.session_id===d);if(f){n(i.filter(m=>m.session_id!==d));try{(await r.revokeASession(d)).success||n(p=>[...p,f]);}catch{n(m=>[...m,f]);}}};return jsxRuntime.jsxs("div",{className:"trieoh trieoh-sessions",children:[jsxRuntime.jsxs("div",{className:"trieoh-sessions__header",children:[jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx("h3",{children:"Navegadores e Dispositivos"}),jsxRuntime.jsx("p",{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 h=>{if(h.preventDefault(),o)return;s(true);let d=await r.revokeSessions(e),f=r.profile()?.session_id;d.success&&(n(e?[]:i.filter(m=>m.session_id===f)),t&&t(d.message)),s(false);},disabled:o,className:`trieoh trieoh-button trieoh-button--all-rounded
5
+ ${o?"trieoh-button--loading":""}`,children:"Revogar todas as sess\xF5es"})]}),jsxRuntime.jsx("div",{className:"trieoh-sessions__content",children:i.length>0?i.map(h=>jsxRuntime.jsx(Se,{...h,is_current:r.profile()?.session_id===h.session_id,onClick:c},h.session_id)):jsxRuntime.jsx("span",{className:"trieoh-sessions__empty",children:"Nenhuma Sess\xE3o Dispon\xEDvel"})})]})}function Je({onSuccess:e,onFailed:t,loginRedirect:r,emailRules:o}){let[s,i]=react.useState(""),[n,a]=react.useState(false),[c,u]=react.useState(false),h=react.useRef(null),{auth:d}=R(),m=T({email:o||[{message:"Digite um e-mail v\xE1lido, ex: exemplo@dominio.com",test:x=>/\S+@\S+\.\S+/.test(x)}]}.email,s);return jsxRuntime.jsxs("form",{className:"trieoh trieoh-card trieoh-card--full-rounded",children:[jsxRuntime.jsx(B,{mainText:"Esqueci a senha",subText:"Insira seu e-mail para receber um link de redefini\xE7\xE3o."}),jsxRuntime.jsx("div",{className:"trieoh-card__fields",children:jsxRuntime.jsx(S,{label:"Email",name:"email",placeholder:"teste@gmail.com",autoComplete:"email",type:"email",value:s,onValueChange:i,inputRef:h,rulesStatus:m,submitted:n})}),jsxRuntime.jsx(L,{label:c?"Enviando...":"Enviar link de redefini\xE7\xE3o",onSubmit:async x=>{if(x.preventDefault(),a(true),m.some(A=>!A.passed)){h.current?.focus();return}u(true);let y=await d.sendForgotPassword(s);y.success?e&&await e(y.message):t&&await t(y.message,y.trace),u(false);},loading:c}),r&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsxs("div",{className:"trieoh-card__divider",children:[jsxRuntime.jsx("hr",{}),"OU",jsxRuntime.jsx("hr",{})]}),jsxRuntime.jsxs("span",{className:"trieoh-card__other",children:["Lembrou-se da sua senha? ",jsxRuntime.jsx("span",{onClick:r,children:"Login"})]})]})]})}exports.AuthProvider=br;exports.BasicInputField=S;exports.BasicLogoutButton=vt;exports.Copyright=pt;exports.ForgotPassword=Je;exports.Sessions=Et;exports.SignIn=ct;exports.SignUp=dt;exports.useAuth=R;//# sourceMappingURL=react.js.map
6
6
  //# sourceMappingURL=react.js.map