@trimble-oss/trimble-id-react 0.1.1 → 1.0.0-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- (function(o,l){typeof exports=="object"&&typeof module<"u"?l(exports,require("@trimble-oss/trimble-id"),require("es-cookie"),require("jwt-decode"),require("react"),require("react/jsx-runtime")):typeof define=="function"&&define.amd?define(["exports","@trimble-oss/trimble-id","es-cookie","jwt-decode","react","react/jsx-runtime"],l):(o=typeof globalThis<"u"?globalThis:o||self,l(o.ReactTID={},o.trimbleId,o.esCookie,o.jwt_decode,o.React,o.jsxRuntime))})(this,function(o,l,k,G,h,E){"use strict";var Se=Object.defineProperty;var me=(o,l,k)=>l in o?Se(o,l,{enumerable:!0,configurable:!0,writable:!0,value:k}):o[l]=k;var c=(o,l,k)=>(me(o,typeof l!="symbol"?l+"":l,k),k);function F(i){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(i){for(const t in i)if(t!=="default"){const s=Object.getOwnPropertyDescriptor(i,t);Object.defineProperty(e,t,s.get?s:{enumerable:!0,get:()=>i[t]})}}return e.default=i,Object.freeze(e)}const _=F(k);class J{constructor(){c(this,"generateCache",function(){const e={token:void 0,user:void 0};return{async getToken(){return e.token},async getUser(){return e.user},async storeToken(t){e.token=t},async storeUser(t){e.user=t},clear(){return e.token=void 0,e.user=void 0,Promise.resolve(void 0)}}}())}}class z{constructor(e){c(this,"localStorage");c(this,"cacheKey");this.localStorage=window.localStorage,this.cacheKey=e.cacheKey}async getToken(){const e=this.getAuthKey(),t=localStorage.getItem(e);return t?JSON.parse(t):void 0}async getUser(){const e=this.getUserKey(),t=localStorage.getItem(e);return t?JSON.parse(t):void 0}async storeToken(e){const t=this.getAuthKey(),s=JSON.stringify(e);localStorage.setItem(t,s)}async storeUser(e){const t=this.getUserKey(),s=JSON.stringify(e);localStorage.setItem(t,s)}getUserKey(){return this.cacheKey.getUserKey()}getAuthKey(){return this.cacheKey.getAuthKey()}clear(){return this.localStorage.removeItem(this.getAuthKey()),this.localStorage.removeItem(this.getUserKey()),Promise.resolve(void 0)}}const I="@TID",H=`${I}_AUTH_KEY`,j=`${I}_USER_KEY`;class q{constructor(e){c(this,"clientId");c(this,"prefix",I);c(this,"authSuffix",H);c(this,"userSuffix",j);this.clientId=e.client_id}getUserKey(){return`${this.prefix}_${this.userSuffix}_${this.clientId}`}getAuthKey(){return`${this.prefix}_${this.authSuffix}_${this.clientId}`}}class B{constructor(e){c(this,"sessionStorage");c(this,"cacheKey");this.sessionStorage=window.sessionStorage,this.cacheKey=e.cacheKey}async getToken(){const e=this.getAuthKey(),t=sessionStorage.getItem(e);return t?JSON.parse(t):void 0}async getUser(){const e=this.getUserKey(),t=sessionStorage.getItem(e);return t?JSON.parse(t):void 0}async storeToken(e){const t=this.getAuthKey(),s=JSON.stringify(e);sessionStorage.setItem(t,s)}async storeUser(e){const t=this.getUserKey(),s=JSON.stringify(e);sessionStorage.setItem(t,s)}getUserKey(){return this.cacheKey.getUserKey()}getAuthKey(){return this.cacheKey.getAuthKey()}clear(){return this.sessionStorage.removeItem(this.getAuthKey()),this.sessionStorage.removeItem(this.getUserKey()),Promise.resolve(void 0)}}class Y{constructor(e){c(this,"persistentStore");c(this,"cacheStorage");c(this,"cacheKey");this.persistentStore=e.persistentStore,this.cacheKey=new q({client_id:e.clientId}),this.persistentStore==="localStorage"?this.cacheStorage=new z({cacheKey:this.cacheKey}):this.persistentStore==="sessionStorage"?this.cacheStorage=new B({cacheKey:this.cacheKey}):this.cacheStorage=new J().generateCache}async setToken(e){await this.cacheStorage.storeToken(e)}async setUser(e){await this.cacheStorage.storeUser(e)}async getUser(){return this.cacheStorage.getUser()}async getToken(){return this.cacheStorage.getToken()}async clear(){await this.cacheStorage.clear()}}const K=5*6e4,Q=["code","state"],C=i=>i.split("?")[0],X=i=>i.split("?")[1],P=i=>{let e=i;if(!i.startsWith("?"))try{e=new URL(i).search}catch{}return new URLSearchParams(e)},Z=(i=window.location.href,e)=>{if(e!=null){const s=C(e),n=C(i??"");if(s!==n)return!1}const t=P(i);for(const s of Q)if(!t.has(s))return!1;return!0},ee=i=>({id:i.sub,name:`${i.given_name} ${i.family_name}`,given_name:i.given_name,family_name:i.family_name,picture:i.picture,email:i.email,email_verified:i.email_verified,phone_number_verified:!1}),te="@TID_COOKIE";class ie{get(e){const t=_.get(e);if(t==null)throw new Error("Cookie not found");return JSON.parse(t)}set(e,t,s){let n={};window.location.protocol==="https:"&&(n={secure:!0,sameSite:"none"}),s!=null&&s.expires&&(n.expires=s.expires),s!=null&&s.domain&&(n.domain=s.domain),_.set(e,JSON.stringify(t),n)}remove(e,t){const s={};t!=null&&t.domain&&(s.domain=t.domain),_.remove(e,s)}}class se{constructor(e){c(this,"cookieKey");c(this,"cookiesStorage");this.cookieKey=`${te}.${e.clientId}`,this.cookiesStorage=new ie}save(e){this.cookiesStorage.set(this.cookieKey,e,{expires:1})}get(){try{return this.cookiesStorage.get(this.cookieKey)}catch{return}}clear(){this.cookiesStorage.remove(this.cookieKey)}}class U extends Error{}class A extends Error{}class ne extends Error{}const u="@trimble-oss/trimble-id-react",g="0.1.1",re={configurationEndpoint:"",clientId:"",redirectUrl:"",logoutRedirectUrl:"",scopes:[]},oe={persistentStore:"in-memory"};class R{constructor(e){c(this,"tokenProvider");c(this,"cacheManager");c(this,"cookiesManager");c(this,"clientId");c(this,"redirectUrl");c(this,"analyticshttpclient");const{config:t=re,persistentOptions:s=oe}=e;if(this.redirectUrl=t.redirectUrl,t.configurationEndpoint==null||t.configurationEndpoint=="")throw new Error("Configuration endpoint not defined");if(t.clientId==null||t.clientId=="")throw new Error("Consumer key is not defined");this.cookiesManager=new se({clientId:t.clientId});const n=this.cookiesManager.get(),y=new l.OpenIdEndpointProvider(t.configurationEndpoint);let d=new l.AuthorizationCodeGrantTokenProvider(y,t.clientId,t.redirectUrl).WithScopes(t.scopes);t.logoutRedirectUrl&&(d=d.WithLogoutRedirect(t.logoutRedirectUrl)),(n==null?void 0:n.code_verifier)!=null&&(d=d.WithProofKeyForCodeExchange(n.code_verifier)),this.tokenProvider=d,this.cacheManager=new Y({clientId:t.clientId,persistentStore:s.persistentStore}),this.clientId=t.clientId,this.analyticshttpclient=l.AnalyticsHttpClient,this.analyticshttpclient.sendInitEvent("TIDClient",this.clientId,u,g)}async loginWithRedirect(e){this.analyticshttpclient.sendMethodEvent(this.loginWithRedirect.name,this.clientId,u,g);const{onRedirect:t}=e||{},s=l.AuthorizationCodeGrantTokenProvider.GenerateCodeVerifier();this.cookiesManager.save({code_verifier:s}),this.tokenProvider=this.tokenProvider.WithProofKeyForCodeExchange(s);const n=await this.tokenProvider.GetOAuthRedirect("state");t!=null?t(n):window.location.assign(n)}async handleCallback(e=window.location.href){const t=this.cookiesManager.get();if(t==null||(t==null?void 0:t.code_verifier)==null)throw new ne("Code verifier not available");const s=X(e),n=P(e),y=n.get("identity_provider")??"",d=n.get("state")??"";return await this.tokenProvider.ValidateQuery(s),await this.generateToken(y),{authState:d}}async generateToken(e){var w,r;const t=await this.tokenProvider.RetrieveToken(),s=await this.tokenProvider.RetrieveRefreshToken(),n=await this.tokenProvider.RetrieveIdToken(),y=await this.tokenProvider.RetrieveTokenExpiry(),v=new Date(y).getTime(),m=(r=(w=this.tokenProvider)==null?void 0:w._scopes)==null?void 0:r.join(" ");await this.cacheManager.setToken({scope:m,state:"",session_state:"",identity_provider:e,token_type:"bearer",access_token:t,refresh_token:s,id_token:n,expires_at:v});const T=G(n),M=ee(T);await this.cacheManager.setUser(M),await this.reloadCodeVerifier()}async reloadCodeVerifier(){const e=await this.tokenProvider.RetrieveCodeVerifier();this.cookiesManager.save({code_verifier:e}),this.tokenProvider=this.tokenProvider.WithProofKeyForCodeExchange(e)}async getUser(){return this.analyticshttpclient.sendMethodEvent(this.getUser.name,this.clientId,u,g),await this.cacheManager.getUser()}async getAccessTokenSilently(){this.analyticshttpclient.sendMethodEvent(this.getAccessTokenSilently.name,this.clientId,u,g);let e=await this.cacheManager.getToken();if(e==null)throw this.analyticshttpclient.sendExceptionEvent(this.getAccessTokenSilently.name,"No token available",this.clientId,u,g),new A("No token available");const t=new Date(new Date().getTime()+K);if((e==null?void 0:e.expires_at)==null||(e==null?void 0:e.expires_at)<t.getTime()){try{await this.tokenProvider.RetrieveToken()}catch(s){throw this.analyticshttpclient.sendExceptionEvent(this.getAccessTokenSilently.name,s.message,this.clientId,u,g),new U(s.message)}await this.generateToken((e==null?void 0:e.identity_provider)??""),e=await this.cacheManager.getToken()}return(e==null?void 0:e.access_token)||""}async getTokens(){this.analyticshttpclient.sendMethodEvent(this.getTokens.name,this.clientId,u,g);let e=await this.cacheManager.getToken();if(e==null)throw this.analyticshttpclient.sendExceptionEvent(this.getTokens.name,"No token available",this.clientId,u,g),new A("No token available");const t=new Date(new Date().getTime()+K);if((e==null?void 0:e.expires_at)==null||(e==null?void 0:e.expires_at)<t.getTime()){try{await this.tokenProvider.RetrieveToken()}catch(s){throw this.analyticshttpclient.sendExceptionEvent(this.getTokens.name,s.message,this.clientId,u,g),new U(s.message)}await this.generateToken((e==null?void 0:e.identity_provider)??""),e=await this.cacheManager.getToken()}return{access_token:(e==null?void 0:e.access_token)||"",expires_at:(e==null?void 0:e.expires_at)||0,id_token:(e==null?void 0:e.id_token)||""}}async logout(e){this.analyticshttpclient.sendMethodEvent(this.logout.name,this.clientId,u,g);const{onRedirect:t,disabledAutoRedirect:s}=e||{};this.cacheManager&&await this.cacheManager.clear(),this.cookiesManager&&this.cookiesManager.clear();const n=await this.tokenProvider.GetOAuthLogoutRedirect("state");if(t!=null)return t(n);s||window.location.assign(n)}async checkSession(){try{await this.getAccessTokenSilently()}catch{return!1}return!0}async loadUserSession(){await this.loadCacheSessionIntoSDK(),await this.checkSession()||await this.cacheManager.clear()}async loadCacheSessionIntoSDK(){const e=await this.cacheManager.getToken();if(e==null)return;const t=e.access_token,s=e.refresh_token||"",n=e.id_token,y=e.expires_at;this.tokenProvider=this.tokenProvider.WithAccessToken(t,y).WithRefreshToken(s).WithIdToken(n)}getBearerTokenHttpClient(e){return new l.BearerTokenHttpClientProvider(this.tokenProvider,e)}getRedirectUrl(){return this.redirectUrl}}const p=h.createContext(null),O=()=>h.useContext(p)??{},ae=(i,e)=>{switch(e.type){case"INIT":return{...i,isLoading:!1,isAuthenticated:e.user!=null,user:e.user,error:void 0};case"GET_TOKENS_COMPLETE":case"HANDLE_CALLBACK_COMPLETE":case"GET_ACCESS_TOKEN_COMPLETE":return{...i,isLoading:!1,isAuthenticated:e.user!=null,user:e.user,error:void 0};case"LOGOUT":return{...i,isAuthenticated:!1,user:void 0};case"ERROR":return{...i,isLoading:!1,error:e.error}}},ce={isLoading:!0,isAuthenticated:!1},x=i=>{if(i==null||Object.keys(i).length<=0)return!0;const e=Object.keys(i);for(const t of e)if(i[t]!=null&&i[t]!=="")return!1;return!0},le=i=>{const e=x(i.config),t=x(i.persistentOptions);return!e||!t},he=i=>{const{children:e,configurationEndpoint:t,clientId:s,redirectUrl:n,logoutRedirectUrl:y,scopes:d,persistentStore:v,onRedirectCallback:m,checkRedirectUrlMatch:T}=i;if(h.useContext(p)!=null)throw new Error("TID Provider already defined");const w={config:{configurationEndpoint:t??"",clientId:s??"",redirectUrl:n??"",logoutRedirectUrl:y??"",scopes:d??[""]},persistentOptions:{persistentStore:v??"in-memory"}},[r]=h.useState(i.tidClient??new R(w)),[D,S]=h.useReducer(ae,ce),L=h.useRef(!1),ye=h.useMemo(()=>T?r.getRedirectUrl():void 0,[T,r]);h.useEffect(()=>{L.current||(i.tidClient!=null&&le({config:{configurationEndpoint:t,clientId:s,redirectUrl:n,logoutRedirectUrl:y,scopes:d},persistentOptions:{persistentStore:v}})&&console.warn("When TID client is pass as prop, any client configuration property sent directly to the TID Provider component will be ignored"),L.current=!0,(async()=>{try{let a;if(Z(void 0,ye)){const{authState:f}=await r.handleCallback();a=await r.getUser(),m!=null&&m(f)}else await r.loadUserSession(),a=await r.getUser();S({type:"INIT",user:a})}catch(a){let f=a;typeof a=="string"&&(f=new Error(a)),S({type:"ERROR",error:f})}})())},[r,m]);const b=h.useCallback(async()=>{const a=await r.getAccessTokenSilently(),f=await r.getUser();return S({type:"GET_ACCESS_TOKEN_COMPLETE",user:f}),a},[r]),N=h.useCallback(async()=>{const a=await r.getTokens(),f=await r.getUser();return S({type:"GET_TOKENS_COMPLETE",user:f}),a},[r]),W=h.useCallback(async a=>{await r.loginWithRedirect(a)},[r]),V=h.useCallback(async a=>{await r.logout(a),(a==null?void 0:a.disabledAutoRedirect)!=null&&a.disabledAutoRedirect&&S({type:"LOGOUT"})},[r]),$=h.useCallback(async a=>{const{authState:f}=await r.handleCallback(a),ke=await r.getUser();return S({type:"HANDLE_CALLBACK_COMPLETE",user:ke}),{authState:f}},[r]),fe=h.useMemo(()=>({...D,getAccessTokenSilently:b,getTokens:N,loginWithRedirect:W,handleCallback:$,logout:V}),[D,b,N,W,$,V]);return E.jsx(p.Provider,{value:fe,children:e})},de=O,ue=he,ge=({renderComponent:i,loader:e})=>{const{isAuthenticated:t,isLoading:s,loginWithRedirect:n}=O();return h.useEffect(()=>{!s&&!t&&(async()=>await n())()},[s,t,n]),t?i:e||E.jsx(E.Fragment,{})};o.AuthenticationGuard=ge,o.TIDClient=R,o.TIDContext=p,o.TIDProvider=ue,o.useAuth=de,Object.defineProperty(o,Symbol.toStringTag,{value:"Module"})});
1
+ (function(o,c){typeof exports=="object"&&typeof module<"u"?c(exports,require("@trimble-oss/trimble-id"),require("es-cookie"),require("jwt-decode"),require("react"),require("react/jsx-runtime")):typeof define=="function"&&define.amd?define(["exports","@trimble-oss/trimble-id","es-cookie","jwt-decode","react","react/jsx-runtime"],c):(o=typeof globalThis<"u"?globalThis:o||self,c(o.ReactTID={},o.trimbleId,o.esCookie,o.jwt_decode,o.React,o.jsxRuntime))})(this,function(o,c,k,W,l,p){"use strict";var le=Object.defineProperty;var de=(o,c,k)=>c in o?le(o,c,{enumerable:!0,configurable:!0,writable:!0,value:k}):o[c]=k;var h=(o,c,k)=>(de(o,typeof c!="symbol"?c+"":c,k),k);function G(i){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(i){for(const t in i)if(t!=="default"){const n=Object.getOwnPropertyDescriptor(i,t);Object.defineProperty(e,t,n.get?n:{enumerable:!0,get:()=>i[t]})}}return e.default=i,Object.freeze(e)}const C=G(k);class V{constructor(){h(this,"generateCache",function(){const e={token:void 0,user:void 0};return{async getToken(){return e.token},async getUser(){return e.user},async storeToken(t){e.token=t},async storeUser(t){e.user=t},clear(){return e.token=void 0,e.user=void 0,Promise.resolve(void 0)}}}())}}class F{constructor(){h(this,"cacheStorage");this.cacheStorage=new V().generateCache}async setToken(e){await this.cacheStorage.storeToken(e)}async setUser(e){await this.cacheStorage.storeUser(e)}async getUser(){return this.cacheStorage.getUser()}async getToken(){return this.cacheStorage.getToken()}async clear(){await this.cacheStorage.clear()}}const S=5*6e4,j=["code","state"],P=i=>i.split("?")[0],q=i=>i.split("?")[1],I=i=>{let e=i;if(!i.startsWith("?"))try{e=new URL(i).search}catch{}return new URLSearchParams(e)},B=(i=window.location.href,e)=>{if(e!=null){const n=P(e),r=P(i??"");if(n!==r)return!1}const t=I(i);for(const n of j)if(!t.has(n))return!1;return!0},$=i=>({id:i.sub,name:`${i.given_name} ${i.family_name}`,given_name:i.given_name,family_name:i.family_name,picture:i.picture,email:i.email,email_verified:i.email_verified}),H="@TID_COOKIE";class z{get(e){const t=C.get(e);if(t==null)throw new Error("Cookie not found");return JSON.parse(t)}set(e,t,n){let r={};window.location.protocol==="https:"&&(r={secure:!0,sameSite:"none"}),n!=null&&n.expires&&(r.expires=n.expires),n!=null&&n.domain&&(r.domain=n.domain),C.set(e,JSON.stringify(t),r)}remove(e,t){const n={};t!=null&&t.domain&&(n.domain=t.domain),C.remove(e,n)}}class Q{constructor(e){h(this,"cookieKey");h(this,"cookiesStorage");this.cookieKey=`${H}.${e.clientId}`,this.cookiesStorage=new z}save(e){this.cookiesStorage.set(this.cookieKey,e,{expires:1})}get(){try{return this.cookiesStorage.get(this.cookieKey)}catch{return}}clear(){this.cookiesStorage.remove(this.cookieKey)}}class R extends Error{}class M extends Error{}class J extends Error{}const u="@trimble-oss/trimble-id-react",g="1.0.0-rc.2",X={configurationEndpoint:"",clientId:"",redirectUrl:"",logoutRedirectUrl:"",scopes:[]};class x{constructor(e){h(this,"tokenProvider");h(this,"cacheManager");h(this,"cookiesManager");h(this,"clientId");h(this,"redirectUrl");h(this,"analyticshttpclient");const{config:t=X}=e;if(this.redirectUrl=t.redirectUrl,t.configurationEndpoint==null||t.configurationEndpoint=="")throw new Error("Configuration endpoint not defined");if(t.clientId==null||t.clientId=="")throw new Error("Consumer key is not defined");this.cookiesManager=new Q({clientId:t.clientId});const n=this.cookiesManager.get(),r=new c.OpenIdEndpointProvider(t.configurationEndpoint);let d=new c.AuthorizationCodeGrantTokenProvider(r,t.clientId,t.redirectUrl).WithScopes(t.scopes);t.logoutRedirectUrl&&(d=d.WithLogoutRedirect(t.logoutRedirectUrl)),(n==null?void 0:n.code_verifier)!=null&&(d=d.WithProofKeyForCodeExchange(n.code_verifier)),this.tokenProvider=d,this.cacheManager=new F,this.clientId=t.clientId,this.analyticshttpclient=c.AnalyticsHttpClient,this.analyticshttpclient.sendInitEvent("TIDClient",this.clientId,u,g)}async loginWithRedirect(e){this.analyticshttpclient.sendMethodEvent(this.loginWithRedirect.name,this.clientId,u,g);const{onRedirect:t}=e||{},n=c.AuthorizationCodeGrantTokenProvider.GenerateCodeVerifier();this.cookiesManager.save({code_verifier:n}),this.tokenProvider=this.tokenProvider.WithProofKeyForCodeExchange(n);const r=await this.tokenProvider.GetOAuthRedirect("state");t!=null?t(r):window.location.assign(r)}async handleCallback(e=window.location.href){const t=this.cookiesManager.get();if(t==null||(t==null?void 0:t.code_verifier)==null)throw new J("Code verifier not available");const n=q(e),r=I(e),d=r.get("identity_provider")??"",T=r.get("state")??"";return await this.tokenProvider.ValidateQuery(n),await this.generateToken(d),{authState:T}}async generateToken(e){var s,w;const t=await this.tokenProvider.RetrieveToken(),n=await this.tokenProvider.RetrieveRefreshToken(),r=await this.tokenProvider.RetrieveIdToken(),d=await this.tokenProvider.RetrieveTokenExpiry(),v=new Date(d).getTime(),m=(w=(s=this.tokenProvider)==null?void 0:s._scopes)==null?void 0:w.join(" ");await this.cacheManager.setToken({scope:m,state:"",session_state:"",identity_provider:e,token_type:"bearer",access_token:t,refresh_token:n,id_token:r,expires_at:v});const U=W(r),_=$(U);await this.cacheManager.setUser(_),await this.reloadCodeVerifier()}async reloadCodeVerifier(){const e=await this.tokenProvider.RetrieveCodeVerifier();this.cookiesManager.save({code_verifier:e}),this.tokenProvider=this.tokenProvider.WithProofKeyForCodeExchange(e)}async getUser(){return this.analyticshttpclient.sendMethodEvent(this.getUser.name,this.clientId,u,g),await this.cacheManager.getUser()}async getAccessTokenSilently(){this.analyticshttpclient.sendMethodEvent(this.getAccessTokenSilently.name,this.clientId,u,g);let e=await this.cacheManager.getToken();if(e==null)throw this.analyticshttpclient.sendExceptionEvent(this.getAccessTokenSilently.name,"No token available",this.clientId,u,g),new M("No token available");const t=new Date(new Date().getTime()+S);if((e==null?void 0:e.expires_at)==null||(e==null?void 0:e.expires_at)<t.getTime()){try{await this.tokenProvider.RetrieveToken()}catch(n){throw this.analyticshttpclient.sendExceptionEvent(this.getAccessTokenSilently.name,n.message,this.clientId,u,g),new R(n.message)}await this.generateToken((e==null?void 0:e.identity_provider)??""),e=await this.cacheManager.getToken()}return(e==null?void 0:e.access_token)||""}async getTokens(){this.analyticshttpclient.sendMethodEvent(this.getTokens.name,this.clientId,u,g);let e=await this.cacheManager.getToken();if(e==null)throw this.analyticshttpclient.sendExceptionEvent(this.getTokens.name,"No token available",this.clientId,u,g),new M("No token available");const t=new Date(new Date().getTime()+S);if((e==null?void 0:e.expires_at)==null||(e==null?void 0:e.expires_at)<t.getTime()){try{await this.tokenProvider.RetrieveToken()}catch(n){throw this.analyticshttpclient.sendExceptionEvent(this.getTokens.name,n.message,this.clientId,u,g),new R(n.message)}await this.generateToken((e==null?void 0:e.identity_provider)??""),e=await this.cacheManager.getToken()}return{access_token:(e==null?void 0:e.access_token)||"",expires_at:(e==null?void 0:e.expires_at)||0,id_token:(e==null?void 0:e.id_token)||""}}async logout(e){this.analyticshttpclient.sendMethodEvent(this.logout.name,this.clientId,u,g);const{onRedirect:t,disabledAutoRedirect:n}=e||{};this.cacheManager&&await this.cacheManager.clear(),this.cookiesManager&&this.cookiesManager.clear();const r=await this.tokenProvider.GetOAuthLogoutRedirect("state");if(t!=null)return t(r);n||window.location.assign(r)}async checkSession(){try{await this.getAccessTokenSilently()}catch{return!1}return!0}async loadUserSession(){await this.loadCacheSessionIntoSDK(),await this.checkSession()||await this.cacheManager.clear()}async loadCacheSessionIntoSDK(){const e=await this.cacheManager.getToken();if(e==null)return;const t=e.access_token,n=e.refresh_token||"",r=e.id_token,d=e.expires_at;this.tokenProvider=this.tokenProvider.WithAccessToken(t,d).WithRefreshToken(n).WithIdToken(r)}getBearerTokenHttpClient(e){return new c.BearerTokenHttpClientProvider(this.tokenProvider,e)}getRedirectUrl(){return this.redirectUrl}}const E=l.createContext(null),A=()=>l.useContext(E)??{},Y=(i,e)=>{switch(e.type){case"INIT":return{...i,isLoading:!1,isAuthenticated:e.user!=null,user:e.user,error:void 0};case"GET_TOKENS_COMPLETE":case"HANDLE_CALLBACK_COMPLETE":case"GET_ACCESS_TOKEN_COMPLETE":return{...i,isLoading:!1,isAuthenticated:e.user!=null,user:e.user,error:void 0};case"LOGOUT":return{...i,isAuthenticated:!1,user:void 0};case"ERROR":return{...i,isLoading:!1,error:e.error}}},Z={isLoading:!0,isAuthenticated:!1},ee=i=>{if(i==null||Object.keys(i).length<=0)return!0;const e=Object.keys(i);for(const t of e)if(i[t]!=null&&i[t]!=="")return!1;return!0},te=i=>!ee(i.config),ie=i=>{const{children:e,configurationEndpoint:t,clientId:n,redirectUrl:r,logoutRedirectUrl:d,scopes:T,onRedirectCallback:v,checkRedirectUrlMatch:m}=i;if(l.useContext(E)!=null)throw new Error("TID Provider already defined");const _={config:{configurationEndpoint:t??"",clientId:n??"",redirectUrl:r??"",logoutRedirectUrl:d??"",scopes:T??[""]}},[s]=l.useState(i.tidClient??new x(_)),[w,y]=l.useReducer(Y,Z),O=l.useRef(!1),oe=l.useMemo(()=>m?s.getRedirectUrl():void 0,[m,s]);l.useEffect(()=>{O.current||(i.tidClient!=null&&te({config:{configurationEndpoint:t,clientId:n,redirectUrl:r,logoutRedirectUrl:d,scopes:T}})&&console.warn("When TID client is pass as prop, any client configuration property sent directly to the TID Provider component will be ignored"),O.current=!0,(async()=>{try{let a;if(B(void 0,oe)){const{authState:f}=await s.handleCallback();a=await s.getUser(),v!=null&&v(f)}else await s.loadUserSession(),a=await s.getUser();y({type:"INIT",user:a})}catch(a){let f=a;typeof a=="string"&&(f=new Error(a)),y({type:"ERROR",error:f})}})())},[s,v]);const D=l.useCallback(async()=>{const a=await s.getAccessTokenSilently(),f=await s.getUser();return y({type:"GET_ACCESS_TOKEN_COMPLETE",user:f}),a},[s]),b=l.useCallback(async()=>{const a=await s.getTokens(),f=await s.getUser();return y({type:"GET_TOKENS_COMPLETE",user:f}),a},[s]),L=l.useCallback(async a=>{await s.loginWithRedirect(a)},[s]),K=l.useCallback(async a=>{await s.logout(a),(a==null?void 0:a.disabledAutoRedirect)!=null&&a.disabledAutoRedirect&&y({type:"LOGOUT"})},[s]),N=l.useCallback(async a=>{const{authState:f}=await s.handleCallback(a),ce=await s.getUser();return y({type:"HANDLE_CALLBACK_COMPLETE",user:ce}),{authState:f}},[s]),ae=l.useMemo(()=>({...w,getAccessTokenSilently:D,getTokens:b,loginWithRedirect:L,handleCallback:N,logout:K}),[w,D,b,L,N,K]);return p.jsx(E.Provider,{value:ae,children:e})},ne=A,re=ie,se=({renderComponent:i,loader:e})=>{const{isAuthenticated:t,isLoading:n,loginWithRedirect:r}=A();return l.useEffect(()=>{!n&&!t&&(async()=>await r())()},[n,t,r]),t?i:e||p.jsx(p.Fragment,{})};o.AuthenticationGuard=se,o.TIDClient=x,o.TIDContext=E,o.TIDProvider=re,o.useAuth=ne,Object.defineProperty(o,Symbol.toStringTag,{value:"Module"})});
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  {
3
3
  "name": "@trimble-oss/trimble-id-react",
4
4
  "private": false,
5
- "version": "0.1.1",
5
+ "version": "1.0.0-rc.2",
6
6
  "homepage": "https://github.com/trimble-oss/trimble-id-sdk-docs-for-react",
7
7
  "author": "Trimble developers <developers@trimble.com>",
8
8
  "license": "MIT",
@@ -13,7 +13,7 @@
13
13
  "type": "module",
14
14
  "scripts": {
15
15
  "build": "tsc && vite build",
16
- "test": "jest",
16
+ "test": "jest --coverage",
17
17
  "docs": "typedoc --out ./docs/documentation ./src/ --tsconfig ./tsconfig.json",
18
18
  "lint": "eslint --ext ts,tsx --report-unused-disable-directives",
19
19
  "lint:fix": "eslint --fix 'src/**/*.{jsx,ts,tsx}'",
@@ -1,46 +0,0 @@
1
- interface CacheKeyOptions {
2
- /**
3
- * Client id of the application created in trimble developer console
4
- * @type {string}
5
- */
6
- client_id: string;
7
- }
8
- /** Class representing the caching keys for storing and retrieving user and token from auth */
9
- export declare class CacheKey {
10
- /**
11
- * Client id of the application created in trimble developer console
12
- * @type {string}
13
- */
14
- private readonly clientId;
15
- /**
16
- * Prefix value of the key, by default the prefix is based on the constant PREFIX_KEY
17
- * @type {string}
18
- */
19
- private readonly prefix;
20
- /**
21
- * Suffix value use it to generate the key to store and retrieve the token, by default the prefix is based on the constant AUTH_KEY
22
- * @type {string}
23
- */
24
- private readonly authSuffix;
25
- /**
26
- * Suffix value use it to generate the key to store and retrieve the user, by default the prefix is based on the constant USER_KEY
27
- * @type {string}
28
- */
29
- private readonly userSuffix;
30
- /**
31
- * Initialized the cache key
32
- * @param {CacheKeyOptions} cacheKeyOptions - Cache key options to edit the default values
33
- */
34
- constructor(cacheKeyOptions: CacheKeyOptions);
35
- /**
36
- * Get key to store/retrieve user
37
- * @return {string} Key for the user
38
- */
39
- getUserKey(): string;
40
- /**
41
- * Get key to store/retrieve token
42
- * @return {string} Key for the token
43
- */
44
- getAuthKey(): string;
45
- }
46
- export {};
@@ -1,67 +0,0 @@
1
- import { CacheStorage, TIDAuthToken, TIDUser } from '../../interfaces';
2
- import { CacheKey } from './CacheKey';
3
- export interface LocalStorageCacheOptions {
4
- /**
5
- * The cache key represents the keys for storing and retrieving user and token from auth
6
- * @type {CacheKey}
7
- */
8
- cacheKey: CacheKey;
9
- }
10
- /**
11
- * Class representing localstorage caching
12
- * NOTE: This type storage do not expired so it will persist even if the user close the browser
13
- */
14
- export declare class LocalStorageCache implements CacheStorage {
15
- /**
16
- * Local storage from the browser
17
- * @type {Storage}
18
- */
19
- private readonly localStorage;
20
- /**
21
- * The cache key represents the keys for storing and retrieving user and token from auth
22
- * @type {CacheKey}
23
- */
24
- private readonly cacheKey;
25
- /**
26
- * Initialized configuration to store information into local storage
27
- * @param {LocalStorageCacheOptions} options - Configuration for caching in localstorage
28
- */
29
- constructor(options: LocalStorageCacheOptions);
30
- /**
31
- * Get token store in localstorage
32
- * @return {Promise<TIDAuthToken | undefined>} - Token store in localstorage
33
- */
34
- getToken(): Promise<TIDAuthToken | undefined>;
35
- /**
36
- * Get user store in localstorage
37
- * @return {Promise<TIDUser | undefined>} - User store in localstorage
38
- */
39
- getUser(): Promise<TIDUser | undefined>;
40
- /**
41
- * Store token in localstorage
42
- * @param {TIDAuthToken} token - Token that you want to store in localstorage
43
- * @return {Promise<void>} Empty promise
44
- */
45
- storeToken(authToken: TIDAuthToken): Promise<void>;
46
- /**
47
- * Store user in cache
48
- * @param {TIDUser} user - User that you want to store in localstorage
49
- * @return {Promise<void>} Empty promise
50
- */
51
- storeUser(user: TIDUser): Promise<void>;
52
- /**
53
- * Get the full key from the cachekey for the user
54
- * @return {string} - Full key to get the token from the localstorage
55
- */
56
- getUserKey(): string;
57
- /**
58
- * Get the full key from the cachekey for the token
59
- * @return {string} - Full key to get the token from the localstorage
60
- */
61
- getAuthKey(): string;
62
- /**
63
- * The clear the cache from the localstorage
64
- * @return {Promise<void>} Empty promise
65
- */
66
- clear(): Promise<void>;
67
- }
@@ -1,67 +0,0 @@
1
- import { CacheStorage, TIDAuthToken, TIDUser } from '../../interfaces';
2
- import { CacheKey } from './CacheKey';
3
- export interface SessionStorageCacheOptions {
4
- /**
5
- * The cache key represents the keys for storing and retrieving user and token from auth
6
- * @type {CacheKey}
7
- */
8
- cacheKey: CacheKey;
9
- }
10
- /**
11
- * Class representing session storage caching
12
- * NOTE: This type storage is cleared when the page session ends
13
- */
14
- export declare class SessionStorageCache implements CacheStorage {
15
- /**
16
- * Session storage from the browser
17
- * @type {Storage}
18
- */
19
- private readonly sessionStorage;
20
- /**
21
- * The cache key represents the keys for storing and retrieving user and token from auth
22
- * @type {CacheKey}
23
- */
24
- private readonly cacheKey;
25
- /**
26
- * Initialized configuration to store information into session storage
27
- * @param {SessionStorageCacheOptions} options - Configuration for caching in session storage
28
- */
29
- constructor(options: SessionStorageCacheOptions);
30
- /**
31
- * Get token store in session storage
32
- * @return {Promise<TIDAuthToken | undefined>} - Token store in session storage
33
- */
34
- getToken(): Promise<TIDAuthToken | undefined>;
35
- /**
36
- * Get user store in session storage
37
- * @return {Promise<TIDUser | undefined>} - User store in session storage
38
- */
39
- getUser(): Promise<TIDUser | undefined>;
40
- /**
41
- * Store token in session storage
42
- * @param {TIDAuthToken} authToken - Token that you want to store in session storage
43
- * @return {Promise<void>} Empty promise
44
- */
45
- storeToken(authToken: TIDAuthToken): Promise<void>;
46
- /**
47
- * Store user in cache
48
- * @param {TIDUser} user - User that you want to store in session storage
49
- * @return {Promise<void>} Empty promise
50
- */
51
- storeUser(user: TIDUser): Promise<void>;
52
- /**
53
- * Get the full key from the cachekey for the user
54
- * @return {string} - Full key to get the token from the session storage
55
- */
56
- getUserKey(): string;
57
- /**
58
- * Get the full key from the cachekey for the token
59
- * @return {string} - Full key to get the token from the session storage
60
- */
61
- getAuthKey(): string;
62
- /**
63
- * The clear the cache from the session storage
64
- * @return {Promise<void>} Empty promise
65
- */
66
- clear(): Promise<void>;
67
- }
@@ -1,15 +0,0 @@
1
- /**
2
- * Default value of the prefix key use it to store the token and the user
3
- * @type {string}
4
- */
5
- export declare const PREFIX_KEY: string;
6
- /**
7
- * Default value of the suffix key use it to store the token
8
- * @type {string}
9
- */
10
- export declare const AUTH_KEY: string;
11
- /**
12
- * Default value of the suffix key use it to store the user
13
- * @type {string}
14
- */
15
- export declare const USER_KEY: string;