@digital-blueprint/sublibrary-app
Version:
[GitHub Repository](https://github.com/digital-blueprint/sublibrary-app) | [npmjs package](https://www.npmjs.com/package/@digital-blueprint/sublibrary-app) | [Unpkg CDN](https://unpkg.com/browse/@digital-blueprint/sublibrary-app/) | [Sublibrary Bundle](ht
10 lines (7 loc) • 30.1 kB
JavaScript
var e,t,n,r,i,a,o,s,c,l,u;function d(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function f(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?d(Object(n),!0).forEach(function(t){m(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):d(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function p(e,t){g(e,t),t.add(e)}function m(e,t,n){return(t=ee(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ee(e){var t=te(e,`string`);return typeof t==`symbol`?t:t+``}function te(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function h(e,t,n){g(e,t),t.set(e,n)}function g(e,t){if(t.has(e))throw TypeError(`Cannot initialize the same private elements twice on an object`)}function _(e,t,n){return e.set(y(e,t),n),n}function v(e,t){return e.get(y(e,t))}function y(e,t,n){if(typeof e==`function`?e===t:e.has(t))return arguments.length<3?t:n;throw TypeError(`Private element is not present on this object`)}var ne=(e=new WeakMap,t=new WeakMap,n=new WeakMap,r=new WeakMap,i=new WeakMap,a=new WeakMap,o=new WeakMap,s=new WeakMap,c=new WeakSet,class{constructor(l){if(p(this,c),h(this,e,[]),h(this,t,void 0),h(this,n,!0),h(this,r,void 0),h(this,i,y(c,this,F).call(this,console.info)),h(this,a,y(c,this,F).call(this,console.warn)),h(this,o,{enable:!0,callbackList:[],interval:5}),h(this,s,void 0),m(this,`didInitialize`,!1),m(this,`authenticated`,!1),m(this,`loginRequired`,!1),m(this,`responseMode`,`fragment`),m(this,`responseType`,`code`),m(this,`flow`,`standard`),m(this,`timeSkew`,null),m(this,`redirectUri`,void 0),m(this,`silentCheckSsoRedirectUri`,void 0),m(this,`silentCheckSsoFallback`,!0),m(this,`pkceMethod`,`S256`),m(this,`enableLogging`,!1),m(this,`logoutMethod`,`GET`),m(this,`scope`,void 0),m(this,`messageReceiveTimeout`,1e4),m(this,`idToken`,void 0),m(this,`idTokenParsed`,void 0),m(this,`token`,void 0),m(this,`tokenParsed`,void 0),m(this,`refreshToken`,void 0),m(this,`refreshTokenParsed`,void 0),m(this,`clientId`,void 0),m(this,`sessionId`,void 0),m(this,`subject`,void 0),m(this,`authServerUrl`,void 0),m(this,`realm`,void 0),m(this,`realmAccess`,void 0),m(this,`resourceAccess`,void 0),m(this,`profile`,void 0),m(this,`userInfo`,void 0),m(this,`endpoints`,void 0),m(this,`tokenTimeoutHandle`,void 0),m(this,`onAuthSuccess`,void 0),m(this,`onAuthError`,void 0),m(this,`onAuthRefreshSuccess`,void 0),m(this,`onAuthRefreshError`,void 0),m(this,`onTokenExpired`,void 0),m(this,`onAuthLogout`,void 0),m(this,`onReady`,void 0),m(this,`onActionUpdate`,void 0),typeof l!=`string`&&!J(l))throw Error(`The 'Keycloak' constructor must be provided with a configuration object, or a URL to a JSON configuration file.`);if(J(l)){let e=`oidcProvider`in l?[`clientId`]:[`url`,`realm`,`clientId`];for(let t of e)if(!(t in l))throw Error(`The configuration object is missing the required '${t}' property.`)}globalThis.isSecureContext||v(a,this).call(this,`[KEYCLOAK] Keycloak JS must be used in a 'secure context' to function properly as it relies on browser APIs that are otherwise not available.
Continuing to run your application insecurely will lead to unexpected behavior and breakage.
For more information see: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts`),_(s,this,l)}async init(e={}){var i;if(this.didInitialize)throw Error(`A 'Keycloak' instance can only be initialized once.`);if(this.didInitialize=!0,_(r,this,B()),typeof e.adapter==`string`&&[`default`,`cordova`,`cordova-native`].includes(e.adapter)?_(t,this,y(c,this,b).call(this,e.adapter)):typeof e.adapter==`object`?_(t,this,e.adapter):`Cordova`in window||`cordova`in window?_(t,this,y(c,this,b).call(this,`cordova`)):_(t,this,y(c,this,b).call(this,`default`)),e.useNonce!==void 0&&_(n,this,e.useNonce),e.checkLoginIframe!==void 0&&(v(o,this).enable=e.checkLoginIframe),e.checkLoginIframeInterval&&(v(o,this).interval=e.checkLoginIframeInterval),e.onLoad===`login-required`&&(this.loginRequired=!0),e.responseMode)if(e.responseMode===`query`||e.responseMode===`fragment`)this.responseMode=e.responseMode;else throw Error(`Invalid value for responseMode`);if(e.flow){switch(e.flow){case`standard`:this.responseType=`code`;break;case`implicit`:this.responseType=`id_token token`;break;case`hybrid`:this.responseType=`code id_token token`;break;default:throw Error(`Invalid value for flow`)}this.flow=e.flow}if(typeof e.timeSkew==`number`&&(this.timeSkew=e.timeSkew),e.redirectUri&&(this.redirectUri=e.redirectUri),e.silentCheckSsoRedirectUri&&(this.silentCheckSsoRedirectUri=e.silentCheckSsoRedirectUri),typeof e.silentCheckSsoFallback==`boolean`&&(this.silentCheckSsoFallback=e.silentCheckSsoFallback),e.pkceMethod!==void 0){if(e.pkceMethod!==`S256`&&e.pkceMethod!==!1)throw TypeError(`Invalid value for pkceMethod', expected 'S256' or false but got ${e.pkceMethod}.`);this.pkceMethod=e.pkceMethod}return typeof e.enableLogging==`boolean`&&(this.enableLogging=e.enableLogging),e.logoutMethod===`POST`&&(this.logoutMethod=`POST`),typeof e.scope==`string`&&(this.scope=e.scope),typeof e.messageReceiveTimeout==`number`&&e.messageReceiveTimeout>0&&(this.messageReceiveTimeout=e.messageReceiveTimeout),await y(c,this,C).call(this),await y(c,this,ae).call(this),await y(c,this,oe).call(this,e),(i=this.onReady)==null||i.call(this,this.authenticated),this.authenticated}login(e){return v(t,this).login(e)}async createLoginUrl(e){let i=I(),a=I(),o=v(t,this).redirectUri(e),s={state:i,nonce:a,redirectUri:o,loginOptions:e};e!=null&&e.prompt&&(s.prompt=e.prompt);let c=e?.action===`register`?this.endpoints.register():this.endpoints.authorize(),l=e?.scope||this.scope,u=l?l.split(` `):[];u.includes(`openid`)||u.unshift(`openid`),l=u.join(` `);let d=new URLSearchParams([[`client_id`,this.clientId],[`redirect_uri`,Q(o)],[`state`,i],[`response_mode`,this.responseMode],[`response_type`,this.responseType],[`scope`,l]]);if(v(n,this)&&d.append(`nonce`,a),e!=null&&e.prompt&&d.append(`prompt`,e.prompt),typeof e?.maxAge==`number`&&d.append(`max_age`,e.maxAge.toString()),e!=null&&e.loginHint&&d.append(`login_hint`,e.loginHint),e!=null&&e.idpHint&&d.append(`kc_idp_hint`,e.idpHint),e!=null&&e.action&&e.action!==`register`&&d.append(`kc_action`,e.action),e!=null&&e.locale&&d.append(`ui_locales`,e.locale),e!=null&&e.acr&&d.append(`claims`,ce(e.acr)),e!=null&&e.acrValues&&d.append(`acr_values`,e.acrValues),this.pkceMethod)try{let e=le(96),t=await ue(this.pkceMethod,e);s.pkceCodeVerifier=e,d.append(`code_challenge`,t),d.append(`code_challenge_method`,this.pkceMethod)}catch(e){throw Error(`Failed to generate PKCE challenge.`,{cause:e})}return v(r,this).add(s),`${c}?${d.toString()}`}logout(e){return v(t,this).logout(e)}createLogoutUrl(e){let n=e?.logoutMethod??this.logoutMethod,r=this.endpoints.logout();if(n===`POST`)return r;let i=new URLSearchParams([[`client_id`,this.clientId],[`post_logout_redirect_uri`,v(t,this).redirectUri(e)]]);return this.idToken&&i.append(`id_token_hint`,this.idToken),`${r}?${i.toString()}`}register(e){return v(t,this).register(e)}createRegisterUrl(e){return this.createLoginUrl(f(f({},e),{},{action:`register`}))}createAccountUrl(e){let n=y(c,this,P).call(this);if(!n)throw Error(`Unable to create account URL, make sure the adapter is not configured using a generic OIDC provider.`);return`${n}/account?${new URLSearchParams([[`referrer`,this.clientId],[`referrer_uri`,v(t,this).redirectUri(e)]]).toString()}`}accountManagement(){return v(t,this).accountManagement()}hasRealmRole(e){let t=this.realmAccess;return!!t&&t.roles.indexOf(e)>=0}hasResourceRole(e,t){if(!this.resourceAccess)return!1;let n=this.resourceAccess[t||this.clientId];return!!n&&n.roles.indexOf(e)>=0}async loadUserProfile(){let e=y(c,this,P).call(this);if(!e)throw Error(`Unable to load user profile, make sure the adapter is not configured using a generic OIDC provider.`);let t=await Y(`${e}/account`,{headers:[X(this.token)]});return this.profile=t}async loadUserInfo(){let e=await Y(this.endpoints.userinfo(),{headers:[X(this.token)]});return this.userInfo=e}isTokenExpired(e){if(!this.tokenParsed||!this.refreshToken&&this.flow!==`implicit`)throw Error(`Not authenticated`);if(this.timeSkew==null)return v(i,this).call(this,`[KEYCLOAK] Unable to determine if token is expired as timeskew is not set`),!0;if(typeof this.tokenParsed.exp!=`number`)return!1;let t=this.tokenParsed.exp-Math.ceil(new Date().getTime()/1e3)+this.timeSkew;if(e){if(isNaN(e))throw Error(`Invalid minValidity`);t-=e}return t<0}async updateToken(t){if(!this.refreshToken)throw Error(`Unable to update token, no refresh token available.`);t||=5,v(o,this).enable&&await y(c,this,D).call(this);let n=!1;if(t===-1?(n=!0,v(i,this).call(this,`[KEYCLOAK] Refreshing token: forced refresh`)):(!this.tokenParsed||this.isTokenExpired(t))&&(n=!0,v(i,this).call(this,`[KEYCLOAK] Refreshing token: token expired`)),!n)return!1;let{promise:r,resolve:s,reject:l}=Promise.withResolvers();if(v(e,this).push({resolve:s,reject:l}),v(e,this).length===1){let t=this.endpoints.token(),n=new Date().getTime();try{var u;let r=await Se(t,this.refreshToken,this.clientId);v(i,this).call(this,`[KEYCLOAK] Token refreshed`),n=(n+new Date().getTime())/2,y(c,this,N).call(this,r.access_token,r.refresh_token,r.id_token,n),(u=this.onAuthRefreshSuccess)==null||u.call(this);for(let t=v(e,this).pop();t!=null;t=v(e,this).pop())t.resolve(!0)}catch(t){var d;v(a,this).call(this,`[KEYCLOAK] Failed to refresh token`),t instanceof $&&t.response.status===400&&this.clearToken(),(d=this.onAuthRefreshError)==null||d.call(this);for(let n=v(e,this).pop();n!=null;n=v(e,this).pop())n.reject(t)}}return await r}clearToken(){if(this.token){var e;y(c,this,N).call(this),(e=this.onAuthLogout)==null||e.call(this),this.loginRequired&&this.login()}}});function b(e){if(e===`default`)return y(c,this,x).call(this);if(e===`cordova`)return v(o,this).enable=!1,y(c,this,re).call(this);if(e===`cordova-native`)return v(o,this).enable=!1,y(c,this,S).call(this);throw Error(`invalid adapter type: `+e)}function x(){let e=e=>e?.redirectUri||this.redirectUri||globalThis.location.href;return{login:async e=>(window.location.assign(await this.createLoginUrl(e)),await new Promise(()=>{})),logout:async t=>{if((t?.logoutMethod??this.logoutMethod)===`GET`){window.location.replace(this.createLogoutUrl(t));return}let n=document.createElement(`form`);n.setAttribute(`method`,`POST`),n.setAttribute(`action`,this.createLogoutUrl(t)),n.style.display=`none`;let r={id_token_hint:this.idToken,client_id:this.clientId,post_logout_redirect_uri:e(t)};for(let[e,t]of Object.entries(r)){let r=document.createElement(`input`);r.setAttribute(`type`,`hidden`),r.setAttribute(`name`,e),r.setAttribute(`value`,t),n.appendChild(r)}document.body.appendChild(n),n.submit()},register:async e=>(window.location.assign(await this.createRegisterUrl(e)),await new Promise(()=>{})),accountManagement:async()=>{let e=this.createAccountUrl();if(e!==void 0)window.location.href=e;else throw Error(`Not supported by the OIDC server`);return await new Promise(()=>{})},redirectUri:e}}function re(){let e=(e,t,n)=>window.cordova&&window.cordova.InAppBrowser?window.cordova.InAppBrowser.open(e,t,n):window.open(e,t,n),t=e=>e&&e.cordovaOptions?Object.keys(e.cordovaOptions).reduce((t,n)=>(t[n]=e.cordovaOptions[n],t),{}):{},n=e=>Object.keys(e).reduce((t,n)=>(t.push(n+`=`+e[n]),t),[]).join(`,`),r=e=>{let r=t(e);return r.location=`no`,e&&e.prompt===`none`&&(r.hidden=`yes`),n(r)},i=()=>this.redirectUri||`http://localhost`;return{login:async t=>{let n=r(t),a=e(await this.createLoginUrl(t),`_blank`,n),o=!1,s=!1;function l(){s=!0,a.close()}return await new Promise((e,t)=>{a.addEventListener(`loadstart`,async n=>{if(n.url.indexOf(i())===0){let r=y(c,this,k).call(this,n.url);try{await y(c,this,j).call(this,r),e()}catch(e){t(e)}l(),o=!0}}),a.addEventListener(`loaderror`,async n=>{if(!o)if(n.url.indexOf(i())===0){let r=y(c,this,k).call(this,n.url);try{await y(c,this,j).call(this,r),e()}catch(e){t(e)}l(),o=!0}else t(Error(`Unable to process login.`)),l()}),a.addEventListener(`exit`,function(e){s||t(Error(`User closed the login window.`))})})},logout:async t=>{let n=e(this.createLogoutUrl(t),`_blank`,`location=no,hidden=yes,clearcache=yes`),r=!1;n.addEventListener(`loadstart`,e=>{e.url.indexOf(i())===0&&n.close()}),n.addEventListener(`loaderror`,e=>{e.url.indexOf(i())===0||(r=!0),n.close()}),await new Promise((e,t)=>{n.addEventListener(`exit`,()=>{r?t(Error(`User closed the login window.`)):(this.clearToken(),e())})})},register:async t=>{let n=e(await this.createRegisterUrl(),`_blank`,r(t));await new Promise((e,t)=>{n.addEventListener(`loadstart`,async r=>{if(r.url.indexOf(i())===0){n.close();let i=y(c,this,k).call(this,r.url);try{await y(c,this,j).call(this,i),e()}catch(e){t(e)}}})})},accountManagement:async()=>{let t=this.createAccountUrl();if(t!==void 0){let n=e(t,`_blank`,`location=no`);n.addEventListener(`loadstart`,function(e){e.url.indexOf(i())===0&&n.close()})}else throw Error(`Not supported by the OIDC server`)},redirectUri:()=>i()}}function S(){return{login:async e=>{let t=await this.createLoginUrl(e);await new Promise((e,n)=>{universalLinks.subscribe(`keycloak`,async t=>{universalLinks.unsubscribe(`keycloak`),window.cordova.plugins.browsertab.close();let r=y(c,this,k).call(this,t.url);try{await y(c,this,j).call(this,r),e()}catch(e){n(e)}}),window.cordova.plugins.browsertab.openUrl(t)})},logout:async e=>{let t=this.createLogoutUrl(e);await new Promise(e=>{universalLinks.subscribe(`keycloak`,()=>{universalLinks.unsubscribe(`keycloak`),window.cordova.plugins.browsertab.close(),this.clearToken(),e()}),window.cordova.plugins.browsertab.openUrl(t)})},register:async e=>{let t=await this.createRegisterUrl(e);await new Promise((e,n)=>{universalLinks.subscribe(`keycloak`,async t=>{universalLinks.unsubscribe(`keycloak`),window.cordova.plugins.browsertab.close();let r=y(c,this,k).call(this,t.url);try{await y(c,this,j).call(this,r),e()}catch(e){n(e)}}),window.cordova.plugins.browsertab.openUrl(t)})},accountManagement:async()=>{let e=this.createAccountUrl();if(e!==void 0)window.cordova.plugins.browsertab.openUrl(e);else throw Error(`Not supported by the OIDC server`)},redirectUri:e=>e&&e.redirectUri?e.redirectUri:this.redirectUri?this.redirectUri:`http://localhost`}}async function C(){if(typeof v(s,this)==`string`){let e=await ye(v(s,this));this.authServerUrl=e[`auth-server-url`],this.realm=e.realm,this.clientId=e.resource,y(c,this,w).call(this)}else this.clientId=v(s,this).clientId,`oidcProvider`in v(s,this)?await y(c,this,ie).call(this,v(s,this).oidcProvider):(this.authServerUrl=v(s,this).url,this.realm=v(s,this).realm,y(c,this,w).call(this))}function w(){this.endpoints={authorize:()=>y(c,this,P).call(this)+`/protocol/openid-connect/auth`,token:()=>y(c,this,P).call(this)+`/protocol/openid-connect/token`,logout:()=>y(c,this,P).call(this)+`/protocol/openid-connect/logout`,checkSessionIframe:()=>y(c,this,P).call(this)+`/protocol/openid-connect/login-status-iframe.html`,thirdPartyCookiesIframe:()=>y(c,this,P).call(this)+`/protocol/openid-connect/3p-cookies/step1.html`,register:()=>y(c,this,P).call(this)+`/protocol/openid-connect/registrations`,userinfo:()=>y(c,this,P).call(this)+`/protocol/openid-connect/userinfo`}}async function ie(e){if(typeof e==`string`){let t=await be(`${Z(e)}/.well-known/openid-configuration`);y(c,this,T).call(this,t)}else y(c,this,T).call(this,e)}function T(e){this.endpoints={authorize(){return e.authorization_endpoint},token(){return e.token_endpoint},logout(){if(!e.end_session_endpoint)throw Error(`Not supported by the OIDC server`);return e.end_session_endpoint},checkSessionIframe(){if(!e.check_session_iframe)throw Error(`Not supported by the OIDC server`);return e.check_session_iframe},register(){throw Error(`Redirection to "Register user" page not supported in standard OIDC mode`)},userinfo(){if(!e.userinfo_endpoint)throw Error(`Not supported by the OIDC server`);return e.userinfo_endpoint}}}async function ae(){if(!v(o,this).enable&&!this.silentCheckSsoRedirectUri||typeof this.endpoints.thirdPartyCookiesIframe!=`function`)return;let e=document.createElement(`iframe`);return e.setAttribute(`src`,this.endpoints.thirdPartyCookiesIframe()),e.setAttribute(`sandbox`,`allow-storage-access-by-user-activation allow-scripts allow-same-origin`),e.setAttribute(`title`,`keycloak-3p-check-iframe`),e.style.display=`none`,document.body.appendChild(e),await z(new Promise(t=>{let n=r=>{e.contentWindow===r.source&&(r.data!==`supported`&&r.data!==`unsupported`||(r.data===`unsupported`&&(v(a,this).call(this,`[KEYCLOAK] Your browser is blocking access to 3rd-party cookies, this means:
- It is not possible to retrieve tokens without redirecting to the Keycloak server (a.k.a. no support for silent authentication).
- It is not possible to automatically detect changes to the session status (such as the user logging out in another tab).
For more information see: https://www.keycloak.org/securing-apps/javascript-adapter#_modern_browsers`),v(o,this).enable=!1,this.silentCheckSsoFallback&&(this.silentCheckSsoRedirectUri=void 0)),document.body.removeChild(e),window.removeEventListener(`message`,n),t()))};window.addEventListener(`message`,n,!1)}),this.messageReceiveTimeout,`Timeout when waiting for 3rd party check iframe message.`)}async function oe(e){let t=y(c,this,k).call(this,window.location.href);if(t!=null&&t.redirectUri&&window.history.replaceState(window.history.state,``,t.redirectUri),t&&t.valid){await y(c,this,E).call(this),await y(c,this,j).call(this,t);return}let n=async t=>{let n={};t||(n.prompt=`none`),e.locale&&(n.locale=e.locale),await this.login(n)},r=async()=>{switch(e.onLoad){case`check-sso`:v(o,this).enable?(await y(c,this,E).call(this),await y(c,this,D).call(this)||(this.silentCheckSsoRedirectUri?await y(c,this,O).call(this):await n(!1))):this.silentCheckSsoRedirectUri?await y(c,this,O).call(this):await n(!1);break;case`login-required`:await n(!0);break;default:throw Error(`Invalid value for onLoad`)}};if(e.token&&e.refreshToken)if(y(c,this,N).call(this,e.token,e.refreshToken,e.idToken),v(o,this).enable){if(await y(c,this,E).call(this),await y(c,this,D).call(this)){var i;(i=this.onAuthSuccess)==null||i.call(this),y(c,this,M).call(this)}}else try{var a;await this.updateToken(-1),(a=this.onAuthSuccess)==null||a.call(this)}catch(t){var s;if((s=this.onAuthError)==null||s.call(this),e.onLoad)await r();else throw t}else e.onLoad&&await r()}async function E(){if(!v(o,this).enable||v(o,this).iframe)return;let e=document.createElement(`iframe`);v(o,this).iframe=e,e.setAttribute(`src`,this.endpoints.checkSessionIframe()),e.setAttribute(`sandbox`,`allow-storage-access-by-user-activation allow-scripts allow-same-origin`),e.setAttribute(`title`,`keycloak-session-iframe`),e.style.display=`none`,document.body.appendChild(e),window.addEventListener(`message`,e=>{if(e.origin!==v(o,this).iframeOrigin||v(o,this).iframe?.contentWindow!==e.source||!(e.data===`unchanged`||e.data===`changed`||e.data===`error`))return;e.data!==`unchanged`&&this.clearToken();let t=v(o,this).callbackList;v(o,this).callbackList=[];for(let n of t.reverse())e.data===`error`?n(Error(`Error while checking login iframe`)):n(null,e.data===`unchanged`)},!1),await new Promise(t=>{e.addEventListener(`load`,()=>{let e=this.endpoints.authorize();e.startsWith(`/`)?v(o,this).iframeOrigin=globalThis.location.origin:v(o,this).iframeOrigin=new URL(e).origin,t()})})}async function D(){if(!v(o,this).iframe||!v(o,this).iframeOrigin)return;let e=`${this.clientId} ${this.sessionId?this.sessionId:``}`,t=v(o,this).iframeOrigin;return await new Promise((n,r)=>{var i;v(o,this).callbackList.push((e,t)=>e?r(e):n(t)),v(o,this).callbackList.length===1&&((i=v(o,this).iframe)==null||(i=i.contentWindow)==null||i.postMessage(e,t))})}async function O(){let e=document.createElement(`iframe`),t=await this.createLoginUrl({prompt:`none`,redirectUri:this.silentCheckSsoRedirectUri});return e.setAttribute(`src`,t),e.setAttribute(`sandbox`,`allow-storage-access-by-user-activation allow-scripts allow-same-origin`),e.setAttribute(`title`,`keycloak-silent-check-sso`),e.style.display=`none`,document.body.appendChild(e),await new Promise((t,n)=>{let r=async i=>{if(i.origin!==window.location.origin||e.contentWindow!==i.source)return;let a=y(c,this,k).call(this,i.data);try{await y(c,this,j).call(this,a),t()}catch(e){n(e)}document.body.removeChild(e),window.removeEventListener(`message`,r)};window.addEventListener(`message`,r)})}function k(e){let t=y(c,this,se).call(this,e);if(!t)return;let n=v(r,this).get(t.state);return n&&(t.valid=!0,t.redirectUri=n.redirectUri,t.storedNonce=n.nonce,t.prompt=n.prompt,t.pkceCodeVerifier=n.pkceCodeVerifier,t.loginOptions=n.loginOptions),t}function se(e){var t;let n=[];switch(this.flow){case`standard`:n=[`code`,`state`,`session_state`,`kc_action_status`,`kc_action`,`iss`];break;case`implicit`:n=[`access_token`,`token_type`,`id_token`,`state`,`session_state`,`expires_in`,`kc_action_status`,`kc_action`,`iss`];break;case`hybrid`:n=[`access_token`,`token_type`,`id_token`,`code`,`state`,`session_state`,`expires_in`,`kc_action_status`,`kc_action`,`iss`];break}n.push(`error`),n.push(`error_description`),n.push(`error_uri`);let r=new URL(e),i=``,a;if(this.responseMode===`query`&&r.searchParams.size>0?(a=y(c,this,A).call(this,r.search,n),r.search=a.paramsString,i=r.toString()):this.responseMode===`fragment`&&r.hash.length>0&&(a=y(c,this,A).call(this,r.hash.substring(1),n),r.hash=``,i=r.toString()),(t=a)!=null&&t.oauthParams){if(this.flow===`standard`||this.flow===`hybrid`){if((a.oauthParams.code||a.oauthParams.error)&&a.oauthParams.state)return a.oauthParams.redirectUri=i,a.oauthParams}else if(this.flow===`implicit`&&(a.oauthParams.access_token||a.oauthParams.error)&&a.oauthParams.state)return a.oauthParams.redirectUri=i,a.oauthParams}}function A(e,t){let n=new URLSearchParams(e),r={};for(let[e,i]of Array.from(n.entries()))t.includes(e)&&(r[e]=i,n.delete(e));return{paramsString:n.toString(),oauthParams:r}}async function j(e){let{code:t,error:r,prompt:a}=e,o=new Date().getTime(),s=(t,r,a)=>{if(o=(o+new Date().getTime())/2,y(c,this,N).call(this,t,r,a,o),v(n,this)&&this.idTokenParsed&&this.idTokenParsed.nonce!==e.storedNonce)throw v(i,this).call(this,`[KEYCLOAK] Invalid nonce, clearing token`),this.clearToken(),Error(`Invalid nonce.`)};if(e.kc_action_status&&this.onActionUpdate&&this.onActionUpdate(e.kc_action_status,e.kc_action),r){if(a!==`none`)if(e.error_description&&e.error_description===`authentication_expired`)await this.login(e.loginOptions);else{var l;let t={error:r,error_description:e.error_description};throw(l=this.onAuthError)==null||l.call(this,t),t}return}else if(this.flow!==`standard`&&(e.access_token||e.id_token)){var u;s(e.access_token,void 0,e.id_token),(u=this.onAuthSuccess)==null||u.call(this)}if(this.flow!==`implicit`&&t)try{var d;let n=await xe(this.endpoints.token(),t,this.clientId,e.redirectUri,e.pkceCodeVerifier);s(n.access_token,n.refresh_token,n.id_token),this.flow===`standard`&&((d=this.onAuthSuccess)==null||d.call(this)),y(c,this,M).call(this)}catch(e){var f;throw(f=this.onAuthError)==null||f.call(this),e}}async function M(){v(o,this).enable&&this.token&&(await we(v(o,this).interval*1e3),await y(c,this,D).call(this)&&await y(c,this,M).call(this))}function N(e,t,n,r){if(this.tokenTimeoutHandle&&=(clearTimeout(this.tokenTimeoutHandle),void 0),t?(this.refreshToken=t,this.refreshTokenParsed=q(t)):(delete this.refreshToken,delete this.refreshTokenParsed),n?(this.idToken=n,this.idTokenParsed=q(n)):(delete this.idToken,delete this.idTokenParsed),e){if(this.token=e,this.tokenParsed=q(e),this.sessionId=this.tokenParsed.sid,this.authenticated=!0,this.subject=this.tokenParsed.sub,this.realmAccess=this.tokenParsed.realm_access,this.resourceAccess=this.tokenParsed.resource_access,r&&(this.timeSkew=Math.floor(r/1e3)-this.tokenParsed.iat),this.timeSkew!==null&&(v(i,this).call(this,`[KEYCLOAK] Estimated time difference between browser and server is `+this.timeSkew+` seconds`),this.onTokenExpired)){let e=(this.tokenParsed.exp-new Date().getTime()/1e3+this.timeSkew)*1e3;v(i,this).call(this,`[KEYCLOAK] Token expires in `+Math.round(e/1e3)+` s`),e<=0?this.onTokenExpired():this.tokenTimeoutHandle=window.setTimeout(this.onTokenExpired,e)}}else delete this.token,delete this.tokenParsed,delete this.subject,delete this.realmAccess,delete this.resourceAccess,this.authenticated=!1}function P(){if(this.authServerUrl!==void 0)return`${Z(this.authServerUrl)}/realms/${encodeURIComponent(this.realm)}`}function F(e){return t=>{this.enableLogging&&e.call(console,t)}}function I(){if(typeof crypto>`u`||crypto.randomUUID===void 0)throw Error(`Web Crypto API is not available.`);return crypto.randomUUID()}function ce(e){return JSON.stringify({id_token:{acr:e}})}function le(e){return L(e,`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`)}async function ue(e,t){if(e!==`S256`)throw TypeError(`Invalid value for 'pkceMethod', expected 'S256' but got '${e}'.`);return he(new Uint8Array(await ge(t))).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=/g,``)}function L(e,t){let n=R(e),r=Array(e);for(let i=0;i<e;i++)r[i]=t.charCodeAt(n[i]%t.length);return String.fromCharCode.apply(null,r)}function R(e){if(typeof crypto>`u`||crypto.getRandomValues===void 0)throw Error(`Web Crypto API is not available.`);return crypto.getRandomValues(new Uint8Array(e))}function z(e,t,n){let r,i=new Promise(function(e,i){r=window.setTimeout(function(){i(Error(n||`Promise is not settled within timeout of `+t+`ms`))},t)});return Promise.race([e,i]).finally(function(){clearTimeout(r)})}function B(){try{return new H}catch{return new pe}}const V=`kc-callback-`;var H=(l=new WeakSet,class{constructor(){p(this,l),globalThis.localStorage.setItem(`kc-test`,`test`),globalThis.localStorage.removeItem(`kc-test`)}get(e){if(!e)return null;y(l,this,U).call(this);let t=V+e,n=globalThis.localStorage.getItem(t);return n?(globalThis.localStorage.removeItem(t),JSON.parse(n)):null}add(e){y(l,this,U).call(this);let t=V+e.state,n=JSON.stringify(f(f({},e),{},{expires:Date.now()+3600*1e3}));try{globalThis.localStorage.setItem(t,n)}catch{y(l,this,de).call(this),globalThis.localStorage.setItem(t,n)}}});function U(){let e=Date.now();for(let[t,n]of y(l,this,W).call(this)){let r=y(l,this,fe).call(this,n);(r===null||r<e)&&globalThis.localStorage.removeItem(t)}}function de(){for(let[e]of y(l,this,W).call(this))globalThis.localStorage.removeItem(e)}function W(){return Object.entries(globalThis.localStorage).filter(([e])=>e.startsWith(V))}function fe(e){let t;try{t=JSON.parse(e)}catch{return null}return J(t)&&`expires`in t&&typeof t.expires==`number`?t.expires:null}var pe=(u=new WeakSet,class{constructor(){p(this,u)}get(e){if(!e)return null;let t=y(u,this,me).call(this,V+e);return y(u,this,G).call(this,V+e,``,y(u,this,K).call(this,-100)),t?JSON.parse(t):null}add(e){y(u,this,G).call(this,V+e.state,JSON.stringify(e),y(u,this,K).call(this,60))}});function me(e){let t=e+`=`,n=document.cookie.split(`;`);for(let e=0;e<n.length;e++){let r=n[e];for(;r.charAt(0)===` `;)r=r.substring(1);if(r.indexOf(t)===0)return r.substring(t.length,r.length)}return``}function G(e,t,n){let r=e+`=`+t+`; expires=`+n.toUTCString()+`; `;document.cookie=r}function K(e){let t=new Date;return t.setTime(t.getTime()+e*60*1e3),t}function he(e){let t=String.fromCodePoint(...e);return btoa(t)}async function ge(e){let t=new TextEncoder().encode(e);if(typeof crypto>`u`||crypto.subtle===void 0)throw Error(`Web Crypto API is not available.`);return await crypto.subtle.digest(`SHA-256`,t)}function q(e){let[,t]=e.split(`.`);if(typeof t!=`string`)throw Error(`Unable to decode token, payload not found.`);let n;try{n=_e(t)}catch(e){throw Error(`Unable to decode token, payload is not a valid Base64URL value.`,{cause:e})}try{return JSON.parse(n)}catch(e){throw Error(`Unable to decode token, payload is not a valid JSON value.`,{cause:e})}}function _e(e){let t=e.replaceAll(`-`,`+`).replaceAll(`_`,`/`);switch(t.length%4){case 0:break;case 2:t+=`==`;break;case 3:t+=`=`;break;default:throw Error(`Input is not of the correct length.`)}try{return ve(t)}catch{return atob(t)}}function ve(e){return decodeURIComponent(atob(e).replace(/(.)/g,(e,t)=>{let n=t.charCodeAt(0).toString(16).toUpperCase();return n.length<2&&(n=`0`+n),`%`+n}))}function J(e){return typeof e==`object`&&!!e}async function ye(e){return await Y(e)}async function be(e){return await Y(e)}async function xe(e,t,n,r,i){let a=new URLSearchParams([[`code`,t],[`grant_type`,`authorization_code`],[`client_id`,n],[`redirect_uri`,Q(r)]]);return i&&a.append(`code_verifier`,i),await Y(e,{method:`POST`,credentials:`include`,body:a})}async function Se(e,t,n){return await Y(e,{method:`POST`,credentials:`include`,body:new URLSearchParams([[`grant_type`,`refresh_token`],[`refresh_token`,t],[`client_id`,n]])})}async function Y(e,t={}){let n=new Headers(t.headers);return n.set(`Accept`,`application/json`),await(await Ce(e,f(f({},t),{},{headers:n}))).json()}async function Ce(e,t){let n=await fetch(e,t);if(!n.ok)throw new $(`Server responded with an invalid status.`,{response:n});return n}function X(e){if(!e)throw Error(`Unable to build authorization header, token is not set, make sure the user is authenticated.`);return[`Authorization`,`bearer ${e}`]}function Z(e){return e.endsWith(`/`)?e.slice(0,-1):e}function Q(e){let t=new URL(e);return t.hash=``,t.toString()}var $=class extends Error{constructor(e,t){super(e,t),m(this,`response`,void 0),this.response=t.response}};const we=e=>new Promise(t=>setTimeout(t,e));export{ne as default};
//# sourceMappingURL=keycloak.Y2aV-3VC.js.map