/* COPYRIGHT Esri - https://js.arcgis.com/5.1.0/LICENSE.txt */
import t from"../request.js";const e="esriJSAPIOAuth";class s{constructor(t,e){this.oAuthInfo=null,this.storage=null,this.appId=null,this.codeVerifier=null,this.expires=null,this.refreshToken=null,this.ssl=null,this.stateUID=null,this.token=null,this.userId=null,this.oAuthInfo=t,this.storage=e,this._init()}isValid(){let t=!1;if(this.oAuthInfo&&this.userId&&(this.refreshToken||this.token))if(null==this.expires&&this.refreshToken)t=!0;else if(this.expires){const e=Date.now();if(this.expires>e){(this.expires-e)/1e3>60*this.oAuthInfo.minTimeUntilExpiration&&(t=!0)}}return t}save(){if(!this.storage)return!1;const t=this._load(),s=this.oAuthInfo;if(s?.authNamespace&&s.portalUrl){let r=t[s.authNamespace];r||(r=t[s.authNamespace]={}),this.appId||(this.appId=s.appId),r[s.portalUrl]={appId:this.appId,codeVerifier:this.codeVerifier,expires:this.expires,refreshToken:this.refreshToken,ssl:this.ssl,stateUID:this.stateUID,token:this.token,userId:this.userId};try{this.storage.setItem(e,JSON.stringify(t))}catch(i){return console.warn(i),!1}return!0}return!1}destroy(){const s=this._load(),i=this.oAuthInfo;if(i?.appId&&i?.portalUrl&&(null==this.expires||this.expires>Date.now())&&(this.refreshToken||this.token)){const e=i.portalUrl.replace(/^http:/i,"https:")+"/sharing/rest/oauth2/revokeToken";t(e,{authMode:"anonymous",keepAlive:!0,method:"post",query:{f:"json",auth_token:this.refreshToken||this.token,client_id:i.appId,token_type_hint:this.refreshToken?"refresh_token":"access_token"}})}if(i?.authNamespace&&i.portalUrl&&this.storage){const t=s[i.authNamespace];if(t){delete t[i.portalUrl];try{this.storage.setItem(e,JSON.stringify(s))}catch(r){console.log(r)}}}i&&(i._oAuthCred=null,this.oAuthInfo=null)}_init(){const t=this._load(),e=this.oAuthInfo;if(e?.authNamespace&&e.portalUrl){let s=t[e.authNamespace];s&&(s=s[e.portalUrl],s&&(this.appId=s.appId,this.codeVerifier=s.codeVerifier,this.expires=s.expires,this.refreshToken=s.refreshToken,this.ssl=s.ssl,this.stateUID=s.stateUID,this.token=s.token,this.userId=s.userId))}}_load(){let t={};if(this.storage){const i=this.storage.getItem(e);if(i)try{t=JSON.parse(i)}catch(s){console.warn(s)}}return t}}s.prototype.declaredClass="esri.identity.OAuthCredential";export{s as default};
