@auth0/auth0-react
Version:
Auth0 SDK for React Single Page Applications (SPA)
1 lines • 62.6 kB
JavaScript
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react")):"function"==typeof define&&define.amd?define(["exports","react"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).reactAuth0={},e.React)}(this,(function(e,t){"use strict";var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},n(e,t)};var o=function(){return o=Object.assign||function(e){for(var t,n=1,o=arguments.length;n<o;n++)for(var r in t=arguments[n])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},o.apply(this,arguments)};function r(e,t,n,o){return new(n||(n=Promise))((function(r,i){function a(e){try{c(o.next(e))}catch(e){i(e)}}function s(e){try{c(o.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,s)}c((o=o.apply(e,t||[])).next())}))}function i(e,t){var n,o,r,i={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=s(0),a.throw=s(1),a.return=s(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(s){return function(c){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;a&&(a=0,s[0]&&(i=0)),i;)try{if(n=1,o&&(r=2&s[0]?o.return:s[0]?o.throw||((r=o.return)&&r.call(o),0):o.next)&&!(r=r.call(o,s[1])).done)return r;switch(o=0,r&&(s=[2&s[0],r.value]),s[0]){case 0:case 1:r=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,o=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!(r=i.trys,(r=r.length>0&&r[r.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!r||s[1]>r[0]&&s[1]<r[3])){i.label=s[1];break}if(6===s[0]&&i.label<r[1]){i.label=r[1],r=s;break}if(r&&i.label<r[2]){i.label=r[2],i.ops.push(s);break}r[2]&&i.ops.pop(),i.trys.pop();continue}s=t.call(e,i)}catch(e){s=[6,e],o=0}finally{n=r=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}}function a(e,t){var n={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(n[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(o=Object.getOwnPropertySymbols(e);r<o.length;r++)t.indexOf(o[r])<0&&Object.prototype.propertyIsEnumerable.call(e,o[r])&&(n[o[r]]=e[o[r]])}return n}"function"==typeof SuppressedError&&SuppressedError,"function"==typeof SuppressedError&&SuppressedError;var s="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function c(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function u(e,t){return e(t={exports:{}},t.exports),t.exports}var l=u((function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var n=function(){function e(){var e=this;this.locked=new Map,this.addToLocked=function(t,n){var o=e.locked.get(t);void 0===o?void 0===n?e.locked.set(t,[]):e.locked.set(t,[n]):void 0!==n&&(o.unshift(n),e.locked.set(t,o))},this.isLocked=function(t){return e.locked.has(t)},this.lock=function(t){return new Promise((function(n,o){e.isLocked(t)?e.addToLocked(t,n):(e.addToLocked(t),n())}))},this.unlock=function(t){var n=e.locked.get(t);if(void 0!==n&&0!==n.length){var o=n.pop();e.locked.set(t,n),void 0!==o&&setTimeout(o,0)}else e.locked.delete(t)}}return e.getInstance=function(){return void 0===e.instance&&(e.instance=new e),e.instance},e}();t.default=function(){return n.getInstance()}}));c(l);var d=c(u((function(e,t){var n=s&&s.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(r,i){function a(e){try{c(o.next(e))}catch(e){i(e)}}function s(e){try{c(o.throw(e))}catch(e){i(e)}}function c(e){e.done?r(e.value):new n((function(t){t(e.value)})).then(a,s)}c((o=o.apply(e,t||[])).next())}))},o=s&&s.__generator||function(e,t){var n,o,r,i,a={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,o&&(r=2&i[0]?o.return:i[0]?o.throw||((r=o.return)&&r.call(o),0):o.next)&&!(r=r.call(o,i[1])).done)return r;switch(o=0,r&&(i=[2&i[0],r.value]),i[0]){case 0:case 1:r=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,o=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((r=(r=a.trys).length>0&&r[r.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!r||i[1]>r[0]&&i[1]<r[3])){a.label=i[1];break}if(6===i[0]&&a.label<r[1]){a.label=r[1],r=i;break}if(r&&a.label<r[2]){a.label=r[2],a.ops.push(i);break}r[2]&&a.ops.pop(),a.trys.pop();continue}i=t.call(e,a)}catch(e){i=[6,e],o=0}finally{n=r=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,s])}}},r=s;Object.defineProperty(t,"__esModule",{value:!0});var i="browser-tabs-lock-key",a={key:function(e){return n(r,void 0,void 0,(function(){return o(this,(function(e){throw new Error("Unsupported")}))}))},getItem:function(e){return n(r,void 0,void 0,(function(){return o(this,(function(e){throw new Error("Unsupported")}))}))},clear:function(){return n(r,void 0,void 0,(function(){return o(this,(function(e){return[2,window.localStorage.clear()]}))}))},removeItem:function(e){return n(r,void 0,void 0,(function(){return o(this,(function(e){throw new Error("Unsupported")}))}))},setItem:function(e,t){return n(r,void 0,void 0,(function(){return o(this,(function(e){throw new Error("Unsupported")}))}))},keySync:function(e){return window.localStorage.key(e)},getItemSync:function(e){return window.localStorage.getItem(e)},clearSync:function(){return window.localStorage.clear()},removeItemSync:function(e){return window.localStorage.removeItem(e)},setItemSync:function(e,t){return window.localStorage.setItem(e,t)}};function c(e){return new Promise((function(t){return setTimeout(t,e)}))}function u(e){for(var t="0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz",n="",o=0;o<e;o++)n+=t[Math.floor(61*Math.random())];return n}var d=function(){function e(t){this.acquiredIatSet=new Set,this.storageHandler=void 0,this.id=Date.now().toString()+u(15),this.acquireLock=this.acquireLock.bind(this),this.releaseLock=this.releaseLock.bind(this),this.releaseLock__private__=this.releaseLock__private__.bind(this),this.waitForSomethingToChange=this.waitForSomethingToChange.bind(this),this.refreshLockWhileAcquired=this.refreshLockWhileAcquired.bind(this),this.storageHandler=t,void 0===e.waiters&&(e.waiters=[])}return e.prototype.acquireLock=function(t,r){return void 0===r&&(r=5e3),n(this,void 0,void 0,(function(){var n,s,l,d,h,p,f;return o(this,(function(o){switch(o.label){case 0:n=Date.now()+u(4),s=Date.now()+r,l=i+"-"+t,d=void 0===this.storageHandler?a:this.storageHandler,o.label=1;case 1:return Date.now()<s?[4,c(30)]:[3,8];case 2:return o.sent(),null!==d.getItemSync(l)?[3,5]:(h=this.id+"-"+t+"-"+n,[4,c(Math.floor(25*Math.random()))]);case 3:return o.sent(),d.setItemSync(l,JSON.stringify({id:this.id,iat:n,timeoutKey:h,timeAcquired:Date.now(),timeRefreshed:Date.now()})),[4,c(30)];case 4:return o.sent(),null!==(p=d.getItemSync(l))&&(f=JSON.parse(p)).id===this.id&&f.iat===n?(this.acquiredIatSet.add(n),this.refreshLockWhileAcquired(l,n),[2,!0]):[3,7];case 5:return e.lockCorrector(void 0===this.storageHandler?a:this.storageHandler),[4,this.waitForSomethingToChange(s)];case 6:o.sent(),o.label=7;case 7:return n=Date.now()+u(4),[3,1];case 8:return[2,!1]}}))}))},e.prototype.refreshLockWhileAcquired=function(e,t){return n(this,void 0,void 0,(function(){var r=this;return o(this,(function(i){return setTimeout((function(){return n(r,void 0,void 0,(function(){var n,r,i;return o(this,(function(o){switch(o.label){case 0:return[4,l.default().lock(t)];case 1:return o.sent(),this.acquiredIatSet.has(t)?(n=void 0===this.storageHandler?a:this.storageHandler,null===(r=n.getItemSync(e))?(l.default().unlock(t),[2]):((i=JSON.parse(r)).timeRefreshed=Date.now(),n.setItemSync(e,JSON.stringify(i)),l.default().unlock(t),this.refreshLockWhileAcquired(e,t),[2])):(l.default().unlock(t),[2])}}))}))}),1e3),[2]}))}))},e.prototype.waitForSomethingToChange=function(t){return n(this,void 0,void 0,(function(){return o(this,(function(n){switch(n.label){case 0:return[4,new Promise((function(n){var o=!1,r=Date.now(),i=!1;function a(){if(i||(window.removeEventListener("storage",a),e.removeFromWaiting(a),clearTimeout(s),i=!0),!o){o=!0;var t=50-(Date.now()-r);t>0?setTimeout(n,t):n(null)}}window.addEventListener("storage",a),e.addToWaiting(a);var s=setTimeout(a,Math.max(0,t-Date.now()))}))];case 1:return n.sent(),[2]}}))}))},e.addToWaiting=function(t){this.removeFromWaiting(t),void 0!==e.waiters&&e.waiters.push(t)},e.removeFromWaiting=function(t){void 0!==e.waiters&&(e.waiters=e.waiters.filter((function(e){return e!==t})))},e.notifyWaiters=function(){void 0!==e.waiters&&e.waiters.slice().forEach((function(e){return e()}))},e.prototype.releaseLock=function(e){return n(this,void 0,void 0,(function(){return o(this,(function(t){switch(t.label){case 0:return[4,this.releaseLock__private__(e)];case 1:return[2,t.sent()]}}))}))},e.prototype.releaseLock__private__=function(t){return n(this,void 0,void 0,(function(){var n,r,s,c;return o(this,(function(o){switch(o.label){case 0:return n=void 0===this.storageHandler?a:this.storageHandler,r=i+"-"+t,null===(s=n.getItemSync(r))?[2]:(c=JSON.parse(s)).id!==this.id?[3,2]:[4,l.default().lock(c.iat)];case 1:o.sent(),this.acquiredIatSet.delete(c.iat),n.removeItemSync(r),l.default().unlock(c.iat),e.notifyWaiters(),o.label=2;case 2:return[2]}}))}))},e.lockCorrector=function(t){for(var n=Date.now()-5e3,o=t,r=[],a=0;;){var s=o.keySync(a);if(null===s)break;r.push(s),a++}for(var c=!1,u=0;u<r.length;u++){var l=r[u];if(l.includes(i)){var d=o.getItemSync(l);if(null!==d){var h=JSON.parse(d);(void 0===h.timeRefreshed&&h.timeAcquired<n||void 0!==h.timeRefreshed&&h.timeRefreshed<n)&&(o.removeItemSync(l),c=!0)}}}c&&e.notifyWaiters()},e.waiters=void 0,e}();t.default=d})));const h={timeoutInSeconds:60},p={name:"auth0-spa-js",version:"2.4.1"},f=()=>Date.now();class m extends Error{constructor(e,t){super(t),this.error=e,this.error_description=t,Object.setPrototypeOf(this,m.prototype)}static fromPayload({error:e,error_description:t}){return new m(e,t)}}class g extends m{constructor(e,t,n,o=null){super(e,t),this.state=n,this.appState=o,Object.setPrototypeOf(this,g.prototype)}}class y extends m{constructor(){super("timeout","Timeout"),Object.setPrototypeOf(this,y.prototype)}}class w extends y{constructor(e){super(),this.popup=e,Object.setPrototypeOf(this,w.prototype)}}class b extends m{constructor(e){super("cancelled","Popup closed"),this.popup=e,Object.setPrototypeOf(this,b.prototype)}}class v extends m{constructor(e,t,n){super(e,t),this.mfa_token=n,Object.setPrototypeOf(this,v.prototype)}}class k extends m{constructor(e,t){super("missing_refresh_token",`Missing Refresh Token (audience: '${I(e,["default"])}', scope: '${I(t)}')`),this.audience=e,this.scope=t,Object.setPrototypeOf(this,k.prototype)}}class _ extends m{constructor(e){super("use_dpop_nonce","Server rejected DPoP proof: wrong nonce"),this.newDpopNonce=e,Object.setPrototypeOf(this,_.prototype)}}function I(e,t=[]){return e&&!t.includes(e)?e:""}const S=()=>window.crypto,T=()=>{const e="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.";let t="";return Array.from(S().getRandomValues(new Uint8Array(43))).forEach((n=>t+=e[n%66])),t},P=e=>btoa(e),O=e=>{var{clientId:t}=e,n=a(e,["clientId"]);return new URLSearchParams((e=>Object.keys(e).filter((t=>void 0!==e[t])).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:e[n]})),{}))(Object.assign({client_id:t},n))).toString()},E=e=>(e=>decodeURIComponent(atob(e).split("").map((e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2))).join("")))(e.replace(/_/g,"/").replace(/-/g,"+")),C=new TextEncoder,x=new TextDecoder;function j(e){return"string"==typeof e?C.encode(e):x.decode(e)}function D(e){if("number"!=typeof e.modulusLength||e.modulusLength<2048)throw new z(`${e.name} modulusLength must be at least 2048 bits`)}let N;if(Uint8Array.prototype.toBase64)N=e=>(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e.toBase64({alphabet:"base64url",omitPadding:!0}));else{const e=32768;N=t=>{t instanceof ArrayBuffer&&(t=new Uint8Array(t));const n=[];for(let o=0;o<t.byteLength;o+=e)n.push(String.fromCharCode.apply(null,t.subarray(o,o+e)));return btoa(n.join("")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}}function K(e){return N(e)}class U extends Error{constructor(e){var t;super(null!=e?e:"operation not supported"),this.name=this.constructor.name,null===(t=Error.captureStackTrace)||void 0===t||t.call(Error,this,this.constructor)}}class z extends Error{constructor(e){var t;super(e),this.name=this.constructor.name,null===(t=Error.captureStackTrace)||void 0===t||t.call(Error,this,this.constructor)}}function R(e){switch(e.algorithm.name){case"RSA-PSS":return function(e){if("SHA-256"===e.algorithm.hash.name)return"PS256";throw new U("unsupported RsaHashedKeyAlgorithm hash name")}(e);case"RSASSA-PKCS1-v1_5":return function(e){if("SHA-256"===e.algorithm.hash.name)return"RS256";throw new U("unsupported RsaHashedKeyAlgorithm hash name")}(e);case"ECDSA":return function(e){if("P-256"===e.algorithm.namedCurve)return"ES256";throw new U("unsupported EcKeyAlgorithm namedCurve")}(e);case"Ed25519":return"Ed25519";default:throw new U("unsupported CryptoKey algorithm name")}}function A(e){return e instanceof CryptoKey}function L(e){return A(e)&&"public"===e.type}async function W(e,t,n,o,r,i){const a=null==e?void 0:e.privateKey,s=null==e?void 0:e.publicKey;if(!A(c=a)||"private"!==c.type)throw new TypeError('"keypair.privateKey" must be a private CryptoKey');var c;if(!L(s))throw new TypeError('"keypair.publicKey" must be a public CryptoKey');if(!0!==s.extractable)throw new TypeError('"keypair.publicKey.extractable" must be true');if("string"!=typeof t)throw new TypeError('"htu" must be a string');if("string"!=typeof n)throw new TypeError('"htm" must be a string');if(void 0!==o&&"string"!=typeof o)throw new TypeError('"nonce" must be a string or undefined');if(void 0!==r&&"string"!=typeof r)throw new TypeError('"accessToken" must be a string or undefined');if(void 0!==i&&("object"!=typeof i||null===i||Array.isArray(i)))throw new TypeError('"additional" must be an object');return async function(e,t,n){if(!1===n.usages.includes("sign"))throw new TypeError('private CryptoKey instances used for signing assertions must include "sign" in their "usages"');const o=`${K(j(JSON.stringify(e)))}.${K(j(JSON.stringify(t)))}`;return`${o}.${K(await crypto.subtle.sign(function(e){switch(e.algorithm.name){case"ECDSA":return{name:e.algorithm.name,hash:"SHA-256"};case"RSA-PSS":return D(e.algorithm),{name:e.algorithm.name,saltLength:32};case"RSASSA-PKCS1-v1_5":return D(e.algorithm),{name:e.algorithm.name};case"Ed25519":return{name:e.algorithm.name}}throw new U}(n),n,j(o)))}`}({alg:R(a),typ:"dpop+jwt",jwk:await Z(s)},Object.assign(Object.assign({},i),{iat:Math.floor(Date.now()/1e3),jti:crypto.randomUUID(),htm:n,nonce:o,htu:t,ath:r?K(await crypto.subtle.digest("SHA-256",j(r))):void 0}),a)}async function Z(e){const{kty:t,e:n,n:o,x:r,y:i,crv:a}=await crypto.subtle.exportKey("jwk",e);return{kty:t,crv:a,e:n,n:o,x:r,y:i}}const H=["authorization_code","refresh_token","urn:ietf:params:oauth:grant-type:token-exchange"];const F=async(e,t)=>{const n=await fetch(e,t);return{ok:n.ok,json:await n.json(),headers:(o=n.headers,[...o].reduce(((e,[t,n])=>(e[t]=n,e)),{}))};var o},G=async(e,t,n,o,r,i,a=1e4)=>r?(async(e,t,n,o,r,i,a)=>{return s={auth:{audience:t,scope:n},timeout:r,fetchUrl:e,fetchOptions:o,useFormData:a},c=i,new Promise((function(e,t){const n=new MessageChannel;n.port1.onmessage=function(o){o.data.error?t(new Error(o.data.error)):e(o.data),n.port1.close()},c.postMessage(s,[n.port2])}));var s,c})(e,t,n,o,a,r,i):(async(e,t,n)=>{const o=new AbortController;let r;return t.signal=o.signal,Promise.race([F(e,t),new Promise(((e,t)=>{r=setTimeout((()=>{o.abort(),t(new Error("Timeout when executing 'fetch'"))}),n)}))]).finally((()=>{clearTimeout(r)}))})(e,o,a);async function V(e,t,n,o,r,i,s,c,u){if(c){const t=await c.generateProof({url:e,method:r.method||"GET",nonce:await c.getNonce()});r.headers=Object.assign(Object.assign({},r.headers),{dpop:t})}let l,d=null;for(let a=0;a<3;a++)try{l=await G(e,n,o,r,i,s,t),d=null;break}catch(e){d=e}if(d)throw d;const h=l.json,{error:p,error_description:f}=h,g=a(h,["error","error_description"]),{headers:y,ok:w}=l;let b;if(c&&(b=y["dpop-nonce"],b&&await c.setNonce(b)),!w){const a=f||`HTTP error. Unable to fetch ${e}`;if("mfa_required"===p)throw new v(p,a,g.mfa_token);if("missing_refresh_token"===p)throw new k(n,o);if("use_dpop_nonce"===p){if(!c||!b||u)throw new _(b);return V(e,t,n,o,r,i,s,c,!0)}throw new m(p||"request_error",a)}return g}async function X(e,t){var{baseUrl:n,timeout:o,audience:r,scope:i,auth0Client:s,useFormData:c,dpop:u}=e,l=a(e,["baseUrl","timeout","audience","scope","auth0Client","useFormData","dpop"]);const d="urn:ietf:params:oauth:grant-type:token-exchange"===l.grant_type,h=Object.assign(Object.assign(Object.assign({},l),d&&r&&{audience:r}),d&&i&&{scope:i}),f=c?O(h):JSON.stringify(h),m=(g=l.grant_type,H.includes(g));var g;return await V(`${n}/oauth/token`,o,r||"default",i,{method:"POST",body:f,headers:{"Content-Type":c?"application/x-www-form-urlencoded":"application/json","Auth0-Client":btoa(JSON.stringify(s||p))}},t,c,m?u:void 0)}const J=(...e)=>{return(t=e.filter(Boolean).join(" ").trim().split(/\s+/),Array.from(new Set(t))).join(" ");var t};class M{constructor(e,t="@@auth0spajs@@",n){this.prefix=t,this.suffix=n,this.clientId=e.clientId,this.scope=e.scope,this.audience=e.audience}toKey(){return[this.prefix,this.clientId,this.audience,this.scope,this.suffix].filter(Boolean).join("::")}static fromKey(e){const[t,n,o,r]=e.split("::");return new M({clientId:n,scope:r,audience:o},t)}static fromCacheEntry(e){const{scope:t,audience:n,client_id:o}=e;return new M({scope:t,audience:n,clientId:o})}}class Y{set(e,t){localStorage.setItem(e,JSON.stringify(t))}get(e){const t=window.localStorage.getItem(e);if(t)try{return JSON.parse(t)}catch(e){return}}remove(e){localStorage.removeItem(e)}allKeys(){return Object.keys(window.localStorage).filter((e=>e.startsWith("@@auth0spajs@@")))}}class ${constructor(){this.enclosedCache=function(){let e={};return{set(t,n){e[t]=n},get(t){const n=e[t];if(n)return n},remove(t){delete e[t]},allKeys:()=>Object.keys(e)}}()}}class B{constructor(e,t,n){this.cache=e,this.keyManifest=t,this.nowProvider=n||f}async setIdToken(e,t,n){var o;const r=this.getIdTokenCacheKey(e);await this.cache.set(r,{id_token:t,decodedToken:n}),await(null===(o=this.keyManifest)||void 0===o?void 0:o.add(r))}async getIdToken(e){const t=await this.cache.get(this.getIdTokenCacheKey(e.clientId));if(!t&&e.scope&&e.audience){const t=await this.get(e);if(!t)return;if(!t.id_token||!t.decodedToken)return;return{id_token:t.id_token,decodedToken:t.decodedToken}}if(t)return{id_token:t.id_token,decodedToken:t.decodedToken}}async get(e,t=0){var n;let o=await this.cache.get(e.toKey());if(!o){const t=await this.getCacheKeys();if(!t)return;const n=this.matchExistingCacheKey(e,t);n&&(o=await this.cache.get(n))}if(!o)return;const r=await this.nowProvider(),i=Math.floor(r/1e3);return o.expiresAt-t<i?o.body.refresh_token?(o.body={refresh_token:o.body.refresh_token},await this.cache.set(e.toKey(),o),o.body):(await this.cache.remove(e.toKey()),void await(null===(n=this.keyManifest)||void 0===n?void 0:n.remove(e.toKey()))):o.body}async set(e){var t;const n=new M({clientId:e.client_id,scope:e.scope,audience:e.audience}),o=await this.wrapCacheEntry(e);await this.cache.set(n.toKey(),o),await(null===(t=this.keyManifest)||void 0===t?void 0:t.add(n.toKey()))}async clear(e){var t;const n=await this.getCacheKeys();n&&(await n.filter((t=>!e||t.includes(e))).reduce((async(e,t)=>{await e,await this.cache.remove(t)}),Promise.resolve()),await(null===(t=this.keyManifest)||void 0===t?void 0:t.clear()))}async wrapCacheEntry(e){const t=await this.nowProvider();return{body:e,expiresAt:Math.floor(t/1e3)+e.expires_in}}async getCacheKeys(){var e;return this.keyManifest?null===(e=await this.keyManifest.get())||void 0===e?void 0:e.keys:this.cache.allKeys?this.cache.allKeys():void 0}getIdTokenCacheKey(e){return new M({clientId:e},"@@auth0spajs@@","@@user@@").toKey()}matchExistingCacheKey(e,t){return t.filter((t=>{var n;const o=M.fromKey(t),r=new Set(o.scope&&o.scope.split(" ")),i=(null===(n=e.scope)||void 0===n?void 0:n.split(" "))||[],a=o.scope&&i.reduce(((e,t)=>e&&r.has(t)),!0);return"@@auth0spajs@@"===o.prefix&&o.clientId===e.clientId&&o.audience===e.audience&&a}))[0]}}class q{constructor(e,t,n){this.storage=e,this.clientId=t,this.cookieDomain=n,this.storageKey=`a0.spajs.txs.${this.clientId}`}create(e){this.storage.save(this.storageKey,e,{daysUntilExpire:1,cookieDomain:this.cookieDomain})}get(){return this.storage.get(this.storageKey)}remove(){this.storage.remove(this.storageKey,{cookieDomain:this.cookieDomain})}}const Q=e=>"number"==typeof e,ee=["iss","aud","exp","nbf","iat","jti","azp","nonce","auth_time","at_hash","c_hash","acr","amr","sub_jwk","cnf","sip_from_tag","sip_date","sip_callid","sip_cseq_num","sip_via_branch","orig","dest","mky","events","toe","txn","rph","sid","vot","vtm"];var te=u((function(e,t){var n=s&&s.__assign||function(){return n=Object.assign||function(e){for(var t,n=1,o=arguments.length;n<o;n++)for(var r in t=arguments[n])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},n.apply(this,arguments)};function o(e,t){if(!t)return"";var n="; "+e;return!0===t?n:n+"="+t}function r(e,t,n){return encodeURIComponent(e).replace(/%(23|24|26|2B|5E|60|7C)/g,decodeURIComponent).replace(/\(/g,"%28").replace(/\)/g,"%29")+"="+encodeURIComponent(t).replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g,decodeURIComponent)+function(e){if("number"==typeof e.expires){var t=new Date;t.setMilliseconds(t.getMilliseconds()+864e5*e.expires),e.expires=t}return o("Expires",e.expires?e.expires.toUTCString():"")+o("Domain",e.domain)+o("Path",e.path)+o("Secure",e.secure)+o("SameSite",e.sameSite)}(n)}function i(e){for(var t={},n=e?e.split("; "):[],o=/(%[\dA-F]{2})+/gi,r=0;r<n.length;r++){var i=n[r].split("="),a=i.slice(1).join("=");'"'===a.charAt(0)&&(a=a.slice(1,-1));try{t[i[0].replace(o,decodeURIComponent)]=a.replace(o,decodeURIComponent)}catch(e){}}return t}function a(){return i(document.cookie)}function c(e,t,o){document.cookie=r(e,t,n({path:"/"},o))}t.__esModule=!0,t.encode=r,t.parse=i,t.getAll=a,t.get=function(e){return a()[e]},t.set=c,t.remove=function(e,t){c(e,"",n(n({},t),{expires:-1}))}}));c(te),te.encode,te.parse,te.getAll;var ne=te.get,oe=te.set,re=te.remove;const ie={get(e){const t=ne(e);if(void 0!==t)return JSON.parse(t)},save(e,t,n){let o={};"https:"===window.location.protocol&&(o={secure:!0,sameSite:"none"}),(null==n?void 0:n.daysUntilExpire)&&(o.expires=n.daysUntilExpire),(null==n?void 0:n.cookieDomain)&&(o.domain=n.cookieDomain),oe(e,JSON.stringify(t),o)},remove(e,t){let n={};(null==t?void 0:t.cookieDomain)&&(n.domain=t.cookieDomain),re(e,n)}},ae={get:e=>ie.get(e)||ie.get(`_legacy_${e}`),save(e,t,n){let o={};"https:"===window.location.protocol&&(o={secure:!0}),(null==n?void 0:n.daysUntilExpire)&&(o.expires=n.daysUntilExpire),(null==n?void 0:n.cookieDomain)&&(o.domain=n.cookieDomain),oe(`_legacy_${e}`,JSON.stringify(t),o),ie.save(e,t,n)},remove(e,t){let n={};(null==t?void 0:t.cookieDomain)&&(n.domain=t.cookieDomain),re(e,n),ie.remove(e,t),ie.remove(`_legacy_${e}`,t)}},se={get(e){if("undefined"==typeof sessionStorage)return;const t=sessionStorage.getItem(e);return null!=t?JSON.parse(t):void 0},save(e,t){sessionStorage.setItem(e,JSON.stringify(t))},remove(e){sessionStorage.removeItem(e)}};var ce,ue=function(e){return ce=ce||function(e,t,n){var o=void 0===t?null:t,r=function(e,t){var n=atob(e);if(t){for(var o=new Uint8Array(n.length),r=0,i=n.length;r<i;++r)o[r]=n.charCodeAt(r);return String.fromCharCode.apply(null,new Uint16Array(o.buffer))}return n}(e,void 0!==n&&n),i=r.indexOf("\n",10)+1,a=r.substring(i)+(o?"//# sourceMappingURL="+o:""),s=new Blob([a],{type:"application/javascript"});return URL.createObjectURL(s)}("Lyogcm9sbHVwLXBsdWdpbi13ZWItd29ya2VyLWxvYWRlciAqLwohZnVuY3Rpb24oKXsidXNlIHN0cmljdCI7Y2xhc3MgZSBleHRlbmRzIEVycm9ye2NvbnN0cnVjdG9yKHIsdCl7c3VwZXIodCksdGhpcy5lcnJvcj1yLHRoaXMuZXJyb3JfZGVzY3JpcHRpb249dCxPYmplY3Quc2V0UHJvdG90eXBlT2YodGhpcyxlLnByb3RvdHlwZSl9c3RhdGljIGZyb21QYXlsb2FkKHtlcnJvcjpyLGVycm9yX2Rlc2NyaXB0aW9uOnR9KXtyZXR1cm4gbmV3IGUocix0KX19Y2xhc3MgciBleHRlbmRzIGV7Y29uc3RydWN0b3IoZSxzKXtzdXBlcigibWlzc2luZ19yZWZyZXNoX3Rva2VuIixgTWlzc2luZyBSZWZyZXNoIFRva2VuIChhdWRpZW5jZTogJyR7dChlLFsiZGVmYXVsdCJdKX0nLCBzY29wZTogJyR7dChzKX0nKWApLHRoaXMuYXVkaWVuY2U9ZSx0aGlzLnNjb3BlPXMsT2JqZWN0LnNldFByb3RvdHlwZU9mKHRoaXMsci5wcm90b3R5cGUpfX1mdW5jdGlvbiB0KGUscj1bXSl7cmV0dXJuIGUmJiFyLmluY2x1ZGVzKGUpP2U6IiJ9ImZ1bmN0aW9uIj09dHlwZW9mIFN1cHByZXNzZWRFcnJvciYmU3VwcHJlc3NlZEVycm9yO2NvbnN0IHM9ZT0+e3ZhcntjbGllbnRJZDpyfT1lLHQ9ZnVuY3Rpb24oZSxyKXt2YXIgdD17fTtmb3IodmFyIHMgaW4gZSlPYmplY3QucHJvdG90eXBlLmhhc093blByb3BlcnR5LmNhbGwoZSxzKSYmci5pbmRleE9mKHMpPDAmJih0W3NdPWVbc10pO2lmKG51bGwhPWUmJiJmdW5jdGlvbiI9PXR5cGVvZiBPYmplY3QuZ2V0T3duUHJvcGVydHlTeW1ib2xzKXt2YXIgbz0wO2ZvcihzPU9iamVjdC5nZXRPd25Qcm9wZXJ0eVN5bWJvbHMoZSk7bzxzLmxlbmd0aDtvKyspci5pbmRleE9mKHNbb10pPDAmJk9iamVjdC5wcm90b3R5cGUucHJvcGVydHlJc0VudW1lcmFibGUuY2FsbChlLHNbb10pJiYodFtzW29dXT1lW3Nbb11dKX1yZXR1cm4gdH0oZSxbImNsaWVudElkIl0pO3JldHVybiBuZXcgVVJMU2VhcmNoUGFyYW1zKChlPT5PYmplY3Qua2V5cyhlKS5maWx0ZXIoKHI9PnZvaWQgMCE9PWVbcl0pKS5yZWR1Y2UoKChyLHQpPT5PYmplY3QuYXNzaWduKE9iamVjdC5hc3NpZ24oe30scikse1t0XTplW3RdfSkpLHt9KSkoT2JqZWN0LmFzc2lnbih7Y2xpZW50X2lkOnJ9LHQpKSkudG9TdHJpbmcoKX07bGV0IG89e307Y29uc3Qgbj0oZSxyKT0+YCR7ZX18JHtyfWA7YWRkRXZlbnRMaXN0ZW5lcigibWVzc2FnZSIsKGFzeW5jKHtkYXRhOnt0aW1lb3V0OmUsYXV0aDp0LGZldGNoVXJsOmMsZmV0Y2hPcHRpb25zOmksdXNlRm9ybURhdGE6YX0scG9ydHM6W3BdfSk9PntsZXQgZix1PXt9O2NvbnN0e2F1ZGllbmNlOmQsc2NvcGU6aH09dHx8e307dHJ5e2NvbnN0IHQ9YT8oZT0+e2NvbnN0IHI9bmV3IFVSTFNlYXJjaFBhcmFtcyhlKSx0PXt9O3JldHVybiByLmZvckVhY2goKChlLHIpPT57dFtyXT1lfSkpLHR9KShpLmJvZHkpOkpTT04ucGFyc2UoaS5ib2R5KTtpZighdC5yZWZyZXNoX3Rva2VuJiYicmVmcmVzaF90b2tlbiI9PT10LmdyYW50X3R5cGUpe2NvbnN0IGU9KChlLHIpPT5vW24oZSxyKV0pKGQsaCk7aWYoIWUpdGhyb3cgbmV3IHIoZCxoKTtpLmJvZHk9YT9zKE9iamVjdC5hc3NpZ24oT2JqZWN0LmFzc2lnbih7fSx0KSx7cmVmcmVzaF90b2tlbjplfSkpOkpTT04uc3RyaW5naWZ5KE9iamVjdC5hc3NpZ24oT2JqZWN0LmFzc2lnbih7fSx0KSx7cmVmcmVzaF90b2tlbjplfSkpfWxldCB5LE87ImZ1bmN0aW9uIj09dHlwZW9mIEFib3J0Q29udHJvbGxlciYmKHk9bmV3IEFib3J0Q29udHJvbGxlcixpLnNpZ25hbD15LnNpZ25hbCk7dHJ5e089YXdhaXQgUHJvbWlzZS5yYWNlKFsoZz1lLG5ldyBQcm9taXNlKChlPT5zZXRUaW1lb3V0KGUsZykpKSksZmV0Y2goYyxPYmplY3QuYXNzaWduKHt9LGkpKV0pfWNhdGNoKGUpe3JldHVybiB2b2lkIHAucG9zdE1lc3NhZ2Uoe2Vycm9yOmUubWVzc2FnZX0pfWlmKCFPKXJldHVybiB5JiZ5LmFib3J0KCksdm9pZCBwLnBvc3RNZXNzYWdlKHtlcnJvcjoiVGltZW91dCB3aGVuIGV4ZWN1dGluZyAnZmV0Y2gnIn0pO2w9Ty5oZWFkZXJzLHU9Wy4uLmxdLnJlZHVjZSgoKGUsW3IsdF0pPT4oZVtyXT10LGUpKSx7fSksZj1hd2FpdCBPLmpzb24oKSxmLnJlZnJlc2hfdG9rZW4/KCgoZSxyLHQpPT57b1tuKHIsdCldPWV9KShmLnJlZnJlc2hfdG9rZW4sZCxoKSxkZWxldGUgZi5yZWZyZXNoX3Rva2VuKTooKGUscik9PntkZWxldGUgb1tuKGUscildfSkoZCxoKSxwLnBvc3RNZXNzYWdlKHtvazpPLm9rLGpzb246ZixoZWFkZXJzOnV9KX1jYXRjaChlKXtwLnBvc3RNZXNzYWdlKHtvazohMSxqc29uOntlcnJvcjplLmVycm9yLGVycm9yX2Rlc2NyaXB0aW9uOmUubWVzc2FnZX0saGVhZGVyczp1fSl9dmFyIGwsZ30pKX0oKTsKCg==",null,false),new Worker(ce,e)};const le={};class de{constructor(e,t){this.cache=e,this.clientId=t,this.manifestKey=this.createManifestKeyFrom(this.clientId)}async add(e){var t;const n=new Set((null===(t=await this.cache.get(this.manifestKey))||void 0===t?void 0:t.keys)||[]);n.add(e),await this.cache.set(this.manifestKey,{keys:[...n]})}async remove(e){const t=await this.cache.get(this.manifestKey);if(t){const n=new Set(t.keys);return n.delete(e),n.size>0?await this.cache.set(this.manifestKey,{keys:[...n]}):await this.cache.remove(this.manifestKey)}}get(){return this.cache.get(this.manifestKey)}clear(){return this.cache.remove(this.manifestKey)}createManifestKeyFrom(e){return`@@auth0spajs@@::${e}`}}const he={memory:()=>(new $).enclosedCache,localstorage:()=>new Y},pe=e=>he[e],fe=e=>{const{openUrl:t,onRedirect:n}=e,o=a(e,["openUrl","onRedirect"]);return Object.assign(Object.assign({},o),{openUrl:!1===t||t?t:n})},me={NONCE:"nonce",KEYPAIR:"keypair"};class ge{constructor(e){this.clientId=e}getVersion(){return 1}createDbHandle(){const e=window.indexedDB.open("auth0-spa-js",this.getVersion());return new Promise(((t,n)=>{e.onupgradeneeded=()=>Object.values(me).forEach((t=>e.result.createObjectStore(t))),e.onerror=()=>n(e.error),e.onsuccess=()=>t(e.result)}))}async getDbHandle(){return this.dbHandle||(this.dbHandle=await this.createDbHandle()),this.dbHandle}async executeDbRequest(e,t,n){const o=n((await this.getDbHandle()).transaction(e,t).objectStore(e));return new Promise(((e,t)=>{o.onsuccess=()=>e(o.result),o.onerror=()=>t(o.error)}))}buildKey(e){const t=e?`_${e}`:"auth0";return`${this.clientId}::${t}`}setNonce(e,t){return this.save(me.NONCE,this.buildKey(t),e)}setKeyPair(e){return this.save(me.KEYPAIR,this.buildKey(),e)}async save(e,t,n){await this.executeDbRequest(e,"readwrite",(e=>e.put(n,t)))}findNonce(e){return this.find(me.NONCE,this.buildKey(e))}findKeyPair(){return this.find(me.KEYPAIR,this.buildKey())}find(e,t){return this.executeDbRequest(e,"readonly",(e=>e.get(t)))}async deleteBy(e,t){const n=await this.executeDbRequest(e,"readonly",(e=>e.getAllKeys()));null==n||n.filter(t).map((t=>this.executeDbRequest(e,"readwrite",(e=>e.delete(t)))))}deleteByClientId(e,t){return this.deleteBy(e,(e=>"string"==typeof e&&e.startsWith(`${t}::`)))}clearNonces(){return this.deleteByClientId(me.NONCE,this.clientId)}clearKeyPairs(){return this.deleteByClientId(me.KEYPAIR,this.clientId)}}class ye{constructor(e){this.storage=new ge(e)}getNonce(e){return this.storage.findNonce(e)}setNonce(e,t){return this.storage.setNonce(e,t)}async getOrGenerateKeyPair(){let e=await this.storage.findKeyPair();return e||(e=await async function(e,t){var n;let o;return o={name:"ECDSA",namedCurve:"P-256"},crypto.subtle.generateKey(o,null!==(n=null==t?void 0:t.extractable)&&void 0!==n&&n,["sign","verify"])}(0,{extractable:!1}),await this.storage.setKeyPair(e)),e}async generateProof(e){const t=await this.getOrGenerateKeyPair();return function({keyPair:e,url:t,method:n,nonce:o,accessToken:r}){const i=function(e){const t=new URL(e);return t.search="",t.hash="",t.href}(t);return W(e,i,n,o,r)}(Object.assign({keyPair:t},e))}async calculateThumbprint(){return function(e){return async function(e){if(!L(e))throw new TypeError('"publicKey" must be a public CryptoKey');if(!0!==e.extractable)throw new TypeError('"publicKey.extractable" must be true');const t=await Z(e);let n;switch(t.kty){case"EC":n={crv:t.crv,kty:t.kty,x:t.x,y:t.y};break;case"OKP":n={crv:t.crv,kty:t.kty,x:t.x};break;case"RSA":n={e:t.e,kty:t.kty,n:t.n};break;default:throw new U("unsupported JWK kty")}return K(await crypto.subtle.digest({name:"SHA-256"},j(JSON.stringify(n))))}(e.publicKey)}(await this.getOrGenerateKeyPair())}async clear(){await Promise.all([this.storage.clearNonces(),this.storage.clearKeyPairs()])}}class we{constructor(e,t){this.hooks=t,this.config=Object.assign(Object.assign({},e),{fetch:e.fetch||("undefined"==typeof window?fetch:window.fetch.bind(window))})}isAbsoluteUrl(e){return/^(https?:)?\/\//i.test(e)}buildUrl(e,t){if(t){if(this.isAbsoluteUrl(t))return t;if(e)return`${e.replace(/\/?\/$/,"")}/${t.replace(/^\/+/,"")}`}throw new TypeError("`url` must be absolute or `baseUrl` non-empty.")}getAccessToken(){return this.config.getAccessToken?this.config.getAccessToken():this.hooks.getAccessToken()}buildBaseRequest(e,t){const n=new Request(e,t);return this.config.baseUrl?new Request(this.buildUrl(this.config.baseUrl,n.url),n):n}async setAuthorizationHeader(e,t){e.headers.set("authorization",`${this.config.dpopNonceId?"DPoP":"Bearer"} ${t}`)}async setDpopProofHeader(e,t){if(!this.config.dpopNonceId)return;const n=await this.hooks.getDpopNonce(),o=await this.hooks.generateDpopProof({accessToken:t,method:e.method,nonce:n,url:e.url});e.headers.set("dpop",o)}async prepareRequest(e){const t=await this.getAccessToken();this.setAuthorizationHeader(e,t),await this.setDpopProofHeader(e,t)}getHeader(e,t){return Array.isArray(e)?new Headers(e).get(t)||"":"function"==typeof e.get?e.get(t)||"":e[t]||""}hasUseDpopNonceError(e){return 401===e.status&&this.getHeader(e.headers,"www-authenticate").includes("use_dpop_nonce")}async handleResponse(e,t){const n=this.getHeader(e.headers,"dpop-nonce");if(n&&await this.hooks.setDpopNonce(n),!this.hasUseDpopNonceError(e))return e;if(!n||!t.onUseDpopNonceError)throw new _(n);return t.onUseDpopNonceError()}async internalFetchWithAuth(e,t,n){const o=this.buildBaseRequest(e,t);await this.prepareRequest(o);const r=await this.config.fetch(o);return this.handleResponse(r,n)}fetchWithAuth(e,t){const n={onUseDpopNonceError:()=>this.internalFetchWithAuth(e,t,Object.assign(Object.assign({},n),{onUseDpopNonceError:void 0}))};return this.internalFetchWithAuth(e,t,n)}}const be=new d;class ve{constructor(e){let t,n;if(this.userCache=(new $).enclosedCache,this.defaultOptions={authorizationParams:{scope:"openid profile email"},useRefreshTokensFallback:!1,useFormData:!0},this._releaseLockOnPageHide=async()=>{await be.releaseLock("auth0.lock.getTokenSilently"),window.removeEventListener("pagehide",this._releaseLockOnPageHide)},this.options=Object.assign(Object.assign(Object.assign({},this.defaultOptions),e),{authorizationParams:Object.assign(Object.assign({},this.defaultOptions.authorizationParams),e.authorizationParams)}),"undefined"!=typeof window&&(()=>{if(!S())throw new Error("For security reasons, `window.crypto` is required to run `auth0-spa-js`.");if(void 0===S().subtle)throw new Error("\n auth0-spa-js must run on a secure origin. See https://github.com/auth0/auth0-spa-js/blob/main/FAQ.md#why-do-i-get-auth0-spa-js-must-run-on-a-secure-origin for more information.\n ")})(),e.cache&&e.cacheLocation&&console.warn("Both `cache` and `cacheLocation` options have been specified in the Auth0Client configuration; ignoring `cacheLocation` and using `cache`."),e.cache)n=e.cache;else{if(t=e.cacheLocation||"memory",!pe(t))throw new Error(`Invalid cache location "${t}"`);n=pe(t)()}this.httpTimeoutMs=e.httpTimeoutInSeconds?1e3*e.httpTimeoutInSeconds:1e4,this.cookieStorage=!1===e.legacySameSiteCookie?ie:ae,this.orgHintCookieName=`auth0.${this.options.clientId}.organization_hint`,this.isAuthenticatedCookieName=(()=>`auth0.${this.options.clientId}.is.authenticated`)(),this.sessionCheckExpiryDays=e.sessionCheckExpiryDays||1;const o=e.useCookiesForTransactions?this.cookieStorage:se;var r;this.scope=J("openid",this.options.authorizationParams.scope,this.options.useRefreshTokens?"offline_access":""),this.transactionManager=new q(o,this.options.clientId,this.options.cookieDomain),this.nowProvider=this.options.nowProvider||f,this.cacheManager=new B(n,n.allKeys?void 0:new de(n,this.options.clientId),this.nowProvider),this.dpop=this.options.useDpop?new ye(this.options.clientId):void 0,this.domainUrl=(r=this.options.domain,/^https?:\/\//.test(r)?r:`https://${r}`),this.tokenIssuer=((e,t)=>e?e.startsWith("https://")?e:`https://${e}/`:`${t}/`)(this.options.issuer,this.domainUrl),"undefined"!=typeof window&&window.Worker&&this.options.useRefreshTokens&&"memory"===t&&(this.options.workerUrl?this.worker=new Worker(this.options.workerUrl):this.worker=new ue)}_url(e){const t=encodeURIComponent(btoa(JSON.stringify(this.options.auth0Client||p)));return`${this.domainUrl}${e}&auth0Client=${t}`}_authorizeUrl(e){return this._url(`/authorize?${O(e)}`)}async _verifyIdToken(e,t,n){const o=await this.nowProvider();return(e=>{if(!e.id_token)throw new Error("ID token is required but missing");const t=(e=>{const t=e.split("."),[n,o,r]=t;if(3!==t.length||!n||!o||!r)throw new Error("ID token could not be decoded");const i=JSON.parse(E(o)),a={__raw:e},s={};return Object.keys(i).forEach((e=>{a[e]=i[e],ee.includes(e)||(s[e]=i[e])})),{encoded:{header:n,payload:o,signature:r},header:JSON.parse(E(n)),claims:a,user:s}})(e.id_token);if(!t.claims.iss)throw new Error("Issuer (iss) claim must be a string present in the ID token");if(t.claims.iss!==e.iss)throw new Error(`Issuer (iss) claim mismatch in the ID token; expected "${e.iss}", found "${t.claims.iss}"`);if(!t.user.sub)throw new Error("Subject (sub) claim must be a string present in the ID token");if("RS256"!==t.header.alg)throw new Error(`Signature algorithm of "${t.header.alg}" is not supported. Expected the ID token to be signed with "RS256".`);if(!t.claims.aud||"string"!=typeof t.claims.aud&&!Array.isArray(t.claims.aud))throw new Error("Audience (aud) claim must be a string or array of strings present in the ID token");if(Array.isArray(t.claims.aud)){if(!t.claims.aud.includes(e.aud))throw new Error(`Audience (aud) claim mismatch in the ID token; expected "${e.aud}" but was not one of "${t.claims.aud.join(", ")}"`);if(t.claims.aud.length>1){if(!t.claims.azp)throw new Error("Authorized Party (azp) claim must be a string present in the ID token when Audience (aud) claim has multiple values");if(t.claims.azp!==e.aud)throw new Error(`Authorized Party (azp) claim mismatch in the ID token; expected "${e.aud}", found "${t.claims.azp}"`)}}else if(t.claims.aud!==e.aud)throw new Error(`Audience (aud) claim mismatch in the ID token; expected "${e.aud}" but found "${t.claims.aud}"`);if(e.nonce){if(!t.claims.nonce)throw new Error("Nonce (nonce) claim must be a string present in the ID token");if(t.claims.nonce!==e.nonce)throw new Error(`Nonce (nonce) claim mismatch in the ID token; expected "${e.nonce}", found "${t.claims.nonce}"`)}if(e.max_age&&!Q(t.claims.auth_time))throw new Error("Authentication Time (auth_time) claim must be a number present in the ID token when Max Age (max_age) is specified");if(null==t.claims.exp||!Q(t.claims.exp))throw new Error("Expiration Time (exp) claim must be a number present in the ID token");if(!Q(t.claims.iat))throw new Error("Issued At (iat) claim must be a number present in the ID token");const n=e.leeway||60,o=new Date(e.now||Date.now()),r=new Date(0);if(r.setUTCSeconds(t.claims.exp+n),o>r)throw new Error(`Expiration Time (exp) claim error in the ID token; current time (${o}) is after expiration time (${r})`);if(null!=t.claims.nbf&&Q(t.claims.nbf)){const e=new Date(0);if(e.setUTCSeconds(t.claims.nbf-n),o<e)throw new Error(`Not Before time (nbf) claim in the ID token indicates that this token can't be used just yet. Current time (${o}) is before ${e}`)}if(null!=t.claims.auth_time&&Q(t.claims.auth_time)){const r=new Date(0);if(r.setUTCSeconds(parseInt(t.claims.auth_time)+e.max_age+n),o>r)throw new Error(`Authentication Time (auth_time) claim in the ID token indicates that too much time has passed since the last end-user authentication. Current time (${o}) is after last auth at ${r}`)}if(e.organization){const n=e.organization.trim();if(n.startsWith("org_")){const e=n;if(!t.claims.org_id)throw new Error("Organization ID (org_id) claim must be a string present in the ID token");if(e!==t.claims.org_id)throw new Error(`Organization ID (org_id) claim mismatch in the ID token; expected "${e}", found "${t.claims.org_id}"`)}else{const e=n.toLowerCase();if(!t.claims.org_name)throw new Error("Organization Name (org_name) claim must be a string present in the ID token");if(e!==t.claims.org_name)throw new Error(`Organization Name (org_name) claim mismatch in the ID token; expected "${e}", found "${t.claims.org_name}"`)}}return t})({iss:this.tokenIssuer,aud:this.options.clientId,id_token:e,nonce:t,organization:n,leeway:this.options.leeway,max_age:(r=this.options.authorizationParams.max_age,"string"!=typeof r?r:parseInt(r,10)||void 0),now:o});var r}_processOrgHint(e){e?this.cookieStorage.save(this.orgHintCookieName,e,{daysUntilExpire:this.sessionCheckExpiryDays,cookieDomain:this.options.cookieDomain}):this.cookieStorage.remove(this.orgHintCookieName,{cookieDomain:this.options.cookieDomain})}async _prepareAuthorizeUrl(e,t,n){var o;const r=P(T()),i=P(T()),a=T(),s=(e=>{const t=new Uint8Array(e);return(e=>{const t={"+":"-","/":"_","=":""};return e.replace(/[+/=]/g,(e=>t[e]))})(window.btoa(String.fromCharCode(...Array.from(t))))})(await(async e=>{const t=S().subtle.digest({name:"SHA-256"},(new TextEncoder).encode(e));return await t})(a)),c=await(null===(o=this.dpop)||void 0===o?void 0:o.calculateThumbprint()),u=((e,t,n,o,r,i,a,s,c)=>Object.assign(Object.assign(Object.assign({client_id:e.clientId},e.authorizationParams),n),{scope:J(t,n.scope),response_type:"code",response_mode:s||"query",state:o,nonce:r,redirect_uri:a||e.authorizationParams.redirect_uri,code_challenge:i,code_challenge_method:"S256",dpop_jkt:c}))(this.options,this.scope,e,r,i,s,e.redirect_uri||this.options.authorizationParams.redirect_uri||n,null==t?void 0:t.response_mode,c),l=this._authorizeUrl(u);return{nonce:i,code_verifier:a,scope:u.scope,audience:u.audience||"default",redirect_uri:u.redirect_uri,state:r,url:l}}async loginWithPopup(e,t){var n;if(e=e||{},!(t=t||{}).popup&&(t.popup=(()=>{const e=window.screenX+(window.innerWidth-400)/2,t=window.screenY+(window.innerHeight-600)/2;return window.open("","auth0:authorize:popup",`left=${e},top=${t},width=400,height=600,resizable,scrollbars=yes,status=1`)})(),!t.popup))throw new Error("Unable to open a popup for loginWithPopup - window.open returned `null`");const o=await this._prepareAuthorizeUrl(e.authorizationParams||{},{response_mode:"web_message"},window.location.origin);t.popup.location.href=o.url;const r=await(e=>new Promise(((t,n)=>{let o;const r=setInterval((()=>{e.popup&&e.popup.closed&&(clearInterval(r),clearTimeout(i),window.removeEventListener("message",o,!1),n(new b(e.popup)))}),1e3),i=setTimeout((()=>{clearInterval(r),n(new w(e.popup)),window.removeEventListener("message",o,!1)}),1e3*(e.timeoutInSeconds||60));o=function(a){if(a.data&&"authorization_response"===a.data.type){if(clearTimeout(i),clearInterval(r),window.removeEventListener("message",o,!1),e.popup.close(),a.data.response.error)return n(m.fromPayload(a.data.response));t(a.data.response)}},window.addEventListener("message",o)})))(Object.assign(Object.assign({},t),{timeoutInSeconds:t.timeoutInSeconds||this.options.authorizeTimeoutInSeconds||60}));if(o.state!==r.state)throw new m("state_mismatch","Invalid state");const i=(null===(n=e.authorizationParams)||void 0===n?void 0:n.organization)||this.options.authorizationParams.organization;await this._requestToken({audience:o.audience,scope:o.scope,code_verifier:o.code_verifier,grant_type:"authorization_code",code:r.code,redirect_uri:o.redirect_uri},{nonceIn:o.nonce,organization:i})}async getUser(){var e;const t=await this._getIdTokenFromCache();return null===(e=null==t?void 0:t.decodedToken)||void 0===e?void 0:e.user}async getIdTokenClaims(){var e;const t=await this._getIdTokenFromCache();return null===(e=null==t?void 0:t.decodedToken)||void 0===e?void 0:e.claims}async loginWithRedirect(e={}){var t;const n=fe(e),{openUrl:o,fragment:r,appState:i}=n,s=a(n,["openUrl","fragment","appState"]),c=(null===(t=s.authorizationParams)||void 0===t?void 0:t.organization)||this.options.authorizationParams.organization,u=await this._prepareAuthorizeUrl(s.authorizationParams||{}),{url:l}=u,d=a(u,["url"]);this.transactionManager.create(Object.assign(Object.assign(Object.assign({},d),{appState:i}),c&&{organization:c}));const h=r?`${l}#${r}`:l;o?await o(h):window.location.assign(h)}async handleRedirectCallback(e=window.location.href){const t=e.split("?").slice(1);if(0===t.length)throw new Error("There are no query params available for parsing.");const{state:n,code:o,error:r,error_description:i}=(e=>{e.indexOf("#")>-1&&(e=e.substring(0,e.indexOf("#")));const t=new URLSearchParams(e);return{state:t.get("state"),code:t.get("code")||void 0,error:t.get("error")||void 0,error_description:t.get("error_description")||void 0}})(t.join("")),a=this.transactionManager.get();if(!a)throw new m("missing_transaction","Invalid state");if(this.transactionManager.remove(),r)throw new g(r,i||r,n,a.appState);if(!a.code_verifier||a.state&&a.state!==n)throw new m("state_mismatch","Invalid state");const s=a.organization,c=a.nonce,u=a.redirect_uri;return await this._requestToken(Object.assign({audience:a.audience,scope:a.scope,code_verifier:a.code_verifier,grant_type:"authorization_code",code:o},u?{redirect_uri:u}:{}),{nonceIn:c,organization:s}),{appState:a.appState}}async checkSession(e){if(!this.cookieStorage.get(this.isAuthenticatedCookieName)){if(!this.cookieStorage.get("auth0.is.authenticated"))return;this.cookieStorage.save(this.isAuthenticatedCookieName,!0,{daysUntilExpire:this.sessionCheckExpiryDays,cookieDomain:this.options.cookieDomain}),this.cookieStorage.remove("auth0.is.authenticated")}try{await this.getTokenSilently(e)}catch(e){}}async getTokenSilently(e={}){var t;const n=Object.assign(Object.assign({cacheMode:"on"},e),{authorizationParams:Object.assign(Object.assign(Object.assign({},this.options.authorizationParams),e.authorizationParams),{scope:J(this.scope,null===(t=e.authorizationParams)||void 0===t?void 0:t.scope)})}),o=await((e,t)=>{let n=le[t];return n||(n=e().finally((()=>{delete le[t],n=null})),le[t]=n),n})((()=>this._getTokenSilently(n)),`${this.options.clientId}::${n.authorizationParams.audience}::${n.authorizationParams.scope}`);return e.detailedResponse?o:null==o?void 0:o.access_token}async _getTokenSilently(e){const{cacheMode:t}=e,n=a(e,["cacheMode"]);if("off"!==t){const e=await this._getEntryFromCache({scope:n.authorizationParams.scope,audience:n.authorizationParams.audience||"default",clientId:this.options.clientId});if(e)return e}if("cache-only"!==t){if(!await(async(e,t=3)=>{for(let n=0;n<t;n++)if(await e())return!0;return!1})((()=>be.acquireLock("auth0.lock.getTokenSilently",5e3)),10))throw new y;try{if(window.addEventListener("pagehide",this._releaseLockOnPageHide),"off"!==t){const e=await this._getEntryFromCache({scope:n.authorizationParams.scope,audience:n.authorizationParams.audience||"default",clientId:this.options.clientId});if(e)return e}const e=this.options.useRefreshTokens?await this._getTokenUsingRefreshToken(n):await this._getTokenFromIFrame(n),{id_token:o,token_type:r,access_token:i,oauthTokenScope:a,expires_in:s}=e;return Object.assign(Object.assign({id_token:o,token_type:r,access_token:i},a?{scope:a}:null),{expires_in:s})}finally{await be.releaseLock("auth0.lock.getTokenSilently"),window.removeEventListener("pagehide",this._releaseLockOnPageHide)}}}async getTokenWithPopup(e={},t={}){var n;const o=Object.assign(Object.assign({},e),{authorizationParams:Object.assign(Object.assign(Object.assign({},this.options.authorizationParams),e.authorizationParams),{scope:J(this.scope,null===(n=e.authorizationParams)||void 0===n?void 0:n.scope)})});return t=Object.assign(Object.assign({},h),t),await this.loginWithPopup(o,t),(await this.cacheManager.get(new M({scope:o.authorizationParams.scope,audience:o.authorizationParams.audience||"default",clientId:this.options.clientId}))).access_token}async isAuthenticated(){return!!await this.getUser()}_buildLogoutUrl(e){null!==e.clientId?e.clientId=e.clientId||this.options.clientId:delete e.clientId;const t=e.logoutParams||{},{federated:n}=t,o=a(t,["federated"]),r=n?"&federated":"";return this._url(`/v2/logout?${O(Object.assign({clientId:e.clientId},o))}`)+r}async logout(e={}){var t;const n=fe(e),{openUrl:o}=n,r=a(n,["openUrl"]);null===e.clientId?await this.cacheManager.clear():await this.cacheManager.clear(e.clientId||this.options.clientId),this.cookieStorage.remove(this.orgHintCookieName,{cookieDomain:this.options.cookieDomain}),this.cookieStorage.remove(this.isAuthenticatedCookieName,{cookieDomain:this.options.cookieDomain}),this.userCache.remove("@@user@@"),await(null===(t=this.dpop)||void 0===t?void 0:t.clear());const i=this._buildLogoutUrl(r);o?await o(i):!1!==o&&window.location.assign(i)}async _getTokenFromIFrame(e){const t=Object.assign(Object.assign({},e.authorizationParams),{prompt:"none"}),n=this.cookieStorage.get(this.orgHintCookieName);n&&!t.organization&&(t.organization=n);const{url:o,state:r,nonce:i,code_verifier:a,redirect_uri:s,scope:c,audience:u}=await this._prepareAuthorizeUrl(t,{response_mode:"web_message"},window.location.origin);try{if(window.crossOriginIsolated)throw new m("login_required","The application is running in a Cross-Origin Isolated context, silently retrieving a token without refresh token is not possible.");const n=e.timeoutInSeconds||this.options.authorizeTimeoutInSeconds;let l;try{l=new URL(this.domainUrl).origin}catch(e){l=this.domainUrl}const d=await((e,t,n=60)=>new Promise(((o,r)=>{const i=window.document.createElement("iframe");i.setAttribute("width","0"),i.setAttribute("height","0"),i.style.display="none";const a=()=>{window.document.body.contains(i)&&(window.document.body.removeChild(i),window.removeEventListener("message",s,!1))};let s;const c=setTimeout((()=>{r(new y),a()}),1e3*n);s=function(e){if(e.origin!=t)return;if(!e.data||"authorization_response"!==e.data.type)return;const n=e.source;n&&n.close(),e.data.response.error?r(m.fromPayload(e.data.response)):o(e.data.response),clearTimeout(c),window.removeEventListener("message",s,!1),setTimeout(a,2e3)},window.addEventListener("message",s,!1),window.document.body.appendChild(i),i.setAttribute("src",e)})))(o,l,n);if(r!==d.state)throw new m("state_mismatch","Invalid state");const h=await this._requestToken(Object.assign(Object.assign({},e.authorizationParams),{code_verifier:a,code:d.code,grant_type:"authorization_code",redirect_uri:s,timeout:e.authorizationParams.t