react-box-tools
Version:
Box tools react components, utils and hooks
1 lines • 52.6 kB
JavaScript
"use strict";var ge=Object.defineProperty;var we=(d,e,t)=>e in d?ge(d,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):d[e]=t;var i=(d,e,t)=>we(d,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class y extends Error{constructor(t,s){super(t.error_description||t.error||"");i(this,"name",y.name);i(this,"error");i(this,"error_description");i(this,"error_uri");i(this,"state");i(this,"session_state");i(this,"url_state");if(this.form=s,!t.error)throw new Error("No error passed");this.error=t.error,this.error_description=t.error_description??null,this.error_uri=t.error_uri??null,this.state=t.userState,this.session_state=t.session_state??null,this.url_state=t.url_state}}class q extends Error{constructor(t){super(t);i(this,"name",q.name)}}const fe="10000000-1000-4000-8000-100000000000",V=d=>btoa([...new Uint8Array(d)].map(e=>String.fromCharCode(e)).join(""));class m{static _randomWord(){const e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]}static generateUUIDv4(){return fe.replace(/[018]/g,t=>(+t^m._randomWord()&15>>+t/4).toString(16)).replace(/-/g,"")}static generateCodeVerifier(){return m.generateUUIDv4()+m.generateUUIDv4()+m.generateUUIDv4()}static async generateCodeChallenge(e){if(!crypto.subtle)throw new Error("Crypto.subtle is available only HTTPS");try{const s=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",s);return V(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}catch(t){throw t}}static generateBasicAuth(e,t){const r=new TextEncoder().encode([e,t].join(":"));return V(r)}}class T{constructor(e){i(this,"_callbacks",[]);this._name=e}addHandler(e){return this._callbacks.push(e),()=>this.removeHandler(e)}removeHandler(e){const t=this._callbacks.lastIndexOf(e);t>=0&&this._callbacks.splice(t,1)}async raise(...e){for(const t of this._callbacks)await t(...e)}}class P extends Error{}P.prototype.name=P.name;function me(d){return decodeURIComponent(atob(d).replace(/(.)/g,(e,t)=>{let s=t.charCodeAt(0).toString(16).toUpperCase();return s.length<2&&(s="0"+s),"%"+s}))}function Se(d){let e=d.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw new Error("base64 incorrect length")}try{return me(e)}catch{return atob(e)}}function ye(d,e){if(typeof d!="string")throw new P("Must be a string");e||(e={});const t=e.header===!0?0:1,s=d.split(".")[t];if(typeof s!="string")throw new P(`Missing part #${t+1}`);let r;try{r=Se(s)}catch(n){throw new P(`Invalid base64 for part #${t+1} (${n.message})`)}try{return JSON.parse(r)}catch(n){throw new P(`Invalid json for part #${t+1} (${n.message})`)}}class ${static decode(e){try{return ye(e)}catch(t){throw t}}}class Q{static center({...e}){return e.width==null&&(e.width=[800,720,600,480].find(t=>t<=window.outerWidth/1.618)??360),e.left??(e.left=Math.max(0,Math.round(window.screenX+(window.outerWidth-e.width)/2))),e.height!=null&&(e.top??(e.top=Math.max(0,Math.round(window.screenY+(window.outerHeight-e.height)/2)))),e}static serialize(e){return Object.entries(e).filter(([,t])=>t!=null).map(([t,s])=>`${t}=${typeof s!="boolean"?s:s?"yes":"no"}`).join(",")}}class w extends T{constructor(){super(...arguments);i(this,"_timerHandle",null);i(this,"_expiration",0);i(this,"_callback",()=>{this._expiration<=w.getEpochTime()&&(this.cancel(),super.raise())})}static getEpochTime(){return Math.floor(Date.now()/1e3)}init(t){t=Math.max(Math.floor(t),1);const s=w.getEpochTime()+t;if(this.expiration===s&&this._timerHandle)return;this.cancel(),this._expiration=s;const r=Math.min(t,5);this._timerHandle=setInterval(this._callback,r*1e3)}get expiration(){return this._expiration}cancel(){this._timerHandle&&(clearInterval(this._timerHandle),this._timerHandle=null)}}class j{static readParams(e,t="query"){if(!e)throw new TypeError("Invalid URL");const r=new URL(e,"http://127.0.0.1")[t==="fragment"?"hash":"search"];return new URLSearchParams(r.slice(1))}static getReturnUrl(){const t=new URLSearchParams(window.location.search).get("returnUrl")??localStorage.getItem("returnUrl");if(t&&!t.startsWith(`${window.location.origin}/`))throw new Error("Return url needs to have same origin as the current page.");return t||`${window.location.origin}/`}}const F=";";class Y{constructor(e){i(this,"_expiringTimer",new w("Access token expiring"));i(this,"_expiredTimer",new w("Access token expired"));i(this,"_expiringNotificationTimeInSeconds");this._expiringNotificationTimeInSeconds=e.expiringNotificationTimeInSeconds}load(e){if(e.access_token&&e.expires_in!==void 0){const t=e.expires_in;if(t>0){let r=t-this._expiringNotificationTimeInSeconds;r<=0&&(r=1),this._expiringTimer.init(r)}else this._expiringTimer.cancel();const s=t+1;this._expiredTimer.init(s)}else this._expiringTimer.cancel(),this._expiredTimer.cancel()}unload(){this._expiringTimer.cancel(),this._expiredTimer.cancel()}addAccessTokenExpiring(e){return this._expiringTimer.addHandler(e)}removeAccessTokenExpiring(e){this._expiringTimer.removeHandler(e)}addAccessTokenExpired(e){return this._expiredTimer.addHandler(e)}removeAccessTokenExpired(e){this._expiredTimer.removeHandler(e)}}class Z{constructor(e,t,s,r,n){i(this,"_frame_origin");i(this,"_frame");i(this,"_timer",null);i(this,"_session_state",null);i(this,"_message",e=>{e.origin===this._frame_origin&&e.source===this._frame.contentWindow&&(e.data==="error"?this._stopOnError&&this.stop():e.data==="changed"?(this.stop(),this._callback()):console.debug(e.data))});this._callback=e,this._client_id=t,this._intervalInSeconds=r,this._stopOnError=n;const a=new URL(s);this._frame_origin=a.origin,this._frame=window.document.createElement("iframe"),this._frame.style.visibility="hidden",this._frame.style.position="fixed",this._frame.style.left="-1000px",this._frame.style.top="0",this._frame.width="0",this._frame.height="0",this._frame.src=a.href}load(){return new Promise(e=>{this._frame.onload=()=>{e()},window.document.body.appendChild(this._frame),window.addEventListener("message",this._message,!1)})}start(e){if(this._session_state===e)return;this.stop(),this._session_state=e;const t=()=>{!this._frame.contentWindow||!this._session_state||this._frame.contentWindow.postMessage(this._client_id+" "+this._session_state,this._frame_origin)};t(),this._timer=setInterval(t,this._intervalInSeconds*1e3)}stop(){this._session_state=null,this._timer&&(clearInterval(this._timer),this._timer=null)}}class K{constructor(){i(this,"_data",{})}clear(){this._data={}}getItem(e){return this._data[e]}setItem(e,t){this._data[e]=t}removeItem(e){delete this._data[e]}get length(){return Object.getOwnPropertyNames(this._data).length}key(e){return Object.getOwnPropertyNames(this._data)[e]}}class D{constructor(e=[],t=null,s={}){i(this,"_contentTypes",[]);this._jwtHandler=t,this._extraHeaders=s,this._contentTypes.push(...e,"application/json"),t&&this._contentTypes.push("application/jwt")}async fetchWithTimeout(e,t={}){const{timeoutInSeconds:s,...r}=t;if(!s)return await fetch(e,r);const n=new AbortController,a=setTimeout(()=>n.abort(),s*1e3);try{return await fetch(e,{...t,signal:n.signal})}catch(o){throw o instanceof DOMException&&o.name==="AbortError"?new q("Network timed out"):o}finally{clearTimeout(a)}}async getJson(e,{token:t,credentials:s}={}){const r={Accept:this._contentTypes.join(", ")};t&&(r.Authorization="Bearer "+t),this.appendExtraHeaders(r);let n;try{n=await this.fetchWithTimeout(e,{method:"GET",headers:r,credentials:s})}catch(c){throw c}const a=n.headers.get("Content-Type");if(a&&!this._contentTypes.find(c=>a.startsWith(c)))throw new Error(`Invalid response Content-Type: ${a??"undefined"}, from URL: ${e}`);if(n.ok&&this._jwtHandler&&(a!=null&&a.startsWith("application/jwt")))return await this._jwtHandler(await n.text());let o;try{o=await n.json()}catch(c){throw n.ok?c:new Error(`${n.statusText} (${n.status})`)}if(!n.ok)throw o.error?new y(o):new Error(`${n.statusText} (${n.status}): ${JSON.stringify(o)}`);return o}async postForm(e,{body:t,basicAuth:s,timeoutInSeconds:r,initCredentials:n,extraHeaders:a}){const o={Accept:this._contentTypes.join(", "),"Content-Type":"application/x-www-form-urlencoded",...a};s!==void 0&&(o.Authorization="Basic "+s),this.appendExtraHeaders(o);let c;try{c=await this.fetchWithTimeout(e,{method:"POST",headers:o,body:t,timeoutInSeconds:r,credentials:n})}catch(u){throw u}const h=c.headers.get("Content-Type");if(h&&!this._contentTypes.find(u=>h.startsWith(u)))throw new Error(`Invalid response Content-Type: ${h??"undefined"}, from URL: ${e}`);const l=await c.text();let _={};if(l)try{_=JSON.parse(l)}catch(u){throw c.ok?u:new Error(`${c.statusText} (${c.status})`)}if(!c.ok)throw _.error?new y(_,t):new Error(`${c.statusText} (${c.status}): ${JSON.stringify(_)}`);return _}appendExtraHeaders(e){const t=Object.keys(this._extraHeaders),s=["authorization","accept","content-type"];t.length!==0&&t.forEach(r=>{if(s.includes(r.toLocaleLowerCase()))return;const n=typeof this._extraHeaders[r]=="function"?this._extraHeaders[r]():this._extraHeaders[r];n&&n!==""&&(e[r]=n)})}}class ee{constructor(e){i(this,"_jsonService");i(this,"_metadataUrl");i(this,"_signingKeys",null);i(this,"_metadata",null);i(this,"_fetchRequestCredentials");this._settings=e,this._metadataUrl=this._settings.metadataUrl,this._jsonService=new D(["application/jwk-set+json"],null,this._settings.extraHeaders),this._settings.signingKeys&&(this._signingKeys=this._settings.signingKeys),this._settings.metadata&&(this._metadata=this._settings.metadata),this._settings.fetchRequestCredentials&&(this._fetchRequestCredentials=this._settings.fetchRequestCredentials)}resetSigningKeys(){this._signingKeys=null}async getMetadata(){if(this._metadata)return this._metadata;if(!this._metadataUrl)throw new Error("No authority or metadataUrl configured on settings");const e=await this._jsonService.getJson(this._metadataUrl,{credentials:this._fetchRequestCredentials});return this._metadata=Object.assign({},this._settings.metadataSeed,e),this._metadata}getIssuer(){return this._getMetadataProperty("issuer")}getAuthorizationEndpoint(){return this._getMetadataProperty("authorization_endpoint")}getUserInfoEndpoint(){return this._getMetadataProperty("userinfo_endpoint")}getTokenEndpoint(e=!0){return this._getMetadataProperty("token_endpoint",e)}getCheckSessionIframe(){return this._getMetadataProperty("check_session_iframe",!0)}getEndSessionEndpoint(){return this._getMetadataProperty("end_session_endpoint",!0)}getRevocationEndpoint(e=!0){return this._getMetadataProperty("revocation_endpoint",e)}getKeysEndpoint(e=!0){return this._getMetadataProperty("jwks_uri",e)}async _getMetadataProperty(e,t=!1){const s=await this.getMetadata();if(s[e]===void 0){if(t===!0){console.warn("Metadata does not contain optional property");return}throw new Error("Metadata does not contain property "+e)}return s[e]}async getSigningKeys(){if(this._signingKeys)return this._signingKeys;const e=await this.getKeysEndpoint(!1),t=await this._jsonService.getJson(e);if(!Array.isArray(t.keys))throw new Error("Missing keys on keyset");return this._signingKeys=t.keys,this._signingKeys}}class z{constructor({prefix:e="oidc.",store:t=localStorage}={}){i(this,"_store");i(this,"_prefix");this._store=t,this._prefix=e}async set(e,t){e=this._prefix+e,await this._store.setItem(e,t)}async get(e){return e=this._prefix+e,await this._store.getItem(e)}async remove(e){e=this._prefix+e;const t=await this._store.getItem(e);return await this._store.removeItem(e),t}async getAllKeys(){const e=await this._store.length,t=[];for(let s=0;s<e;s++){const r=await this._store.key(s);r&&r.indexOf(this._prefix)===0&&t.push(r.substr(this._prefix.length))}return t}}const ve="code",ke="openid",Te="client_secret_post",be=60*15;class H{constructor({authority:e,metadataUrl:t,metadata:s,signingKeys:r,metadataSeed:n,client_id:a,client_secret:o,response_type:c=ve,scope:h=ke,redirect_uri:l,post_logout_redirect_uri:_,client_authentication:u=Te,prompt:g,display:E,max_age:I,ui_locales:x,acr_values:R,resource:U,response_mode:S,filterProtocolClaims:p=!0,loadUserInfo:v=!1,staleStateAgeInSeconds:k=be,mergeClaimsStrategy:f={array:"replace"},disablePKCE:C=!1,stateStore:M,revokeTokenAdditionalContentTypes:L,fetchRequestCredentials:B,refreshTokenAllowedScope:he,extraQueryParams:le={},extraTokenParams:_e={},extraHeaders:ue={}}){i(this,"authority");i(this,"metadataUrl");i(this,"metadata");i(this,"metadataSeed");i(this,"signingKeys");i(this,"client_id");i(this,"client_secret");i(this,"response_type");i(this,"scope");i(this,"redirect_uri");i(this,"post_logout_redirect_uri");i(this,"client_authentication");i(this,"prompt");i(this,"display");i(this,"max_age");i(this,"ui_locales");i(this,"acr_values");i(this,"resource");i(this,"response_mode");i(this,"filterProtocolClaims");i(this,"loadUserInfo");i(this,"staleStateAgeInSeconds");i(this,"mergeClaimsStrategy");i(this,"stateStore");i(this,"extraQueryParams");i(this,"extraTokenParams");i(this,"extraHeaders");i(this,"revokeTokenAdditionalContentTypes");i(this,"fetchRequestCredentials");i(this,"refreshTokenAllowedScope");i(this,"disablePKCE");if(this.authority=e,t?this.metadataUrl=t:(this.metadataUrl=e,e&&(this.metadataUrl.endsWith("/")||(this.metadataUrl+="/"),this.metadataUrl+=".well-known/openid-configuration")),this.metadata=s,this.metadataSeed=n,this.signingKeys=r,this.client_id=a,this.client_secret=o,this.response_type=c,this.scope=h,this.redirect_uri=l,this.post_logout_redirect_uri=_,this.client_authentication=u,this.prompt=g,this.display=E,this.max_age=I,this.ui_locales=x,this.acr_values=R,this.resource=U,this.response_mode=S,this.filterProtocolClaims=p??!0,this.loadUserInfo=!!v,this.staleStateAgeInSeconds=k,this.mergeClaimsStrategy=f,this.disablePKCE=!!C,this.revokeTokenAdditionalContentTypes=L,this.fetchRequestCredentials=B||"same-origin",M)this.stateStore=M;else{const pe=typeof window<"u"?window.localStorage:new K;this.stateStore=new z({store:pe})}this.refreshTokenAllowedScope=he,this.extraQueryParams=le,this.extraTokenParams=_e,this.extraHeaders=ue}}class Ee{constructor(e,t){i(this,"_jsonService");i(this,"_getClaimsFromJwt",async e=>{try{return $.decode(e)}catch(t){throw t}});this._settings=e,this._metadataService=t,this._jsonService=new D(void 0,this._getClaimsFromJwt,this._settings.extraHeaders)}async getClaims(e){if(!e)throw new Error("No token passed");const t=await this._metadataService.getUserInfoEndpoint();return await this._jsonService.getJson(t,{token:e,credentials:this._settings.fetchRequestCredentials})}}class te{constructor(e,t){i(this,"_jsonService");this._settings=e,this._metadataService=t,this._jsonService=new D(this._settings.revokeTokenAdditionalContentTypes,null,this._settings.extraHeaders)}async exchangeCode({grant_type:e="authorization_code",redirect_uri:t=this._settings.redirect_uri,client_id:s=this._settings.client_id,client_secret:r=this._settings.client_secret,extraHeaders:n,...a}){if(!s)throw new Error("A client_id is required");if(!t)throw new Error("A redirect_uri is required");if(!a.code)throw new Error("A code is required");const o=new URLSearchParams({grant_type:e,redirect_uri:t});for(const[_,u]of Object.entries(a))u!=null&&o.set(_,u);let c;switch(this._settings.client_authentication){case"client_secret_basic":if(!r)throw new Error("A client_secret is required");c=m.generateBasicAuth(s,r);break;case"client_secret_post":o.append("client_id",s),r&&o.append("client_secret",r);break}const h=await this._metadataService.getTokenEndpoint(!1);return await this._jsonService.postForm(h,{body:o,basicAuth:c,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:n})}async exchangeCredentials({grant_type:e="password",client_id:t=this._settings.client_id,client_secret:s=this._settings.client_secret,scope:r=this._settings.scope,...n}){if(!t)throw new Error("A client_id is required");const a=new URLSearchParams({grant_type:e,scope:r});for(const[l,_]of Object.entries(n))_!=null&&a.set(l,_);let o;switch(this._settings.client_authentication){case"client_secret_basic":if(!s)throw new Error("A client_secret is required");o=m.generateBasicAuth(t,s);break;case"client_secret_post":a.append("client_id",t),s&&a.append("client_secret",s);break}const c=await this._metadataService.getTokenEndpoint(!1);return await this._jsonService.postForm(c,{body:a,basicAuth:o,initCredentials:this._settings.fetchRequestCredentials})}async exchangeRefreshToken({grant_type:e="refresh_token",client_id:t=this._settings.client_id,client_secret:s=this._settings.client_secret,timeoutInSeconds:r,extraHeaders:n,...a}){if(!t)throw new Error("A client_id is required");if(!a.refresh_token)throw new Error("A refresh_token is required");const o=new URLSearchParams({grant_type:e});for(const[_,u]of Object.entries(a))Array.isArray(u)?u.forEach(g=>o.append(_,g)):u!=null&&o.set(_,u);let c;switch(this._settings.client_authentication){case"client_secret_basic":if(!s)throw new Error("A client_secret is required");c=m.generateBasicAuth(t,s);break;case"client_secret_post":o.append("client_id",t),s&&o.append("client_secret",s);break}const h=await this._metadataService.getTokenEndpoint(!1);return await this._jsonService.postForm(h,{body:o,basicAuth:c,timeoutInSeconds:r,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:n})}async revoke(e){if(!e.token)throw new Error("A token is required");const t=await this._metadataService.getRevocationEndpoint(!1),s=new URLSearchParams;for(const[r,n]of Object.entries(e))n!=null&&s.set(r,n);s.set("client_id",this._settings.client_id),this._settings.client_secret&&s.set("client_secret",this._settings.client_secret),await this._jsonService.postForm(t,{body:s})}}class Ie{constructor(e,t,s){i(this,"_userInfoService");i(this,"_tokenClient");this._settings=e,this._metadataService=t,this._claimsService=s,this._userInfoService=new Ee(this._settings,this._metadataService),this._tokenClient=new te(this._settings,this._metadataService)}async validateSigninResponse(e,t,s){this._processSigninState(e,t),await this._processCode(e,t,s),e.isOpenId&&this._validateIdTokenAttributes(e),await this._processClaims(e,t==null?void 0:t.skipUserInfo,e.isOpenId)}async validateCredentialsResponse(e,t){e.isOpenId&&e.id_token&&this._validateIdTokenAttributes(e),await this._processClaims(e,t,e.isOpenId)}async validateRefreshResponse(e,t){e.userState=t.data,e.session_state??(e.session_state=t.session_state),e.scope??(e.scope=t.scope),e.isOpenId&&e.id_token&&this._validateIdTokenAttributes(e,t.id_token),e.id_token||(e.id_token=t.id_token,e.profile=t.profile);const s=e.isOpenId&&!!e.id_token;await this._processClaims(e,!1,s)}validateSignoutResponse(e,t){if(t.id!==e.state)throw new Error("State does not match");if(e.userState=t.data,e.error)throw new y(e)}_processSigninState(e,t){if(t.id!==e.state)throw new Error("State does not match");if(!t.client_id)throw new Error("No client_id on state");if(!t.authority)throw new Error("No authority on state");if(this._settings.authority!==t.authority)throw new Error("authority mismatch on settings vs. signin state");if(this._settings.client_id&&this._settings.client_id!==t.client_id)throw new Error("client_id mismatch on settings vs. signin state");if(e.userState=t.data,e.url_state=t.url_state,e.scope??(e.scope=t.scope),e.error)throw new y(e);if(t.code_verifier&&!e.code)throw new Error("Expected code in response")}async _processClaims(e,t=!1,s=!0){if(e.profile=this._claimsService.filterProtocolClaims(e.profile),t||!this._settings.loadUserInfo||!e.access_token)return;const r=await this._userInfoService.getClaims(e.access_token);if(s&&r.sub!==e.profile.sub)throw new Error("subject from UserInfo response does not match subject in ID Token");e.profile=this._claimsService.mergeClaims(e.profile,this._claimsService.filterProtocolClaims(r))}async _processCode(e,t,s){if(e.code){const r=await this._tokenClient.exchangeCode({client_id:t.client_id,client_secret:t.client_secret,code:e.code,redirect_uri:t.redirect_uri,code_verifier:t.code_verifier,extraHeaders:s,...t.extraTokenParams});Object.assign(e,r)}else console.debug("No code to process")}_validateIdTokenAttributes(e,t){const s=$.decode(e.id_token??"");if(!s.sub)throw new Error("ID Token is missing a subject claim");if(t){const r=$.decode(t);if(s.sub!==r.sub)throw new Error("sub in id_token does not match current sub");if(s.auth_time&&s.auth_time!==r.auth_time)throw new Error("auth_time in id_token does not match original auth_time");if(s.azp&&s.azp!==r.azp)throw new Error("azp in id_token does not match original azp");if(!s.azp&&r.azp)throw new Error("azp not in id_token, but present in original id_token")}e.profile=s}}class b{constructor(e){i(this,"id");i(this,"created");i(this,"request_type");i(this,"url_state");i(this,"data");this.id=e.id||m.generateUUIDv4(),this.data=e.data,e.created&&e.created>0?this.created=e.created:this.created=w.getEpochTime(),this.request_type=e.request_type,this.url_state=e.url_state}toStorageString(){return JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state})}static fromStorageString(e){return Promise.resolve(new b(JSON.parse(e)))}static async clearStaleState(e,t){const s=w.getEpochTime()-t,r=await e.getAllKeys();for(let n=0;n<r.length;n++){const a=r[n],o=await e.get(a);let c=!1;if(o)try{(await b.fromStorageString(o)).created<=s&&(c=!0)}catch{c=!0}else c=!0;c&&e.remove(a)}}}class O extends b{constructor(t){super(t);i(this,"code_verifier");i(this,"code_challenge");i(this,"authority");i(this,"client_id");i(this,"redirect_uri");i(this,"scope");i(this,"client_secret");i(this,"extraTokenParams");i(this,"response_mode");i(this,"skipUserInfo");this.code_verifier=t.code_verifier,this.code_challenge=t.code_challenge,this.authority=t.authority,this.client_id=t.client_id,this.redirect_uri=t.redirect_uri,this.scope=t.scope,this.client_secret=t.client_secret,this.extraTokenParams=t.extraTokenParams,this.response_mode=t.response_mode,this.skipUserInfo=t.skipUserInfo}static async create(t){const s=t.code_verifier===!0?m.generateCodeVerifier():t.code_verifier||void 0,r=s?await m.generateCodeChallenge(s):void 0;return new O({...t,code_verifier:s,code_challenge:r})}toStorageString(){return JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state,code_verifier:this.code_verifier,authority:this.authority,client_id:this.client_id,redirect_uri:this.redirect_uri,scope:this.scope,client_secret:this.client_secret,extraTokenParams:this.extraTokenParams,response_mode:this.response_mode,skipUserInfo:this.skipUserInfo})}static fromStorageString(t){const s=JSON.parse(t);return O.create(s)}}class J{constructor(e){i(this,"url");i(this,"state");this.url=e.url,this.state=e.state}static async create({url:e,authority:t,client_id:s,redirect_uri:r,response_type:n,scope:a,state_data:o,response_mode:c,request_type:h,client_secret:l,nonce:_,url_state:u,resource:g,skipUserInfo:E,extraQueryParams:I,extraTokenParams:x,disablePKCE:R,...U}){if(!e)throw new Error("url");if(!s)throw new Error("client_id");if(!r)throw new Error("redirect_uri");if(!n)throw new Error("response_type");if(!a)throw new Error("scope");if(!t)throw new Error("authority");const S=await O.create({data:o,request_type:h,url_state:u,code_verifier:!R,client_id:s,authority:t,redirect_uri:r,response_mode:c,client_secret:l,scope:a,extraTokenParams:x,skipUserInfo:E}),p=new URL(e);p.searchParams.append("client_id",s),p.searchParams.append("redirect_uri",r),p.searchParams.append("response_type",n),p.searchParams.append("scope",a),_&&p.searchParams.append("nonce",_);let v=S.id;u&&(v=`${v}${F}${u}`),p.searchParams.append("state",v),S.code_challenge&&(p.searchParams.append("code_challenge",S.code_challenge),p.searchParams.append("code_challenge_method","S256")),g&&(Array.isArray(g)?g:[g]).forEach(f=>p.searchParams.append("resource",f));for(const[k,f]of Object.entries({response_mode:c,...U,...I}))f!=null&&p.searchParams.append(k,f.toString());return new J({url:p.href,state:S})}}const xe="openid";class N{constructor(e){i(this,"state");i(this,"session_state");i(this,"error");i(this,"error_description");i(this,"error_uri");i(this,"code");i(this,"id_token");i(this,"access_token","");i(this,"token_type","");i(this,"refresh_token");i(this,"scope");i(this,"expires_at");i(this,"userState");i(this,"url_state");i(this,"profile",{});if(this.state=e.get("state"),this.session_state=e.get("session_state"),this.state){const t=decodeURIComponent(this.state).split(F);this.state=t[0],t.length>1&&(this.url_state=t.slice(1).join(F))}this.error=e.get("error"),this.error_description=e.get("error_description"),this.error_uri=e.get("error_uri"),this.code=e.get("code")}get expires_in(){if(this.expires_at!==void 0)return this.expires_at-w.getEpochTime()}set expires_in(e){typeof e=="string"&&(e=Number(e)),e!==void 0&&e>=0&&(this.expires_at=Math.floor(e)+w.getEpochTime())}get isOpenId(){var e;return((e=this.scope)==null?void 0:e.split(" ").includes(xe))||!!this.id_token}}class Re{constructor({url:e,state_data:t,id_token_hint:s,post_logout_redirect_uri:r,extraQueryParams:n,request_type:a,client_id:o}){i(this,"url");i(this,"state");if(!e)throw new Error("url");const c=new URL(e);s&&c.searchParams.append("id_token_hint",s),o&&c.searchParams.append("client_id",o),r&&(c.searchParams.append("post_logout_redirect_uri",r),t&&(this.state=new b({data:t,request_type:a}),c.searchParams.append("state",this.state.id)));for(const[h,l]of Object.entries({...n}))l!=null&&c.searchParams.append(h,l.toString());this.url=c.href}}class se{constructor(e){i(this,"state");i(this,"error");i(this,"error_description");i(this,"error_uri");i(this,"userState");this.state=e.get("state"),this.error=e.get("error"),this.error_description=e.get("error_description"),this.error_uri=e.get("error_uri")}}const Ue=["nbf","jti","auth_time","nonce","acr","amr","azp","at_hash"],Ce=["sub","iss","aud","exp","iat"];class Pe{constructor(e){this._settings=e}filterProtocolClaims(e){const t={...e};if(this._settings.filterProtocolClaims){let s;Array.isArray(this._settings.filterProtocolClaims)?s=this._settings.filterProtocolClaims:s=Ue;for(const r of s)Ce.includes(r)||delete t[r]}return t}mergeClaims(e,t){const s={...e};for(const[r,n]of Object.entries(t))if(s[r]!==n)if(Array.isArray(s[r])||Array.isArray(n))if(this._settings.mergeClaimsStrategy.array=="replace")s[r]=n;else{const a=Array.isArray(s[r])?s[r]:[s[r]];for(const o of Array.isArray(n)?n:[n])a.includes(o)||a.push(o);s[r]=a}else typeof s[r]=="object"&&typeof n=="object"?s[r]=this.mergeClaims(s[r],n):s[r]=n;return s}}class ie{constructor(e,t){i(this,"settings");i(this,"metadataService");i(this,"_claimsService");i(this,"_validator");i(this,"_tokenClient");this.settings=e instanceof H?e:new H(e),this.metadataService=t??new ee(this.settings),this._claimsService=new Pe(this.settings),this._validator=new Ie(this.settings,this.metadataService,this._claimsService),this._tokenClient=new te(this.settings,this.metadataService)}async createSigninRequest({state:e,request:t,request_uri:s,request_type:r,id_token_hint:n,login_hint:a,skipUserInfo:o,nonce:c,url_state:h,response_type:l=this.settings.response_type,scope:_=this.settings.scope,redirect_uri:u=this.settings.redirect_uri,prompt:g=this.settings.prompt,display:E=this.settings.display,max_age:I=this.settings.max_age,ui_locales:x=this.settings.ui_locales,acr_values:R=this.settings.acr_values,resource:U=this.settings.resource,response_mode:S=this.settings.response_mode,extraQueryParams:p=this.settings.extraQueryParams,extraTokenParams:v=this.settings.extraTokenParams}){if(l!=="code")throw new Error("Only the Authorization Code flow (with PKCE) is supported");const k=await this.metadataService.getAuthorizationEndpoint(),f=await J.create({url:k,authority:this.settings.authority,client_id:this.settings.client_id,redirect_uri:u,response_type:l,scope:_,state_data:e,url_state:h,prompt:g,display:E,max_age:I,ui_locales:x,id_token_hint:n,login_hint:a,acr_values:R,resource:U,request:t,request_uri:s,extraQueryParams:p,extraTokenParams:v,request_type:r,response_mode:S,client_secret:this.settings.client_secret,skipUserInfo:o,nonce:c,disablePKCE:this.settings.disablePKCE});await this.clearStaleState();const C=f.state;return await this.settings.stateStore.set(C.id,C.toStorageString()),f}async readSigninResponseState(e,t=!1){const s=new N(j.readParams(e,this.settings.response_mode));if(!s.state)throw new Error("No state in response");const r=await this.settings.stateStore[t?"remove":"get"](s.state);if(!r)throw new Error("No matching state found in storage");return{state:await O.fromStorageString(r),response:s}}async processSigninResponse(e,t){const{state:s,response:r}=await this.readSigninResponseState(e,!0);return await this._validator.validateSigninResponse(r,s,t),r}async processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:s=!1,extraTokenParams:r={}}){const n=await this._tokenClient.exchangeCredentials({username:e,password:t,...r}),a=new N(new URLSearchParams);return Object.assign(a,n),await this._validator.validateCredentialsResponse(a,s),a}async useRefreshToken({state:e,redirect_uri:t,resource:s,timeoutInSeconds:r,extraHeaders:n,extraTokenParams:a}){var l;let o;if(this.settings.refreshTokenAllowedScope===void 0)o=e.scope;else{const _=this.settings.refreshTokenAllowedScope.split(" ");o=(((l=e.scope)==null?void 0:l.split(" "))||[]).filter(g=>_.includes(g)).join(" ")}const c=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:o,redirect_uri:t,resource:s,timeoutInSeconds:r,extraHeaders:n,...a}),h=new N(new URLSearchParams);return Object.assign(h,c),await this._validator.validateRefreshResponse(h,{...e,scope:o}),h}async createSignoutRequest({state:e,id_token_hint:t,client_id:s,request_type:r,post_logout_redirect_uri:n=this.settings.post_logout_redirect_uri,extraQueryParams:a=this.settings.extraQueryParams}={}){const o=await this.metadataService.getEndSessionEndpoint();if(!o)throw new Error("No end session endpoint");!s&&n&&!t&&(s=this.settings.client_id);const c=new Re({url:o,id_token_hint:t,client_id:s,post_logout_redirect_uri:n,state_data:e,extraQueryParams:a,request_type:r});await this.clearStaleState();const h=c.state;return h&&await this.settings.stateStore.set(h.id,h.toStorageString()),c}async readSignoutResponseState(e,t=!1){const s=new se(j.readParams(e,this.settings.response_mode));if(!s.state){if(s.error)throw new y(s);return{state:void 0,response:s}}const r=await this.settings.stateStore[t?"remove":"get"](s.state);if(!r)throw new Error("No matching state found in storage");return{state:await b.fromStorageString(r),response:s}}async processSignoutResponse(e){const{state:t,response:s}=await this.readSignoutResponseState(e,!0);return t?this._validator.validateSignoutResponse(s,t):console.debug("No state from storage"),s}clearStaleState(){return b.clearStaleState(this.settings.stateStore,this.settings.staleStateAgeInSeconds)}async revokeToken(e,t){return await this._tokenClient.revoke({token:e,token_type_hint:t})}}class re{constructor(e){i(this,"_sub");i(this,"_checkSessionIFrame");i(this,"_start",async e=>{const t=e.session_state;if(t){if(e.profile?this._sub=e.profile.sub:this._sub=void 0,this._checkSessionIFrame){this._checkSessionIFrame.start(t);return}try{const s=await this._userManager.metadataService.getCheckSessionIframe();if(s){const r=this._userManager.settings.client_id,n=this._userManager.settings.checkSessionIntervalInSeconds,a=this._userManager.settings.stopCheckSessionOnError,o=new Z(this._callback,r,s,n,a);await o.load(),this._checkSessionIFrame=o,o.start(t)}else console.warn("no check session iframe found in the metadata")}catch(s){console.error("Error from getCheckSessionIframe:",s instanceof Error?s.message:s)}}});i(this,"_stop",()=>{if(this._sub=void 0,this._checkSessionIFrame&&this._checkSessionIFrame.stop(),this._userManager.settings.monitorAnonymousSession){const e=setInterval(async()=>{clearInterval(e);try{const t=await this._userManager.querySessionStatus();if(t){const s={session_state:t.session_state,profile:t.sub?{sub:t.sub}:null};this._start(s)}}catch(t){console.error("error from querySessionStatus",t instanceof Error?t.message:t)}},1e3)}});i(this,"_callback",async()=>{try{const e=await this._userManager.querySessionStatus();let t=!0;e&&this._checkSessionIFrame?e.sub===this._sub?(t=!1,this._checkSessionIFrame.start(e.session_state),await this._userManager.events._raiseUserSessionChanged()):console.debug("different subject signed into OP",e.sub):console.debug("subject no longer signed into OP"),t?this._sub?await this._userManager.events._raiseUserSignedOut():await this._userManager.events._raiseUserSignedIn():console.debug("no change in session detected, no event to raise")}catch{this._sub&&await this._userManager.events._raiseUserSignedOut()}});if(this._userManager=e,!e)throw new Error("No user manager passed");this._userManager.events.addUserLoaded(this._start),this._userManager.events.addUserUnloaded(this._stop),this._init().catch(t=>{console.error(t)})}async _init(){const e=await this._userManager.getUser();if(e)this._start(e);else if(this._userManager.settings.monitorAnonymousSession){const t=await this._userManager.querySessionStatus();if(t){const s={session_state:t.session_state,profile:t.sub?{sub:t.sub}:null};this._start(s)}}}}class A{constructor(e){i(this,"id_token");i(this,"session_state");i(this,"access_token");i(this,"refresh_token");i(this,"token_type");i(this,"scope");i(this,"profile");i(this,"expires_at");i(this,"state");i(this,"url_state");this.id_token=e.id_token,this.session_state=e.session_state??null,this.access_token=e.access_token,this.refresh_token=e.refresh_token,this.token_type=e.token_type,this.scope=e.scope,this.profile=e.profile,this.expires_at=e.expires_at,this.state=e.userState,this.url_state=e.url_state}get expires_in(){if(this.expires_at!==void 0)return this.expires_at-w.getEpochTime()}set expires_in(e){e!==void 0&&(this.expires_at=Math.floor(e)+w.getEpochTime())}get expired(){const e=this.expires_in;if(e!==void 0)return e<=0}get scopes(){var e;return((e=this.scope)==null?void 0:e.split(" "))??[]}toStorageString(){return JSON.stringify({id_token:this.id_token,session_state:this.session_state,access_token:this.access_token,refresh_token:this.refresh_token,token_type:this.token_type,scope:this.scope,profile:this.profile,expires_at:this.expires_at})}static fromStorageString(e){return new A(JSON.parse(e))}}const G="oidc-client";class ne{constructor(){i(this,"_abort",new T("Window navigation aborted"));i(this,"_disposeHandlers",new Set);i(this,"_window",null)}async navigate(e){if(!this._window)throw new Error("Attempted to navigate on a disposed window");this._window.location.replace(e.url);const{url:t,keepOpen:s}=await new Promise((r,n)=>{const a=o=>{const c=o.data,h=e.scriptOrigin??window.location.origin;if(!(o.origin!==h||(c==null?void 0:c.source)!==G)){try{const l=j.readParams(c.url,e.response_mode).get("state");if(o.source!==this._window&&l!==e.state)return}catch{this._dispose(),n(new Error("Invalid response from window"))}r(c)}};window.addEventListener("message",a,!1),this._disposeHandlers.add(()=>window.removeEventListener("message",a,!1)),this._disposeHandlers.add(this._abort.addHandler(o=>{this._dispose(),n(o)}))});return this._dispose(),s||this.close(),{url:t}}_dispose(){for(const e of this._disposeHandlers)e();this._disposeHandlers.clear()}static _notifyParent(e,t,s=!1,r=window.location.origin){e.postMessage({source:G,url:t,keepOpen:s},r)}}const oe={location:!1,toolbar:!1,height:640,closePopupWindowAfterInSeconds:-1},ae="_blank",Ae=60,Oe=2,ce=10;class de extends H{constructor(t){const{popup_redirect_uri:s=t.redirect_uri,popup_post_logout_redirect_uri:r=t.post_logout_redirect_uri,popupWindowFeatures:n=oe,popupWindowTarget:a=ae,redirectMethod:o="assign",redirectTarget:c="self",iframeNotifyParentOrigin:h=t.iframeNotifyParentOrigin,iframeScriptOrigin:l=t.iframeScriptOrigin,silent_redirect_uri:_=t.redirect_uri,silentRequestTimeoutInSeconds:u=ce,automaticSilentRenew:g=!0,validateSubOnSilentRenew:E=!0,includeIdTokenInSilentRenew:I=!1,monitorSession:x=!1,monitorAnonymousSession:R=!1,checkSessionIntervalInSeconds:U=Oe,query_status_response_type:S="code",stopCheckSessionOnError:p=!0,revokeTokenTypes:v=["access_token","refresh_token"],revokeTokensOnSignout:k=!1,includeIdTokenInSilentSignout:f=!1,accessTokenExpiringNotificationTimeInSeconds:C=Ae,userStore:M}=t;super(t);i(this,"popup_redirect_uri");i(this,"popup_post_logout_redirect_uri");i(this,"popupWindowFeatures");i(this,"popupWindowTarget");i(this,"redirectMethod");i(this,"redirectTarget");i(this,"iframeNotifyParentOrigin");i(this,"iframeScriptOrigin");i(this,"silent_redirect_uri");i(this,"silentRequestTimeoutInSeconds");i(this,"automaticSilentRenew");i(this,"validateSubOnSilentRenew");i(this,"includeIdTokenInSilentRenew");i(this,"monitorSession");i(this,"monitorAnonymousSession");i(this,"checkSessionIntervalInSeconds");i(this,"query_status_response_type");i(this,"stopCheckSessionOnError");i(this,"revokeTokenTypes");i(this,"revokeTokensOnSignout");i(this,"includeIdTokenInSilentSignout");i(this,"accessTokenExpiringNotificationTimeInSeconds");i(this,"userStore");if(this.popup_redirect_uri=s,this.popup_post_logout_redirect_uri=r,this.popupWindowFeatures=n,this.popupWindowTarget=a,this.redirectMethod=o,this.redirectTarget=c,this.iframeNotifyParentOrigin=h,this.iframeScriptOrigin=l,this.silent_redirect_uri=_,this.silentRequestTimeoutInSeconds=u,this.automaticSilentRenew=g,this.validateSubOnSilentRenew=E,this.includeIdTokenInSilentRenew=I,this.monitorSession=x,this.monitorAnonymousSession=R,this.checkSessionIntervalInSeconds=U,this.stopCheckSessionOnError=p,this.query_status_response_type=S,this.revokeTokenTypes=v,this.revokeTokensOnSignout=k,this.includeIdTokenInSilentSignout=f,this.accessTokenExpiringNotificationTimeInSeconds=C,M)this.userStore=M;else{const L=typeof window<"u"?window.sessionStorage:new K;this.userStore=new z({store:L})}}}class W extends ne{constructor({silentRequestTimeoutInSeconds:t=ce}){super();i(this,"_frame");i(this,"_timeoutInSeconds");this._timeoutInSeconds=t,this._frame=W.createHiddenIframe(),this._window=this._frame.contentWindow}static createHiddenIframe(){const t=window.document.createElement("iframe");return t.style.visibility="hidden",t.style.position="fixed",t.style.left="-1000px",t.style.top="0",t.width="0",t.height="0",window.document.body.appendChild(t),t}async navigate(t){const s=setTimeout(()=>void this._abort.raise(new q("IFrame timed out without a response")),this._timeoutInSeconds*1e3);return this._disposeHandlers.add(()=>clearTimeout(s)),await super.navigate(t)}close(){var t;this._frame&&(this._frame.parentNode&&(this._frame.addEventListener("load",s=>{var n;const r=s.target;(n=r.parentNode)==null||n.removeChild(r),this._abort.raise(new Error("IFrame removed from DOM"))},!0),(t=this._frame.contentWindow)==null||t.location.replace("about:blank")),this._frame=null),this._window=null}static notifyParent(t,s){return super._notifyParent(window.parent,t,!1,s)}}class qe{constructor(e){this._settings=e}async prepare({silentRequestTimeoutInSeconds:e=this._settings.silentRequestTimeoutInSeconds}){return new W({silentRequestTimeoutInSeconds:e})}async callback(e){W.notifyParent(e,this._settings.iframeNotifyParentOrigin)}}const Me=500,Ne=1e3;class X extends ne{constructor({popupWindowTarget:t=ae,popupWindowFeatures:s={}}){super();i(this,"_window");const r=Q.center({...oe,...s});this._window=window.open(void 0,t,Q.serialize(r)),s.closePopupWindowAfterInSeconds&&s.closePopupWindowAfterInSeconds>0&&setTimeout(()=>{if(!this._window||typeof this._window.closed!="boolean"||this._window.closed){this._abort.raise(new Error("Popup blocked by user"));return}this.close()},s.closePopupWindowAfterInSeconds*Ne)}async navigate(t){var r;(r=this._window)==null||r.focus();const s=setInterval(()=>{(!this._window||this._window.closed)&&this._abort.raise(new Error("Popup closed by user"))},Me);return this._disposeHandlers.add(()=>clearInterval(s)),await super.navigate(t)}close(){this._window&&(this._window.closed||(this._window.close(),this._abort.raise(new Error("Popup closed")))),this._window=null}static notifyOpener(t,s){if(!window.opener)throw new Error("No window.opener. Can't complete notification.");return super._notifyParent(window.opener,t,s)}}class je{constructor(e){this._settings=e}async prepare({popupWindowFeatures:e=this._settings.popupWindowFeatures,popupWindowTarget:t=this._settings.popupWindowTarget}){return new X({popupWindowFeatures:e,popupWindowTarget:t})}async callback(e,{keepOpen:t=!1}){X.notifyOpener(e,t)}}class He{constructor(e){this._settings=e}async prepare({redirectMethod:e=this._settings.redirectMethod,redirectTarget:t=this._settings.redirectTarget}){let s=window.self;t==="top"&&(s=window.top??window.self);const r=s.location[e].bind(s.location);let n;return{navigate:async a=>{const o=new Promise((c,h)=>{n=h});return r(a.url),await o},close:()=>{n==null||n(new Error("Redirect aborted")),s.stop()}}}async callback(){}}class We extends Y{constructor(t){super({expiringNotificationTimeInSeconds:t.accessTokenExpiringNotificationTimeInSeconds});i(this,"_userLoaded",new T("User loaded"));i(this,"_userUnloaded",new T("User unloaded"));i(this,"_silentRenewError",new T("Silent renew error"));i(this,"_userSignedIn",new T("User signed in"));i(this,"_userSignedOut",new T("User signed out"));i(this,"_userSessionChanged",new T("User session changed"))}async load(t,s=!0){super.load(t),s&&await this._userLoaded.raise(t)}async unload(){super.unload(),await this._userUnloaded.raise()}addUserLoaded(t){return this._userLoaded.addHandler(t)}removeUserLoaded(t){return this._userLoaded.removeHandler(t)}addUserUnloaded(t){return this._userUnloaded.addHandler(t)}removeUserUnloaded(t){return this._userUnloaded.removeHandler(t)}addSilentRenewError(t){return this._silentRenewError.addHandler(t)}removeSilentRenewError(t){return this._silentRenewError.removeHandler(t)}async _raiseSilentRenewError(t){await this._silentRenewError.raise(t)}addUserSignedIn(t){return this._userSignedIn.addHandler(t)}removeUserSignedIn(t){this._userSignedIn.removeHandler(t)}async _raiseUserSignedIn(){await this._userSignedIn.raise()}addUserSignedOut(t){return this._userSignedOut.addHandler(t)}removeUserSignedOut(t){this._userSignedOut.removeHandler(t)}async _raiseUserSignedOut(){await this._userSignedOut.raise()}addUserSessionChanged(t){return this._userSessionChanged.addHandler(t)}removeUserSessionChanged(t){this._userSessionChanged.removeHandler(t)}async _raiseUserSessionChanged(){await this._userSessionChanged.raise()}}class Le{constructor(e){i(this,"_isStarted",!1);i(this,"_retryTimer",new w("Retry Silent Renew"));i(this,"_tokenExpiring",async()=>{try{await this._userManager.signinSilent()}catch(e){if(e instanceof q){this._retryTimer.init(5);return}await this._userManager.events._raiseSilentRenewError(e)}});this._userManager=e}async start(){if(!this._isStarted){this._isStarted=!0,this._userManager.events.addAccessTokenExpiring(this._tokenExpiring),this._retryTimer.addHandler(this._tokenExpiring);try{await this._userManager.getUser()}catch(e){console.error("getUser error",e)}}}stop(){this._isStarted&&(this._retryTimer.cancel(),this._retryTimer.removeHandler(this._tokenExpiring),this._userManager.events.removeAccessTokenExpiring(this._tokenExpiring),this._isStarted=!1)}}class $e{constructor(e){i(this,"data");i(this,"refresh_token");i(this,"id_token");i(this,"session_state");i(this,"scope");i(this,"profile");this.refresh_token=e.refresh_token,this.id_token=e.id_token,this.session_state=e.session_state,this.scope=e.scope,this.profile=e.profile,this.data=e.state}}class Fe{constructor(e,t,s,r){i(this,"settings");i(this,"_client");i(this,"_redirectNavigator");i(this,"_popupNavigator");i(this,"_iframeNavigator");i(this,"_events");i(this,"_silentRenewService");i(this,"_sessionMonitor");i(this,"ssr",typeof window>"u");i(this,"isAuthenticated",()=>{if(this.ssr)return;const e=JSON.parse(sessionStorage.getItem(`oidc.user:${this.settings.authority}:${this.settings.client_id}`));return!!e&&!!e.access_token});this.settings=new de(e),this._client=new ie(e),this._redirectNavigator=t??new He(this.settings),this._popupNavigator=s??new je(this.settings),this._iframeNavigator=r??new qe(this.settings),this._events=new We(this.settings),this._silentRenewService=new Le(this),this.settings.automaticSilentRenew&&this.startSilentRenew(),this._sessionMonitor=null,this.settings.monitorSession&&(this._sessionMonitor=new re(this))}get events(){return this._events}get metadataService(){return this._client.metadataService}async getUser(){const e=await this._loadUser();return e?(await this._events.load(e,!1),e):null}async removeUser(){await this.storeUser(null),await this._events.unload()}async signinRedirect(e={}){const{redirectMethod:t,...s}=e;if(this.isAuthenticated())return;localStorage.setItem("returnUrl",window.location.href);const r=await this._redirectNavigator.prepare({redirectMethod:t});await this._signinStart({request_type:"si:r",...s},r)}async signinRedirectCallback(e=window.location.href){const t=await this._signinEnd(e);return window.location.href=j.getReturnUrl(),localStorage.removeItem("returnUrl"),t}async signinResourceOwnerCredentials({username:e,password:t,skipUserInfo:s=!1}){const r=await this._client.processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:s,extraTokenParams:this.settings.extraTokenParams});return await this._buildUser(r)}async signinPopup(e={}){const{popupWindowFeatures:t,popupWindowTarget:s,...r}=e,n=this.settings.popup_redirect_uri;if(!n)throw new Error("No popup_redirect_uri configured");const a=await this._popupNavigator.prepare({popupWindowFeatures:t,popupWindowTarget:s});return await this._signin({request_type:"si:p",redirect_uri:n,display:"popup",...r},a)}async signinPopupCallback(e=window.location.href,t=!1){await this._popupNavigator.callback(e,{keepOpen:t})}async signinSilent(e={}){const{silentRequestTimeoutInSeconds:t,...s}=e;let r=await this._loadUser();if(r!=null&&r.refresh_token){const c=new $e(r);return await this._useRefreshToken({state:c,redirect_uri:s.redirect_uri,resource:s.resource,extraTokenParams:s.extraTokenParams,timeoutInSeconds:t})}const n=this.settings.silent_redirect_uri;if(!n)throw new Error("No silent_redirect_uri configured");let a;r&&this.settings.validateSubOnSilentRenew&&(a=r.profile.sub);const o=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:t});return r=await this._signin({request_type:"si:s",redirect_uri:n,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?r==null?void 0:r.id_token:void 0,...s},o,a),r}async _useRefreshToken(e){const t=await this._client.useRefreshToken({...e,timeoutInSeconds:this.settings.silentRequestTimeoutInSeconds}),s=new A({...e.state,...t});return await this.storeUser(s),await this._events.load(s),s}async signinSilentCallback(e=window.location.href){await this._iframeNavigator.callback(e)}async signinCallback(e=window.location.href){const{state:t}=await this._client.readSigninResponseState(e);switch(t.request_type){case"si:r":return await this.signinRedirectCallback(e);case"si:p":return await this.signinPopupCallback(e);case"si:s":return await this.signinSilentCallback(e);default:throw new Error("invalid response_type in state")}}async signoutCallback(e=window.location.href,t=!1){const{state:s}=await this._client.readSignoutResponseState(e);if(s)switch(s.request_type){case"so:r":await this.signoutRedirectCallback(e);break;case"so:p":await this.signoutPopupCallback(e,t);break;case"so:s":await this.signoutSilentCallback(e);break;default:throw new Error("invalid response_type in state")}}async querySessionStatus(e={}){const{silentRequestTimeoutInSeconds:t,...s}=e,r=this.settings.silent_redirect_uri;if(!r)throw new Error("No silent_redirect_uri configured");const n=await this._loadUser(),a=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:t}),o=await this._signinStart({request_type:"si:s",redirect_uri:r,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?n==null?void 0:n.id_token:void 0,response_type:this.settings.query_status_response_type,scope:"openid",skipUserInfo:!0,...s},a);try{const c=await this._client.processSigninResponse(o.url);return c.session_state&&c.profile.sub?{session_state:c.session_state,sub:c.profile.sub}:null}catch(c){if(this.settings.monitorAnonymousSession&&c instanceof y)switch(c.error){case"login_required":case"consent_required":case"interaction_required":case"account_selection_required":return{session_state:c.session_state}}throw c}}async _signin(e,t,s){const r=await this._signinStart(e,t);return await this._signinEnd(r.url,s)}async _signinStart(e,t){try{const s=await this._client.createSigninRequest(e);return await t.navigate({url:s.url,state:s.state.id,response_mode:s.state.response_mode,scriptOrigin:this.settings.iframeScriptOrigin})}catch(s){throw t.close(),s}}async _signinEnd(e,t){const s=await this._client.processSigninResponse(e);return await this._buildUser(s,t)}async _buildUser(e,t){const s=new A(e);if(t&&t!==s.profile.sub)throw new y({...e,error:"login_required"});return await this.storeUser(s),await this._events.load(s),s}async signoutRedirect(e={id_token_hint:localStorage.getItem("id_token")??""}){const{redirectMethod:t,...s}=e,r=await this._redirectNavigator.prepare({redirectMethod:t});await this._signoutStart({request_type:"so:r",post_logout_redirect_uri:this.settings.post_logout_redirect_uri,...s},r),this.clearStaleState()}async signoutRedirectCallback(e=window.location.href){const t=await this._signoutEnd(e);return this.clearStaleState(),t}async signoutPopup(e={}){const{popupWindowFeatures:t,popupWindowTarget:s,...r}=e,n=this.settings.popup_post_logout_redirect_uri,a=await this._popupNavigator.prepare({popupWindowFeatures:t,popupWindowTarget:s});await this._signout({request_type:"so:p",post_logout_redirect_uri:n,state:n==null?void 0:{},...r},a