UNPKG

@accounter/client

Version:
5 lines • 200 kB
import{s as e}from"./dist-BmACi7k_.js";import{o as t}from"./utils-BxkqV8PM.js";import{n,t as r}from"./dist-CQgUtVPI.js";n();var i=e(t()),a=function(e,t){return a=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])},a(e,t)};function o(e,t){if(typeof t!=`function`&&t!==null)throw TypeError(`Class extends value `+String(t)+` is not a constructor or null`);a(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}var s=function(){return s=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n],t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},s.apply(this,arguments)};function c(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols==`function`)for(var i=0,r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]]);return n}function l(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})}function u(e,t){var n={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},r,i,a,o=Object.create((typeof Iterator==`function`?Iterator:Object).prototype);return o.next=s(0),o.throw=s(1),o.return=s(2),typeof Symbol==`function`&&(o[Symbol.iterator]=function(){return this}),o;function s(e){return function(t){return c([e,t])}}function c(s){if(r)throw TypeError(`Generator is already executing.`);for(;o&&(o=0,s[0]&&(n=0)),n;)try{if(r=1,i&&(a=s[0]&2?i.return:s[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,s[1])).done)return a;switch(i=0,a&&(s=[s[0]&2,a.value]),s[0]){case 0:case 1:a=s;break;case 4:return n.label++,{value:s[1],done:!1};case 5:n.label++,i=s[1],s=[0];continue;case 7:s=n.ops.pop(),n.trys.pop();continue;default:if((a=n.trys,!(a=a.length>0&&a[a.length-1]))&&(s[0]===6||s[0]===2)){n=0;continue}if(s[0]===3&&(!a||s[1]>a[0]&&s[1]<a[3])){n.label=s[1];break}if(s[0]===6&&n.label<a[1]){n.label=a[1],a=s;break}if(a&&n.label<a[2]){n.label=a[2],n.ops.push(s);break}a[2]&&n.ops.pop(),n.trys.pop();continue}s=t.call(e,n)}catch(e){s=[6,e],i=0}finally{r=a=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}}function d(e,t,n){if(n||arguments.length===2)for(var r=0,i=t.length,a;r<i;r++)(a||!(r in t))&&(a||=Array.prototype.slice.call(t,0,r),a[r]=t[r]);return e.concat(a||Array.prototype.slice.call(t))}function f(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols==`function`){var i=0;for(r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]])}return n}function p(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)}function m(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n}function h(e,t){this.v=e,this.k=t}function g(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function _(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`)}function ee(e){return new h(e,0)}function v(e,t){if(t.has(e))throw TypeError(`Cannot initialize the same private elements twice on an object`)}function y(e,t){return e.get(_(e,t))}function b(e,t,n){v(e,t),t.set(e,n)}function x(e,t,n){return e.set(_(e,t),n),n}function te(e,t){v(e,t),t.add(e)}function S(e,t,n){return(t=function(e){var t=function(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)}(e,`string`);return typeof t==`symbol`?t:t+``}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ne(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 C(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?ne(Object(n),!0).forEach(function(t){S(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ne(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function re(e,t){if(e==null)return{};var n,r,i=function(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function w(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=e==null?null:typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n!=null){var r,i,a,o,s=[],c=!0,l=!1;try{if(a=(n=n.call(e)).next,t===0){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=a.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){l=!0,i=e}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(l)throw i}}return s}}(e,t)||function(e,t){if(e){if(typeof e==`string`)return g(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?g(e,t):void 0}}(e,t)||function(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}()}function ie(e){return function(){return new ae(e.apply(this,arguments))}}function ae(e){var t,n;function r(t,n){try{var a=e[t](n),o=a.value,s=o instanceof h;Promise.resolve(s?o.v:o).then(function(n){if(s){var c=t===`return`&&o.k?t:`next`;if(!o.k||n.done)return r(c,n);n=e[c](n).value}i(!!a.done,n)},function(e){r(`throw`,e)})}catch(e){i(2,e)}}function i(e,i){e===2?t.reject(i):t.resolve({value:i,done:e}),(t=t.next)?r(t.key,t.arg):n=null}this._invoke=function(e,i){return new Promise(function(a,o){var s={key:e,arg:i,resolve:a,reject:o,next:null};n?n=n.next=s:(t=n=s,r(e,i))})},typeof e.return!=`function`&&(this.return=void 0)}ae.prototype[typeof Symbol==`function`&&Symbol.asyncIterator||`@@asyncIterator`]=function(){return this},ae.prototype.next=function(e){return this._invoke(`next`,e)},ae.prototype.throw=function(e){return this._invoke(`throw`,e)},ae.prototype.return=function(e){return this._invoke(`return`,e)};var oe={timeoutInSeconds:60},se=1e4,ce=`memory`,le=`online_access`,ue={name:`auth0-spa-js`,version:`2.23.0`},de=()=>Date.now(),T=`default`,E=class e extends Error{constructor(t,n){super(n),this.error=t,this.error_description=n,Object.setPrototypeOf(this,e.prototype)}static fromPayload(t){let n=t.error,r=t.error_description;return new e(n,r)}},fe=class e extends E{constructor(t,n){super(`invalid_configuration`,`${t} ${n}`),this.suggestion=n,Object.setPrototypeOf(this,e.prototype)}},pe=class e extends E{constructor(t,n,r){let i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:null;super(t,n),this.state=r,this.appState=i,Object.setPrototypeOf(this,e.prototype)}},me=class e extends E{constructor(t,n,r,i){let a=arguments.length>4&&arguments[4]!==void 0?arguments[4]:null;super(t,n),this.connection=r,this.state=i,this.appState=a,Object.setPrototypeOf(this,e.prototype)}},he=class e extends E{constructor(){super(`timeout`,`Timeout`),Object.setPrototypeOf(this,e.prototype)}},ge=class e extends he{constructor(t){super(),this.popup=t,Object.setPrototypeOf(this,e.prototype)}},_e=class e extends E{constructor(t){super(`cancelled`,`Popup closed`),this.popup=t,Object.setPrototypeOf(this,e.prototype)}},ve=class e extends E{constructor(){super(`popup_open`,"Unable to open a popup for loginWithPopup - window.open returned `null`"),Object.setPrototypeOf(this,e.prototype)}},ye=class e extends E{constructor(t,n,r,i){super(t,n),this.mfa_token=r,this.mfa_requirements=i,Object.setPrototypeOf(this,e.prototype)}},be=class e extends E{constructor(t,n){super(`missing_refresh_token`,`Missing Refresh Token (audience: '${Ce(t,[`default`])}', scope: '${Ce(n)}')`),this.audience=t,this.scope=n,Object.setPrototypeOf(this,e.prototype)}},xe=class e extends E{constructor(t,n){super(`missing_scopes`,`Missing requested scopes after refresh (audience: '${Ce(t,[`default`])}', missing scope: '${Ce(n)}')`),this.audience=t,this.scope=n,Object.setPrototypeOf(this,e.prototype)}},Se=class e extends E{constructor(t){super(`use_dpop_nonce`,`Server rejected DPoP proof: wrong nonce`),this.newDpopNonce=t,Object.setPrototypeOf(this,e.prototype)}};function Ce(e){return e&&!(arguments.length>1&&arguments[1]!==void 0?arguments[1]:[]).includes(e)?e:``}var we=()=>window.crypto,Te=()=>{let e=``;for(;e.length<43;){let t=we().getRandomValues(new Uint8Array(43-e.length));for(let n of t)e.length<43&&n<198&&(e+=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.`[n%66])}return e},Ee=e=>btoa(e),De=[{key:`name`,type:[`string`]},{key:`version`,type:[`string`,`number`]},{key:`env`,type:[`object`]}],Oe=function(e){let t=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return Object.keys(e).reduce((n,r)=>{if(t&&r===`env`)return n;let i=De.find(e=>e.key===r);return i&&i.type.includes(typeof e[r])&&(n[r]=e[r]),n},{})},ke=e=>{var t=e.clientId,n=f(e,[`clientId`]);return new URLSearchParams((e=>Object.keys(e).filter(t=>e[t]!==void 0).reduce((t,n)=>Object.assign(Object.assign({},t),{[n]:e[n]}),{}))(Object.assign({client_id:t},n))).toString()},Ae=async e=>await we().subtle.digest({name:`SHA-256`},new TextEncoder().encode(e)),je=e=>(e=>decodeURIComponent(atob(e).split(``).map(e=>`%`+(`00`+e.charCodeAt(0).toString(16)).slice(-2)).join(``)))(e.replace(/_/g,`/`).replace(/-/g,`+`)),Me=e=>{let t=new Uint8Array(e);return(e=>{let t={"+":`-`,"/":`_`,"=":``};return e.replace(/[+/=]/g,e=>t[e])})(window.btoa(String.fromCharCode(...Array.from(t))))},Ne=typeof globalThis<`u`?globalThis:typeof window<`u`?window:r===void 0?typeof self<`u`?self:{}:r,Pe={},Fe={};Object.defineProperty(Fe,"__esModule",{value:!0});var Ie=function(){function e(){var e=this;this.locked=new Map,this.addToLocked=function(t,n){var r=e.locked.get(t);r===void 0?n===void 0?e.locked.set(t,[]):e.locked.set(t,[n]):n!==void 0&&(r.unshift(n),e.locked.set(t,r))},this.isLocked=function(t){return e.locked.has(t)},this.lock=function(t){return new Promise(function(n,r){e.isLocked(t)?e.addToLocked(t,n):(e.addToLocked(t),n())})},this.unlock=function(t){var n=e.locked.get(t);if(n!==void 0&&n.length!==0){var r=n.pop();e.locked.set(t,n),r!==void 0&&setTimeout(r,0)}else e.locked.delete(t)}}return e.getInstance=function(){return e.instance===void 0&&(e.instance=new e),e.instance},e}();Fe.default=function(){return Ie.getInstance()};var D=Ne&&Ne.__awaiter||function(e,t,n,r){return new(n||=Promise)(function(i,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?i(e.value):new n(function(t){t(e.value)}).then(o,s)}c((r=r.apply(e,t||[])).next())})},Le=Ne&&Ne.__generator||function(e,t){var n,r,i,a,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol==`function`&&(a[Symbol.iterator]=function(){return this}),a;function s(a){return function(s){return function(a){if(n)throw TypeError(`Generator is already executing.`);for(;o;)try{if(n=1,r&&(i=2&a[0]?r.return:a[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,a[1])).done)return i;switch(r=0,i&&(a=[2&a[0],i.value]),a[0]){case 0:case 1:i=a;break;case 4:return o.label++,{value:a[1],done:!1};case 5:o.label++,r=a[1],a=[0];continue;case 7:a=o.ops.pop(),o.trys.pop();continue;default:if(i=o.trys,!((i=i.length>0&&i[i.length-1])||a[0]!==6&&a[0]!==2)){o=0;continue}if(a[0]===3&&(!i||a[1]>i[0]&&a[1]<i[3])){o.label=a[1];break}if(a[0]===6&&o.label<i[1]){o.label=i[1],i=a;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(a);break}i[2]&&o.ops.pop(),o.trys.pop();continue}a=t.call(e,o)}catch(e){a=[6,e],r=0}finally{n=i=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,s])}}},Re=Ne;Object.defineProperty(Pe,"__esModule",{value:!0});var ze=Fe,Be=`browser-tabs-lock-key`,Ve={key:function(e){return D(Re,void 0,void 0,function(){return Le(this,function(e){throw Error(`Unsupported`)})})},getItem:function(e){return D(Re,void 0,void 0,function(){return Le(this,function(e){throw Error(`Unsupported`)})})},clear:function(){return D(Re,void 0,void 0,function(){return Le(this,function(e){return[2,window.localStorage.clear()]})})},removeItem:function(e){return D(Re,void 0,void 0,function(){return Le(this,function(e){throw Error(`Unsupported`)})})},setItem:function(e,t){return D(Re,void 0,void 0,function(){return Le(this,function(e){throw 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 He(e){return new Promise(function(t){return setTimeout(t,e)})}function Ue(e){for(var t=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz`,n=``,r=0;r<e;r++)n+=t[Math.floor(61*Math.random())];return n}var We=Pe.default=function(){function e(t){this.acquiredIatSet=new Set,this.storageHandler=void 0,this.id=Date.now().toString()+Ue(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,e.waiters===void 0&&(e.waiters=[])}return e.prototype.acquireLock=function(t,n){return n===void 0&&(n=5e3),D(this,void 0,void 0,function(){var r,i,a,o,s,c,l;return Le(this,function(u){switch(u.label){case 0:r=Date.now()+Ue(4),i=Date.now()+n,a=Be+`-`+t,o=this.storageHandler===void 0?Ve:this.storageHandler,u.label=1;case 1:return Date.now()<i?[4,He(30)]:[3,8];case 2:return u.sent(),o.getItemSync(a)===null?(s=this.id+`-`+t+`-`+r,[4,He(Math.floor(25*Math.random()))]):[3,5];case 3:return u.sent(),o.setItemSync(a,JSON.stringify({id:this.id,iat:r,timeoutKey:s,timeAcquired:Date.now(),timeRefreshed:Date.now()})),[4,He(30)];case 4:return u.sent(),(c=o.getItemSync(a))!==null&&(l=JSON.parse(c)).id===this.id&&l.iat===r?(this.acquiredIatSet.add(r),this.refreshLockWhileAcquired(a,r),[2,!0]):[3,7];case 5:return e.lockCorrector(this.storageHandler===void 0?Ve:this.storageHandler),[4,this.waitForSomethingToChange(i)];case 6:u.sent(),u.label=7;case 7:return r=Date.now()+Ue(4),[3,1];case 8:return[2,!1]}})})},e.prototype.refreshLockWhileAcquired=function(e,t){return D(this,void 0,void 0,function(){var n=this;return Le(this,function(r){return setTimeout(function(){return D(n,void 0,void 0,function(){var n,r,i;return Le(this,function(a){switch(a.label){case 0:return[4,ze.default().lock(t)];case 1:return a.sent(),this.acquiredIatSet.has(t)?(n=this.storageHandler===void 0?Ve:this.storageHandler,(r=n.getItemSync(e))===null?(ze.default().unlock(t),[2]):((i=JSON.parse(r)).timeRefreshed=Date.now(),n.setItemSync(e,JSON.stringify(i)),ze.default().unlock(t),this.refreshLockWhileAcquired(e,t),[2])):(ze.default().unlock(t),[2])}})})},1e3),[2]})})},e.prototype.waitForSomethingToChange=function(t){return D(this,void 0,void 0,function(){return Le(this,function(n){switch(n.label){case 0:return[4,new Promise(function(n){var r=!1,i=Date.now(),a=!1;function o(){if(a||=(window.removeEventListener(`storage`,o),e.removeFromWaiting(o),clearTimeout(s),!0),!r){r=!0;var t=50-(Date.now()-i);t>0?setTimeout(n,t):n(null)}}window.addEventListener(`storage`,o),e.addToWaiting(o);var s=setTimeout(o,Math.max(0,t-Date.now()))})];case 1:return n.sent(),[2]}})})},e.addToWaiting=function(t){this.removeFromWaiting(t),e.waiters!==void 0&&e.waiters.push(t)},e.removeFromWaiting=function(t){e.waiters!==void 0&&(e.waiters=e.waiters.filter(function(e){return e!==t}))},e.notifyWaiters=function(){e.waiters!==void 0&&e.waiters.slice().forEach(function(e){return e()})},e.prototype.releaseLock=function(e){return D(this,void 0,void 0,function(){return Le(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 D(this,void 0,void 0,function(){var n,r,i,a;return Le(this,function(o){switch(o.label){case 0:return n=this.storageHandler===void 0?Ve:this.storageHandler,r=Be+`-`+t,(i=n.getItemSync(r))===null?[2]:(a=JSON.parse(i)).id===this.id?[4,ze.default().lock(a.iat)]:[3,2];case 1:o.sent(),this.acquiredIatSet.delete(a.iat),n.removeItemSync(r),ze.default().unlock(a.iat),e.notifyWaiters(),o.label=2;case 2:return[2]}})})},e.lockCorrector=function(t){for(var n=Date.now()-5e3,r=t,i=[],a=0;;){var o=r.keySync(a);if(o===null)break;i.push(o),a++}for(var s=!1,c=0;c<i.length;c++){var l=i[c];if(l.includes(Be)){var u=r.getItemSync(l);if(u!==null){var d=JSON.parse(u);(d.timeRefreshed===void 0&&d.timeAcquired<n||d.timeRefreshed!==void 0&&d.timeRefreshed<n)&&(r.removeItemSync(l),s=!0)}}}s&&e.notifyWaiters()},e.waiters=void 0,e}(),Ge=class{async runWithLock(e,t,n){let r=new AbortController,i=setTimeout(()=>r.abort(),t);try{return await navigator.locks.request(e,{mode:`exclusive`,signal:r.signal},async e=>{if(clearTimeout(i),!e)throw Error(`Lock not available`);return await n()})}catch(e){throw clearTimeout(i),e?.name===`AbortError`?new he:e}}},Ke=class{constructor(){this.activeLocks=new Set,this.lock=new We,this.pagehideHandler=()=>{this.activeLocks.forEach(e=>this.lock.releaseLock(e)),this.activeLocks.clear()}}async runWithLock(e,t,n){let r=!1;for(let n=0;n<10&&!r;n++)r=await this.lock.acquireLock(e,t);if(!r)throw new he;this.activeLocks.add(e),this.activeLocks.size===1&&typeof window<`u`&&window.addEventListener(`pagehide`,this.pagehideHandler);try{return await n()}finally{this.activeLocks.delete(e),await this.lock.releaseLock(e),this.activeLocks.size===0&&typeof window<`u`&&window.removeEventListener(`pagehide`,this.pagehideHandler)}}};function qe(){return typeof navigator<`u`&&typeof(e=navigator.locks)?.request==`function`?new Ge:new Ke;var e}var Je=null,Ye=new TextEncoder,Xe=new TextDecoder;function Ze(e){return typeof e==`string`?Ye.encode(e):Xe.decode(e)}function Qe(e){if(typeof e.modulusLength!=`number`||e.modulusLength<2048)throw new rt(`${e.name} modulusLength must be at least 2048 bits`)}async function $e(e,t,n){if(!1===n.usages.includes(`sign`))throw TypeError(`private CryptoKey instances used for signing assertions must include "sign" in their "usages"`);let r=`${tt(Ze(JSON.stringify(e)))}.${tt(Ze(JSON.stringify(t)))}`;return`${r}.${tt(await crypto.subtle.sign(function(e){switch(e.algorithm.name){case`ECDSA`:return{name:e.algorithm.name,hash:`SHA-256`};case`RSA-PSS`:return Qe(e.algorithm),{name:e.algorithm.name,saltLength:32};case`RSASSA-PKCS1-v1_5`:return Qe(e.algorithm),{name:e.algorithm.name};case`Ed25519`:return{name:e.algorithm.name}}throw new nt}(n),n,Ze(r)))}`}var et;if(Uint8Array.prototype.toBase64)et=e=>(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e.toBase64({alphabet:`base64url`,omitPadding:!0}));else{let e=32768;et=t=>{t instanceof ArrayBuffer&&(t=new Uint8Array(t));let n=[];for(let r=0;r<t.byteLength;r+=e)n.push(String.fromCharCode.apply(null,t.subarray(r,r+e)));return btoa(n.join(``)).replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`)}}function tt(e){return et(e)}var nt=class extends Error{constructor(e){var t;super(e??`operation not supported`),this.name=this.constructor.name,(t=Error.captureStackTrace)==null||t.call(Error,this,this.constructor)}},rt=class extends Error{constructor(e){var t;super(e),this.name=this.constructor.name,(t=Error.captureStackTrace)==null||t.call(Error,this,this.constructor)}};function it(e){switch(e.algorithm.name){case`RSA-PSS`:return function(e){if(e.algorithm.hash.name===`SHA-256`)return`PS256`;throw new nt(`unsupported RsaHashedKeyAlgorithm hash name`)}(e);case`RSASSA-PKCS1-v1_5`:return function(e){if(e.algorithm.hash.name===`SHA-256`)return`RS256`;throw new nt(`unsupported RsaHashedKeyAlgorithm hash name`)}(e);case`ECDSA`:return function(e){if(e.algorithm.namedCurve===`P-256`)return`ES256`;throw new nt(`unsupported EcKeyAlgorithm namedCurve`)}(e);case`Ed25519`:return`Ed25519`;default:throw new nt(`unsupported CryptoKey algorithm name`)}}function at(e){return e instanceof CryptoKey}function ot(e){return at(e)&&e.type===`public`}async function st(e,t,n,r,i,a){let o=e?.privateKey,s=e?.publicKey;if(!at(c=o)||c.type!==`private`)throw TypeError(`"keypair.privateKey" must be a private CryptoKey`);var c;if(!ot(s))throw TypeError(`"keypair.publicKey" must be a public CryptoKey`);if(!0!==s.extractable)throw TypeError(`"keypair.publicKey.extractable" must be true`);if(typeof t!=`string`)throw TypeError(`"htu" must be a string`);if(typeof n!=`string`)throw TypeError(`"htm" must be a string`);if(r!==void 0&&typeof r!=`string`)throw TypeError(`"nonce" must be a string or undefined`);if(i!==void 0&&typeof i!=`string`)throw TypeError(`"accessToken" must be a string or undefined`);if(a!==void 0&&(typeof a!=`object`||!a||Array.isArray(a)))throw TypeError(`"additional" must be an object`);return $e({alg:it(o),typ:`dpop+jwt`,jwk:await ct(s)},Object.assign(Object.assign({},a),{iat:Math.floor(Date.now()/1e3),jti:crypto.randomUUID(),htm:n,nonce:r,htu:t,ath:i?tt(await crypto.subtle.digest(`SHA-256`,Ze(i))):void 0}),o)}async function ct(e){let{kty:t,e:n,n:r,x:i,y:a,crv:o}=await crypto.subtle.exportKey(`jwk`,e);return{kty:t,crv:o,e:n,n:r,x:i,y:a}}var lt=`dpop-nonce`,ut=[`authorization_code`,`refresh_token`,`urn:ietf:params:oauth:grant-type:token-exchange`,`urn:okta:params:oauth:grant-type:webauthn`,`http://auth0.com/oauth/grant-type/mfa-oob`,`http://auth0.com/oauth/grant-type/mfa-otp`,`http://auth0.com/oauth/grant-type/mfa-recovery-code`];function dt(){return async function(e,t){var n;let r;if(typeof e!=`string`||e.length===0)throw TypeError(`"alg" must be a non-empty string`);switch(e){case`PS256`:r={name:`RSA-PSS`,hash:`SHA-256`,modulusLength:2048,publicExponent:new Uint8Array([1,0,1])};break;case`RS256`:r={name:`RSASSA-PKCS1-v1_5`,hash:`SHA-256`,modulusLength:2048,publicExponent:new Uint8Array([1,0,1])};break;case`ES256`:r={name:`ECDSA`,namedCurve:`P-256`};break;case`Ed25519`:r={name:`Ed25519`};break;default:throw new nt}return crypto.subtle.generateKey(r,(n=t?.extractable)!=null&&n,[`sign`,`verify`])}(`ES256`,{extractable:!1})}function ft(e){return async function(e){if(!ot(e))throw TypeError(`"publicKey" must be a public CryptoKey`);if(!0!==e.extractable)throw TypeError(`"publicKey.extractable" must be true`);let t=await ct(e),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 nt(`unsupported JWK kty`)}return tt(await crypto.subtle.digest({name:`SHA-256`},Ze(JSON.stringify(n))))}(e.publicKey)}function pt(e){let t=e.keyPair,n=e.url,r=e.method,i=e.nonce,a=e.accessToken;return st(t,function(e){let t=new URL(e);return t.search=``,t.hash=``,t.href}(n),r,i,a)}var mt=(e,t)=>new Promise(function(n,r){let i=new MessageChannel;i.port1.onmessage=function(e){e.data.error?r(Error(e.data.error)):n(e.data),i.port1.close()},t.postMessage(e,[i.port2])}),ht=(e,t,n)=>{let r=new AbortController,i;return t.signal=r.signal,Promise.race([fetch(e,t),new Promise((e,t)=>{i=setTimeout(()=>{r.abort(),t(Error(`Timeout when executing 'fetch'`))},n)})]).finally(()=>{clearTimeout(i)})},gt=async function(e,t,n,r,i,a){let o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:se;return i?(async(e,t,n,r,i,a,o,s,c,l)=>mt({type:`refresh`,auth:{audience:t,scope:n},timeout:i,fetchUrl:e,fetchOptions:r,useFormData:o,useMrrt:s,skipTokenStorage:c,preserveRefreshToken:l},a))(e,t,n,r,o,i,a,arguments.length>7?arguments[7]:void 0,arguments.length>8?arguments[8]:void 0,arguments.length>9?arguments[9]:void 0):(async(e,t,n)=>{let r=await ht(e,t,n);return{ok:r.ok,json:await r.json(),headers:(i=r.headers,[...i].reduce((e,t)=>{let n=w(t,2),r=n[0];return e[r]=n[1],e},{}))};var i})(e,r,o)};async function _t(e,t,n,r,i,a,o,s,c,l,u,d){if(c){let t=await c.generateProof({url:e,method:i.method||`GET`,nonce:await c.getNonce()});i.headers=Object.assign(Object.assign({},i.headers),{dpop:t})}let p,m=null;for(let c=0;c<3;c++)try{p=await gt(e,n,r,i,a,o,t,s,u,d),m=null;break}catch(e){m=e}if(m)throw m;let h=p.json,g=h.error,_=h.error_description,ee=f(h,[`error`,`error_description`]),v=p,y=v.headers,b=v.ok,x;if(c&&(x=y[lt],x&&await c.setNonce(x)),!b){let f=_||`HTTP error. Unable to fetch ${e}`;if(g===`mfa_required`)throw new ye(g,f,ee.mfa_token,ee.mfa_requirements);if(g===`missing_refresh_token`)throw new be(n,r);if(g===`use_dpop_nonce`){if(!c||!x||l)throw new Se(x);return _t(e,t,n,r,i,a,o,s,c,!0,u,d)}throw new E(g||`request_error`,f)}return ee}async function vt(e,t,n){var r=e.baseUrl,i=e.timeout,a=e.audience,o=e.scope,s=e.auth0Client,c=e.useFormData,l=e.useMrrt,u=e.dpop,d=e.preserveRefreshToken,p=f(e,[`baseUrl`,`timeout`,`audience`,`scope`,`auth0Client`,`useFormData`,`useMrrt`,`dpop`,`preserveRefreshToken`]);let m=p.grant_type===`urn:ietf:params:oauth:grant-type:token-exchange`,h=p.grant_type===`urn:okta:params:oauth:grant-type:webauthn`,g=p.grant_type===`refresh_token`&&l,_=m||h||g,ee=Object.assign(Object.assign(Object.assign({},p),_&&a&&{audience:a}),_&&o&&{scope:o}),v=h||!c,y=v?JSON.stringify(ee):ke(ee),b=(x=p.grant_type,ut.includes(x));var x;return await _t(`${r}/oauth/token`,i,a||T,o,{method:`POST`,body:y,headers:{"Content-Type":v?`application/json`:`application/x-www-form-urlencoded`,"Auth0-Client":btoa(JSON.stringify(Oe(s||ue)))}},t,c,l,b?u:void 0,void 0,n,d)}var yt=function(){return(e=[...arguments].filter(Boolean).join(` `).trim().split(/\s+/),Array.from(new Set(e))).join(` `);var e},bt=(e,t,n)=>{let r;return n&&(r=e[n]),r||=e[T],yt(r,t)},xt=`@@auth0spajs@@`,St=`@@user@@`,O=class e{constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:xt,n=arguments.length>2?arguments[2]:void 0;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(t){let n=w(t.split(`::`),4),r=n[0],i=n[1],a=n[2],o=n[3];return new e({clientId:i,scope:o,audience:a},r)}static fromCacheEntry(t){let n=t.scope,r=t.audience,i=t.client_id;return new e({scope:n,audience:r,clientId:i})}},Ct=class{set(e,t){localStorage.setItem(e,JSON.stringify(t))}get(e){let t=window.localStorage.getItem(e);if(t)try{return JSON.parse(t)}catch{return}}remove(e){localStorage.removeItem(e)}allKeys(){return Object.keys(window.localStorage).filter(e=>e.startsWith(xt))}},wt=class{constructor(){this.enclosedCache=function(){let e={};return{set(t,n){e[t]=n},get(t){let n=e[t];if(n)return n},remove(t){delete e[t]},allKeys:()=>Object.keys(e)}}()}},Tt=class{constructor(e,t,n){this.cache=e,this.keyManifest=t,this.nowProvider=n||de}async setIdToken(e,t,n){let r=this.getIdTokenCacheKey(e);await this.cache.set(r,{id_token:t,decodedToken:n}),await this.keyManifest?.add(r)}async getIdToken(e){let t=await this.cache.get(this.getIdTokenCacheKey(e.clientId));if(!t&&e.scope&&e.audience){let t=await this.get(e);return!t||!t.id_token||!t.decodedToken?void 0:{id_token:t.id_token,decodedToken:t.decodedToken}}if(t)return{id_token:t.id_token,decodedToken:t.decodedToken}}async get(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,n=arguments.length>2&&arguments[2]!==void 0&&arguments[2],r=arguments.length>3?arguments[3]:void 0,i=await this.cache.get(e.toKey()),a=e;if(!i){let t=await this.getCacheKeys();if(!t)return;let o=this.matchExistingCacheKey(e,t);if(o&&(i=await this.cache.get(o),a=O.fromKey(o)),!i&&n&&r!==`cache-only`)return this.getEntryWithRefreshToken(e,t)}if(!i)return;let o=await this.nowProvider(),s=Math.floor(o/1e3);return i.expiresAt-t<s?i.body.refresh_token?this.modifiedCachedEntry(i,a):(await this.cache.remove(a.toKey()),void await this.keyManifest?.remove(a.toKey())):i.body}async modifiedCachedEntry(e,t){let n={refresh_token:e.body.refresh_token,audience:e.body.audience,scope:e.body.scope},r={body:n,expiresAt:e.expiresAt};return await this.cache.set(t.toKey(),r),{refresh_token:n.refresh_token,audience:n.audience,scope:n.scope}}async set(e){let t=new O({clientId:e.client_id,scope:e.scope,audience:e.audience}),n=await this.wrapCacheEntry(e);await this.cache.set(t.toKey(),n),await this.keyManifest?.add(t.toKey())}async remove(e,t,n){let r=new O({clientId:e,scope:n,audience:t});await this.cache.remove(r.toKey())}async stripRefreshToken(e){let t=await this.getCacheKeys();if(t)for(let n of t){let t=await this.cache.get(n);t?.body?.refresh_token===e&&(delete t.body.refresh_token,await this.cache.set(n,t))}}async clear(e){let t=await this.getCacheKeys();t&&(await t.filter(t=>!e||t.includes(e)).reduce(async(e,t)=>{await e,await this.cache.remove(t)},Promise.resolve()),await this.keyManifest?.clear())}async wrapCacheEntry(e){let t=await this.nowProvider();return{body:e,expiresAt:Math.floor(t/1e3)+e.expires_in}}async getCacheKeys(){return this.keyManifest?(await this.keyManifest.get())?.keys:this.cache.allKeys?this.cache.allKeys():void 0}getIdTokenCacheKey(e){return new O({clientId:e},xt,St).toKey()}matchExistingCacheKey(e,t){return t.filter(t=>{let n=O.fromKey(t),r=new Set(n.scope&&n.scope.split(` `)),i=e.scope?.split(` `)||[],a=n.scope&&i.reduce((e,t)=>e&&r.has(t),!0);return n.prefix===xt&&n.clientId===e.clientId&&n.audience===e.audience&&a})[0]}async getEntryWithRefreshToken(e,t){for(let n of t){let t=O.fromKey(n);if(t.prefix===xt&&t.clientId===e.clientId){let e=await this.cache.get(n);if(e?.body?.refresh_token)return{refresh_token:e.body.refresh_token,audience:e.body.audience,scope:e.body.scope}}}}async getRefreshTokensByAudience(e,t){var n;let r=await this.getCacheKeys();if(!r)return[];let i=new Set;for(let a of r){let r=O.fromKey(a);if(r.prefix===xt&&r.clientId===t&&r.audience===e){let e=await this.cache.get(a);(n=e?.body)!=null&&n.refresh_token&&i.add(e.body.refresh_token)}}return Array.from(i)}async updateEntry(e,t){let n=await this.getCacheKeys();if(n)for(let r of n){let n=await this.cache.get(r);n?.body?.refresh_token===e&&(n.body.refresh_token=t,await this.cache.set(r,n))}}},Et=class{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})}},Dt=e=>typeof e==`number`,Ot=`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`.split(`.`),kt=e=>{if(!e.id_token)throw Error(`ID token is required but missing`);let t=(e=>{let t=e.split(`.`),n=w(t,3),r=n[0],i=n[1],a=n[2];if(t.length!==3||!r||!i||!a)throw Error(`ID token could not be decoded`);let o=JSON.parse(je(i)),s={__raw:e},c={};return Object.keys(o).forEach(e=>{s[e]=o[e],Ot.includes(e)||(c[e]=o[e])}),{encoded:{header:r,payload:i,signature:a},header:JSON.parse(je(r)),claims:s,user:c}})(e.id_token);if(!t.claims.iss)throw Error(`Issuer (iss) claim must be a string present in the ID token`);if(t.claims.iss!==e.iss)throw Error(`Issuer (iss) claim mismatch in the ID token; expected "${e.iss}", found "${t.claims.iss}"`);if(!t.user.sub)throw Error(`Subject (sub) claim must be a string present in the ID token`);if(t.header.alg!==`RS256`)throw Error(`Signature algorithm of "${t.header.alg}" is not supported. Expected the ID token to be signed with "RS256".`);if(!t.claims.aud||typeof t.claims.aud!=`string`&&!Array.isArray(t.claims.aud))throw 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 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 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 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 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 Error(`Nonce (nonce) claim must be a string present in the ID token`);if(t.claims.nonce!==e.nonce)throw Error(`Nonce (nonce) claim mismatch in the ID token; expected "${e.nonce}", found "${t.claims.nonce}"`)}if(e.max_age&&!Dt(t.claims.auth_time))throw Error(`Authentication Time (auth_time) claim must be a number present in the ID token when Max Age (max_age) is specified`);if(t.claims.exp==null||!Dt(t.claims.exp))throw Error(`Expiration Time (exp) claim must be a number present in the ID token`);if(!Dt(t.claims.iat))throw Error(`Issued At (iat) claim must be a number present in the ID token`);let n=e.leeway||60,r=new Date(e.now||Date.now()),i=new Date(0);if(i.setUTCSeconds(t.claims.exp+n),r>i)throw Error(`Expiration Time (exp) claim error in the ID token; current time (${r}) is after expiration time (${i})`);if(t.claims.nbf!=null&&Dt(t.claims.nbf)){let e=new Date(0);if(e.setUTCSeconds(t.claims.nbf-n),r<e)throw Error(`Not Before time (nbf) claim in the ID token indicates that this token can't be used just yet. Current time (${r}) is before ${e}`)}if(t.claims.auth_time!=null&&Dt(t.claims.auth_time)){let i=new Date(0);if(i.setUTCSeconds(parseInt(t.claims.auth_time)+e.max_age+n),r>i)throw 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 (${r}) is after last auth at ${i}`)}if(e.organization){let n=e.organization.trim();if(n.startsWith(`org_`)){let e=n;if(!t.claims.org_id)throw Error(`Organization ID (org_id) claim must be a string present in the ID token`);if(e!==t.claims.org_id)throw Error(`Organization ID (org_id) claim mismatch in the ID token; expected "${e}", found "${t.claims.org_id}"`)}else{let e=n.toLowerCase();if(!t.claims.org_name)throw Error(`Organization Name (org_name) claim must be a string present in the ID token`);if(e!==t.claims.org_name)throw Error(`Organization Name (org_name) claim mismatch in the ID token; expected "${e}", found "${t.claims.org_name}"`)}}return t},At=Ne&&Ne.__assign||function(){return At=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},At.apply(this,arguments)};function jt(e,t){if(!t)return``;var n=`; `+e;return!0===t?n:n+`=`+t}function Mt(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(typeof e.expires==`number`){var t=new Date;t.setMilliseconds(t.getMilliseconds()+864e5*e.expires),e.expires=t}return jt(`Expires`,e.expires?e.expires.toUTCString():``)+jt(`Domain`,e.domain)+jt(`Path`,e.path)+jt(`Secure`,e.secure)+jt(`SameSite`,e.sameSite)}(n)}function Nt(){return function(e){for(var t={},n=e?e.split(`; `):[],r=/(%[\dA-F]{2})+/gi,i=0;i<n.length;i++){var a=n[i].split(`=`),o=a.slice(1).join(`=`);o.charAt(0)===`"`&&(o=o.slice(1,-1));try{t[a[0].replace(r,decodeURIComponent)]=o.replace(r,decodeURIComponent)}catch{}}return t}(document.cookie)}var Pt=function(e){return Nt()[e]};function Ft(e,t,n){document.cookie=Mt(e,t,At({path:`/`},n))}var It=Ft,Lt=function(e,t){Ft(e,``,At(At({},t),{expires:-1}))},Rt={get(e){let t=Pt(e);if(t!==void 0)return JSON.parse(t)},save(e,t,n){let r={};window.location.protocol===`https:`&&(r={secure:!0,sameSite:`none`}),n!=null&&n.daysUntilExpire&&(r.expires=n.daysUntilExpire),n!=null&&n.cookieDomain&&(r.domain=n.cookieDomain),It(e,JSON.stringify(t),r)},remove(e,t){let n={};t!=null&&t.cookieDomain&&(n.domain=t.cookieDomain),Lt(e,n)}},zt=`_legacy_`,Bt={get(e){return Rt.get(e)||Rt.get(`${zt}${e}`)},save(e,t,n){let r={};window.location.protocol===`https:`&&(r={secure:!0}),n!=null&&n.daysUntilExpire&&(r.expires=n.daysUntilExpire),n!=null&&n.cookieDomain&&(r.domain=n.cookieDomain),It(`${zt}${e}`,JSON.stringify(t),r),Rt.save(e,t,n)},remove(e,t){let n={};t!=null&&t.cookieDomain&&(n.domain=t.cookieDomain),Lt(e,n),Rt.remove(e,t),Rt.remove(`${zt}${e}`,t)}},Vt={get(e){if(typeof sessionStorage>`u`)return;let t=sessionStorage.getItem(e);return t==null?void 0:JSON.parse(t)},save(e,t){sessionStorage.setItem(e,JSON.stringify(t))},remove(e){sessionStorage.removeItem(e)}},Ht;(function(e){e.Code=`code`,e.ConnectCode=`connect_code`})(Ht||={});function Ut(e,t,n){var r=t===void 0?null:t,i=function(e,t){var n=atob(e);if(t){for(var r=new Uint8Array(n.length),i=0,a=n.length;i<a;++i)r[i]=n.charCodeAt(i);return String.fromCharCode.apply(null,new Uint16Array(r.buffer))}return n}(e,n!==void 0&&n),a=i.indexOf(`
`,10)+1,o=i.substring(a)+(r?`//# sourceMappingURL=`+r:``),s=new Blob([o],{type:`application/javascript`});return URL.createObjectURL(s)}var Wt,Gt,Kt,qt,Jt=(Wt=`Lyogcm9sbHVwLXBsdWdpbi13ZWItd29ya2VyLWxvYWRlciAqLwohZnVuY3Rpb24oKXsidXNlIHN0cmljdCI7ZnVuY3Rpb24gZShlLHQpeyhudWxsPT10fHx0PmUubGVuZ3RoKSYmKHQ9ZS5sZW5ndGgpO2Zvcih2YXIgcj0wLG89QXJyYXkodCk7cjx0O3IrKylvW3JdPWVbcl07cmV0dXJuIG99ZnVuY3Rpb24gdCh0LHIpe3JldHVybiBmdW5jdGlvbihlKXtpZihBcnJheS5pc0FycmF5KGUpKXJldHVybiBlfSh0KXx8ZnVuY3Rpb24oZSx0KXt2YXIgcj1udWxsPT1lP251bGw6InVuZGVmaW5lZCIhPXR5cGVvZiBTeW1ib2wmJmVbU3ltYm9sLml0ZXJhdG9yXXx8ZVsiQEBpdGVyYXRvciJdO2lmKG51bGwhPXIpe3ZhciBvLG4scyxpLGE9W10sYz0hMCxsPSExO3RyeXtpZihzPShyPXIuY2FsbChlKSkubmV4dCwwPT09dCl7aWYoT2JqZWN0KHIpIT09cilyZXR1cm47Yz0hMX1lbHNlIGZvcig7IShjPShvPXMuY2FsbChyKSkuZG9uZSkmJihhLnB1c2goby52YWx1ZSksYS5sZW5ndGghPT10KTtjPSEwKTt9Y2F0Y2goZSl7bD0hMCxuPWV9ZmluYWxseXt0cnl7aWYoIWMmJm51bGwhPXIucmV0dXJuJiYoaT1yLnJldHVybigpLE9iamVjdChpKSE9PWkpKXJldHVybn1maW5hbGx5e2lmKGwpdGhyb3cgbn19cmV0dXJuIGF9fSh0LHIpfHxmdW5jdGlvbih0LHIpe2lmKHQpe2lmKCJzdHJpbmciPT10eXBlb2YgdClyZXR1cm4gZSh0LHIpO3ZhciBvPXt9LnRvU3RyaW5nLmNhbGwodCkuc2xpY2UoOCwtMSk7cmV0dXJuIk9iamVjdCI9PT1vJiZ0LmNvbnN0cnVjdG9yJiYobz10LmNvbnN0cnVjdG9yLm5hbWUpLCJNYXAiPT09b3x8IlNldCI9PT1vP0FycmF5LmZyb20odCk6IkFyZ3VtZW50cyI9PT1vfHwvXig/OlVpfEkpbnQoPzo4fDE2fDMyKSg/OkNsYW1wZWQpP0FycmF5JC8udGVzdChvKT9lKHQscik6dm9pZCAwfX0odCxyKXx8ZnVuY3Rpb24oKXt0aHJvdyBuZXcgVHlwZUVycm9yKCJJbnZhbGlkIGF0dGVtcHQgdG8gZGVzdHJ1Y3R1cmUgbm9uLWl0ZXJhYmxlIGluc3RhbmNlLlxuSW4gb3JkZXIgdG8gYmUgaXRlcmFibGUsIG5vbi1hcnJheSBvYmplY3RzIG11c3QgaGF2ZSBhIFtTeW1ib2wuaXRlcmF0b3JdKCkgbWV0aG9kLiIpfSgpfWNsYXNzIHIgZXh0ZW5kcyBFcnJvcntjb25zdHJ1Y3RvcihlLHQpe3N1cGVyKHQpLHRoaXMuZXJyb3I9ZSx0aGlzLmVycm9yX2Rlc2NyaXB0aW9uPXQsT2JqZWN0LnNldFByb3RvdHlwZU9mKHRoaXMsci5wcm90b3R5cGUpfXN0YXRpYyBmcm9tUGF5bG9hZChlKXtsZXQgdD1lLmVycm9yLG89ZS5lcnJvcl9kZXNjcmlwdGlvbjtyZXR1cm4gbmV3IHIodCxvKX19Y2xhc3MgbyBleHRlbmRzIHJ7Y29uc3RydWN0b3IoZSx0KXtzdXBlcigibWlzc2luZ19yZWZyZXNoX3Rva2VuIiwiTWlzc2luZyBSZWZyZXNoIFRva2VuIChhdWRpZW5jZTogJyIuY29uY2F0KG4oZSxbImRlZmF1bHQiXSksIicsIHNjb3BlOiAnIikuY29uY2F0KG4odCksIicpIikpLHRoaXMuYXVkaWVuY2U9ZSx0aGlzLnNjb3BlPXQsT2JqZWN0LnNldFByb3RvdHlwZU9mKHRoaXMsby5wcm90b3R5cGUpfX1mdW5jdGlvbiBuKGUpe3JldHVybiBlJiYhKGFyZ3VtZW50cy5sZW5ndGg+MSYmdm9pZCAwIT09YXJndW1lbnRzWzFdP2FyZ3VtZW50c1sxXTpbXSkuaW5jbHVkZXMoZSk/ZToiIn0iZnVuY3Rpb24iPT10eXBlb2YgU3VwcHJlc3NlZEVycm9yJiZTdXBwcmVzc2VkRXJyb3I7Y29uc3Qgcz1lPT57dmFyIHQ9ZS5jbGllbnRJZCxyPWZ1bmN0aW9uKGUsdCl7dmFyIHI9e307Zm9yKHZhciBvIGluIGUpT2JqZWN0LnByb3RvdHlwZS5oYXNPd25Qcm9wZXJ0eS5jYWxsKGUsbykmJnQuaW5kZXhPZihvKTwwJiYocltvXT1lW29dKTtpZihudWxsIT1lJiYiZnVuY3Rpb24iPT10eXBlb2YgT2JqZWN0LmdldE93blByb3BlcnR5U3ltYm9scyl7dmFyIG49MDtmb3Iobz1PYmplY3QuZ2V0T3duUHJvcGVydHlTeW1ib2xzKGUpO248by5sZW5ndGg7bisrKXQuaW5kZXhPZihvW25dKTwwJiZPYmplY3QucHJvdG90eXBlLnByb3BlcnR5SXNFbnVtZXJhYmxlLmNhbGwoZSxvW25dKSYmKHJbb1tuXV09ZVtvW25dXSl9cmV0dXJuIHJ9KGUsWyJjbGllbnRJZCJdKTtyZXR1cm4gbmV3IFVSTFNlYXJjaFBhcmFtcygoZT0+T2JqZWN0LmtleXMoZSkuZmlsdGVyKHQ9PnZvaWQgMCE9PWVbdF0pLnJlZHVjZSgodCxyKT0+T2JqZWN0LmFzc2lnbihPYmplY3QuYXNzaWduKHt9LHQpLHtbcl06ZVtyXX0pLHt9KSkoT2JqZWN0LmFzc2lnbih7Y2xpZW50X2lkOnR9LHIpKSkudG9TdHJpbmcoKX07bGV0IGk9e30sYT1udWxsO2NvbnN0IGM9KGUsdCk9PiIiLmNvbmNhdChlLCJ8IikuY29uY2F0KHQpLGw9KGUsdCk9PnQuc3RhcnRzV2l0aCgiIi5jb25jYXQoZSwifCIpKSx1PWU9PntPYmplY3QuZW50cmllcyhpKS5mb3JFYWNoKHI9PntsZXQgbz10KHIsMiksbj1vWzBdO29bMV09PT1lJiZkZWxldGUgaVtuXX0pfSxmPWU9Pntjb25zdCB0PW5ldyBVUkxTZWFyY2hQYXJhbXMoZSkscj17fTtyZXR1cm4gdC5mb3JFYWNoKChlLHQpPT57clt0XT1lfSkscn0saD1hc3luYyBlPT57bGV0IHIsbixhPWUuZGF0YSx1PWEudGltZW91dCxoPWEuYXV0aCxkPWEuZmV0Y2hVcmwscD1hLmZldGNoT3B0aW9ucyx5PWEudXNlRm9ybURhdGEsZz1hLnVzZU1ycnQsYj1hLnNraXBUb2tlblN0b3JhZ2UsTz1hLnByZXNlcnZlUmVmcmVzaFRva2VuLGs9dChlLnBvcnRzLDEpWzBdLG09e307Y29uc3Qgaj1ofHx7fSx2PWouYXVkaWVuY2UsXz1qLnNjb3BlO3RyeXtjb25zdCBlPXk/ZihwLmJvZHkpOkpTT04ucGFyc2UocC5ib2R5KTtpZighZS5yZWZyZXNoX3Rva2VuJiYicmVmcmVzaF90b2tlbiI9PT1lLmdyYW50X3R5cGUpe2lmKG49KChlLHQpPT5pW2MoZSx0KV0pKHYsXyksIW4mJmcpe2NvbnN0IGU9aS5sYXRlc3RfcmVmcmVzaF90b2tlbix0PSgoZSx0KT0+ISFPYmplY3Qua2V5cyhpKS5maW5kKHI9PntpZigibGF0ZXN0X3JlZnJlc2hfdG9rZW4iIT09cil7Y29uc3Qgbz1sKHQsciksbj1yLnNwbGl0KCJ8IilbMV0uc3BsaXQoIiAiKSxzPWUuc3BsaXQoIiAiKS5ldmVyeShlPT5uLmluY2x1ZGVzKGUpKTtyZXR1cm4gbyYmc319KSkoXyx2KTtlJiYhdCYmKG49ZSl9aWYoIW4pdGhyb3cgbmV3IG8odixfKTtwLmJvZHk9eT9zKE9iamVjdC5hc3NpZ24oT2JqZWN0LmFzc2lnbih7fSxlKSx7cmVmcmVzaF90b2tlbjpufSkpOkpTT04uc3RyaW5naWZ5KE9iamVjdC5hc3NpZ24oT2JqZWN0LmFzc2lnbih7fSxlKSx7cmVmcmVzaF90b2tlbjpufSkpfWxldCBhLGg7ImZ1bmN0aW9uIj09dHlwZW9mIEFib3J0Q29udHJvbGxlciYmKGE9bmV3IEFib3J0Q29udHJvbGxlcixwLnNpZ25hbD1hLnNpZ25hbCk7dHJ5e2g9YXdhaXQgUHJvbWlzZS5yYWNlKFsoVT11LG5ldyBQcm9taXNlKGU9PnNldFRpbWVvdXQoZSxVKSkpLGZldGNoKGQsT2JqZWN0LmFzc2lnbih7fSxwKSldKX1jYXRjaChlKXtyZXR1cm4gdm9pZCBrLnBvc3RNZXNzYWdlKHtlcnJvcjplLm1lc3NhZ2V9KX1pZighaClyZXR1cm4gYSYmYS5hYm9ydCgpLHZvaWQgay5wb3N0TWVzc2FnZSh7ZXJyb3I6IlRpbWVvdXQgd2hlbiBleGVjdXRpbmcgJ2ZldGNoJyJ9KTtpZihNPWguaGVhZGVycyxtPVsuLi5NXS5yZWR1Y2UoKGUscik9PntsZXQgbz10KHIsMiksbj1vWzBdLHM9b1sxXTtyZXR1cm4gZVtuXT1zLGV9LHt9KSxyPWF3YWl0IGguanNvbigpLGIpcmV0dXJuIGRlbGV0ZSByLnJlZnJlc2hfdG9rZW4sdm9pZCBrLnBvc3RNZXNzYWdlKHtvazpoLm9rLGpzb246cixoZWFkZXJzOm19KTtyLnJlZnJlc2hfdG9rZW4/KGcmJihpLmxhdGVzdF9yZWZyZXNoX3Rva2VuPXIucmVmcmVzaF90b2tlbix3PW4sUz1yLnJlZnJlc2hfdG9rZW4sT2JqZWN0LmVudHJpZXMoaSkuZm9yRWFjaChlPT57bGV0IHI9dChlLDIpLG89clswXTtyWzFdPT09dyYmKGlbb109Uyl9KSksKChlLHQscik9PntpW2ModCxyKV09ZX0pKHIucmVmcmVzaF90b2tlbix2LF8pLGRlbGV0ZSByLnJlZnJlc2hfdG9rZW4pOk98fCgoZSx0KT0+e2RlbGV0ZSBpW2MoZSx0KV19KSh2LF8pLGsucG9zdE1lc3NhZ2Uoe29rOmgub2ssanNvbjpyLGhlYWRlcnM6bX0pfWNhdGNoKGUpe2sucG9zdE1lc3NhZ2Uoe29rOiExLGpzb246e2Vycm9yOmUuZXJyb3IsZXJyb3JfZGVzY3JpcHRpb246ZS5tZXNzYWdlfSxoZWFkZXJzOm19KX12YXIgdyxTLE0sVX0sZD1hc3luYyBlPT57bGV0IHI9ZS5kYXRhLG89ci50aW1lb3V0LG49ci5hdXRoLGE9ci5mZXRjaFVybCxjPXIuZmV0Y2hPcHRpb25zLGg9ci51c2VGb3JtRGF0YSxkPXQoZS5wb3J0cywxKVswXTtjb25zdCBwPShufHx7fSkuYXVkaWVuY2U7dHJ5e2NvbnN0IGU9KGU9Pntjb25zdCByPW5ldyBTZXQ7cmV0dXJuIE9iamVjdC5lbnRyaWVzKGkpLmZvckVhY2gobz0+e2xldCBuPXQobywyKSxzPW5bMF0saT1uWzFdO2woZSxzKSYmci5hZGQoaSl9KSxBcnJheS5mcm9tKHIpfSkocCk7aWYoMD09PWUubGVuZ3RoKXJldHVybiB2b2lkIGQucG9zdE1lc3NhZ2Uoe29rOiEwfSk7Y29uc3Qgcj1oP2YoYy5ib2R5KTpKU09OLnBhcnNlKGMuYm9keSk7Zm9yKGNvbnN0IHQgb2YgZSl7Y29uc3QgZT1oP3MoT2JqZWN0LmFzc2lnbihPYmplY3QuYXNzaWduKHt9LHIpLHt0b2tlbjp0fSkpOkpTT04uc3RyaW5naWZ5KE9iamVjdC5hc3NpZ24oT2JqZWN0LmFzc2lnbih7fSxyKSx7dG9rZW46dH0pKTtsZXQgbixpLGwsZjsiZnVuY3Rpb24iPT10eXBlb2YgQWJvcnRDb250cm9sbGVyJiYobj1uZXcgQWJvcnRDb250cm9sbGVyLGk9bi5zaWduYWwpO3RyeXtmPWF3YWl0IFByb21pc2UucmFjZShbbmV3IFByb21pc2UoZT0+e2w9c2V0VGltZW91dChlLG8pfSksZmV0Y2goYSxPYmplY3QuYXNzaWduKE9iamVjdC5hc3NpZ24oe30sYykse2JvZHk6ZSxzaWduYWw6aX0pKV0pLmZpbmFsbHkoKCk9PmNsZWFyVGltZW91dChsKSl9Y2F0Y2goZSl7cmV0dXJuIHZvaWQgZC5wb3N0TWVzc2FnZSh7ZXJyb3I6ZS5tZXNzYWdlfSl9aWYoIWYpcmV0dXJuIG4mJm4uYWJvcnQoKSx2b2lkIGQucG9zdE1lc3NhZ2Uoe2Vycm9yOiJUaW1lb3V0IHdoZW4gZXhlY3V0aW5nICdmZXRjaCcifSk7aWYoIWYub2spe2xldCBlO3RyeXtjb25zdCB0PUpTT04ucGFyc2UoYXdhaXQgZi50ZXh0KCkpO2U9dC5lcnJvcl9kZXNjcmlwdGlvbn1jYXRjaChlKXt9cmV0dXJuIHZvaWQgZC5wb3N0TWVzc2FnZSh7ZXJyb3I6ZXx8IkhUVFAgZXJyb3IgIi5jb25jYXQoZi5zdGF0dXMpfSl9dSh0KX1kLnBvc3RNZXNzYWdlKHtvazohMH0pfWNhdGNoKGUpe2QucG9zdE1lc3NhZ2Uoe2Vycm9yOmUubWVzc2FnZXx8IlVua25vd24gZXJyb3IgZHVyaW5nIHRva2VuIHJldm9jYXRpb24ifSl9fSxwPShlLHQpPT57aWYoIWEpcmV0dXJuITE7dHJ5e2NvbnN0IHI9bmV3IFVSTChhKS5vcmlnaW4sbz1uZXcgVVJMKGUuZmV0Y2hVcmwpO3JldHVybiBvLm9yaWdpbj09PXImJm8ucGF0aG5hbWU9PT10fWNhdGNoKGUpe3JldHVybiExfX07YWRkRXZlbnRMaXN0ZW5lcigibWVzc2FnZSIsZT0+e2NvbnN0IHI9ZS5kYXRhLG89dChlLnBvcnRzLDEpWzBdO2lmKCEoInR5cGUiaW4gcil8fCJpbml0IiE9PXIudHlwZSlyZXR1cm4idHlwZSJpbiByJiYiY2xlYXIiPT09ci50eXBlPyhpPXt9LHZvaWQobnVsbD09b3x8by5wb3N0TWVzc2FnZSh7b2s6ITB9KSkpOiJ0eXBlImluIHImJiJyZXZva2UiPT09ci50eXBlP3AociwiL29hdXRoL3Jldm9rZSIpP3ZvaWQgZChlKTp2b2lkKG51bGw9PW98fG8ucG9zdE1lc3NhZ2Uoe29rOiExLGpzb246e2Vycm9yOiJpbnZhbGlkX2ZldGNoX3VybCIsZXJyb3JfZGVzY3JpcHRpb246IlVuYXV0aG9yaXplZCBmZXRjaCBVUkwifSxoZWFkZXJzOnt9fSkpOnZvaWQoImZldGNoVXJsImluIHImJnAociwiL29hdXRoL3Rva2VuIik/aChlKTpudWxsPT1vfHxvLnBvc3RNZXNzYWdlKHtvazohMSxqc29uOntlcnJvcjoiaW52YWxpZF9mZXRjaF91cmwiLGVycm9yX2Rlc2NyaXB0aW9uOiJVbmF1dGhvcml6ZWQgZmV0Y2ggVVJMIn0saGVhZGVyczp7fX0pKTtpZihudWxsPT09YSl0cnl7bmV3IFVSTChyLmFsbG93ZWRCYXNlVXJsKSxhPXIuYWxsb3dlZEJhc2VVcmx9Y2F0Y2goZSl7cmV0dXJufX0pfSgpOwoK`,Gt=null,Kt=!1,function(e){return qt||=Ut(Wt,Gt,Kt),new Worker(qt,e)}),Yt={},Xt=class{constructor(e,t){this.cache=e,this.clientId=t,this.manifestKey=this.createManifestKeyFrom(this.clientId)}async add(e){let t=new Set((await this.cache.get(this.manifestKey))?.keys||[]);t.add(e),await this.cache.set(this.manifestKey,{keys:[...t]})}async remove(e){let t=await this.cache.get(this.manifestKey);if(t){let 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`${xt}::${e}`}},Zt=`auth0.is.authenticated`,Qt={memory:()=>new wt().enclosedCache,localstorage:()=>new Ct},$t=e=>Qt[e],en=e=>{let t=e.openUrl,n=e.onRedirect,r=f(e,[`openUrl`,`onRedirect`]);return Object.assign(Object.assign({},r),{openUrl:!1===t||t?t:n})},tn=(e,t,n)=>{let r=e?.split(` `)||[],i=n?r.filter(e=>e!==le):r,a=t?.split(` `)||[];return i.filter(e=>a.indexOf(e)==-1).join(`,`)},nn={NONCE:`nonce`,KEYPAIR:`keypair`},rn=class{constructor(e){this.clientId=e}getVersion(){return 1}createDbHandle(){let e=window.indexedDB.open(`auth0-spa-js`,this.getVersion());return new Promise((t,n)=>{e.onupgradeneeded=()=>Object.values(nn).forEach(t=>e.result.createObjectStore(t)),e.onerror=()=>n(e.error),e.onsuccess=()=>t(e.result)})}async getDbHandle(){return this.dbHandle||=await this.createDbHandle(),this.dbHandle}async executeDbRequest(e,t,n){let r=n((await this.getDbHandle()).transaction(e,t).objectStore(e));return new Promise((e,t)=>{r.onsuccess=()=>e(r.result),r.onerror=()=>t(r.error)})}buildKey(e){let t=e?`_${e}`:`auth0`;return`${this.clientId}::${t}`}setNonce(e,t){return this.save(nn.NONCE,this.buildKey(t),e)}setKeyPair(e){return this.save(nn.KEYPAIR,this.buildKey(),e)}async save(e,t,n){await this.executeDbRequest(e,`readwrite`,e=>e.put(n,t))}findNonce(e){return this.find(nn.NONCE,this.buildKey(e))}findKeyPair(){return this.find(nn.KEYPAIR,this.buildKey())}find(e,t){return this.executeDbRequest(e,`readonly`,e=>e.get(t))}async deleteBy(e,t){let n=await this.executeDbRequest(e,`readonly`,e=>e.getAllKeys());await Promise.all(n?.filter(t).map(t=>this.executeDbRequest(e,`readwrite`,e=>e.delete(t)))||[])}deleteByClientId(e,t){return this.deleteBy(e,e=>typeof e==`string`&&e.startsWith(`${t}::`))}clearNonces(){return this.deleteByClientId(nn.NONCE,this.clientId)}clearKeyPairs(){return this.deleteByClientId(nn.KEYPAIR,this.clientId)}},an=class{constructor(e){this.storage=new rn(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 dt(),await this.storage.setKeyPair(e)),e}async generateProof(e){let t=await this.getOrGenerateKeyPair();return pt(Object.assign({keyPair:t},e))}async calculateThumbprint(){return ft(await this.getOrGenerateKeyPair())}async clear(){await Promise.all([this.storage.clearNonces(),this.storage.clearKeyPairs()])}},on;(function(e){e.Bearer=`Bearer`,e.DPoP=`DPoP`})(on||={});var sn=class{constructor(e,t){this.hooks=t,this.config=Object.assign(Object.assign({},e),{fetch:e.fetch||(typeof window>`u`?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 TypeError("`url` must be absolute or `baseUrl` non-empty.")}getAccessToken(e){return this.config.getAccessToken?this.config.getAccessToken(e):this.hooks.getAccessToken(e)}extractUrl(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}buildBaseRequest(e,t){if(!this.config.baseUrl)return new Request(e,t);let n=this.buildUrl(this.config.baseUrl,this.extractUrl(e)),r=e instanceof Request?new Request(n,e):n;return new Request(r,t)}setAuthorizationHeader(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:on.Bearer;e.headers.set(`authorization`,`${n} ${t}`)}async setDpopProofHeader(e,t){if(!this.config.dpopNonceId)return;let n=await this.hooks.getDpopNonce(),r=await this.hooks.generateDpopProof({accessToken:t,method:e.method,nonce:n,url:e.url});e.headers.set(`dpop`,r)}async prepareRequest(e,t){let n=await this.getAccessToken(t),r,i;typeof n==`string`?(r=this.config.dpopNonceId?on.DPoP:on.Bearer,i=n):(r=n.token_type,i=n.access_token),this.setAuthorizationHeader(e,i,r),r===on.DPoP&&await this.setDpopProofHeader(e,i)}getHeader(e,t){return Array.isArray(e)?new Headers(e).get(t)||``:typeof e.get==`function`?e.get(t)||``:e[t]||``}hasUseDpopNonceError(e){if(e.status!==401)return!1;let t=this.getHeader(e.headers,`www-authenticate`);return t.includes(`invalid_dpop_nonce`)||t.includes(`use_dpop_nonce`)}async handleResponse(e,t){let n=this.getHeader(e.headers,lt);if(n&&await this.hooks.setDpopNonce(n),!this.hasUseDpopNonceError(e))return e;if(!n||!t.onUseDpopNonceError)throw new Se(n);return t.onUseDpopNonceError()}async internalFetchWithAuth(e,t,n,r){let i=this.buildBaseRequest(e,t);await this.prepareRequest(i,r);let a=await this.config.fetch(i);return this.handleResponse(a,n)}fetchWithAuth(e,t,n){let r={onUseDpopNonceError:()=>this.internalFetchWithAuth(e,t,Object.assign(Object.assign({},r),{onUseDpopNonceError:void 0}),n)};return this.internalFetchWithAuth(e,t,r,n)}},cn=class{constructor(e,t){this.myAccountFetcher=e,this.apiBase=t}async connectAccount(e){let t=await this.myAccountFetcher.fetchWithAuth(`${this.apiBase}v1/connected-accounts/connect`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e)},{scope:[`create:me:connected_accounts`]});return this._handleResponse(t)}async completeAccount(e){let t=await this.myAccountFetcher.fetchWithAuth(`${this.apiBase}v1/connected-accounts/complete`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e)},{scope:[`create:me:connected_accounts`]});return this._handleResponse(t)}async getFactors(){let e=await this.myAccountFetcher.fetchWithAuth(`${this.apiBase}v1/factors`,{method:`GET`},{scope:[`read:me:factors`]});return(await this._handleResponse(e)).factors}async getAuthenticationMethods(e){let t=e?`?${new URLSearchParams({type:e})}`:``,n=await this.myAccountFetcher.fetchWithAuth(`${this.apiBase}v1/authentication-methods${t}`,{method:`GET`},{scope:[`read:me:authentication_methods`]});return(await this._handleResponse(n)).authentication_methods}async getAuthenticationMethod(e){let t=await this.myAccountFetcher.fetchWithAuth(`${this.apiBase}v1/authentication-methods/${encodeURIComponent(e)}`,{method:`GET`},{scope:[`read:me:authentication_methods`]});return this._handleResponse(t)}async deleteAuthenticationMethod(e){let t=await this.myAccountFetcher.fetchWithAuth(`${this.apiBase}v1/authentication-methods/${encodeURIComponent(e)}`,{method:`DELETE`},{scope:[`delete:me:authentication_methods`]});t.ok||await this._handleResponse(t)}async updateAuthenticationMethod(e,t){let n=await this.myAccountFetcher.fetchWithAuth(`${this.apiBase}v1/authentication-methods/${encodeURIComponent(e)}`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)},{scope:[`update:me:authentication_methods`]});return this._handleResponse(n)}async enrollmentChallenge(e){let t=await this.myAccountFetcher.fetchWithAuth(`${this.apiBase}v1/authentication-methods`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e)},{scope:[`create:me:authentication_methods`]}),n=await this._handleResponse(t),r=t.headers.get(`location`)??``,i=decodeURIComponent(r.split(`/`).pop()||``);return Object.assign(Object.assign({},n),{id:i,location:r})}async enrollmentVerify(e){let t=e,n=t.location;t.type;let r=f(t,[`location`,`type`]),i=await this.myAccountFetcher.fetchWithAuth(`${n}/verify`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(r)},{scope:[`create:me:authentication_methods`]});return this._handleResponse(i)}async _handleResponse(e){let t;try{t=await e.text(),t=JSON.parse(t)}catch(n){throw new ln({type:`invalid_json`,status:e.status,title:`Invalid JSON response`,detail:t||String(n)})}if(e.ok)return t;throw new ln(t)}},ln=class e extends Error{constructor(t){let n=t.type,r=t.status,i=t.title,a=t.detail,o=t.validation_errors;super(a),this.name=`MyAccountApiError`,this.type=n,this.status=r,this.title=i,this.detail=a,this.validation_errors=o,Object.setPrototypeOf(this,e.prototype)}},un={otp:{authenticatorTypes:[`otp`]},sms:{authenticatorTypes:[`oob`],oobChannels:[`sms`]},email:{authenticatorTypes:[`oob`],oobChannels:[`email`]},push:{authenticatorTypes:[`oob`],oobChannels:[`auth0`]},voice:{authenticatorTypes:[`oob`],oobChannels:[`voice`]}},dn=`http://auth0.com/oauth/grant-type/mfa-otp`,fn=`http://auth0.com/oauth/grant-type/mfa-oob`,pn=`http://auth0.com/oauth/grant-type/mfa-recovery-code`,mn,hn,gn;(typeof navigator>`u`||(mn=navigator.userAgent)==null||(hn=mn.startsWith)==null||!hn.call(mn,`Mozilla/5.0 `))&&(gn=`oauth4webapi/v3.8.6`);function _n(e,t){if(e==null)return!1;try{return e instanceof t||Object.getPrototypeOf(e)[Symbol.toStringTag]===t.prototype[Symbol.toStringTag]}catch{return!1}}var k=`ERR_INVALID_ARG_VALUE`,A=`ERR_INVALID_ARG_TYPE`;function j(e,t,n){let r=TypeError(e,{cause:n});return Object.assign(r,{code:t}),r}var M=Symbol(),vn=Symbol(),yn=Symbol(),bn=Symbol(),xn=Symbol(),Sn=Symbol(),Cn=new TextEncoder,wn=new TextDecoder;function Tn(e){return typeof e==`string`?Cn.encode(e):wn.decode(e)}var En,Dn;if(Uint8Array.prototype.toBase64)En=e=>(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e.toBase64({alphabet:`base64url`,omitPadding:!0}));else{let e=32768;En=t=>{t instanceof ArrayBuffer&&(t=new Uint8Array(t));let n=[];for(let r=0;r<t.byteLength;r+=e)n.push(String.fromCharCode.apply(null,t.subarray(r,r+e)));return btoa(n.join(``)).replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`)}}function On(e){return typeof e==`string`?Dn(e):En(e)}Dn=Uint8Array.fromBase64?e=>{try{return Uint8Array.fromBase64(e,{alphabet:`base64url`})}catch(e){throw j(`The input to be decoded is not correctly encoded.`,k,e)}}:e=>{try{let t=atob(e.replace(/-/g,`+`).replace(/_/g,`/`).replace(/\s/g,``)),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}catch(e){throw j(`The input to be decoded is not correctly encoded.`,k,e)}};var N=class extends Error{constructor(e,t){var n;super(e,t),S(this,`code`,void 0),this.name=this.constructor.name,this.code=wr,(n=Error.captureStackTrace)==null||n.call(Error,this,this.constructor)}},kn=class extends Error{constructor(e,t){var n;super(e,t),S(this,`code`,void 0),this.name=this.constructor.name,t!=null&&t.code&&(this.code=t?.code),(n=Error.captureStackTrace)==null||n.call(Error,this,this.constructor)}};function P(e,t,n){return new kn(e,{code:t,cause:n})}function An(e,t){if(function(e,t){if(!(e instanceof CryptoKey))throw j(`${t} must be a CryptoKey`,A)}(e,t),e.type!==`private`)throw j(`${t} must be a private CryptoKey`,k)}function jn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Mn(e){_n(e,Headers)&&(e=Object.fromEntries(e.entries()));let t=new Headers(e??{});if(gn&&!t.has(`user-agent`)&&t.set(`user-agent`,gn),t.has(`authorization`))throw j(`"options.headers" must not include the "authorization" header name`,k);return t}function Nn(e,t){if(t!==void 0){if(typeof t==`function`&&(t=t(e.href)),!(t instanceof AbortSignal))throw j(`"options.signal" must return or be an instance of AbortSignal`,A);return t}}function Pn(e){return e.includes(`//`)?e.replace(`//`,`/`):e}async function Fn(e,t){return async function(e,t,n,r){if(!(e instanceof URL))throw j(`"${t}" must be an instance of URL`,A);Jn(e,!0!==r?.[M]);let i=n(new URL(e.href)),a=Mn(r?.headers);return a.set(`accept`,`application/json`),(r?.[bn]||fetch)(i.href,{body:void 0,headers:Object.fromEntries(a.entries()),method:`GET`,redirect:`manual`,signal:Nn(i,r?.signal)})}(e,`issuerIdentifier`,e=>{switch(t?.algorithm){case void 0:case`oidc`:(function(e,t){e.pathname=Pn(`${e.pathname}/${t}`)})(e,`.well-known/openid-configuration`);break;case`oauth2`:(function(e,t){let n=arguments.length>2&&arguments[2]!==void 0&&arguments[2];e.pathname===`/`?e.pathname=t:e.pathname=Pn(`${t}/${n?e.pathname:e.pathname.replace(/(\/)$/,``)}`)})(e,`.well-known/oauth-authorization-server`);break;default:throw j(`"options.algorithm" must be "oidc" (default), or "oauth2"`,k)}return e},t)}function In(e,t,n,r,i){try{if(typeof e!=`number`||!Number.isFinite(e))throw j(`${n} must be a number`,A,i);if(e>0)return;if(t){if(e!==0)throw j(`${n} must be a non-negative number`,k,i);return}throw j(`${n} must be a positive number`,k,i)}catch(e){throw r?P(e.message,r,i):e}}function F(e,t,n,r){try{if(typeof e!=`string`)throw j(`${t} must be a string`,A,r);if(e.length===0)throw j(`${t} must not be empty`,k,r)}catch(e){throw n?P(e.message,n,r):e}}function Ln(e){(function(e,t){if(or(e)!==t)throw function(e){let t=`"response" content-type must be `;var n=[...arguments].slice(1);if(n.length>2){let e=n.pop();t+=`${n.join(`, `)}, or ${e}`}else n.length===2?t+=`${n[0]} or ${n[1]}`:t+=n[0];return P(t,Dr,e)}(e,t)})(e,`application/json`)}function Rn(){return On(crypto.getRandomValues(new Uint8Array(32)))}function zn(e){switch(e.algorithm.name){case`RSA-PSS`:return function(e){switch(e.algorithm.hash.name){case`SHA-256`:return`PS256`;case`SHA-384`:return`PS384`;case`SHA-512`:return`PS512`;default:throw new N(`unsupported RsaHashedKeyAlgorithm hash name`,{cause:e})}}(e);case`RSASSA-PKCS1-v1_5`:return function(e){switch(e.algorithm.hash.name){case`SHA-256`:return`RS256`;case`SHA-384`:return`RS384`;case`SHA-512`:return`RS512`;default:throw new N(`unsupported RsaHashedKeyAlgorithm hash name`,{cause:e})}}(e);case`ECDSA`:return function(e){switch(e.algorithm.namedCurve){case`P-256`:return`ES256`;case`P-384`:return`ES384`;case`P-521`:return`ES512`;default:throw new N(`unsupported EcKeyAlgorithm namedCurve`,{cause:e})}}(e);case`Ed25519`:case`ML-DSA-44`:case`ML-DSA-65`:case`ML-DSA-87`:return e.algorithm.name;case`EdDSA`:return`Ed25519`;default:throw new N(`unsupported CryptoKey algorithm name`,{cause:e})}}function Bn(e){let t=e?.[vn];return typeof t==`number`&&Number.isFinite(t)?t:0}function Vn(e){let t=e?.[yn];return typeof t==`number`&&Number.isFinite(t)&&Math.sign(t)!==-1?t:30}function Hn(){return Math.floor(Date.now()/1e3)}function Un(e){if(typeof e!=`object`||!e)throw j(`"as" must be an object`,A);F(e.issuer,`"as.issuer"`)}function Wn(e){if(typeof e!=`object`||!e)throw j(`"client" must be an object`,A);F(e.client_id,`"client.client_id"`)}function Gn(e){return F(e,`"clientSecret"`),(t,n,r,i)=>{r.set(`client_id`,n.client_id),r.set(`client_secret`,e)}}function Kn(e,t){let n=(a=e)instanceof CryptoKey?{key:a}:a?.key instanceof CryptoKey?(a.kid!==void 0&&F(a.kid,`"kid"`),{key:a.key,kid:a.kid}):{},r=n.key,i=n.kid;var a;return An(r,`"clientPrivateKey.key"`),async(e,n,a,o)=>{var s;let c={alg:zn(r),kid:i},l=function(e,t){let n=Hn()+Bn(t);return{jti:Rn(),aud:e.issuer,exp:n+60,iat:n,nbf:n,iss:t.client_id,sub:t.client_id}}(e,n);t==null||(s=t[xn])==null||s.call(t,c,l),a.set(`client_id`,n.client_id),a.set(`client_assertion_type`,`urn:ietf:params:oauth:client-assertion-type:jwt-bearer`),a.set(`client_assertion`,await async function(e,t,n){if(!n.usages.includes(`sign`))throw j(`CryptoKey instances used for signing assertions must include "sign" in their "usages"`,k);let r=`${On(Tn(JSON.stringify(e)))}.${On(Tn(JSON.stringify(t)))}`;return`${r}.${On(await crypto.subtle.sign(function(e){switch(e.algorithm.name){case`ECDSA`:return{name:e.algorithm.name,hash:Rr(e)};case`RSA-PSS`:switch(Lr(e),e.algorithm.hash.name){case`SHA-256`:case`SHA-384`:case`SHA-512`:return{name:e.algorithm.name,saltLength:parseInt(e.algorithm.hash.name.slice(-3),10)>>3};default:throw new N(`unsupported RSA-PSS hash name`,{cause:e})}case`RSASSA-PKCS1-v1_5`:return Lr(e),e.algorithm.name;case`ML-DSA-44`:case`ML-DSA-65`:case`ML-DSA-87`:case`Ed25519`:return e.algorithm.name}throw new N(`unsupported CryptoKey algorithm name`,{cause:e})}(n),n,Tn(r)))}`}(c,l,r))}}var qn=URL.parse?(e,t)=>URL.parse(e,t):(e,t)=>{try{return new URL(e,t)}catch{return null}};function Jn(e,t){if(t&&e.protocol!==`https:`)throw P(`only requests to HTTPS are allowed`,kr,e);if(e.protocol!==`https:`&&e.protocol!==`http:`)throw P(`only HTTP and HTTPS requests are allowed`,Ar,e)}function Yn(e,t,n,r){let i;if(typeof e!=`string`||!(i=qn(e)))throw P(`authorization server metadata does not contain a valid ${n?`"as.mtls_endpoint_aliases.${t}"`:`"as.${t}"`}`,e===void 0?Pr:Fr,{attribute:n?`mtls_endpoint_aliases.${t}`:t});return Jn(i,r),i}function Xn(e,t,n,r){return n&&e.mtls_endpoint_aliases&&t in e.mtls_endpoint_aliases?Yn(e.mtls_endpoint_aliases[t],t,n,r):Yn(e[t],t,n,r)}var Zn=class extends Error{constructor(e,t){var n;super(e,t),S(this,`cause`,void 0),S(this,`code`,void 0),S(this,`error`,void 0),S(this,`status`,void 0),S(this,`error_description`,void 0),S(this,`response`,void 0),this.name=this.constructor.name,this.code=Cr,this.cause=t.cause,this.error=t.cause.error,this.status=t.response.status,this.error_description=t.cause.error_description,Object.defineProperty(this,"response",{enumerable:!1,value:t.response}),(n=Error.captureStackTrace)==null||n.call(Error,this,this.constructor)}},Qn=class extends Error{constructor(e,t){var n;super(e,t),S(this,`cause`,void 0),S(this,`code`,void 0),S(this,`error`,void 0),S(this,`error_description`,void 0),this.name=this.constructor.name,this.code=Tr,this.cause=t.cause,this.error=t.cause.get(`error`),this.error_description=t.cause.get(`error_description`)??void 0,(n=Error.captureStackTrace)==null||n.call(Error,this,this.constructor)}},$n=class extends Error{constructor(e,t){var n;super(e,t),S(this,`cause`,void 0),S(this,`code`,void 0),S(this,`response`,void 0),S(this,`status`,void 0),this.name=this.constructor.name,this.code=Sr,this.cause=t.cause,this.status=t.response.status,this.response=t.response,Object.defineProperty(this,"response",{enumerable:!1}),(n=Error.captureStackTrace)==null||n.call(Error,this,this.constructor)}},er=RegExp("^[,\\s]*([a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+)"),tr=RegExp(`^[,\\s]*([a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_\`\\|~]+)\\s*=\\s*"((?:[^"\\\\]|\\\\[\\s\\S])*)"[,\\s]*(.*)`),nr=RegExp("^[,\\s]*([a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+)\\s*=\\s*([a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+)[,\\s]*(.*)"),rr=RegExp(`^([a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2})(?:$|[,\\s])(.*)`);async function ir(e,t,n){if(e.status!==t){let t;throw function(e){let t;if(t=function(e){if(!_n(e,Response))throw j(`"response" must be an instance of Response`,A);let t=e.headers.get(`www-authenticate`);if(t===null)return;let n=[],r=t;for(;r;){let e=r.match(er),t=e?.[1].toLowerCase();if(!t)return;let s=r.substring(e[0].length);if(s&&!s.match(/^[\s,]/))return;let c=s.match(/^\s+(.*)$/),l=!!c;r=c?c[1]:void 0;let u={},d;if(l)for(;r;){let t,n;if(e=r.match(tr)){var i=w(e,4);if(t=i[1],n=i[2],r=i[3],n.includes(`\\`))try{n=JSON.parse(`"${n}"`)}catch{}u[t.toLowerCase()]=n}else{if(!(e=r.match(nr))){if(e=r.match(rr)){if(Object.keys(u).length)break;var a=w(e,3);d=a[1],r=a[2];break}return}var o=w(e,4);t=o[1],n=o[2],r=o[3],u[t.toLowerCase()]=n}}else r=s||void 0;let f={scheme:t,parameters:u};d&&(f.token68=d),n.push(f)}return n.length?n:void 0}(e))throw new $n(`server responded with a challenge in the WWW-Authenticate HTTP Header`,{cause:t,response:e})}(e),(t=await async function(e){if(e.status>399&&e.status<500){Ir(e),Ln(e);try{let t=await e.clone().json();if(jn(t)&&typeof t.error==`string`&&t.error.length)return t}catch{}}}(e))?(await e.body?.cancel(),new Zn(`server responded with an error in the response body`,{cause:t,response:e})):P(`"response" is not a conform ${n} response (unexpected HTTP status code)`,Or,e)}}function ar(e){if(!hr.has(e))throw j(`"options.DPoP" is not a valid DPoPHandle`,k)}function or(e){return e.headers.get(`content-type`)?.split(`;`)[0]}async function sr(e,t,n,r,i,a,o){return await n(e,t,i,a),a.set(`content-type`,`application/x-www-form-urlencoded;charset=UTF-8`),(o?.[bn]||fetch)(r.href,{body:i,headers:Object.fromEntries(a.entries()),method:`POST`,redirect:`manual`,signal:Nn(r,o?.signal)})}async function cr(e,t,n,r,i,a){var o;let s=Xn(e,`token_endpoint`,t.use_mtls_endpoint_aliases,!0!==a?.[M]);i.set(`grant_type`,r);let c=Mn(a?.headers);c.set(`accept`,`application/json`),a?.DPoP!==void 0&&(ar(a.DPoP),await a.DPoP.addProof(s,c,`POST`));let l=await sr(e,t,n,s,i,c,a);return a==null||(o=a.DPoP)==null||o.cacheNonce(l,s),l}var lr=new WeakMap,ur=new WeakMap;function dr(e){if(!e.id_token)return;let t=lr.get(e);if(!t)throw j(`"ref" was already garbage collected or did not resolve from the proper sources`,k);return t}async function fr(e,t,n,r,i,a){if(Un(e),Wn(t),!_n(n,Response))throw j(`"response" must be an instance of Response`,A);await ir(n,200,`Token Endpoint`),Ir(n);let o=await Gr(n);if(F(o.access_token,`"response" body "access_token" property`,I,{body:o}),F(o.token_type,`"response" body "token_type" property`,I,{body:o}),o.token_type=o.token_type.toLowerCase(),o.expires_in!==void 0){let e=typeof o.expires_in==`number`?o.expires_in:parseFloat(o.expires_in);In(e,!0,`"response" body "expires_in" property`,I,{body:o}),o.expires_in=e}if(o.refresh_token!==void 0&&F(o.refresh_token,`"response" body "refresh_token" property`,I,{body:o}),o.scope!==void 0&&typeof o.scope!=`string`)throw P(`"response" body "scope" property must be a string`,I,{body:o});if(o.id_token!==void 0){F(o.id_token,`"response" body "id_token" property`,I,{body:o});let a=[`aud`,`exp`,`iat`,`iss`,`sub`];!0===t.require_auth_time&&a.push(`auth_time`),t.default_max_age!==void 0&&(In(t.default_max_age,!0,`"client.default_max_age"`),a.push(`auth_time`)),r!=null&&r.length&&a.push(...r);let s=await async function(e,t,n,r,i){let a,o,s=e.split(`.`),c=s[0],l=s[1],u=s.length;if(u===5){if(i===void 0)throw new N(`JWE decryption is not configured`,{cause:e});var d=(e=await i(e)).split(`.`);c=d[0],l=d[1],u=d.length}if(u!==3)throw P(`Invalid JWT`,I,e);try{a=JSON.parse(Tn(On(c)))}catch(e){throw P(`failed to parse JWT Header body as base64url encoded JSON`,Er,e)}if(!jn(a))throw P(`JWT Header must be a top level object`,I,e);if(t(a),a.crit!==void 0)throw new N(`no JWT "crit" header parameter extensions are supported`,{cause:{header:a}});try{o=JSON.parse(Tn(On(l)))}catch(e){throw P(`failed to parse JWT Payload body as base64url encoded JSON`,Er,e)}if(!jn(o))throw P(`JWT Payload must be a top level object`,I,e);let f=Hn()+n;if(o.exp!==void 0){if(typeof o.exp!=`number`)throw P(`unexpected JWT "exp" (expiration time) claim type`,I,{claims:o});if(o.exp<=f-r)throw P(`unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp`,jr,{claims:o,now:f,tolerance:r,claim:`exp`})}if(o.iat!==void 0&&typeof o.iat!=`number`)throw P(`unexpected JWT "iat" (issued at) claim type`,I,{claims:o});if(o.iss!==void 0&&typeof o.iss!=`string`)throw P(`unexpected JWT "iss" (issuer) claim type`,I,{claims:o});if(o.nbf!==void 0){if(typeof o.nbf!=`number`)throw P(`unexpected JWT "nbf" (not before) claim type`,I,{claims:o});if(o.nbf>f+r)throw P(`unexpected JWT "nbf" (not before) claim value`,jr,{claims:o,now:f,tolerance:r,claim:`nbf`})}if(o.aud!==void 0&&typeof o.aud!=`string`&&!Array.isArray(o.aud))throw P(`unexpected JWT "aud" (audience) claim type`,I,{claims:o});return{header:a,claims:o,jwt:e}}(o.id_token,Br.bind(void 0,t.id_token_signed_response_alg,e.id_token_signing_alg_values_supported,`RS256`),Bn(t),Vn(t),i).then(vr.bind(void 0,a)).then(mr.bind(void 0,e)).then(pr.bind(void 0,t.client_id)),c=s.claims,l=s.jwt;if(Array.isArray(c.aud)&&c.aud.length!==1){if(c.azp===void 0)throw P(`ID Token "aud" (audience) claim includes additional untrusted audiences`,Mr,{claims:c,claim:`aud`});if(c.azp!==t.client_id)throw P(`unexpected ID Token "azp" (authorized party) claim value`,Mr,{expected:t.client_id,claims:c,claim:`azp`})}c.auth_time!==void 0&&In(c.auth_time,!0,`ID Token "auth_time" (authentication time)`,I,{claims:c}),ur.set(n,l),lr.set(o,c)}if(a?.[o.token_type]!==void 0)a[o.token_type](n,o);else if(o.token_type!==`dpop`&&o.token_type!==`bearer`)throw new N("unsupported `token_type` value",{cause:{body:o}});return o}function pr(e,t){if(Array.isArray(t.claims.aud)){if(!t.claims.aud.includes(e))throw P(`unexpected JWT "aud" (audience) claim value`,Mr,{expected:e,claims:t.claims,claim:`aud`})}else if(t.claims.aud!==e)throw P(`unexpected JWT "aud" (audience) claim value`,Mr,{expected:e,claims:t.claims,claim:`aud`});return t}function mr(e,t){let n=e[qr]?.call(e,t)??e.issuer;if(t.claims.iss!==n)throw P(`unexpected JWT "iss" (issuer) claim value`,Mr,{expected:n,claims:t.claims,claim:`iss`});return t}var hr=new WeakSet,gr=Symbol(),_r={aud:`audience`,c_hash:`code hash`,client_id:`client id`,exp:`expiration time`,iat:`issued at`,iss:`issuer`,jti:`jwt id`,nonce:`nonce`,s_hash:`state hash`,sub:`subject`,ath:`access token hash`,htm:`http method`,htu:`http uri`,cnf:`confirmation`,auth_time:`authentication time`};function vr(e,t){for(let n of e)if(t.claims[n]===void 0)throw P(`JWT "${n}" (${_r[n]}) claim missing`,I,{claims:t.claims});return t}var yr=Symbol(),br=Symbol();async function xr(e,t,n,r){return typeof r?.expectedNonce==`string`||typeof r?.maxAge==`number`||r!=null&&r.requireIdToken?async function(e,t,n,r,i,a,o){let s=[];switch(r){case void 0:r=yr;break;case yr:break;default:F(r,`"expectedNonce" argument`),s.push(`nonce`)}switch(i??=t.default_max_age,i){case void 0:i=br;break;case br:break;default:In(i,!0,`"maxAge" argument`),s.push(`auth_time`)}let c=await fr(e,t,n,s,a,o);F(c.id_token,`"response" body "id_token" property`,I,{body:c});let l=dr(c);if(i!==br){let e=Hn()+Bn(t),n=Vn(t);if(l.auth_time+i<e-n)throw P(`too much time has elapsed since the last End-User authentication`,jr,{claims:l,now:e,tolerance:n,claim:`auth_time`})}if(r===yr){if(l.nonce!==void 0)throw P(`unexpected ID Token "nonce" claim value`,Mr,{expected:void 0,claims:l,claim:`nonce`})}else if(l.nonce!==r)throw P(`unexpected ID Token "nonce" claim value`,Mr,{expected:r,claims:l,claim:`nonce`});return c}(e,t,n,r.expectedNonce,r.maxAge,r[Sn],r.recognizedTokenTypes):async function(e,t,n,r,i){let a=await fr(e,t,n,void 0,r,i),o=dr(a);if(o){if(t.default_max_age!==void 0){In(t.default_max_age,!0,`"client.default_max_age"`);let e=Hn()+Bn(t),n=Vn(t);if(o.auth_time+t.default_max_age<e-n)throw P(`too much time has elapsed since the last End-User authentication`,jr,{claims:o,now:e,tolerance:n,claim:`auth_time`})}if(o.nonce!==void 0)throw P(`unexpected ID Token "nonce" claim value`,Mr,{expected:void 0,claims:o,claim:`nonce`})}return a}(e,t,n,r?.[Sn],r?.recognizedTokenTypes)}var Sr=`OAUTH_WWW_AUTHENTICATE_CHALLENGE`,Cr=`OAUTH_RESPONSE_BODY_ERROR`,wr=`OAUTH_UNSUPPORTED_OPERATION`,Tr=`OAUTH_AUTHORIZATION_RESPONSE_ERROR`,Er=`OAUTH_PARSE_ERROR`,I=`OAUTH_INVALID_RESPONSE`,Dr=`OAUTH_RESPONSE_IS_NOT_JSON`,Or=`OAUTH_RESPONSE_IS_NOT_CONFORM`,kr=`OAUTH_HTTP_REQUEST_FORBIDDEN`,Ar=`OAUTH_REQUEST_PROTOCOL_FORBIDDEN`,jr=`OAUTH_JWT_TIMESTAMP_CHECK_FAILED`,Mr=`OAUTH_JWT_CLAIM_COMPARISON_FAILED`,Nr=`OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED`,Pr=`OAUTH_MISSING_SERVER_METADATA`,Fr=`OAUTH_INVALID_SERVER_METADATA`;function Ir(e){if(e.bodyUsed)throw j(`"response" body has been used already`,k)}function Lr(e){let t=e.algorithm;if(typeof t.modulusLength!=`number`||t.modulusLength<2048)throw new N(`unsupported ${t.name} modulusLength`,{cause:e})}function Rr(e){switch(e.algorithm.namedCurve){case`P-256`:return`SHA-256`;case`P-384`:return`SHA-384`;case`P-521`:return`SHA-512`;default:throw new N(`unsupported ECDSA namedCurve`,{cause:e})}}async function zr(e){if(e.method!==`POST`)throw j(`form_post responses are expected to use the POST method`,k,{cause:e});if(or(e)!==`application/x-www-form-urlencoded`)throw j(`form_post responses are expected to use the application/x-www-form-urlencoded content-type`,k,{cause:e});return async function(e){if(e.bodyUsed)throw j(`form_post Request instances must contain a readable body`,k,{cause:e});return e.text()}(e)}function Br(e,t,n,r){if(e===void 0)if(Array.isArray(t)){if(!t.includes(r.alg))throw P(`unexpected JWT "alg" header parameter`,I,{header:r,expected:t,reason:`authorization server metadata`})}else{if(n===void 0)throw P(`missing client or server configuration to verify used JWT "alg" header parameter`,void 0,{client:e,issuer:t,fallback:n});if(typeof n==`string`?r.alg!==n:typeof n==`function`?!n(r.alg):!n.includes(r.alg))throw P(`unexpected JWT "alg" header parameter`,I,{header:r,expected:n,reason:`default value`})}else if(typeof e==`string`?r.alg!==e:!e.includes(r.alg))throw P(`unexpected JWT "alg" header parameter`,I,{header:r,expected:e,reason:`client configuration`})}function Vr(e,t){let n=e.getAll(t),r=n[0];if(n.length>1)throw P(`"${t}" parameter must be provided only once`,I);return r}var Hr=Symbol(),Ur=Symbol();function Wr(e,t,n,r){if(Un(e),Wn(t),n instanceof URL&&(n=n.searchParams),!(n instanceof URLSearchParams))throw j(`"parameters" must be an instance of URLSearchParams, or URL`,A);if(Vr(n,`response`))throw P(`"parameters" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()`,I,{parameters:n});let i=Vr(n,`iss`),a=Vr(n,`state`);if(!i&&e.authorization_response_iss_parameter_supported)throw P(`response parameter "iss" (issuer) missing`,I,{parameters:n});if(i&&i!==e.issuer)throw P(`unexpected "iss" (issuer) response parameter value`,I,{expected:e.issuer,parameters:n});switch(r){case void 0:case Ur:if(a!==void 0)throw P(`unexpected "state" response parameter encountered`,I,{expected:void 0,parameters:n});break;case Hr:break;default:if(F(r,`"expectedState" argument`),a!==r)throw P(a===void 0?`response parameter "state" missing`:`unexpected "state" response parameter value`,I,{expected:r,parameters:n})}if(Vr(n,`error`))throw new Qn(`authorization response from the server is an error`,{cause:n});let o=Vr(n,`id_token`),s=Vr(n,`token`);if(o!==void 0||s!==void 0)throw new N(`implicit and hybrid flows are not supported`);return c=new URLSearchParams(n),hr.add(c),c;var c}async function Gr(e){let t,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Ln;try{t=await e.json()}catch(t){throw n(e),P(`failed to parse "response" body as JSON`,Er,t)}if(!jn(t))throw P(`"response" body must be a top level object`,I,{body:t});return t}var Kr=Symbol(),qr=Symbol(),Jr=new TextEncoder,Yr=new TextDecoder;function Xr(){var e=[...arguments];let t=e.reduce((e,t)=>e+t.length,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function Zr(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r>127)throw TypeError(`non-ASCII string encountered in encode()`);t[n]=r}return t}function Qr(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function $r(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof e==`string`?e:Yr.decode(e),{alphabet:`base64url`});let t=e;t instanceof Uint8Array&&(t=Yr.decode(t)),t=t.replace(/-/g,`+`).replace(/_/g,`/`);try{return Qr(t)}catch{throw TypeError(`The input to be decoded is not correctly encoded.`)}}function ei(e){let t=e;return typeof t==`string`&&(t=Jr.encode(t)),Uint8Array.prototype.toBase64?t.toBase64({alphabet:`base64url`,omitPadding:!0}):function(e){if(Uint8Array.prototype.toBase64)return e.toBase64();let t=[];for(let n=0;n<e.length;n+=32768)t.push(String.fromCharCode.apply(null,e.subarray(n,n+32768)));return btoa(t.join(``))}(t).replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`)}var ti=function(e){return TypeError(`CryptoKey does not support this operation, its ${arguments.length>1&&arguments[1]!==void 0?arguments[1]:`algorithm.name`} must be ${e}`)},ni=(e,t)=>e.name===t;function ri(e,t){var n;if((n=e.hash,parseInt(n.name.slice(4),10))!==t)throw ti(`SHA-${t}`,`algorithm.hash`)}function ii(e,t,n){switch(t){case`HS256`:case`HS384`:case`HS512`:if(!ni(e.algorithm,`HMAC`))throw ti(`HMAC`);ri(e.algorithm,parseInt(t.slice(2),10));break;case`RS256`:case`RS384`:case`RS512`:if(!ni(e.algorithm,`RSASSA-PKCS1-v1_5`))throw ti(`RSASSA-PKCS1-v1_5`);ri(e.algorithm,parseInt(t.slice(2),10));break;case`PS256`:case`PS384`:case`PS512`:if(!ni(e.algorithm,`RSA-PSS`))throw ti(`RSA-PSS`);ri(e.algorithm,parseInt(t.slice(2),10));break;case`Ed25519`:case`EdDSA`:if(!ni(e.algorithm,`Ed25519`))throw ti(`Ed25519`);break;case`ML-DSA-44`:case`ML-DSA-65`:case`ML-DSA-87`:if(!ni(e.algorithm,t))throw ti(t);break;case`ES256`:case`ES384`:case`ES512`:{if(!ni(e.algorithm,`ECDSA`))throw ti(`ECDSA`);let n=function(e){switch(e){case`ES256`:return`P-256`;case`ES384`:return`P-384`;case`ES512`:return`P-521`;default:throw Error(`unreachable`)}}(t);if(e.algorithm.namedCurve!==n)throw ti(n,`algorithm.namedCurve`);break}default:throw TypeError(`CryptoKey does not support this operation`)}(function(e,t){if(t&&!e.usages.includes(t))throw TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)})(e,n)}function ai(e,t){var n=[...arguments].slice(2);if((n=n.filter(Boolean)).length>2){let t=n.pop();e+=`one of type ${n.join(`, `)}, or ${t}.`}else n.length===2?e+=`one of type ${n[0]} or ${n[1]}.`:e+=`of type ${n[0]}.`;if(t==null)e+=` Received ${t}`;else if(typeof t==`function`&&t.name)e+=` Received function ${t.name}`;else if(typeof t==`object`&&t){var r;(r=t.constructor)!=null&&r.name&&(e+=` Received an instance of ${t.constructor.name}`)}return e}var oi=function(e,t){var n=[...arguments].slice(2);return ai(`Key for the ${e} algorithm must be `,t,...n)},L=class extends Error{constructor(e,t){var n;super(e,t),S(this,`code`,`ERR_JOSE_GENERIC`),this.name=this.constructor.name,(n=Error.captureStackTrace)==null||n.call(Error,this,this.constructor)}};S(L,`code`,`ERR_JOSE_GENERIC`);var R=class extends L{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:`unspecified`,r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:`unspecified`;super(e,{cause:{claim:n,reason:r,payload:t}}),S(this,`code`,`ERR_JWT_CLAIM_VALIDATION_FAILED`),S(this,`claim`,void 0),S(this,`reason`,void 0),S(this,`payload`,void 0),this.claim=n,this.reason=r,this.payload=t}};S(R,`code`,`ERR_JWT_CLAIM_VALIDATION_FAILED`);var si=class extends L{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:`unspecified`,r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:`unspecified`;super(e,{cause:{claim:n,reason:r,payload:t}}),S(this,`code`,`ERR_JWT_EXPIRED`),S(this,`claim`,void 0),S(this,`reason`,void 0),S(this,`payload`,void 0),this.claim=n,this.reason=r,this.payload=t}};S(si,`code`,`ERR_JWT_EXPIRED`);var ci=class extends L{constructor(){super(...arguments),S(this,`code`,`ERR_JOSE_ALG_NOT_ALLOWED`)}};S(ci,`code`,`ERR_JOSE_ALG_NOT_ALLOWED`);var z=class extends L{constructor(){super(...arguments),S(this,`code`,`ERR_JOSE_NOT_SUPPORTED`)}};S(z,`code`,`ERR_JOSE_NOT_SUPPORTED`),S(class extends L{constructor(){super(arguments.length>0&&arguments[0]!==void 0?arguments[0]:`decryption operation failed`,arguments.length>1?arguments[1]:void 0),S(this,`code`,`ERR_JWE_DECRYPTION_FAILED`)}},`code`,`ERR_JWE_DECRYPTION_FAILED`),S(class extends L{constructor(){super(...arguments),S(this,`code`,`ERR_JWE_INVALID`)}},`code`,`ERR_JWE_INVALID`);var B=class extends L{constructor(){super(...arguments),S(this,`code`,`ERR_JWS_INVALID`)}};S(B,`code`,`ERR_JWS_INVALID`);var V=class extends L{constructor(){super(...arguments),S(this,`code`,`ERR_JWT_INVALID`)}};S(V,`code`,`ERR_JWT_INVALID`),S(class extends L{constructor(){super(...arguments),S(this,`code`,`ERR_JWK_INVALID`)}},`code`,`ERR_JWK_INVALID`);var li=class extends L{constructor(){super(...arguments),S(this,`code`,`ERR_JWKS_INVALID`)}};S(li,`code`,`ERR_JWKS_INVALID`);var ui=class extends L{constructor(){super(arguments.length>0&&arguments[0]!==void 0?arguments[0]:`no applicable key found in the JSON Web Key Set`,arguments.length>1?arguments[1]:void 0),S(this,`code`,`ERR_JWKS_NO_MATCHING_KEY`)}};S(ui,`code`,`ERR_JWKS_NO_MATCHING_KEY`);var di=class extends L{constructor(){super(arguments.length>0&&arguments[0]!==void 0?arguments[0]:`multiple matching keys found in the JSON Web Key Set`,arguments.length>1?arguments[1]:void 0),S(this,Symbol.asyncIterator,void 0),S(this,`code`,`ERR_JWKS_MULTIPLE_MATCHING_KEYS`)}};S(di,`code`,`ERR_JWKS_MULTIPLE_MATCHING_KEYS`);var fi=class extends L{constructor(){super(arguments.length>0&&arguments[0]!==void 0?arguments[0]:`request timed out`,arguments.length>1?arguments[1]:void 0),S(this,`code`,`ERR_JWKS_TIMEOUT`)}};S(fi,`code`,`ERR_JWKS_TIMEOUT`);var pi=class extends L{constructor(){super(arguments.length>0&&arguments[0]!==void 0?arguments[0]:`signature verification failed`,arguments.length>1?arguments[1]:void 0),S(this,`code`,`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`)}};S(pi,`code`,`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`);var mi=e=>{if(e?.[Symbol.toStringTag]===`CryptoKey`)return!0;try{return e instanceof CryptoKey}catch{return!1}},hi=e=>e?.[Symbol.toStringTag]===`KeyObject`,gi=e=>mi(e)||hi(e);function _i(e,t){if(e)throw TypeError(`${t} can only be called once`)}function vi(e,t,n){try{return $r(e)}catch{throw new n(`Failed to base64url decode the ${t}`)}}function yi(e){if(typeof(t=e)!=`object`||t===null||Object.prototype.toString.call(e)!==`[object Object]`)return!1;var t;if(Object.getPrototypeOf(e)===null)return!0;let n=e;for(;Object.getPrototypeOf(n)!==null;)n=Object.getPrototypeOf(n);return Object.getPrototypeOf(e)===n}function bi(){let e=[...arguments].filter(Boolean);if(e.length===0||e.length===1)return!0;let t;for(let n of e){let e=Object.keys(n);if(t&&t.size!==0)for(let n of e){if(t.has(n))return!1;t.add(n)}else t=new Set(e)}return!0}var xi=e=>yi(e)&&typeof e.kty==`string`;function Si(e,t){if(e.startsWith(`RS`)||e.startsWith(`PS`)){let n=t.algorithm.modulusLength;if(typeof n!=`number`||n<2048)throw TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}}function Ci(e,t){let n=`SHA-${e.slice(-3)}`;switch(e){case`HS256`:case`HS384`:case`HS512`:return{hash:n,name:`HMAC`};case`PS256`:case`PS384`:case`PS512`:return{hash:n,name:`RSA-PSS`,saltLength:parseInt(e.slice(-3),10)>>3};case`RS256`:case`RS384`:case`RS512`:return{hash:n,name:`RSASSA-PKCS1-v1_5`};case`ES256`:case`ES384`:case`ES512`:return{hash:n,name:`ECDSA`,namedCurve:t.namedCurve};case`Ed25519`:case`EdDSA`:return{name:`Ed25519`};case`ML-DSA-44`:case`ML-DSA-65`:case`ML-DSA-87`:return{name:e};default:throw new z(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function wi(e,t,n){if(t instanceof Uint8Array){if(!e.startsWith(`HS`))throw TypeError(function(e){return ai(`Key must be `,e,...[...arguments].slice(1))}(t,`CryptoKey`,`KeyObject`,`JSON Web Key`));return crypto.subtle.importKey(`raw`,t,{hash:`SHA-${e.slice(-3)}`,name:`HMAC`},!1,[n])}return ii(t,e,n),t}var Ti=`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`;async function Ei(e){if(!e.alg)throw TypeError(`"alg" argument is required when "jwk.alg" is not present`);let t=function(e){let t,n;switch(e.kty){case`AKP`:switch(e.alg){case`ML-DSA-44`:case`ML-DSA-65`:case`ML-DSA-87`:t={name:e.alg},n=e.priv?[`sign`]:[`verify`];break;default:throw new z(Ti)}break;case`RSA`:switch(e.alg){case`PS256`:case`PS384`:case`PS512`:t={name:`RSA-PSS`,hash:`SHA-${e.alg.slice(-3)}`},n=e.d?[`sign`]:[`verify`];break;case`RS256`:case`RS384`:case`RS512`:t={name:`RSASSA-PKCS1-v1_5`,hash:`SHA-${e.alg.slice(-3)}`},n=e.d?[`sign`]:[`verify`];break;case`RSA-OAEP`:case`RSA-OAEP-256`:case`RSA-OAEP-384`:case`RSA-OAEP-512`:t={name:`RSA-OAEP`,hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},n=e.d?[`decrypt`,`unwrapKey`]:[`encrypt`,`wrapKey`];break;default:throw new z(Ti)}break;case`EC`:switch(e.alg){case`ES256`:case`ES384`:case`ES512`:t={name:`ECDSA`,namedCurve:{ES256:`P-256`,ES384:`P-384`,ES512:`P-521`}[e.alg]},n=e.d?[`sign`]:[`verify`];break;case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:t={name:`ECDH`,namedCurve:e.crv},n=e.d?[`deriveBits`]:[];break;default:throw new z(Ti)}break;case`OKP`:switch(e.alg){case`Ed25519`:case`EdDSA`:t={name:`Ed25519`},n=e.d?[`sign`]:[`verify`];break;case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:t={name:e.crv},n=e.d?[`deriveBits`]:[];break;default:throw new z(Ti)}break;default:throw new z(`Invalid or unsupported JWK "kty" (Key Type) Parameter value`)}return{algorithm:t,keyUsages:n}}(e),n=t.algorithm,r=t.keyUsages,i=C({},e);return i.kty!==`AKP`&&delete i.alg,delete i.use,crypto.subtle.importKey(`jwk`,i,n,e.ext??(!e.d&&!e.priv),e.key_ops??r)}var Di=`given KeyObject instance cannot be used for this algorithm`,Oi,ki=async function(e,t,n){let r=arguments.length>3&&arguments[3]!==void 0&&arguments[3];Oi||=new WeakMap;let i=Oi.get(e);if(i!=null&&i[n])return i[n];let a=await Ei(C(C({},t),{},{alg:n}));return r&&Object.freeze(e),i?i[n]=a:Oi.set(e,{[n]:a}),a};async function Ai(e,t){if(e instanceof Uint8Array||mi(e))return e;if(hi(e)){if(e.type===`secret`)return e.export();if(`toCryptoKey`in e&&typeof e.toCryptoKey==`function`)try{return((e,t)=>{Oi||=new WeakMap;let n=Oi.get(e);if(n!=null&&n[t])return n[t];let r=e.type===`public`,i=!!r,a;if(e.asymmetricKeyType===`x25519`){switch(t){case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:break;default:throw TypeError(Di)}a=e.toCryptoKey(e.asymmetricKeyType,i,r?[]:[`deriveBits`])}if(e.asymmetricKeyType===`ed25519`){if(t!==`EdDSA`&&t!==`Ed25519`)throw TypeError(Di);a=e.toCryptoKey(e.asymmetricKeyType,i,[r?`verify`:`sign`])}switch(e.asymmetricKeyType){case`ml-dsa-44`:case`ml-dsa-65`:case`ml-dsa-87`:if(t!==e.asymmetricKeyType.toUpperCase())throw TypeError(Di);a=e.toCryptoKey(e.asymmetricKeyType,i,[r?`verify`:`sign`])}if(e.asymmetricKeyType===`rsa`){let n;switch(t){case`RSA-OAEP`:n=`SHA-1`;break;case`RS256`:case`PS256`:case`RSA-OAEP-256`:n=`SHA-256`;break;case`RS384`:case`PS384`:case`RSA-OAEP-384`:n=`SHA-384`;break;case`RS512`:case`PS512`:case`RSA-OAEP-512`:n=`SHA-512`;break;default:throw TypeError(Di)}if(t.startsWith(`RSA-OAEP`))return e.toCryptoKey({name:`RSA-OAEP`,hash:n},i,r?[`encrypt`]:[`decrypt`]);a=e.toCryptoKey({name:t.startsWith(`PS`)?`RSA-PSS`:`RSASSA-PKCS1-v1_5`,hash:n},i,[r?`verify`:`sign`])}if(e.asymmetricKeyType===`ec`){let n=new Map([[`prime256v1`,`P-256`],[`secp384r1`,`P-384`],[`secp521r1`,`P-521`]]).get(e.asymmetricKeyDetails?.namedCurve);if(!n)throw TypeError(Di);let o={ES256:`P-256`,ES384:`P-384`,ES512:`P-521`};o[t]&&n===o[t]&&(a=e.toCryptoKey({name:`ECDSA`,namedCurve:n},i,[r?`verify`:`sign`])),t.startsWith(`ECDH-ES`)&&(a=e.toCryptoKey({name:`ECDH`,namedCurve:n},i,r?[]:[`deriveBits`]))}if(!a)throw TypeError(Di);return n?n[t]=a:Oi.set(e,{[t]:a}),a})(e,t)}catch(e){if(e instanceof TypeError)throw e}return ki(e,e.export({format:`jwk`}),t)}if(xi(e))return e.k?$r(e.k):ki(e,e,t,!0);throw Error(`unreachable`)}var ji=(e,t)=>{if(e.byteLength!==t.length)return!1;for(let n=0;n<e.byteLength;n++)if(e[n]!==t[n])return!1;return!0},Mi=e=>{let t=e.data[e.pos++];if(128&t){let n=127&t,r=0;for(let t=0;t<n;t++)r=r<<8|e.data[e.pos++];return r}return t},Ni=(e,t,n)=>{if(e.data[e.pos++]!==t)throw Error(n)},Pi=(e,t)=>{let n=e.data.subarray(e.pos,e.pos+t);return e.pos+=t,n},Fi=e=>{let t=(e=>(Ni(e,6,`Expected algorithm OID`),Pi(e,Mi(e))))(e);if(ji(t,[43,101,110]))return`X25519`;if(!ji(t,[42,134,72,206,61,2,1]))throw Error(`Unsupported key algorithm`);Ni(e,6,`Expected curve OID`);let n=Pi(e,Mi(e));for(let e of[{name:`P-256`,oid:[42,134,72,206,61,3,1,7]},{name:`P-384`,oid:[43,129,4,0,34]},{name:`P-521`,oid:[43,129,4,0,35]}]){let t=e.name,r=e.oid;if(ji(n,r))return t}throw Error(`Unsupported named curve`)},Ii=async(e,t,n,r)=>{let i,a,o=e===`spki`,s=()=>o?[`verify`]:[`sign`];switch(n){case`PS256`:case`PS384`:case`PS512`:i={name:`RSA-PSS`,hash:`SHA-${n.slice(-3)}`},a=s();break;case`RS256`:case`RS384`:case`RS512`:i={name:`RSASSA-PKCS1-v1_5`,hash:`SHA-${n.slice(-3)}`},a=s();break;case`RSA-OAEP`:case`RSA-OAEP-256`:case`RSA-OAEP-384`:case`RSA-OAEP-512`:i={name:`RSA-OAEP`,hash:`SHA-${parseInt(n.slice(-3),10)||1}`},a=o?[`encrypt`,`wrapKey`]:[`decrypt`,`unwrapKey`];break;case`ES256`:case`ES384`:case`ES512`:i={name:`ECDSA`,namedCurve:{ES256:`P-256`,ES384:`P-384`,ES512:`P-521`}[n]},a=s();break;case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:try{let e=r.getNamedCurve(t);i=e===`X25519`?{name:`X25519`}:{name:`ECDH`,namedCurve:e}}catch{throw new z(`Invalid or unsupported key format`)}a=o?[]:[`deriveBits`];break;case`Ed25519`:case`EdDSA`:i={name:`Ed25519`},a=s();break;case`ML-DSA-44`:case`ML-DSA-65`:case`ML-DSA-87`:i={name:n},a=s();break;default:throw new z(`Invalid or unsupported "alg" (Algorithm) value`)}return crypto.subtle.importKey(e,t,i,r?.extractable??!!o,a)},Li=(e,t,n)=>{var r;let i=((e,t)=>Qr(e.replace(t,``)))(e,/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g),a=n;return t!=null&&(r=t.startsWith)!=null&&r.call(t,`ECDH-ES`)&&(a||={},a.getNamedCurve=e=>{let t={data:e,pos:0};return function(e){Ni(e,48,`Invalid PKCS#8 structure`),Mi(e),Ni(e,2,`Expected version field`);let t=Mi(e);e.pos+=t,Ni(e,48,`Expected algorithm identifier`),Mi(e),e.pos}(t),Fi(t)}),Ii(`pkcs8`,i,t,a)};async function Ri(e,t,n){if(typeof e!=`string`||e.indexOf(`-----BEGIN PRIVATE KEY-----`)!==0)throw TypeError(`"pkcs8" must be PKCS#8 formatted string`);return Li(e,t,n)}function zi(e,t,n,r,i){if(i.crit!==void 0&&r?.crit===void 0)throw new e(`"crit" (Critical) Header Parameter MUST be integrity protected`);if(!r||r.crit===void 0)return new Set;if(!Array.isArray(r.crit)||r.crit.length===0||r.crit.some(e=>typeof e!=`string`||e.length===0))throw new e(`"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present`);let a;a=n===void 0?t:new Map([...Object.entries(n),...t.entries()]);for(let t of r.crit){if(!a.has(t))throw new z(`Extension Header Parameter "${t}" is not recognized`);if(i[t]===void 0)throw new e(`Extension Header Parameter "${t}" is missing`);if(a.get(t)&&r[t]===void 0)throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return new Set(r.crit)}var Bi=e=>e?.[Symbol.toStringTag],Vi=(e,t,n)=>{if(t.use!==void 0){let e;switch(n){case`sign`:case`verify`:e=`sig`;break;case`encrypt`:case`decrypt`:e=`enc`}if(t.use!==e)throw TypeError(`Invalid key for this operation, its "use" must be "${e}" when present`)}if(t.alg!==void 0&&t.alg!==e)throw TypeError(`Invalid key for this operation, its "alg" must be "${e}" when present`);if(Array.isArray(t.key_ops)){var r,i;let a;switch(!0){case n===`sign`||n===`verify`:case e===`dir`:case e.includes(`CBC-HS`):a=n;break;case e.startsWith(`PBES2`):a=`deriveBits`;break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(e):a=!e.includes(`GCM`)&&e.endsWith(`KW`)?n===`encrypt`?`wrapKey`:`unwrapKey`:n;break;case n===`encrypt`&&e.startsWith(`RSA`):a=`wrapKey`;break;case n===`decrypt`:a=e.startsWith(`RSA`)?`unwrapKey`:`deriveBits`}if(a&&!1===((r=t.key_ops)==null||(i=r.includes)==null?void 0:i.call(r,a)))throw TypeError(`Invalid key for this operation, its "key_ops" must include "${a}" when present`)}return!0};function Hi(e,t,n){switch(e.substring(0,2)){case`A1`:case`A2`:case`di`:case`HS`:case`PB`:((e,t,n)=>{if(!(t instanceof Uint8Array)){if(xi(t)){if((e=>e.kty===`oct`&&typeof e.k==`string`)(t)&&Vi(e,t,n))return;throw TypeError(`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`)}if(!gi(t))throw TypeError(oi(e,t,`CryptoKey`,`KeyObject`,`JSON Web Key`,`Uint8Array`));if(t.type!==`secret`)throw TypeError(`${Bi(t)} instances for symmetric algorithms must be of type "secret"`)}})(e,t,n);break;default:((e,t,n)=>{if(xi(t))switch(n){case`decrypt`:case`sign`:if((e=>e.kty!==`oct`&&(e.kty===`AKP`&&typeof e.priv==`string`||typeof e.d==`string`))(t)&&Vi(e,t,n))return;throw TypeError(`JSON Web Key for this operation must be a private JWK`);case`encrypt`:case`verify`:if((e=>e.kty!==`oct`&&e.d===void 0&&e.priv===void 0)(t)&&Vi(e,t,n))return;throw TypeError(`JSON Web Key for this operation must be a public JWK`)}if(!gi(t))throw TypeError(oi(e,t,`CryptoKey`,`KeyObject`,`JSON Web Key`));if(t.type===`secret`)throw TypeError(`${Bi(t)} instances for asymmetric algorithms must not be of type "secret"`);if(t.type===`public`)switch(n){case`sign`:throw TypeError(`${Bi(t)} instances for asymmetric algorithm signing must be of type "private"`);case`decrypt`:throw TypeError(`${Bi(t)} instances for asymmetric algorithm decryption must be of type "private"`)}if(t.type===`private`)switch(n){case`verify`:throw TypeError(`${Bi(t)} instances for asymmetric algorithm verifying must be of type "public"`);case`encrypt`:throw TypeError(`${Bi(t)} instances for asymmetric algorithm encryption must be of type "public"`)}})(e,t,n)}}var Ui,Wi,Gi,Ki;(typeof navigator>`u`||(Ui=navigator.userAgent)==null||(Wi=Ui.startsWith)==null||!Wi.call(Ui,`Mozilla/5.0 `))&&(Ki=`openid-client/v6.8.4`,Gi={"user-agent":Ki});var H=e=>qi.get(e),qi,Ji;function Yi(e){return e===void 0?(Ji||=new WeakMap,(e,t,n,r)=>{let i;return(i=Ji.get(t))||(function(e,t){if(typeof e!=`string`)throw $i(`${t} must be a string`,Qi);if(e.length===0)throw $i(`${t} must not be empty`,Zi)}(t.client_secret,`"metadata.client_secret"`),i=Gn(t.client_secret),Ji.set(t,i)),i(e,t,n,r)}):Gn(e)}var Xi=bn,Zi=`ERR_INVALID_ARG_VALUE`,Qi=`ERR_INVALID_ARG_TYPE`;function $i(e,t,n){let r=TypeError(e,{cause:n});return Object.assign(r,{code:t}),r}function ea(e){return async function(e){return F(e,`codeVerifier`),On(await crypto.subtle.digest(`SHA-256`,Tn(e)))}(e)}function ta(){return Rn()}var na=class extends Error{constructor(e,t){var n;super(e,t),S(this,`code`,void 0),this.name=this.constructor.name,this.code=t?.code,(n=Error.captureStackTrace)==null||n.call(Error,this,this.constructor)}};function U(e,t,n){return new na(e,{cause:t,code:n})}function W(e){if(e instanceof TypeError||e instanceof na||e instanceof Zn||e instanceof Qn||e instanceof $n)throw e;if(e instanceof kn)switch(e.code){case kr:throw U(`only requests to HTTPS are allowed`,e,e.code);case Ar:throw U(`only requests to HTTP or HTTPS are allowed`,e,e.code);case Or:throw U(`unexpected HTTP response status code`,e.cause,e.code);case Dr:throw U(`unexpected response content-type`,e.cause,e.code);case Er:throw U(`parsing error occured`,e,e.code);case I:throw U(`invalid response encountered`,e,e.code);case Mr:throw U(`unexpected JWT claim value encountered`,e,e.code);case Nr:throw U(`unexpected JSON attribute value encountered`,e,e.code);case jr:throw U(`JWT timestamp claim value failed validation`,e,e.code);default:throw U(e.message,e,e.code)}if(e instanceof N)throw U(`unsupported operation`,e,e.code);if(e instanceof DOMException)switch(e.name){case`OperationError`:throw U(`runtime operation error`,e,wr);case`NotSupportedError`:throw U(`runtime unsupported operation`,e,wr);case`TimeoutError`:throw U(`operation timed out`,e,`OAUTH_TIMEOUT`);case`AbortError`:throw U(`operation aborted`,e,`OAUTH_ABORT`)}throw new na(`something went wrong`,{cause:e})}async function ra(e,t,n,r,i){let a=new aa(await async function(e,t){var n;if(!(e instanceof URL))throw $i(`"server" must be an instance of URL`,Qi);let r=!e.href.includes(`/.well-known/`),i=t?.timeout??30,a=AbortSignal.timeout(1e3*i),o=await(r?Fn(e,{algorithm:t?.algorithm,[bn]:t?.[Xi],[M]:t==null||(n=t.execute)==null?void 0:n.includes(da),signal:a,headers:new Headers(Gi)}):(t?.[Xi]||fetch)((Jn(e,t==null||(s=t.execute)==null||!s.includes(da)),e.href),{headers:Object.fromEntries(new Headers(C({accept:`application/json`},Gi)).entries()),body:void 0,method:`GET`,redirect:`manual`,signal:a})).then(e=>async function(e,t){let n=e;if(!(n instanceof URL)&&n!==Kr)throw j(`"expectedIssuerIdentifier" must be an instance of URL`,A);if(!_n(t,Response))throw j(`"response" must be an instance of Response`,A);if(t.status!==200)throw P(`"response" is not a conform Authorization Server Metadata response (unexpected HTTP status code)`,Or,t);Ir(t);let r=await Gr(t);if(F(r.issuer,`"response" body "issuer" property`,I,{body:r}),n!==Kr&&new URL(r.issuer).href!==n.href)throw P(`"response" body "issuer" property does not match the expected value`,Nr,{expected:n.href,body:r,attribute:`issuer`});return r}(Kr,e)).catch(W);var s;return r&&new URL(o.issuer).href!==e.href&&(function(e,t,n){return!(e.origin!==`https://login.microsoftonline.com`||n!=null&&n.algorithm&&n.algorithm!==`oidc`||(t[ia]=!0,0))}(e,o,t)||function(e,t){return!(!e.hostname.endsWith(`.b2clogin.com`)||t!=null&&t.algorithm&&t.algorithm!==`oidc`)}(e,t)||(()=>{throw new na(`discovered metadata issuer does not match the expected issuer`,{code:Nr,cause:{expected:e.href,body:o,attribute:`issuer`}})})()),o}(e,i),t,n,r),o=H(a);if(i!=null&&i[Xi]&&(o.fetch=i[Xi]),i!=null&&i.timeout&&(o.timeout=i.timeout),i!=null&&i.execute)for(let e of i.execute)e(a);return a}new TextDecoder;var ia=Symbol(),aa=class{constructor(e,t,n,r){if(typeof t!=`string`||!t.length)throw $i(`"clientId" must be a non-empty string`,Qi);if(typeof n==`string`&&(n={client_secret:n}),n?.client_id!==void 0&&t!==n.client_id)throw $i(`"clientId" and "metadata.client_id" must be the same`,Zi);let i=C(C({},structuredClone(n)),{},{client_id:t}),a;i[vn]=n?.[vn]??0,i[yn]=n?.[yn]??30,a=r||(typeof i.client_secret==`string`&&i.client_secret.length?Yi(i.client_secret):(e,t,n,r)=>{n.set(`client_id`,t.client_id)});let o=Object.freeze(i),s=structuredClone(e);ia in e&&(s[qr]=t=>{let n=t.claims.tid;return e.issuer.replace(`{tenantid}`,n)});let c=Object.freeze(s);qi||=new WeakMap,qi.set(this,{__proto__:null,as:c,c:o,auth:a,tlsOnly:!0,jwksCache:{}})}serverMetadata(){let e=structuredClone(H(this).as);return function(e){Object.defineProperties(e,function(e){return{supportsPKCE:{__proto__:null,value(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:`S256`;return!0===e.code_challenge_methods_supported?.includes(t)}}}}(e))}(e),e}clientMetadata(){return structuredClone(H(this).c)}get timeout(){return H(this).timeout}set timeout(e){H(this).timeout=e}get[Xi](){return H(this).fetch}set[Xi](e){H(this).fetch=e}};function oa(e){Object.defineProperties(e,function(e){let t;if(e.expires_in!==void 0){let n=new Date;n.setSeconds(n.getSeconds()+e.expires_in),t=n.getTime()}return{expiresIn:{__proto__:null,value(){if(t){let e=Date.now();return t>e?Math.floor((t-e)/1e3):0}}},claims:{__proto__:null,value(){try{return dr(this)}catch{return}}}}}(e))}async function sa(e,t,n){let r=arguments.length>3&&arguments[3]!==void 0&&arguments[3],i=e.headers.get(`retry-after`)?.trim();if(i===void 0)return;let a;if(/^\d+$/.test(i))a=parseInt(i,10);else{let e=new Date(i);if(Number.isFinite(e.getTime())){let t=new Date,n=e.getTime()-t.getTime();n>0&&(a=Math.ceil(n/1e3))}}if(r&&!Number.isFinite(a))throw new kn(`invalid Retry-After header value`,{cause:e});a>t&&await ca(a-t,n)}function ca(e,t){return new Promise((n,r)=>{let i=e=>{try{t.throwIfAborted()}catch(e){r(e);return}if(e<=0)return void n();let a=Math.min(e,5);setTimeout(()=>i(e-a),1e3*a)};i(e)})}async function la(e,t){_a(e);let n=H(e),r=n.as,i=n.c,a=n.auth,o=n.fetch,s=n.tlsOnly,c=n.timeout;return async function(e,t,n,r,i){Un(e),Wn(t);let a=Xn(e,`backchannel_authentication_endpoint`,t.use_mtls_endpoint_aliases,!0!==i?.[M]),o=new URLSearchParams(r);o.set(`client_id`,t.client_id);let s=Mn(i?.headers);return s.set(`accept`,`application/json`),sr(e,t,n,a,o,s,i)}(r,i,a,t,{[bn]:o,[M]:!s,headers:new Headers(Gi),signal:va(c)}).then(e=>async function(e,t,n){if(Un(e),Wn(t),!_n(n,Response))throw j(`"response" must be an instance of Response`,A);await ir(n,200,`Backchannel Authentication Endpoint`),Ir(n);let r=await Gr(n);F(r.auth_req_id,`"response" body "auth_req_id" property`,I,{body:r});let i=typeof r.expires_in==`number`?r.expires_in:parseFloat(r.expires_in);return In(i,!0,`"response" body "expires_in" property`,I,{body:r}),r.expires_in=i,r.interval!==void 0&&In(r.interval,!1,`"response" body "interval" property`,I,{body:r}),r}(r,i,e)).catch(W)}async function ua(e,t,n,r){_a(e),n=new URLSearchParams(n);let i=t.interval??5,a=r?.signal??AbortSignal.timeout(1e3*t.expires_in);try{await ca(i,a)}catch(e){W(e)}let o=H(e),s=o.as,c=o.c,l=o.auth,u=o.fetch,d=o.tlsOnly,f=o.nonRepudiation,p=o.timeout,m=o.decrypt,h=(i,o)=>ua(e,C(C({},t),{},{interval:i}),n,C(C({},r),{},{signal:a,flag:o})),g=function(e,t){let n=va(t);if(!n)return{signal:e,cleanup(){}};let r=new AbortController,i=e=>{let t=e.target;r.abort(t.reason)};return e.aborted?r.abort(e.reason):n.aborted?r.abort(n.reason):(e.addEventListener(`abort`,i,{once:!0}),n.addEventListener(`abort`,i,{once:!0})),{signal:r.signal,cleanup(){e.removeEventListener(`abort`,i),n.removeEventListener(`abort`,i)}}}(a,p),_=await async function(e,t,n,r,i){Un(e),Wn(t),F(r,`"authReqId"`);let a=new URLSearchParams(i?.additionalParameters);return a.set(`auth_req_id`,r),cr(e,t,n,`urn:openid:params:grant-type:ciba`,a,i)}(s,c,l,t.auth_req_id,{[bn]:u,[M]:!d,additionalParameters:n,DPoP:r?.DPoP,headers:new Headers(Gi),signal:g.signal}).catch(W).finally(g.cleanup);if(_.status===503&&_.headers.has(`retry-after`))return await sa(_,i,a,!0),await _.body?.cancel(),h(i);let ee=async function(e,t,n,r){return fr(e,t,n,void 0,r?.[Sn],r?.recognizedTokenTypes)}(s,c,_,{[Sn]:m}),v;try{v=await ee}catch(e){if(ya(e,r))return h(i,ba);if(e instanceof Zn)switch(e.error){case`slow_down`:i+=5;case`authorization_pending`:return await sa(e.response,i,a),h(i)}W(e)}return v.id_token&&await f?.(_),oa(v),v}function da(e){H(e).tlsOnly=!1}async function fa(e,t,n,r,i){if(_a(e),!(i?.flag===ba||t instanceof URL||function(e,t){try{return Object.getPrototypeOf(e)[Symbol.toStringTag]===t}catch{return!1}}(t,`Request`)))throw $i(`"currentUrl" must be an instance of URL, or Request`,Qi);let a,o,s=H(e),c=s.as,l=s.c,u=s.auth,d=s.fetch,f=s.tlsOnly,p=s.jarm,m=s.hybrid,h=s.nonRepudiation,g=s.timeout,_=s.decrypt,ee=s.implicit;if(i?.flag===ba)a=i.authResponse,o=i.redirectUri;else{if(!(t instanceof URL)){let e=t;switch(t=new URL(t.url),e.method){case`GET`:break;case`POST`:let n=new URLSearchParams(await zr(e));if(m)t.hash=n.toString();else for(let e of n.entries()){var v=w(e,2);let n=v[0],r=v[1];t.searchParams.append(n,r)}break;default:throw $i(`unexpected Request HTTP method`,Zi)}}switch(o=function(e){return(e=new URL(e)).search=``,e.hash=``,e.href}(t),!0){case!!p:a=await p(t,n?.expectedState);break;case!!m:a=await m(t,n?.expectedNonce,n?.expectedState,n?.maxAge);break;case!!ee:throw TypeError(`authorizationCodeGrant() cannot be used by response_type=id_token clients`);default:try{a=Wr(c,l,t.searchParams,n?.expectedState)}catch(e){W(e)}}}let y=await async function(e,t,n,r,i,a,o){if(Un(e),Wn(t),!hr.has(r))throw j(`"callbackParameters" must be an instance of URLSearchParams obtained from "validateAuthResponse()", or "validateJwtAuthResponse()`,k);F(i,`"redirectUri"`);let s=Vr(r,`code`);if(!s)throw P(`no authorization code in "callbackParameters"`,I);let c=new URLSearchParams(o?.additionalParameters);return c.set(`redirect_uri`,i),c.set(`code`,s),a!==gr&&(F(a,`"codeVerifier"`),c.set(`code_verifier`,a)),cr(e,t,n,`authorization_code`,c,o)}(c,l,u,a,o,n?.pkceCodeVerifier||gr,{additionalParameters:r,[bn]:d,[M]:!f,DPoP:i?.DPoP,headers:new Headers(Gi),signal:va(g)}).catch(W);typeof n?.expectedNonce!=`string`&&typeof n?.maxAge!=`number`||(n.idTokenExpected=!0);let b=xr(c,l,y,{expectedNonce:n?.expectedNonce,maxAge:n?.maxAge,requireIdToken:n?.idTokenExpected,[Sn]:_}),x;try{x=await b}catch(t){if(ya(t,i))return fa(e,void 0,n,r,C(C({},i),{},{flag:ba,authResponse:a,redirectUri:o}));W(t)}return x.id_token&&await h?.(y),oa(x),x}async function pa(e,t,n,r){_a(e),n=new URLSearchParams(n);let i=H(e),a=i.as,o=i.c,s=i.auth,c=i.fetch,l=i.tlsOnly,u=i.nonRepudiation,d=i.timeout,f=i.decrypt,p=await async function(e,t,n,r,i){Un(e),Wn(t),F(r,`"refreshToken"`);let a=new URLSearchParams(i?.additionalParameters);return a.set(`refresh_token`,r),cr(e,t,n,`refresh_token`,a,i)}(a,o,s,t,{[bn]:c,[M]:!l,additionalParameters:n,DPoP:r?.DPoP,headers:new Headers(Gi),signal:va(d)}).catch(W),m=async function(e,t,n,r){return fr(e,t,n,void 0,r?.[Sn],r?.recognizedTokenTypes)}(a,o,p,{[Sn]:f}),h;try{h=await m}catch(i){if(ya(i,r))return pa(e,t,n,C(C({},r),{},{flag:ba}));W(i)}return h.id_token&&await u?.(p),oa(h),h}async function ma(e,t,n){_a(e),t=new URLSearchParams(t);let r=H(e),i=r.as,a=r.c,o=r.auth,s=r.fetch,c=r.tlsOnly,l=r.timeout,u=async function(e,t,n,r){return fr(e,t,n,void 0,r?.[Sn],r?.recognizedTokenTypes)}(i,a,await async function(e,t,n,r,i){return Un(e),Wn(t),cr(e,t,n,`client_credentials`,new URLSearchParams(r),i)}(i,a,o,t,{[bn]:s,[M]:!c,DPoP:n?.DPoP,headers:new Headers(Gi),signal:va(l)}).catch(W)),d;try{d=await u}catch(r){if(ya(r,n))return ma(e,t,C(C({},n),{},{flag:ba}));W(r)}return oa(d),d}function ha(e,t){_a(e);let n=H(e),r=n.as,i=n.c,a=n.tlsOnly,o=n.hybrid,s=n.jarm,c=n.implicit,l=Xn(r,`authorization_endpoint`,!1,a);if((t=new URLSearchParams(t)).has(`client_id`)||t.set(`client_id`,i.client_id),!t.has(`request_uri`)&&!t.has(`request`)){if(t.has(`response_type`)||t.set(`response_type`,o?`code id_token`:c?`id_token`:`code`),c&&!t.has(`nonce`))throw $i(`response_type=id_token clients must provide a nonce parameter in their authorization request parameters`,Zi);s&&t.set(`response_mode`,`jwt`)}for(let e of t.entries()){var u=w(e,2);let t=u[0],n=u[1];l.searchParams.append(t,n)}return l}async function ga(e,t,n){_a(e);let r=ha(e,t),i=H(e),a=i.as,o=i.c,s=i.auth,c=i.fetch,l=i.tlsOnly,u=i.timeout,d=async function(e,t,n){if(Un(e),Wn(t),!_n(n,Response))throw j(`"response" must be an instance of Response`,A);await ir(n,201,`Pushed Authorization Request Endpoint`),Ir(n);let r=await Gr(n);F(r.request_uri,`"response" body "request_uri" property`,I,{body:r});let i=typeof r.expires_in==`number`?r.expires_in:parseFloat(r.expires_in);return In(i,!0,`"response" body "expires_in" property`,I,{body:r}),r.expires_in=i,r}(a,o,await async function(e,t,n,r,i){var a;Un(e),Wn(t);let o=Xn(e,`pushed_authorization_request_endpoint`,t.use_mtls_endpoint_aliases,!0!==i?.[M]),s=new URLSearchParams(r);s.set(`client_id`,t.client_id);let c=Mn(i?.headers);c.set(`accept`,`application/json`),i?.DPoP!==void 0&&(ar(i.DPoP),await i.DPoP.addProof(o,c,`POST`));let l=await sr(e,t,n,o,s,c,i);return i==null||(a=i.DPoP)==null||a.cacheNonce(l,o),l}(a,o,s,r.searchParams,{[bn]:c,[M]:!l,DPoP:n?.DPoP,headers:new Headers(Gi),signal:va(u)}).catch(W)),f;try{f=await d}catch(r){if(ya(r,n))return ga(e,t,C(C({},n),{},{flag:ba}));W(r)}return ha(e,{request_uri:f.request_uri})}function _a(e){if(!(e instanceof aa))throw $i(`"config" must be an instance of Configuration`,Qi);if(Object.getPrototypeOf(e)!==aa.prototype)throw $i(`subclassing Configuration is not allowed`,Zi)}function va(e){return e?AbortSignal.timeout(1e3*e):void 0}function ya(e,t){return!(t==null||!t.DPoP||t.flag===ba)&&function(e){if(e instanceof $n){let t=e.cause,n=t[0];return t.length===1&&n.scheme===`dpop`&&n.parameters.error===`use_dpop_nonce`}return e instanceof Zn&&e.error===`use_dpop_nonce`}(e)}Object.freeze(aa.prototype);var ba=Symbol();async function xa(e,t,n,r){_a(e);let i=H(e),a=i.as,o=i.c,s=i.auth,c=i.fetch,l=i.tlsOnly,u=i.timeout,d=i.decrypt,f=i.nonRepudiation,p=await async function(e,t,n,r,i,a){return Un(e),Wn(t),F(r,`"grantType"`),cr(e,t,n,r,new URLSearchParams(i),a)}(a,o,s,t,new URLSearchParams(n),{[bn]:c,[M]:!l,DPoP:r?.DPoP,headers:new Headers(Gi),signal:va(u)}).catch(W),m;t===`urn:ietf:params:oauth:grant-type:token-exchange`&&(m={n_a:()=>{}});let h=async function(e,t,n,r){return fr(e,t,n,void 0,r?.[Sn],r?.recognizedTokenTypes)}(a,o,p,{[Sn]:d,recognizedTokenTypes:m}),g;try{g=await h}catch(i){if(ya(i,r))return xa(e,t,n,C(C({},r),{},{flag:ba}));W(i)}return g.id_token&&await f?.(p),oa(g),g}async function Sa(e,t,n){if(!yi(e))throw new B(`Flattened JWS must be an object`);if(e.protected===void 0&&e.header===void 0)throw new B(`Flattened JWS must have either of the "protected" or "header" members`);if(e.protected!==void 0&&typeof e.protected!=`string`)throw new B(`JWS Protected Header incorrect type`);if(e.payload===void 0)throw new B(`JWS Payload missing`);if(typeof e.signature!=`string`)throw new B(`JWS Signature missing or incorrect type`);if(e.header!==void 0&&!yi(e.header))throw new B(`JWS Unprotected Header incorrect type`);let r={};if(e.protected)try{let t=$r(e.protected);r=JSON.parse(Yr.decode(t))}catch{throw new B(`JWS Protected Header is invalid`)}if(!bi(r,e.header))throw new B(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let i=C(C({},r),e.header),a=!0;if(zi(B,new Map([[`b64`,!0]]),n?.crit,r,i).has(`b64`)&&(a=r.b64,typeof a!=`boolean`))throw new B(`The "b64" (base64url-encode payload) Header Parameter must be a boolean`);let o=i.alg;if(typeof o!=`string`||!o)throw new B(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);let s=n&&function(e,t){if(t!==void 0&&(!Array.isArray(t)||t.some(e=>typeof e!=`string`)))throw TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)}(`algorithms`,n.algorithms);if(s&&!s.has(o))throw new ci(`"alg" (Algorithm) Header Parameter value not allowed`);if(a){if(typeof e.payload!=`string`)throw new B(`JWS Payload must be a string`)}else if(typeof e.payload!=`string`&&!(e.payload instanceof Uint8Array))throw new B(`JWS Payload must be a string or an Uint8Array instance`);let c=!1;typeof t==`function`&&(t=await t(r,e),c=!0),Hi(o,t,`verify`);let l=Xr(e.protected===void 0?new Uint8Array:Zr(e.protected),Zr(`.`),typeof e.payload==`string`?a?Zr(e.payload):Jr.encode(e.payload):e.payload),u=vi(e.signature,`signature`,B),d=await Ai(t,o);if(!await async function(e,t,n,r){let i=await wi(e,t,`verify`);Si(e,i);let a=Ci(e,i.algorithm);try{return await crypto.subtle.verify(a,i,n,r)}catch{return!1}}(o,d,u,l))throw new pi;let f;f=a?vi(e.payload,`payload`,B):typeof e.payload==`string`?Jr.encode(e.payload):e.payload;let p={payload:f};return e.protected!==void 0&&(p.protectedHeader=r),e.header!==void 0&&(p.unprotectedHeader=e.header),c?C(C({},p),{},{key:d}):p}var Ca=e=>Math.floor(e.getTime()/1e3),wa=86400,Ta=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function Ea(e){let t=Ta.exec(e);if(!t||t[4]&&t[1])throw TypeError(`Invalid time period format`);let n=parseFloat(t[2]),r;switch(t[3].toLowerCase()){case`sec`:case`secs`:case`second`:case`seconds`:case`s`:r=Math.round(n);break;case`minute`:case`minutes`:case`min`:case`mins`:case`m`:r=Math.round(60*n);break;case`hour`:case`hours`:case`hr`:case`hrs`:case`h`:r=Math.round(3600*n);break;case`day`:case`days`:case`d`:r=Math.round(n*wa);break;case`week`:case`weeks`:case`w`:r=Math.round(604800*n);break;default:r=Math.round(31557600*n)}return t[1]===`-`||t[4]===`ago`?-r:r}function Da(e,t){if(!Number.isFinite(t))throw TypeError(`Invalid ${e} input`);return t}var Oa=e=>e.includes(`/`)?e.toLowerCase():`application/${e.toLowerCase()}`;function ka(e,t){let n,r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};try{n=JSON.parse(Yr.decode(t))}catch{}if(!yi(n))throw new V(`JWT Claims Set must be a top-level JSON object`);let i=r.typ;if(i&&(typeof e.typ!=`string`||Oa(e.typ)!==Oa(i)))throw new R(`unexpected "typ" JWT header value`,n,`typ`,`check_failed`);let a=r.requiredClaims,o=a===void 0?[]:a,s=r.issuer,c=r.subject,l=r.audience,u=r.maxTokenAge,d=[...o];u!==void 0&&d.push(`iat`),l!==void 0&&d.push(`aud`),c!==void 0&&d.push(`sub`),s!==void 0&&d.push(`iss`);for(let e of new Set(d.reverse()))if(!(e in n))throw new R(`missing required "${e}" claim`,n,e,`missing`);if(s&&!(Array.isArray(s)?s:[s]).includes(n.iss))throw new R(`unexpected "iss" claim value`,n,`iss`,`check_failed`);if(c&&n.sub!==c)throw new R(`unexpected "sub" claim value`,n,`sub`,`check_failed`);if(l&&(f=n.aud,p=typeof l==`string`?[l]:l,!(typeof f==`string`?p.includes(f):Array.isArray(f)&&p.some(Set.prototype.has.bind(new Set(f))))))throw new R(`unexpected "aud" claim value`,n,`aud`,`check_failed`);var f,p;let m;switch(typeof r.clockTolerance){case`string`:m=Ea(r.clockTolerance);break;case`number`:m=r.clockTolerance;break;case`undefined`:m=0;break;default:throw TypeError(`Invalid clockTolerance option type`)}let h=r.currentDate,g=Ca(h||new Date);if((n.iat!==void 0||u)&&typeof n.iat!=`number`)throw new R(`"iat" claim must be a number`,n,`iat`,`invalid`);if(n.nbf!==void 0){if(typeof n.nbf!=`number`)throw new R(`"nbf" claim must be a number`,n,`nbf`,`invalid`);if(n.nbf>g+m)throw new R(`"nbf" claim timestamp check failed`,n,`nbf`,`check_failed`)}if(n.exp!==void 0){if(typeof n.exp!=`number`)throw new R(`"exp" claim must be a number`,n,`exp`,`invalid`);if(n.exp<=g-m)throw new si(`"exp" claim timestamp check failed`,n,`exp`,`check_failed`)}if(u){let e=g-n.iat;if(e-m>(typeof u==`number`?u:Ea(u)))throw new si(`"iat" claim timestamp check failed (too far in the past)`,n,`iat`,`check_failed`);if(e<0-m)throw new R(`"iat" claim timestamp check failed (it should be in the past)`,n,`iat`,`check_failed`)}return n}var G=new WeakMap,Aa=class{constructor(e){if(b(this,G,void 0),!yi(e))throw TypeError(`JWT Claims Set MUST be an object`);x(G,this,structuredClone(e))}data(){return Jr.encode(JSON.stringify(y(G,this)))}get iss(){return y(G,this).iss}set iss(e){y(G,this).iss=e}get sub(){return y(G,this).sub}set sub(e){y(G,this).sub=e}get aud(){return y(G,this).aud}set aud(e){y(G,this).aud=e}set jti(e){y(G,this).jti=e}set nbf(e){typeof e==`number`?y(G,this).nbf=Da(`setNotBefore`,e):e instanceof Date?y(G,this).nbf=Da(`setNotBefore`,Ca(e)):y(G,this).nbf=Ca(new Date)+Ea(e)}set exp(e){typeof e==`number`?y(G,this).exp=Da(`setExpirationTime`,e):e instanceof Date?y(G,this).exp=Da(`setExpirationTime`,Ca(e)):y(G,this).exp=Ca(new Date)+Ea(e)}set iat(e){e===void 0?y(G,this).iat=Ca(new Date):e instanceof Date?y(G,this).iat=Da(`setIssuedAt`,Ca(e)):y(G,this).iat=Da(`setIssuedAt`,typeof e==`string`?Ca(new Date)+Ea(e):e)}};async function ja(e,t,n){var r;let i=await async function(e,t,n){if(e instanceof Uint8Array&&(e=Yr.decode(e)),typeof e!=`string`)throw new B(`Compact JWS must be a string or Uint8Array`);let r=e.split(`.`),i=r[0],a=r[1],o=r[2];if(r.length!==3)throw new B(`Invalid Compact JWS`);let s=await Sa({payload:a,protected:i,signature:o},t,n),c={payload:s.payload,protectedHeader:s.protectedHeader};return typeof t==`function`?C(C({},c),{},{key:s.key}):c}(e,t,n);if((r=i.protectedHeader.crit)!=null&&r.includes(`b64`)&&!1===i.protectedHeader.b64)throw new V(`JWTs MUST NOT use unencoded payload`);let a={payload:ka(i.protectedHeader,i.payload,n),protectedHeader:i.protectedHeader};return typeof t==`function`?C(C({},a),{},{key:i.key}):a}var Ma=new WeakMap,Na=new WeakMap,Pa=new WeakMap,Fa=class{constructor(e){if(b(this,Ma,void 0),b(this,Na,void 0),b(this,Pa,void 0),!(e instanceof Uint8Array))throw TypeError(`payload must be an instance of Uint8Array`);x(Ma,this,e)}setProtectedHeader(e){return _i(y(Na,this),`setProtectedHeader`),x(Na,this,e),this}setUnprotectedHeader(e){return _i(y(Pa,this),`setUnprotectedHeader`),x(Pa,this,e),this}async sign(e,t){if(!y(Na,this)&&!y(Pa,this))throw new B(`either setProtectedHeader or setUnprotectedHeader must be called before #sign()`);if(!bi(y(Na,this),y(Pa,this)))throw new B(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let n=C(C({},y(Na,this)),y(Pa,this)),r=!0;if(zi(B,new Map([[`b64`,!0]]),t?.crit,y(Na,this),n).has(`b64`)&&(r=y(Na,this).b64,typeof r!=`boolean`))throw new B(`The "b64" (base64url-encode payload) Header Parameter must be a boolean`);let i=n.alg;if(typeof i!=`string`||!i)throw new B(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);let a,o,s,c;Hi(i,e,`sign`),r?(a=ei(y(Ma,this)),o=Zr(a)):(o=y(Ma,this),a=``),y(Na,this)?(s=ei(JSON.stringify(y(Na,this))),c=Zr(s)):(s=``,c=new Uint8Array);let l=Xr(c,Zr(`.`),o),u={signature:ei(await async function(e,t,n){let r=await wi(e,t,`sign`);Si(e,r);let i=await crypto.subtle.sign(Ci(e,r.algorithm),r,n);return new Uint8Array(i)}(i,await Ai(e,i),l)),payload:a};return y(Pa,this)&&(u.header=y(Pa,this)),y(Na,this)&&(u.protected=s),u}},Ia=new WeakMap,La=class{constructor(e){b(this,Ia,void 0),x(Ia,this,new Fa(e))}setProtectedHeader(e){return y(Ia,this).setProtectedHeader(e),this}async sign(e,t){let n=await y(Ia,this).sign(e,t);if(n.payload===void 0)throw TypeError(`use the flattened module for creating JWS with b64: false`);return`${n.protected}.${n.payload}.${n.signature}`}},Ra=new WeakMap,za=new WeakMap,Ba=class{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};b(this,Ra,void 0),b(this,za,void 0),x(za,this,new Aa(e))}setIssuer(e){return y(za,this).iss=e,this}setSubject(e){return y(za,this).sub=e,this}setAudience(e){return y(za,this).aud=e,this}setJti(e){return y(za,this).jti=e,this}setNotBefore(e){return y(za,this).nbf=e,this}setExpirationTime(e){return y(za,this).exp=e,this}setIssuedAt(e){return y(za,this).iat=e,this}setProtectedHeader(e){return x(Ra,this,e),this}async sign(e,t){let n=new La(y(za,this).data());if(n.setProtectedHeader(y(Ra,this)),Array.isArray(y(Ra,this)?.crit)&&y(Ra,this).crit.includes(`b64`)&&!1===y(Ra,this).b64)throw new V(`JWTs MUST NOT use unencoded payload`);return n.sign(e,t)}};function Va(e){return yi(e)}var Ha,Ua,Wa=new WeakMap,Ga=new WeakMap,Ka=class{constructor(e){if(b(this,Wa,void 0),b(this,Ga,new WeakMap),!function(e){return e&&typeof e==`object`&&Array.isArray(e.keys)&&e.keys.every(Va)}(e))throw new li(`JSON Web Key Set malformed`);x(Wa,this,structuredClone(e))}jwks(){return y(Wa,this)}async getKey(e,t){let n=C(C({},e),t?.header),r=n.alg,i=n.kid,a=function(e){switch(typeof e==`string`&&e.slice(0,2)){case`RS`:case`PS`:return`RSA`;case`ES`:return`EC`;case`Ed`:return`OKP`;case`ML`:return`AKP`;default:throw new z(`Unsupported "alg" value for a JSON Web Key Set`)}}(r),o=y(Wa,this).keys.filter(e=>{let t=a===e.kty;if(t&&typeof i==`string`&&(t=i===e.kid),!t||typeof e.alg!=`string`&&a!==`AKP`||(t=r===e.alg),t&&typeof e.use==`string`&&(t=e.use===`sig`),t&&Array.isArray(e.key_ops)&&(t=e.key_ops.includes(`verify`)),t)switch(r){case`ES256`:t=e.crv===`P-256`;break;case`ES384`:t=e.crv===`P-384`;break;case`ES512`:t=e.crv===`P-521`;break;case`Ed25519`:case`EdDSA`:t=e.crv===`Ed25519`}return t}),s=o[0],c=o.length;if(c===0)throw new ui;if(c!==1){let e=new di,t=y(Ga,this);throw e[Symbol.asyncIterator]=ie(function*(){for(let e of o)try{yield yield ee(qa(t,e,r))}catch{}}),e}return qa(y(Ga,this),s,r)}};async function qa(e,t,n){let r=e.get(t)||e.set(t,{}).get(t);if(r[n]===void 0){let e=await async function(e,t,n){if(!yi(e))throw TypeError(`JWK must be an object`);let r;switch(t??=e.alg,r??=n?.extractable??e.ext,e.kty){case`oct`:if(typeof e.k!=`string`||!e.k)throw TypeError(`missing "k" (Key Value) Parameter value`);return $r(e.k);case`RSA`:if(`oth`in e&&e.oth!==void 0)throw new z(`RSA JWK "oth" (Other Primes Info) Parameter value is not supported`);return Ei(C(C({},e),{},{alg:t,ext:r}));case`AKP`:if(typeof e.alg!=`string`||!e.alg)throw TypeError(`missing "alg" (Algorithm) Parameter value`);if(t!==void 0&&t!==e.alg)throw TypeError(`JWK alg and alg option value mismatch`);return Ei(C(C({},e),{},{ext:r}));case`EC`:case`OKP`:return Ei(C(C({},e),{},{alg:t,ext:r}));default:throw new z(`Unsupported "kty" (Key Type) Parameter value`)}}(C(C({},t),{},{ext:!0}),n);if(e instanceof Uint8Array||e.type!==`public`)throw new li(`JSON Web Key Set members must be public keys`);r[n]=e}return r[n]}function Ja(e){let t=new Ka(e),n=async(e,n)=>t.getKey(e,n);return Object.defineProperties(n,{jwks:{value:()=>structuredClone(t.jwks()),enumerable:!1,configurable:!1,writable:!1}}),n}var Ya;(typeof navigator>`u`||(Ha=navigator.userAgent)==null||(Ua=Ha.startsWith)==null||!Ua.call(Ha,`Mozilla/5.0 `))&&(Ya=`jose/v6.2.3`);var Xa=Symbol(),Za=Symbol(),Qa=new WeakMap,$a=new WeakMap,eo=new WeakMap,to=new WeakMap,no=new WeakMap,ro=new WeakMap,io=new WeakMap,ao=new WeakMap,oo=new WeakMap,so=new WeakMap,co=class{constructor(e,t){if(b(this,Qa,void 0),b(this,$a,void 0),b(this,eo,void 0),b(this,to,void 0),b(this,no,void 0),b(this,ro,void 0),b(this,io,void 0),b(this,ao,void 0),b(this,oo,void 0),b(this,so,void 0),!(e instanceof URL))throw TypeError(`url must be an instance of URL`);var n,r;x(Qa,this,new URL(e.href)),x($a,this,typeof t?.timeoutDuration==`number`?t?.timeoutDuration:5e3),x(eo,this,typeof t?.cooldownDuration==`number`?t?.cooldownDuration:3e4),x(to,this,typeof t?.cacheMaxAge==`number`?t?.cacheMaxAge:6e5),x(io,this,new Headers(t?.headers)),Ya&&!y(io,this).has(`User-Agent`)&&y(io,this).set(`User-Agent`,Ya),y(io,this).has(`accept`)||(y(io,this).set(`accept`,`application/json`),y(io,this).append(`accept`,`application/jwk-set+json`)),x(ao,this,t?.[Xa]),t?.[Za]!==void 0&&(x(so,this,t?.[Za]),n=t?.[Za],r=y(to,this),typeof n==`object`&&n&&`uat`in n&&typeof n.uat==`number`&&!(Date.now()-n.uat>=r)&&`jwks`in n&&yi(n.jwks)&&Array.isArray(n.jwks.keys)&&Array.prototype.every.call(n.jwks.keys,yi)&&(x(no,this,y(so,this).uat),x(oo,this,Ja(y(so,this).jwks))))}pendingFetch(){return!!y(ro,this)}coolingDown(){return typeof y(no,this)==`number`&&Date.now()<y(no,this)+y(eo,this)}fresh(){return typeof y(no,this)==`number`&&Date.now()<y(no,this)+y(to,this)}jwks(){return y(oo,this)?.jwks()}async getKey(e,t){y(oo,this)&&this.fresh()||await this.reload();try{return await y(oo,this).call(this,e,t)}catch(n){if(n instanceof ui&&!1===this.coolingDown())return await this.reload(),y(oo,this).call(this,e,t);throw n}}async reload(){y(ro,this)&&(typeof WebSocketPair<`u`||typeof navigator<`u`&&navigator.userAgent===`Cloudflare-Workers`||typeof EdgeRuntime<`u`&&EdgeRuntime===`vercel`)&&x(ro,this,void 0),y(ro,this)||x(ro,this,async function(e,t,n){let r=await(arguments.length>3&&arguments[3]!==void 0?arguments[3]:fetch)(e,{method:`GET`,signal:n,redirect:`manual`,headers:t}).catch(e=>{throw e.name===`TimeoutError`?new fi:e});if(r.status!==200)throw new L(`Expected 200 OK from the JSON Web Key Set HTTP response`);try{return await r.json()}catch{throw new L(`Failed to parse the JSON Web Key Set HTTP response as JSON`)}}(y(Qa,this).href,y(io,this),AbortSignal.timeout(y($a,this)),y(ao,this)).then(e=>{x(oo,this,Ja(e)),y(so,this)&&(y(so,this).uat=Date.now(),y(so,this).jwks=e),x(no,this,Date.now()),x(ro,this,void 0)}).catch(e=>{throw x(ro,this,void 0),e})),await y(ro,this)}},lo=[`mfaToken`],uo=[`mfaToken`],fo,po,mo,ho,go,_o,vo,yo,bo,xo,So,Co,wo,To,Eo,Do,K,Oo,ko,Ao,jo,Mo,q,J,No,Po,Fo,Io,Y;function Lo(e){if(typeof e!=`object`||!e)return{error:`unknown_error`,error_description:String(e)};let t=e,n={error:t.error??``,error_description:t.error_description??``,message:t.message};if(t.error===`mfa_required`&&t.cause){n.mfa_token=typeof t.cause.mfa_token==`string`?t.cause.mfa_token:void 0;let e=t.cause.mfa_requirements;typeof e==`object`&&e&&(n.mfa_requirements=e)}return n}var Ro=class extends Error{constructor(e,t){super(t),S(this,`code`,void 0),this.name=`NotSupportedError`,this.code=e}},zo=class extends Error{constructor(e,t,n){super(t),S(this,`cause`,void 0),S(this,`code`,void 0),this.code=e,this.cause=n&&{error:n.error,error_description:n.error_description,message:n.message,mfa_token:n.mfa_token,mfa_requirements:n.mfa_requirements}}},Bo=class extends zo{constructor(e,t){super(`token_by_code_error`,e,t),this.name=`TokenByCodeError`}},Vo=class extends zo{constructor(e,t){super(`token_by_client_credentials_error`,e,t),this.name=`TokenByClientCredentialsError`}},Ho=class extends zo{constructor(e,t){super(`token_by_refresh_token_error`,e,t),this.name=`TokenByRefreshTokenError`}},Uo=class extends zo{constructor(e,t){super(`token_by_password_error`,e,t),this.name=`TokenByPasswordError`}},Wo=class extends zo{constructor(e,t){super(`token_for_connection_error`,e,t),this.name=`TokenForConnectionErrorCode`}},X=class extends zo{constructor(e,t){super(`token_exchange_error`,e,t),this.name=`TokenExchangeError`}},Go=class extends Error{constructor(e){super(e),S(this,`code`,`verify_logout_token_error`),this.name=`VerifyLogoutTokenError`}},Ko=class extends zo{constructor(e){super(`backchannel_authentication_error`,`There was an error when trying to use Client-Initiated Backchannel Authentication.`,e),S(this,`code`,`backchannel_authentication_error`),this.name=`BackchannelAuthenticationError`}},qo=class extends zo{constructor(e){super(`build_authorization_url_error`,`There was an error when trying to build the authorization URL.`,e),this.name=`BuildAuthorizationUrlError`}},Jo=class extends zo{constructor(e){super(`build_link_user_url_error`,`There was an error when trying to build the Link User URL.`,e),this.name=`BuildLinkUserUrlError`}},Yo=class extends zo{constructor(e){super(`build_unlink_user_url_error`,`There was an error when trying to build the Unlink User URL.`,e),this.name=`BuildUnlinkUserUrlError`}},Xo=class extends Error{constructor(){super(`The client secret or client assertion signing key must be provided.`),S(this,`code`,`missing_client_auth_error`),this.name=`MissingClientAuthError`}},Zo=class extends Error{constructor(e){super(e),S(this,`code`,`organization_validation_error`),this.name=`OrganizationValidationError`}};function Qo(e){return Object.entries(e).filter(e=>w(e,2)[1]!==void 0).reduce((e,t)=>C(C({},e),{},{[t[0]]:t[1]}),{})}function $o(e){if(!e.trim())throw new Zo(`organization must not be blank`)}function es(e,t){if(!e)return;let n=t.trim();if(n.startsWith(`org_`)){let t=e.org_id;if(typeof t!=`string`)throw new Zo(`Organization Id (org_id) claim must be a string present in the ID token`);if(t!==n)throw new Zo(`Organization Id (org_id) claim value mismatch in the ID token; expected "${n}", found "${t}"`)}else{let t=e.org_name;if(typeof t!=`string`)throw new Zo(`Organization Name (org_name) claim must be a string present in the ID token`);if(t.toLowerCase()!==n.toLowerCase())throw new Zo(`Organization Name (org_name) claim value mismatch in the ID token; expected "${n}", found "${t}"`)}}var ts=class extends Error{constructor(e,t,n){super(t),S(this,`cause`,void 0),S(this,`code`,void 0),this.code=e,this.cause=n&&{error:n.error,error_description:n.error_description,message:n.message}}},ns=class extends ts{constructor(e,t){super(`mfa_list_authenticators_error`,e,t),this.name=`MfaListAuthenticatorsError`}},rs=class extends ts{constructor(e,t){super(`mfa_enrollment_error`,e,t),this.name=`MfaEnrollmentError`}},is=class extends ts{constructor(e,t){super(`mfa_delete_authenticator_error`,e,t),this.name=`MfaDeleteAuthenticatorError`}},as=class extends ts{constructor(e,t){super(`mfa_challenge_error`,e,t),this.name=`MfaChallengeError`}},os=class extends ts{constructor(e,t){super(`mfa_verify_error`,e,t),this.name=`MfaVerifyError`}};function ss(e){return{id:e.id,authenticatorType:e.authenticator_type,active:e.active,name:e.name,oobChannels:e.oob_channels,type:e.type}}var Z=class e{constructor(e,t,n,r,i,a,o){S(this,`accessToken`,void 0),S(this,`idToken`,void 0),S(this,`refreshToken`,void 0),S(this,`expiresAt`,void 0),S(this,`scope`,void 0),S(this,`claims`,void 0),S(this,`authorizationDetails`,void 0),S(this,`tokenType`,void 0),S(this,`issuedTokenType`,void 0),S(this,`recoveryCode`,void 0),S(this,`act`,void 0),this.accessToken=e,this.idToken=n,this.refreshToken=r,this.expiresAt=t,this.scope=i,this.claims=a,this.authorizationDetails=o}static fromTokenEndpointResponse(t){let n=t.id_token?t.claims():void 0,r=new e(t.access_token,Math.floor(Date.now()/1e3)+Number(t.expires_in),t.id_token,t.refresh_token,t.scope,n,t.authorization_details);return r.tokenType=t.token_type,r.issuedTokenType=t.issued_token_type,r}},cs={otp:`http://auth0.com/oauth/grant-type/mfa-otp`,oob:`http://auth0.com/oauth/grant-type/mfa-oob`,"recovery-code":`http://auth0.com/oauth/grant-type/mfa-recovery-code`},ls=(fo=new WeakMap,po=new WeakMap,mo=new WeakMap,ho=new WeakMap,go=new WeakMap,class{constructor(e){b(this,fo,void 0),b(this,po,void 0),b(this,mo,void 0),b(this,ho,void 0),b(this,go,void 0),x(fo,this,`https://${e.domain}`),x(po,this,e.clientId),x(mo,this,e.clientSecret),x(ho,this,e.customFetch??function(){return fetch(...arguments)}),x(go,this,e.getConfiguration)}async listAuthenticators(e){let t=`${y(fo,this)}/mfa/authenticators`,n=e.mfaToken,r=await y(ho,this).call(this,t,{method:`GET`,headers:{Authorization:`Bearer ${n}`,"Content-Type":`application/json`}});if(!r.ok){let e;try{e=await r.json()}catch{throw new ns(`Failed to list authenticators`)}throw new ns(e.error_description||`Failed to list authenticators`,e)}return(await r.json()).map(ss)}async enrollAuthenticator(e){let t=`${y(fo,this)}/mfa/associate`,n=e.mfaToken,r=re(e,lo),i={authenticator_types:r.authenticatorTypes};`oobChannels`in r&&(i.oob_channels=r.oobChannels),`phoneNumber`in r&&r.phoneNumber&&(i.phone_number=r.phoneNumber),`email`in r&&r.email&&(i.email=r.email);let a=await y(ho,this).call(this,t,{method:`POST`,headers:{Authorization:`Bearer ${n}`,"Content-Type":`application/json`},body:JSON.stringify(i)});if(!a.ok){let e;try{e=await a.json()}catch{throw new rs(`Failed to enroll authenticator`)}throw new rs(e.error_description||`Failed to enroll authenticator`,e)}return function(e){if(e.authenticator_type===`otp`)return{authenticatorType:`otp`,secret:e.secret,barcodeUri:e.barcode_uri,recoveryCodes:e.recovery_codes,id:e.id};if(e.authenticator_type===`oob`)return{authenticatorType:`oob`,oobChannel:e.oob_channel,oobCode:e.oob_code,bindingMethod:e.binding_method,id:e.id,barcodeUri:e.barcode_uri,recoveryCodes:e.recovery_codes};throw Error(`Unexpected authenticator type: ${e.authenticator_type}`)}(await a.json())}async deleteAuthenticator(e){let t=e.authenticatorId,n=e.mfaToken,r=`${y(fo,this)}/mfa/authenticators/${encodeURIComponent(t)}`,i=await y(ho,this).call(this,r,{method:`DELETE`,headers:{Authorization:`Bearer ${n}`,"Content-Type":`application/json`}});if(!i.ok){let e;try{e=await i.json()}catch{throw new is(`Failed to delete authenticator`)}throw new is(e.error_description||`Failed to delete authenticator`,e)}}async challengeAuthenticator(e){let t=`${y(fo,this)}/mfa/challenge`,n=e.mfaToken,r=re(e,uo),i={mfa_token:n,client_id:y(po,this),challenge_type:r.challengeType};y(mo,this)&&(i.client_secret=y(mo,this)),r.authenticatorId&&(i.authenticator_id=r.authenticatorId);let a=await y(ho,this).call(this,t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(i)});if(!a.ok){let e;try{e=await a.json()}catch{throw new as(`Failed to challenge authenticator`)}throw new as(e.error_description||`Failed to challenge authenticator`,e)}return function(e){let t={challengeType:e.challenge_type};return e.oob_code!==void 0&&(t.oobCode=e.oob_code),e.binding_method!==void 0&&(t.bindingMethod=e.binding_method),t}(await a.json())}async verify(e){if(!y(go,this))throw Error(`MFA verify requires a configuration provider (getConfiguration was not set)`);let t=await y(go,this).call(this),n={mfa_token:e.mfaToken};e.audience&&(n.audience=e.audience),e.factorType===`otp`?n.otp=e.otp:e.factorType===`oob`?(n.oob_code=e.oobCode,e.bindingCode&&(n.binding_code=e.bindingCode)):e.factorType===`recovery-code`&&(n.recovery_code=e.recoveryCode);try{let r=await xa(t,cs[e.factorType],n),i=Z.fromTokenEndpointResponse(r);return r.recovery_code&&(i.recoveryCode=r.recovery_code),i}catch(e){if(e instanceof os)throw e;let t=e;throw new os(t.error_description||t.message||`Failed to verify MFA challenge`,{error:t.error??`mfa_verify_error`,error_description:t.error_description??t.message??`Failed to verify MFA challenge`})}}}),us=class extends Error{constructor(e,t,n){super(t),S(this,`cause`,void 0),S(this,`code`,void 0),this.code=e,this.cause=n&&{error:n.error,error_description:n.error_description,message:n.message}}},ds=class extends us{constructor(e,t){super(`passkey_register_error`,e,t),this.name=`PasskeyRegisterError`}},fs=class extends us{constructor(e,t){super(`passkey_challenge_error`,e,t),this.name=`PasskeyChallengeError`}},ps=class extends us{constructor(e,t){super(`passkey_get_token_error`,e,t),this.name=`PasskeyGetTokenError`,this.cause=t&&{error:t.error,error_description:t.error_description,message:t.message,mfa_token:t.mfa_token,mfa_requirements:t.mfa_requirements}}},ms=`urn:okta:params:oauth:grant-type:webauthn`,hs=(_o=new WeakMap,vo=new WeakMap,yo=new WeakMap,bo=new WeakMap,xo=new WeakSet,class{constructor(e){te(this,xo),b(this,_o,void 0),b(this,vo,void 0),b(this,yo,void 0),b(this,bo,void 0),x(_o,this,`https://${e.domain}`),x(vo,this,e.clientId),x(yo,this,e.customFetch??function(){return fetch(...arguments)}),x(bo,this,e.grantRequest)}async register(e){let t=`${y(_o,this)}/passkey/register`,n=C(C(C(C(C(C(C(C({},e.email&&{email:e.email}),e.name&&{name:e.name}),e.phoneNumber&&{phone_number:e.phoneNumber}),e.username&&{username:e.username}),e.givenName&&{given_name:e.givenName}),e.familyName&&{family_name:e.familyName}),e.nickname&&{nickname:e.nickname}),e.picture&&{picture:e.picture}),r={client_id:y(vo,this),user_profile:n};e.realm&&(r.realm=e.realm),e.organization&&(r.organization=e.organization),e.userMetadata&&(r.user_metadata=e.userMetadata);let i=await y(yo,this).call(this,t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(r)});if(!i.ok){let e=await _(xo,this,gs).call(this,i);throw new ds(e.error_description||`Failed to request signup challenge`,e)}return{authSession:(a=await i.json()).auth_session,authnParamsPublicKey:C({},a.authn_params_public_key)};var a}async challenge(e){let t=`${y(_o,this)}/passkey/challenge`,n={client_id:y(vo,this)};e!=null&&e.realm&&(n.realm=e.realm),e!=null&&e.organization&&(n.organization=e.organization);let r=await y(yo,this).call(this,t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)});if(!r.ok){let e=await _(xo,this,gs).call(this,r);throw new fs(e.error_description||`Failed to request login challenge`,e)}return{authSession:(i=await r.json()).auth_session,authnParamsPublicKey:C({},i.authn_params_public_key)};var i}async getTokenByPasskey(e){e.organization!==void 0&&$o(e.organization);let t=new URLSearchParams({auth_session:e.authSession,authn_response:JSON.stringify(e.credential)}),n;e.realm&&t.append(`realm`,e.realm),e.scope&&t.append(`scope`,e.scope),e.audience&&t.append(`audience`,e.audience),e.organization&&t.append(`organization`,e.organization);try{n=await y(bo,this).call(this,ms,t)}catch(e){let t=Lo(e);throw new ps(t.error_description||`Failed to exchange passkey credential for tokens.`,t)}return e.organization&&es(n.claims,e.organization),n}});async function gs(e){try{return await e.json()}catch{return{error:`unknown_error`,error_description:`HTTP ${e.status} ${e.statusText}`}}}var _s=class extends Error{constructor(e,t,n){super(t),S(this,`cause`,void 0),S(this,`code`,void 0),Object.setPrototypeOf(this,new.target.prototype),this.code=e,this.cause=n&&{error:n.error,error_description:n.error_description,message:n.message,mfa_token:n.mfa_token,mfa_requirements:n.mfa_requirements}}},vs=class extends _s{constructor(e,t){super(`passwordless_start_error`,e,t),this.name=`PasswordlessStartError`}},ys=class extends _s{constructor(e,t){super(`passwordless_verify_error`,e,t),this.name=`PasswordlessVerifyError`}};function bs(e){return/^\+[1-9]\d{1,14}$/.test(e)}var xs=(So=new WeakMap,Co=new WeakMap,wo=new WeakMap,To=new WeakMap,Eo=new WeakMap,Do=new WeakSet,class{constructor(e){te(this,Do),b(this,So,void 0),b(this,Co,void 0),b(this,wo,void 0),b(this,To,void 0),b(this,Eo,void 0),x(Co,this,e.domain),x(So,this,`https://${e.domain}`),x(wo,this,e.clientId),x(To,this,e.customFetch??function(){return fetch(...arguments)}),x(Eo,this,{clientSecret:e.clientSecret,clientAssertionSigningKey:e.clientAssertionSigningKey,clientAssertionSigningAlg:e.clientAssertionSigningAlg,useMtls:e.useMtls})}async sendEmail(e){await _(Do,this,Ss).call(this,function(e){let t=e.send??`code`,n={email:e.email,connection:`email`,send:t};return t===`link`&&e.authParams&&(n.authParams=e.authParams),n}(e),`Failed to send passwordless email`,e.language)}async sendSms(e){if(!bs(e.phoneNumber))throw new vs(`Phone number must be in E.164 format (e.g. +14155550100).`);await _(Do,this,Ss).call(this,function(e){return{phone_number:e.phoneNumber,connection:`sms`}}(e),`Failed to send passwordless SMS`,e.language)}});async function Ss(e,t,n){let r=await async function(e,t,n){if(e.useMtls)return{};if(e.clientAssertionSigningKey){let r=e.clientAssertionSigningAlg??`RS256`,i=e.clientAssertionSigningKey instanceof CryptoKey?e.clientAssertionSigningKey:await Ri(e.clientAssertionSigningKey,r);return{client_assertion:await new Ba({}).setProtectedHeader({alg:r}).setIssuer(t).setSubject(t).setAudience(`https://${n}/`).setJti(crypto.randomUUID()).setIssuedAt().setExpirationTime(`120s`).sign(i),client_assertion_type:`urn:ietf:params:oauth:client-assertion-type:jwt-bearer`}}if(e.clientSecret)return{client_secret:e.clientSecret};throw new Xo}(y(Eo,this),y(wo,this),y(Co,this)),i=C(C({client_id:y(wo,this)},e),r),a,o;try{a=await y(To,this).call(this,`${y(So,this)}/passwordless/start`,{method:`POST`,headers:C({"Content-Type":`application/json`},n?{"x-request-language":n}:{}),body:JSON.stringify(i)})}catch{throw new vs(`${t}: a network error occurred.`)}if(!a.ok){if(a.status!==204)try{o=await a.json()}catch{o=void 0}throw new vs(o?.error_description||t,o)}}var Cs=(K=new WeakMap,Oo=new WeakMap,ko=new WeakMap,class{constructor(e,t){b(this,K,new Map),b(this,Oo,void 0),b(this,ko,void 0),x(ko,this,Math.max(1,Math.floor(e))),x(Oo,this,Math.max(0,Math.floor(t)))}get(e){let t=y(K,this).get(e);if(t){if(!(Date.now()>=t.expiresAt))return y(K,this).delete(e),y(K,this).set(e,t),t.value;y(K,this).delete(e)}}set(e,t){for(y(K,this).has(e)&&y(K,this).delete(e),y(K,this).set(e,{value:t,expiresAt:Date.now()+y(Oo,this)});y(K,this).size>y(ko,this);){let e=y(K,this).keys().next().value;if(e===void 0)break;y(K,this).delete(e)}}}),ws=new Map;function Ts(e){return{ttlMs:1e3*(typeof e?.ttl==`number`?e.ttl:600),maxEntries:typeof e?.maxEntries==`number`&&e.maxEntries>0?e.maxEntries:100}}var Es=class{static createDiscoveryCache(e){let t=(n=e.maxEntries,r=e.ttlMs,`${n}:${r}`);var n,r;let i=(a=t,ws.get(a));var a;return i||(i=new Cs(e.maxEntries,e.ttlMs),ws.set(t,i)),i}static createJwksCache(){return{}}},Ds=`openid profile email offline_access`,Os=Object.freeze(new Set([`grant_type`,`client_id`,`client_secret`,`client_assertion`,`client_assertion_type`,`subject_token`,`subject_token_type`,`requested_token_type`,`actor_token`,`actor_token_type`,`audience`,`aud`,`resource`,`resources`,`resource_indicator`,`scope`,`connection`,`login_hint`,`organization`,`assertion`]));function ks(e){if(e==null)throw new X(`subject_token is required`);if(typeof e!=`string`)throw new X(`subject_token must be a string`);if(e.trim().length===0)throw new X(`subject_token cannot be blank or whitespace`);if(e!==e.trim())throw new X(`subject_token must not include leading or trailing whitespace`);if(/^bearer\s+/i.test(e))throw new X(`subject_token must not include the 'Bearer ' prefix`)}function As(e,t){if(t)for(let r of Object.entries(t)){var n=w(r,2);let t=n[0],i=n[1];if(!Os.has(t))if(Array.isArray(i)){if(i.length>20)throw new X(`Parameter '${t}' exceeds maximum array size of 20`);i.forEach(n=>{e.append(t,n)})}else e.append(t,i)}}var js=`urn:ietf:params:oauth:token-type:access_token`,Ms=(Ao=new WeakMap,jo=new WeakMap,Mo=new WeakMap,q=new WeakMap,J=new WeakMap,No=new WeakMap,Po=new WeakMap,Fo=new WeakMap,Io=new WeakMap,Y=new WeakSet,class{constructor(e){var t;if(te(this,Y),b(this,Ao,void 0),b(this,jo,void 0),b(this,Mo,void 0),b(this,q,void 0),b(this,J,void 0),b(this,No,void 0),b(this,Po,void 0),b(this,Fo,void 0),b(this,Io,void 0),S(this,`mfa`,void 0),S(this,`passkey`,void 0),S(this,`passwordless`,void 0),x(q,this,e),e.useMtls&&!e.customFetch)throw new Ro(`mtls_without_custom_fetch_not_supported`,`Using mTLS without a custom fetch implementation is not supported`);x(J,this,function(e,t){if(!1===t.enabled)return e;let n={name:t.name,version:t.version},r=btoa(JSON.stringify(n));return async(t,n)=>{let i=t instanceof Request?new Headers(t.headers):new Headers;return n!=null&&n.headers&&new Headers(n.headers).forEach((e,t)=>{i.set(t,e)}),i.set(`Auth0-Client`,r),e(t,C(C({},n),{},{headers:i}))}}(e.customFetch??function(){return fetch(...arguments)},!1===(t=e.telemetry)?.enabled?t:{enabled:!0,name:t?.name??`@auth0/auth0-auth-js`,version:t?.version??`1.10.0`}));let n=Ts(e.discoveryCache);x(Po,this,Es.createDiscoveryCache(n)),x(Fo,this,new Map),x(Io,this,Es.createJwksCache()),this.mfa=new ls({domain:y(q,this).domain,clientId:y(q,this).clientId,clientSecret:y(q,this).clientSecret,customFetch:y(J,this),getConfiguration:async()=>(await _(Y,this,Q).call(this)).configuration}),this.passkey=new hs({domain:y(q,this).domain,clientId:y(q,this).clientId,customFetch:y(J,this),grantRequest:async(e,t)=>{let n=(await _(Y,this,Q).call(this)).serverMetadata,r=await _(Y,this,Ps).call(this,n);r[Xi]=function(e,t){return(n,r)=>{let i=r?.body;if(t!==ms||!(i instanceof URLSearchParams))return e(n,r);let a={};for(let e of i){var o=w(e,2);let t=o[0],n=o[1];a[t]=t===`authn_response`?JSON.parse(n):n}let s=new Headers(r?.headers);return s.set(`Content-Type`,`application/json`),e(n,C(C({},r),{},{headers:s,body:JSON.stringify(a)}))}}(y(J,this),e);let i=await xa(r,e,t);return Z.fromTokenEndpointResponse(i)}}),this.passwordless=new xs({domain:y(q,this).domain,clientId:y(q,this).clientId,customFetch:y(J,this),clientSecret:y(q,this).clientSecret,clientAssertionSigningKey:y(q,this).clientAssertionSigningKey,clientAssertionSigningAlg:y(q,this).clientAssertionSigningAlg,useMtls:y(q,this).useMtls})}async getServerMetadata(){return(await _(Y,this,Q).call(this)).serverMetadata}async buildAuthorizationUrl(e){let t=(await _(Y,this,Q).call(this)).serverMetadata;if(e!=null&&e.pushedAuthorizationRequests&&!t.pushed_authorization_request_endpoint)throw new Ro(`par_not_supported_error`,`The Auth0 tenant does not have pushed authorization requests enabled. Learn how to enable it here: https://auth0.com/docs/get-started/applications/configure-par`);try{return await _(Y,this,zs).call(this,e)}catch(e){throw new qo(e)}}async buildLinkUserUrl(e){try{let t=await _(Y,this,zs).call(this,{authorizationParams:C(C({},e.authorizationParams),{},{requested_connection:e.connection,requested_connection_scope:e.connectionScope,scope:`openid link_account offline_access`,id_token_hint:e.idToken})});return{linkUserUrl:t.authorizationUrl,codeVerifier:t.codeVerifier}}catch(e){throw new Jo(e)}}async buildUnlinkUserUrl(e){try{let t=await _(Y,this,zs).call(this,{authorizationParams:C(C({},e.authorizationParams),{},{requested_connection:e.connection,scope:`openid unlink_account`,id_token_hint:e.idToken})});return{unlinkUserUrl:t.authorizationUrl,codeVerifier:t.codeVerifier}}catch(e){throw new Yo(e)}}async backchannelAuthentication(e){let t=await _(Y,this,Q).call(this),n=t.configuration,r=t.serverMetadata,i=Qo(C(C({},y(q,this).authorizationParams),e?.authorizationParams)),a=new URLSearchParams(C(C({scope:Ds},i),{},{client_id:y(q,this).clientId,binding_message:e.bindingMessage,login_hint:JSON.stringify({format:`iss_sub`,iss:r.issuer,sub:e.loginHint.sub})}));e.requestedExpiry&&a.append(`requested_expiry`,e.requestedExpiry.toString()),e.authorizationDetails&&a.append(`authorization_details`,JSON.stringify(e.authorizationDetails));try{let e=await ua(n,await la(n,a));return Z.fromTokenEndpointResponse(e)}catch(e){throw new Ko(e)}}async initiateBackchannelAuthentication(e){let t=await _(Y,this,Q).call(this),n=t.configuration,r=t.serverMetadata,i=Qo(C(C({},y(q,this).authorizationParams),e?.authorizationParams)),a=new URLSearchParams(C(C({scope:Ds},i),{},{client_id:y(q,this).clientId,binding_message:e.bindingMessage,login_hint:JSON.stringify({format:`iss_sub`,iss:r.issuer,sub:e.loginHint.sub})}));e.requestedExpiry&&a.append(`requested_expiry`,e.requestedExpiry.toString()),e.authorizationDetails&&a.append(`authorization_details`,JSON.stringify(e.authorizationDetails));try{let e=await la(n,a);return{authReqId:e.auth_req_id,expiresIn:e.expires_in,interval:e.interval}}catch(e){throw new Ko(e)}}async backchannelAuthenticationGrant(e){let t=e.authReqId,n=(await _(Y,this,Q).call(this)).configuration,r=new URLSearchParams({auth_req_id:t});try{let e=await xa(n,`urn:openid:params:grant-type:ciba`,r);return Z.fromTokenEndpointResponse(e)}catch(e){throw new Ko(e)}}async getTokenForConnection(e){if(e.refreshToken&&e.accessToken)throw new Wo(`Either a refresh or access token should be specified, but not both.`);let t=e.accessToken??e.refreshToken;if(!t)throw new Wo(`Either a refresh or access token must be specified.`);try{return await this.exchangeToken({connection:e.connection,subjectToken:t,subjectTokenType:e.accessToken?js:`urn:ietf:params:oauth:token-type:refresh_token`,loginHint:e.loginHint})}catch(e){throw e instanceof X?new Wo(e.message,e.cause):e}}async exchangeToken(e){return`connection`in e?_(Y,this,Fs).call(this,e):_(Y,this,Is).call(this,e)}async getTokenByCode(e,t){let n=(await _(Y,this,Q).call(this)).configuration,r;t.organization!==void 0&&$o(t.organization);try{let i=await fa(n,e,{pkceCodeVerifier:t.codeVerifier});r=Z.fromTokenEndpointResponse(i)}catch(e){throw new Bo(`There was an error while trying to request a token.`,Lo(e))}return t.organization&&es(r.claims,t.organization),r}async getTokenByMagicLinkCode(e,t){let n=(await _(Y,this,Q).call(this)).configuration;try{let r=await fa(n,e,{expectedState:t?.expectedState});return Z.fromTokenEndpointResponse(r)}catch(e){throw new Bo(e instanceof Error&&e.message?e.message:`There was an error while trying to request a token.`,e)}}async getTokenByRefreshToken(e){let t=(await _(Y,this,Q).call(this)).configuration,n=new URLSearchParams;e.audience&&n.append(`audience`,e.audience),e.scope&&n.append(`scope`,e.scope);try{let r=await pa(t,e.refreshToken,n);return Z.fromTokenEndpointResponse(r)}catch(e){throw new Ho(`The access token has expired and there was an error while trying to refresh it.`,Lo(e))}}async getTokenByPassword(e){let t=(await _(Y,this,Q).call(this)).configuration,n=new URLSearchParams({username:e.username,password:e.password});e.audience&&n.append(`audience`,e.audience),e.scope&&n.append(`scope`,e.scope),e.realm&&n.append(`realm`,e.realm);let r=t;if(e.auth0ForwardedFor){let n=await _(Y,this,Rs).call(this);r=new aa(t.serverMetadata(),y(q,this).clientId,y(q,this).clientSecret,n),r[Xi]=(t,n)=>y(J,this).call(this,t,C(C({},n),{},{headers:C(C({},n.headers),{},{"auth0-forwarded-for":e.auth0ForwardedFor})}))}try{let e=await xa(r,`password`,n);return Z.fromTokenEndpointResponse(e)}catch(e){throw new Uo(`There was an error while trying to request a token.`,Lo(e))}}async getTokenByPasswordlessEmail(e){let t=new URLSearchParams({username:e.email,otp:e.code,realm:`email`});return e.audience&&t.append(`audience`,e.audience),e.scope&&t.append(`scope`,e.scope),_(Y,this,Ls).call(this,t)}async getTokenByPasswordlessSms(e){if(!bs(e.phoneNumber))throw new ys(`Phone number must be in E.164 format (e.g. +14155550100).`);let t=new URLSearchParams({username:e.phoneNumber,otp:e.code,realm:`sms`});return e.audience&&t.append(`audience`,e.audience),e.scope&&t.append(`scope`,e.scope),_(Y,this,Ls).call(this,t)}async getTokenByClientCredentials(e){let t=(await _(Y,this,Q).call(this)).configuration;try{let n=new URLSearchParams({audience:e.audience});e.organization&&n.append(`organization`,e.organization);let r=await ma(t,n);return Z.fromTokenEndpointResponse(r)}catch(e){throw new Vo(`There was an error while trying to request a token.`,Lo(e))}}async buildLogoutUrl(e){let t=await _(Y,this,Q).call(this),n=t.configuration;if(!t.serverMetadata.end_session_endpoint){let t=new URL(`https://${y(q,this).domain}/v2/logout`);return t.searchParams.set(`returnTo`,e.returnTo),t.searchParams.set(`client_id`,y(q,this).clientId),t}return function(e,t){_a(e);let n=H(e),r=n.as,i=n.c,a=Xn(r,`end_session_endpoint`,!1,n.tlsOnly);(t=new URLSearchParams(t)).has(`client_id`)||t.set(`client_id`,i.client_id);for(let e of t.entries()){var o=w(e,2);let t=o[0],n=o[1];a.searchParams.append(t,n)}return a}(n,{post_logout_redirect_uri:e.returnTo})}async verifyLogoutToken(e){let t=(await _(Y,this,Q).call(this)).serverMetadata,n=Ts(y(q,this).discoveryCache),r=t.jwks_uri;y(No,this)||x(No,this,function(e,t){let n=new co(e,t),r=async(e,t)=>n.getKey(e,t);return Object.defineProperties(r,{coolingDown:{get:()=>n.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>n.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>n.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>n.pendingFetch(),enumerable:!0,configurable:!1},jwks:{value:()=>n.jwks(),enumerable:!0,configurable:!1,writable:!1}}),r}(new URL(r),{cacheMaxAge:n.ttlMs,[Xa]:y(J,this),[Za]:y(Io,this)}));let i=(await ja(e.logoutToken,y(No,this),{issuer:t.issuer,audience:y(q,this).clientId,algorithms:[`RS256`],requiredClaims:[`iat`]})).payload;if(!(`sid`in i)&&!(`sub`in i))throw new Go(`either "sid" or "sub" (or both) claims must be present`);if(`sid`in i&&typeof i.sid!=`string`)throw new Go(`"sid" claim must be a string`);if(`sub`in i&&typeof i.sub!=`string`)throw new Go(`"sub" claim must be a string`);if(`nonce`in i)throw new Go(`"nonce" claim is prohibited`);if(!(`events`in i))throw new Go(`"events" claim is missing`);if(typeof i.events!=`object`||i.events===null)throw new Go(`"events" claim must be an object`);if(!(`http://schemas.openid.net/event/backchannel-logout`in i.events))throw new Go(`"http://schemas.openid.net/event/backchannel-logout" member is missing in the "events" claim`);if(typeof i.events[`http://schemas.openid.net/event/backchannel-logout`]!=`object`)throw new Go(`"http://schemas.openid.net/event/backchannel-logout" member in the "events" claim must be an object`);return{sid:i.sid,sub:i.sub}}});function Ns(){return`${y(q,this).domain.toLowerCase()}|mtls:${y(q,this).useMtls?`1`:`0`}`}async function Ps(e){let t=await _(Y,this,Rs).call(this),n=new aa(e,y(q,this).clientId,y(q,this).clientSecret,t);return n[Xi]=y(J,this),n}async function Q(){if(y(Ao,this)&&y(jo,this))return{configuration:y(Ao,this),serverMetadata:y(jo,this)};let e=_(Y,this,Ns).call(this),t=y(Po,this).get(e);if(t)return x(jo,this,t.serverMetadata),x(Ao,this,await _(Y,this,Ps).call(this,t.serverMetadata)),{configuration:y(Ao,this),serverMetadata:y(jo,this)};let n=y(Fo,this).get(e);if(n){let e=await n;return x(jo,this,e.serverMetadata),x(Ao,this,await _(Y,this,Ps).call(this,e.serverMetadata)),{configuration:y(Ao,this),serverMetadata:y(jo,this)}}let r=(async()=>{let t=await _(Y,this,Rs).call(this),n=await ra(new URL(`https://${y(q,this).domain}`),y(q,this).clientId,{use_mtls_endpoint_aliases:y(q,this).useMtls},t,{[Xi]:y(J,this)}),r=n.serverMetadata();return y(Po,this).set(e,{serverMetadata:r}),{configuration:n,serverMetadata:r}})(),i=r.then(e=>({serverMetadata:e.serverMetadata}));i.catch(()=>{}),y(Fo,this).set(e,i);try{let e=await r,t=e.configuration,n=e.serverMetadata;x(Ao,this,t),x(jo,this,n),y(Ao,this)[Xi]=y(J,this)}finally{y(Fo,this).delete(e)}return{configuration:y(Ao,this),serverMetadata:y(jo,this)}}async function Fs(e){let t=(await _(Y,this,Q).call(this)).configuration;if(`audience`in e||`resource`in e)throw new X(`audience and resource parameters are not supported for Token Vault exchanges`);ks(e.subjectToken);let n=new URLSearchParams({connection:e.connection,subject_token:e.subjectToken,subject_token_type:e.subjectTokenType??js,requested_token_type:e.requestedTokenType??`http://auth0.com/oauth/token-type/federated-connection-access-token`});e.loginHint&&n.append(`login_hint`,e.loginHint),e.scope&&n.append(`scope`,e.scope),As(n,e.extra);try{let e=await xa(t,`urn:auth0:params:oauth:grant-type:token-exchange:federated-connection-access-token`,n);return Z.fromTokenEndpointResponse(e)}catch(t){throw new X(`Failed to exchange token for connection '${e.connection}'.`,Lo(t))}}async function Is(e){let t=(await _(Y,this,Q).call(this)).configuration;if(ks(e.subjectToken),e.organization!==void 0&&$o(e.organization),e.actorToken!==void 0&&e.actorTokenType===void 0)throw new X(`actorTokenType is required when actorToken is provided`);let n=new URLSearchParams({subject_token_type:e.subjectTokenType,subject_token:e.subjectToken}),r,i;e.audience&&n.append(`audience`,e.audience),e.scope&&n.append(`scope`,e.scope),e.requestedTokenType&&n.append(`requested_token_type`,e.requestedTokenType),e.organization&&n.append(`organization`,e.organization),e.actorToken&&n.append(`actor_token`,e.actorToken),e.actorTokenType&&n.append(`actor_token_type`,e.actorTokenType),As(n,e.extra);try{i=await xa(t,`urn:ietf:params:oauth:grant-type:token-exchange`,n),r=Z.fromTokenEndpointResponse(i)}catch(t){throw new X(`Failed to exchange token of type '${e.subjectTokenType}'${e.audience?` for audience '${e.audience}'`:``}.`,Lo(t))}var a;if(e.organization&&es(r.claims,e.organization),e.actorToken)if((a=r.claims)!=null&&a.act)r.act=r.claims.act;else try{r.act=function(e){if(typeof e!=`string`)throw new V(`JWTs must use Compact JWS serialization, JWT must be a string`);let t=e.split(`.`),n=t[1],r=t.length;if(r===5)throw new V(`Only JWTs using Compact JWS serialization can be decoded`);if(r!==3)throw new V(`Invalid JWT`);if(!n)throw new V(`JWTs must contain a payload`);let i,a;try{i=$r(n)}catch{throw new V(`Failed to base64url decode the payload`)}try{a=JSON.parse(Yr.decode(i))}catch{throw new V(`Failed to parse the decoded payload as JSON`)}if(!yi(a))throw new V(`Invalid JWT Claims Set`);return a}(i.access_token).act}catch{}return r}async function Ls(e){let t=(await _(Y,this,Q).call(this)).configuration;try{let n=await xa(t,`http://auth0.com/oauth/grant-type/passwordless/otp`,e);return Z.fromTokenEndpointResponse(n)}catch(e){throw new ys(`There was an error while trying to request a token.`,Lo(e))}}async function Rs(){return y(Mo,this)||x(Mo,this,(async()=>{if(!y(q,this).clientSecret&&!y(q,this).clientAssertionSigningKey&&!y(q,this).useMtls)throw new Xo;if(y(q,this).useMtls)return(e,t,n,r)=>{n.set(`client_id`,t.client_id)};let e=y(q,this).clientAssertionSigningKey;return!e||e instanceof CryptoKey||(e=await Ri(e,y(q,this).clientAssertionSigningAlg||`RS256`)),e?function(e,t){return Kn(e,t)}(e):Yi(y(q,this).clientSecret)})().catch(e=>{throw x(Mo,this,void 0),e})),y(Mo,this)}async function zs(e){let t=(await _(Y,this,Q).call(this)).configuration,n=ta(),r=await ea(n),i=Qo(C(C({},y(q,this).authorizationParams),e?.authorizationParams)),a=new URLSearchParams(C(C({scope:Ds},i),{},{client_id:y(q,this).clientId,code_challenge:r,code_challenge_method:`S256`}));return{authorizationUrl:e!=null&&e.pushedAuthorizationRequests?await ga(t,a):await ha(t,a),codeVerifier:n}}var Bs=class e extends E{constructor(t,n){super(t,n),Object.setPrototypeOf(this,e.prototype)}static fromPayload(t){let n=t.error,r=t.error_description;return new e(n,r)}},Vs=class e extends Bs{constructor(t,n){super(t,n),Object.setPrototypeOf(this,e.prototype)}},Hs=class e extends Bs{constructor(t,n){super(t,n),Object.setPrototypeOf(this,e.prototype)}},Us=class e extends Bs{constructor(t,n){super(t,n),Object.setPrototypeOf(this,e.prototype)}},Ws=class e extends Bs{constructor(t,n){super(t,n),Object.setPrototypeOf(this,e.prototype)}},Gs=class e extends Bs{constructor(t,n){super(t,n),Object.setPrototypeOf(this,e.prototype)}},Ks=class{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:6e5;this.contexts=new Map,this.ttlMs=e}set(e,t){this.cleanup(),this.contexts.set(e,Object.assign(Object.assign({},t),{createdAt:Date.now()}))}get(e){let t=this.contexts.get(e);if(t){if(!(Date.now()-t.createdAt>this.ttlMs))return t;this.contexts.delete(e)}}remove(e){this.contexts.delete(e)}cleanup(){let e=Date.now();for(let n of this.contexts){var t=w(n,2);let r=t[0];e-t[1].createdAt>this.ttlMs&&this.contexts.delete(r)}}get size(){return this.contexts.size}},qs=class{constructor(e,t){this.authJsMfaClient=e,this.auth0Client=t,this.contextManager=new Ks}setMFAAuthDetails(e,t,n,r){this.contextManager.set(e,{scope:t,audience:n,mfaRequirements:r})}async getAuthenticators(e){let t=this.contextManager.get(e);if(!t)throw new Vs(`invalid_request`,`MFA context not found for this MFA token`);let n=(t.mfaRequirements?.challenge)?.map(e=>e.type);try{let t=await this.authJsMfaClient.listAuthenticators({mfaToken:e});return n&&n.length!==0?t.filter(e=>!!e.type&&n.includes(e.type)):t}catch(e){throw e instanceof ns?new Vs(e.cause?.error,e.message):e}}async enroll(e){let t=function(e){let t=un[e.factorType];return Object.assign(Object.assign(Object.assign({mfaToken:e.mfaToken,authenticatorTypes:t.authenticatorTypes},t.oobChannels&&{oobChannels:t.oobChannels}),`phoneNumber`in e&&{phoneNumber:e.phoneNumber}),`email`in e&&{email:e.email})}(e);try{return await this.authJsMfaClient.enrollAuthenticator(t)}catch(e){throw e instanceof rs?new Hs(e.cause?.error,e.message):e}}async challenge(e){try{let t={challengeType:e.challengeType,mfaToken:e.mfaToken};return e.authenticatorId&&(t.authenticatorId=e.authenticatorId),await this.authJsMfaClient.challengeAuthenticator(t)}catch(e){throw e instanceof as?new Us(e.cause?.error,e.message):e}}async getEnrollmentFactors(e){let t=this.contextManager.get(e);if(!t||!t.mfaRequirements)throw new Gs(`mfa_context_not_found`,`MFA context not found for this MFA token. Please retry the original request to get a new MFA token.`);return t.mfaRequirements.enroll&&t.mfaRequirements.enroll.length!==0?t.mfaRequirements.enroll:[]}async verify(e){let t=this.contextManager.get(e.mfaToken);if(!t)throw new Ws(`mfa_context_not_found`,`MFA context not found for this MFA token. Please retry the original request to get a new MFA token.`);let n=function(e){return`otp`in e&&e.otp?dn:`oobCode`in e&&e.oobCode?fn:`recoveryCode`in e&&e.recoveryCode?pn:void 0}(e);if(!n)throw new Ws(`invalid_request`,`Unable to determine grant type. Provide one of: otp, oobCode, or recoveryCode.`);let r=t.scope,i=t.audience;try{let t=await this.auth0Client._requestTokenForMfa({grant_type:n,mfaToken:e.mfaToken,scope:r,audience:i,otp:e.otp,oob_code:e.oobCode,binding_code:e.bindingCode,recovery_code:e.recoveryCode});return this.contextManager.remove(e.mfaToken),t}catch(e){throw e instanceof Ws?new Ws(e.error,e.error_description):e}}},Js=class e extends Error{constructor(t,n,r){super(n),this.name=`PasskeyError`,this.code=t,this.cause=r,Object.setPrototypeOf(this,e.prototype)}},Ys,Xs,Zs=class{constructor(e,t){Ys.set(this,void 0),Xs.set(this,void 0),m(this,Ys,e,`f`),m(this,Xs,t,`f`)}async signup(e){if(!window.PublicKeyCredential)throw new Js(`passkey_not_supported`,`WebAuthn is not supported in this browser.`);let t=e.scope,n=e.audience,r=f(e,[`scope`,`audience`]),i=await p(this,Ys,`f`).register(r),a=(o=i.authnParamsPublicKey,Object.assign(Object.assign({},o),{challenge:$s(o.challenge),user:Object.assign(Object.assign({},o.user),{id:$s(o.user.id)}),pubKeyCredParams:o.pubKeyCredParams,authenticatorSelection:o.authenticatorSelection}));var o;let s=await navigator.credentials.create({publicKey:a});if(!s)throw new Js(`passkey_cancelled`,`Passkey creation was cancelled or no credential was returned.`);let c=function(e){let t=e.response;return{id:e.id,rawId:Qs(e.rawId),type:e.type,authenticatorAttachment:e.authenticatorAttachment??void 0,response:{clientDataJSON:Qs(t.clientDataJSON),attestationObject:Qs(t.attestationObject)},clientExtensionResults:e.getClientExtensionResults()}}(s);return p(this,Xs,`f`)._requestTokenForPasskey({authSession:i.authSession,credential:c,realm:r.realm,organization:r.organization,scope:t,audience:n})}async login(e){if(!window.PublicKeyCredential)throw new Js(`passkey_not_supported`,`WebAuthn is not supported in this browser.`);let t=e||{},n=t.scope,r=t.audience,i=f(t,[`scope`,`audience`]),a=await p(this,Ys,`f`).challenge(Object.keys(i).length>0?i:void 0),o=(s=a.authnParamsPublicKey,Object.assign(Object.assign({},s),{challenge:$s(s.challenge)}));var s;let c=await navigator.credentials.get({publicKey:o});if(!c)throw new Js(`passkey_cancelled`,`Passkey authentication was cancelled or no credential was returned.`);let l=function(e){let t=e.response;return{id:e.id,rawId:Qs(e.rawId),type:e.type,authenticatorAttachment:e.authenticatorAttachment??void 0,response:{clientDataJSON:Qs(t.clientDataJSON),authenticatorData:Qs(t.authenticatorData),signature:Qs(t.signature),userHandle:t.userHandle?Qs(t.userHandle):void 0},clientExtensionResults:e.getClientExtensionResults()}}(c);return p(this,Xs,`f`)._requestTokenForPasskey({authSession:a.authSession,credential:l,realm:i.realm,organization:i.organization,scope:n,audience:r})}};function Qs(e){let t=new Uint8Array(e),n=Array.from(t,e=>String.fromCharCode(e)).join(``);return btoa(n).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function $s(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`),n=t+`=`.repeat((4-t.length%4)%4),r=atob(n),i=new Uint8Array(r.length);for(let e=0;e<r.length;e++)i[e]=r.charCodeAt(e);return i.buffer}Ys=new WeakMap,Xs=new WeakMap;var ec=class{resolveOnlineAccess(e){if(e.refreshTokenMode!==`online`)return!1;if(!0!==e.useRefreshTokens)throw new fe('`refreshTokenMode: "online"` requires the refresh-token grant.',"Set `useRefreshTokens: true`.");if(!0!==e.useDpop)throw new fe('`refreshTokenMode: "online"` requires DPoP, which is missing or disabled.',"Set `useDpop: true` (DPoP is mandatory for online access).");return!0}constructor(e){let t,n;if(this.userCache=new wt().enclosedCache,this.defaultOptions={authorizationParams:{scope:`openid profile email`},useRefreshTokensFallback:!1,useFormData:!0,refreshTokenMode:`offline`},this.onlineAccess=this.resolveOnlineAccess(e),this.options=Object.assign(Object.assign(Object.assign({},this.defaultOptions),e),{authorizationParams:Object.assign(Object.assign({},this.defaultOptions.authorizationParams),e.authorizationParams)}),typeof window<`u`&&(()=>{if(!we())throw Error("For security reasons, `window.crypto` is required to run `auth0-spa-js`.");if(we().subtle===void 0)throw Error(`
      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.
    `)})(),this.lockManager=(Je||=qe(),Je),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||ce,!$t(t))throw Error(`Invalid cache location "${t}"`);n=$t(t)()}var r;this.httpTimeoutMs=e.httpTimeoutInSeconds?1e3*e.httpTimeoutInSeconds:se,this.cookieStorage=!1===e.legacySameSiteCookie?Rt:Bt,this.orgHintCookieName=(r=this.options.clientId,`auth0.${r}.organization_hint`),this.isAuthenticatedCookieName=(e=>`auth0.${e}.is.authenticated`)(this.options.clientId),this.sessionCheckExpiryDays=e.sessionCheckExpiryDays||1;let i=e.useCookiesForTransactions?this.cookieStorage:Vt,a=``;var o;this.onlineAccess?a=le:this.options.useRefreshTokens&&(a=`offline_access`),this.scope=function(e,t){var n=[...arguments].slice(2);if(typeof e!=`object`)return{[T]:yt(t,e,...n)};let r={[T]:yt(t,...n)};return Object.keys(e).forEach(i=>{let a=e[i];r[i]=yt(t,a,...n)}),r}(this.options.authorizationParams.scope,`openid`,a),this.transactionManager=new Et(i,this.options.clientId,this.options.cookieDomain),this.nowProvider=this.options.nowProvider||de,this.cacheManager=new Tt(n,n.allKeys?void 0:new Xt(n,this.options.clientId),this.nowProvider),this.dpop=this.options.useDpop?new an(this.options.clientId):void 0,this.domainUrl=(o=this.options.domain,/^https?:\/\//.test(o)?o:`https://${o}`),this.tokenIssuer=((e,t)=>e?e.startsWith(`https://`)?e:`https://${e}/`:`${t}/`)(this.options.issuer,this.domainUrl);let s=`${this.domainUrl}/me/`,c=this.createFetcher(Object.assign(Object.assign({},this.options.useDpop&&{dpopNonceId:`__auth0_my_account_api__`}),{getAccessToken:e=>this.getTokenSilently({authorizationParams:{scope:(e?.scope)?.join(` `),audience:s},detailedResponse:!0})}));this.myAccount=new cn(c,s),this.authJsClient=new Ms({domain:this.options.domain,clientId:this.options.clientId}),this.mfa=new qs(this.authJsClient.mfa,this),this.passkey=new Zs(this.authJsClient.passkey,this),typeof window<`u`&&window.Worker&&this.options.useRefreshTokens&&t===ce&&(this.options.workerUrl?this.worker=new Worker(this.options.workerUrl):this.worker=new Jt,this.worker.postMessage({type:`init`,allowedBaseUrl:this.domainUrl}))}getConfiguration(){return Object.freeze({domain:this.options.domain,clientId:this.options.clientId})}_url(e){let t=Oe(this.options.auth0Client||ue,!0),n=encodeURIComponent(btoa(JSON.stringify(t)));return`${this.domainUrl}${e}&auth0Client=${n}`}_authorizeUrl(e){return this._url(`/authorize?${ke(e)}`)}async _verifyIdToken(e,t,n){let r=await this.nowProvider();return kt({iss:this.tokenIssuer,aud:this.options.clientId,id_token:e,nonce:t,organization:n,leeway:this.options.leeway,max_age:(i=this.options.authorizationParams.max_age,typeof i==`string`?parseInt(i,10)||void 0:i),now:r});var i}_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})}_extractSessionTransferToken(e){return new URLSearchParams(window.location.search).get(e)||void 0}_clearSessionTransferTokenFromUrl(e){try{let t=new URL(window.location.href);t.searchParams.has(e)&&(t.searchParams.delete(e),window.history.replaceState({},``,t.toString()))}catch{}}_applySessionTransferToken(e){let t=this.options.sessionTransferTokenQueryParamName;if(!t||e.session_transfer_token)return e;let n=this._extractSessionTransferToken(t);return n?(this._clearSessionTransferTokenFromUrl(t),Object.assign(Object.assign({},e),{session_transfer_token:n})):e}async _prepareAuthorizeUrl(e,t,n){let r=Ee(Te()),i=Ee(Te()),a=Te(),o=Me(await Ae(a)),s=await this.dpop?.calculateThumbprint(),c=((e,t,n,r,i,a,o,s,c)=>Object.assign(Object.assign(Object.assign({client_id:e.clientId},e.authorizationParams),n),{scope:bt(t,n.scope,n.audience),response_type:`code`,response_mode:s||`query`,state:r,nonce:i,redirect_uri:o||e.authorizationParams.redirect_uri,code_challenge:a,code_challenge_method:`S256`,dpop_jkt:c}))(this.options,this.scope,e,r,i,o,e.redirect_uri||this.options.authorizationParams.redirect_uri||n,t?.response_mode,s),l=this._authorizeUrl(c);return{nonce:i,code_verifier:a,scope:c.scope,audience:c.audience||T,redirect_uri:c.redirect_uri,state:r,url:l}}async loginWithPopup(e,t){if(e||={},!(t||={}).popup&&(t.popup=(e=>{let t=window.screenX+(window.innerWidth-400)/2,n=window.screenY+(window.innerHeight-600)/2;return window.open(e,`auth0:authorize:popup`,`left=${t},top=${n},width=400,height=600,resizable,scrollbars=yes,status=1`)})(``),!t.popup))throw new ve;let n=this._applySessionTransferToken(e.authorizationParams||{}),r=await this._prepareAuthorizeUrl(n,{response_mode:`web_message`},window.location.origin);t.popup.location.href=r.url;let i=await((e,t)=>new Promise((n,r)=>{let i,a=setInterval(()=>{e.popup&&e.popup.closed&&(clearInterval(a),clearTimeout(o),window.removeEventListener(`message`,i,!1),r(new _e(e.popup)))},1e3),o=setTimeout(()=>{clearInterval(a),r(new ge(e.popup)),window.removeEventListener(`message`,i,!1)},1e3*(e.timeoutInSeconds||60));i=function(s){if(s.origin===t&&s.data&&s.data.type===`authorization_response`){if(clearTimeout(o),clearInterval(a),window.removeEventListener(`message`,i,!1),!1!==e.closePopup&&e.popup.close(),s.data.response.error)return r(E.fromPayload(s.data.response));n(s.data.response)}},window.addEventListener(`message`,i)}))(Object.assign(Object.assign({},t),{timeoutInSeconds:t.timeoutInSeconds||this.options.authorizeTimeoutInSeconds||60}),new URL(r.url).origin);if(r.state!==i.state)throw new E(`state_mismatch`,`Invalid state`);let a=e.authorizationParams?.organization||this.options.authorizationParams.organization;await this._requestToken({audience:r.audience,scope:r.scope,code_verifier:r.code_verifier,grant_type:`authorization_code`,code:i.code,redirect_uri:r.redirect_uri},{nonceIn:r.nonce,organization:a})}async getUser(){return await this._isSessionCeilingReached()?void 0:(await this._getIdTokenFromCache())?.decodedToken?.user}async getIdTokenClaims(){return await this._isSessionCeilingReached()?void 0:(await this._getIdTokenFromCache())?.decodedToken?.claims}async loginWithRedirect(){let e=en(arguments.length>0&&arguments[0]!==void 0?arguments[0]:{}),t=e.openUrl,n=e.fragment,r=e.appState,i=f(e,[`openUrl`,`fragment`,`appState`]),a=i.authorizationParams?.organization||this.options.authorizationParams.organization,o=this._applySessionTransferToken(i.authorizationParams||{}),s=await this._prepareAuthorizeUrl(o),c=s.url,l=f(s,[`url`]);this.transactionManager.create(Object.assign(Object.assign(Object.assign({},l),{appState:r,response_type:Ht.Code}),a&&{organization:a}));let u=n?`${c}#${n}`:c;t?await t(u):window.location.assign(u)}async handleRedirectCallback(){let e=(arguments.length>0&&arguments[0]!==void 0?arguments[0]:window.location.href).split(`?`).slice(1);if(e.length===0)throw Error(`There are no query params available for parsing.`);let t=this.transactionManager.get();if(!t)throw new E(`missing_transaction`,`Invalid state`);this.transactionManager.remove();let n=(e=>{e.indexOf(`#`)>-1&&(e=e.substring(0,e.indexOf(`#`)));let t=new URLSearchParams(e);return{state:t.get(`state`),code:t.get(`code`)||void 0,connect_code:t.get(`connect_code`)||void 0,error:t.get(`error`)||void 0,error_description:t.get(`error_description`)||void 0}})(e.join(``));return t.response_type===Ht.ConnectCode?this._handleConnectAccountRedirectCallback(n,t):this._handleLoginRedirectCallback(n,t)}async _handleLoginRedirectCallback(e,t){let n=e.code,r=e.state,i=e.error,a=e.error_description;if(i)throw new pe(i,a||i,r,t.appState);if(!t.code_verifier||t.state&&t.state!==r)throw new E(`state_mismatch`,`Invalid state`);let o=t.organization,s=t.nonce,c=t.redirect_uri;return await this._requestToken(Object.assign({audience:t.audience,scope:t.scope,code_verifier:t.code_verifier,grant_type:`authorization_code`,code:n},c?{redirect_uri:c}:{}),{nonceIn:s,organization:o}),{appState:t.appState,response_type:Ht.Code}}async _handleConnectAccountRedirectCallback(e,t){let n=e.connect_code,r=e.state,i=e.error,a=e.error_description;if(i)throw new me(i,a||i,t.connection,r,t.appState);if(!n)throw new E(`missing_connect_code`,`Missing connect code`);if(!(t.code_verifier&&t.state&&t.auth_session&&t.redirect_uri&&t.state===r))throw new E(`state_mismatch`,`Invalid state`);let o=await this.myAccount.completeAccount({auth_session:t.auth_session,connect_code:n,redirect_uri:t.redirect_uri,code_verifier:t.code_verifier});return Object.assign(Object.assign({},o),{appState:t.appState,response_type:Ht.ConnectCode})}async checkSession(e){if(!this.cookieStorage.get(this.isAuthenticatedCookieName)){if(!this.cookieStorage.get(Zt))return;this.cookieStorage.save(this.isAuthenticatedCookieName,!0,{daysUntilExpire:this.sessionCheckExpiryDays,cookieDomain:this.options.cookieDomain}),this.cookieStorage.remove(Zt)}try{await this.getTokenSilently(e)}catch{}}async getTokenSilently(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=Object.assign(Object.assign({cacheMode:`on`},e),{authorizationParams:Object.assign(Object.assign(Object.assign({},this.options.authorizationParams),e.authorizationParams),{scope:bt(this.scope,e.authorizationParams?.scope,e.authorizationParams?.audience||this.options.authorizationParams.audience)})}),n=await((e,t)=>{let n=Yt[t];return n||(n=e().finally(()=>{delete Yt[t],n=null}),Yt[t]=n),n})(()=>this._getTokenSilently(t),`${this.options.clientId}::${t.authorizationParams.audience}::${t.authorizationParams.scope}`);return e.detailedResponse?n:n?.access_token}async _getTokenSilently(e){let t=e.cacheMode,n=f(e,[`cacheMode`]);if(await this._isSessionCeilingReached())return;if(t!==`off`){let e=await this._getEntryFromCache({scope:n.authorizationParams.scope,audience:n.authorizationParams.audience||T,clientId:this.options.clientId,cacheMode:t});if(e)return e}if(t===`cache-only`)return;let r=(i=this.options.clientId,a=n.authorizationParams.audience||`default`,`auth0.lock.getTokenSilently.${i}.${a}`);var i,a;try{return await this.lockManager.runWithLock(r,5e3,async()=>{if(t!==`off`){let e=await this._getEntryFromCache({scope:n.authorizationParams.scope,audience:n.authorizationParams.audience||T,clientId:this.options.clientId});if(e)return e}let e=this.options.useRefreshTokens?await this._getTokenUsingRefreshToken(n):await this._getTokenFromIFrame(n),r=e.id_token,i=e.token_type,a=e.access_token,o=e.oauthTokenScope,s=e.expires_in;return Object.assign(Object.assign({id_token:r,token_type:i,access_token:a},o?{scope:o}:null),{expires_in:s})})}catch(e){if(this._isInteractiveError(e)&&this.options.interactiveErrorHandler===`popup`)return await this._handleInteractiveErrorWithPopup(n);throw e}}_isInteractiveError(e){return e instanceof ye||e instanceof E&&this._isIframeMfaError(e)}_isIframeMfaError(e){return e.error===`login_required`&&e.error_description===`Multifactor authentication required`}async _handleInteractiveErrorWithPopup(e){try{await this.loginWithPopup({authorizationParams:e.authorizationParams});let t=await this._getEntryFromCache({scope:e.authorizationParams.scope,audience:e.authorizationParams.audience||T,clientId:this.options.clientId});if(!t)throw new E(`interactive_handler_cache_miss`,`Token not found in cache after interactive authentication`);return t}catch(e){throw e}}async getTokenWithPopup(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=Object.assign(Object.assign({},e),{authorizationParams:Object.assign(Object.assign(Object.assign({},this.options.authorizationParams),e.authorizationParams),{scope:bt(this.scope,e.authorizationParams?.scope,e.authorizationParams?.audience||this.options.authorizationParams.audience)})});return t=Object.assign(Object.assign({},oe),t),await this.loginWithPopup(n,t),(await this.cacheManager.get(new O({scope:n.authorizationParams.scope,audience:n.authorizationParams.audience||T,clientId:this.options.clientId}),void 0,this.options.useMrrt)).access_token}async isAuthenticated(){return!!await this.getUser()}_buildLogoutUrl(e){e.clientId===null?delete e.clientId:e.clientId=e.clientId||this.options.clientId;let t=e.logoutParams||{},n=t.federated,r=f(t,[`federated`]),i=n?`&federated`:``;return this._url(`/v2/logout?${ke(Object.assign({clientId:e.clientId},r))}`)+i}async revokeRefreshToken(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!this.options.useRefreshTokens)return;let t=e.audience||this.options.authorizationParams.audience||T,n=await this.cacheManager.getRefreshTokensByAudience(t,this.options.clientId);await async function(e,t){let n=e.baseUrl,r=e.timeout,i=e.auth0Client,a=e.useFormData,o=e.refreshTokens,s=e.audience,c=e.client_id,l=e.onRefreshTokenRevoked,u=r||se,d=`refresh_token`,f=`${n}/oauth/revoke`,p={"Content-Type":a?`application/x-www-form-urlencoded`:`application/json`,"Auth0-Client":btoa(JSON.stringify(Oe(i||ue)))};if(t){let e={client_id:c,token_type_hint:d},n=a?ke(e):JSON.stringify(e);try{return await mt({type:`revoke`,timeout:u,fetchUrl:f,fetchOptions:{method:`POST`,body:n,headers:p},useFormData:a,auth:{audience:s??T}},t)}catch(e){throw new E(`revoke_error`,e.message)}}for(let e of o){let t={client_id:c,token_type_hint:d,token:e},n=await ht(f,{method:`POST`,body:a?ke(t):JSON.stringify(t),headers:p},u);if(!n.ok){let e,t;try{var m=JSON.parse(await n.text());e=m.error,t=m.error_description}catch{}throw new E(e||`revoke_error`,t||`HTTP error ${n.status}`)}await l?.(e)}}({baseUrl:this.domainUrl,timeout:this.httpTimeoutMs,auth0Client:this.options.auth0Client,useFormData:this.options.useFormData,client_id:this.options.clientId,refreshTokens:n,audience:t,onRefreshTokenRevoked:e=>this.cacheManager.stripRefreshToken(e)},this.worker),this.onlineAccess&&await this._clearLocalSession()}async logout(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=en(e),n=t.openUrl,r=f(t,[`openUrl`]);await this._clearLocalSession(e.clientId);let i=this._buildLogoutUrl(r);n?await n(i):!1!==n&&window.location.assign(i)}async _getTokenFromIFrame(e){let t=(n=this.options.clientId,`auth0.lock.getTokenFromIFrame.${n}`);var n;try{return await this.lockManager.runWithLock(t,5e3,async()=>{let t=Object.assign(Object.assign({},e.authorizationParams),{prompt:`none`}),n=this.cookieStorage.get(this.orgHintCookieName);n&&!t.organization&&(t.organization=n);let r=await this._prepareAuthorizeUrl(t,{response_mode:`web_message`},window.location.origin),i=r.url,a=r.state,o=r.nonce,s=r.code_verifier,c=r.redirect_uri,l=r.scope,u=r.audience;if(window.crossOriginIsolated)throw new E(`login_required`,`The application is running in a Cross-Origin Isolated context, silently retrieving a token without refresh token is not possible.`);let d=e.timeoutInSeconds||this.options.authorizeTimeoutInSeconds,f;try{f=new URL(this.domainUrl).origin}catch{f=this.domainUrl}let p=await function(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:60;return new Promise((r,i)=>{let a=window.document.createElement(`iframe`);a.setAttribute(`width`,`0`),a.setAttribute(`height`,`0`),a.style.display=`none`;let o=()=>{window.document.body.contains(a)&&(window.document.body.removeChild(a),window.removeEventListener(`message`,s,!1))},s,c=setTimeout(()=>{i(new he),o()},1e3*n);s=function(e){if(e.origin!=t||!e.data||e.data.type!==`authorization_response`)return;let n=e.source;n&&n.close(),e.data.response.error?i(E.fromPayload(e.data.response)):r(e.data.response),clearTimeout(c),window.removeEventListener(`message`,s,!1),setTimeout(o,2e3)},window.addEventListener(`message`,s,!1),window.document.body.appendChild(a),a.setAttribute(`src`,e)})}(i,f,d);if(a!==p.state)throw new E(`state_mismatch`,`Invalid state`);let m=await this._requestToken(Object.assign(Object.assign({},e.authorizationParams),{code_verifier:s,code:p.code,grant_type:`authorization_code`,redirect_uri:c,timeout:e.authorizationParams.timeout||this.httpTimeoutMs}),{nonceIn:o,organization:t.organization});return Object.assign(Object.assign({},m),{scope:l,oauthTokenScope:m.scope,audience:u})})}catch(e){throw e.error===`login_required`&&(e instanceof E&&this._isIframeMfaError(e)&&this.options.interactiveErrorHandler===`popup`||this.logout({openUrl:!1})),e}}async _getTokenUsingRefreshToken(e){let t=await this.cacheManager.get(new O({scope:e.authorizationParams.scope,audience:e.authorizationParams.audience||T,clientId:this.options.clientId}),void 0,this.options.useMrrt);if(!(t&&t.refresh_token||this.worker)){if(this.options.useRefreshTokensFallback)return await this._getTokenFromIFrame(e);throw new be(e.authorizationParams.audience||T,e.authorizationParams.scope)}let n=e.authorizationParams.redirect_uri||this.options.authorizationParams.redirect_uri||window.location.origin,r=typeof e.timeoutInSeconds==`number`?1e3*e.timeoutInSeconds:null,i=((e,t,n,r)=>{if(e&&n&&r){if(t.audience!==n)return t.scope;let e=r.split(` `),i=t.scope?.split(` `)||[],a=i.every(t=>e.includes(t));return e.length>=i.length&&a?r:t.scope}return t.scope})(this.options.useMrrt,e.authorizationParams,t?.audience,t?.scope);try{let l=await this._requestToken(Object.assign(Object.assign(Object.assign({},e.authorizationParams),{grant_type:`refresh_token`,refresh_token:t&&t.refresh_token,redirect_uri:n}),r&&{timeout:r}),{scopesToRequest:i});if(!this.onlineAccess&&l.refresh_token&&t!=null&&t.refresh_token&&await this.cacheManager.updateEntry(t.refresh_token,l.refresh_token),this.options.useMrrt&&(a=t?.audience,o=t?.scope,s=e.authorizationParams.audience,c=e.authorizationParams.scope,a!==s||!((e,t)=>{let n=t?.split(` `)||[];return(e?.split(` `)||[]).every(e=>n.includes(e))})(c,o))){let t=tn(i,l.scope,this.onlineAccess);if(t){if(this.options.useRefreshTokensFallback)return await this._getTokenFromIFrame(e);throw await this.cacheManager.remove(this.options.clientId,e.authorizationParams.audience,e.authorizationParams.scope),new xe(e.authorizationParams.audience||`default`,t)}}return Object.assign(Object.assign({},l),{scope:e.authorizationParams.scope,oauthTokenScope:l.scope,audience:e.authorizationParams.audience||T})}catch(t){if(t.message){if(t.message.includes(`user is blocked`))throw await this.logout({openUrl:!1}),t;if((t.message.includes(`Missing Refresh Token`)||t.message.includes(`invalid refresh token`))&&this.options.useRefreshTokensFallback)return await this._getTokenFromIFrame(e)}throw t}var a,o,s,c}async _saveEntryInCache(e){let t=e.decodedToken.claims,n=t.session_expiry,r=t.iat;if(n!==void 0){if(typeof n!=`number`)throw new E(`invalid_token`,`Invalid session_expiry: value must be a number.`);if(n>=1e10)throw new E(`invalid_token`,`Invalid session_expiry: value appears to be in milliseconds; expected a Unix timestamp in seconds.`);if(r===void 0||n<=r)throw new E(`invalid_token`,`Invalid session_expiry: session ceiling is before or at the token issue time.`)}let i=e.id_token,a=e.decodedToken,o=f(e,[`id_token`,`decodedToken`]);this.userCache.set(St,{id_token:i,decodedToken:a}),await this.cacheManager.setIdToken(this.options.clientId,e.id_token,e.decodedToken),await this.cacheManager.set(o)}async _clearLocalSession(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.options.clientId;e===null?await this.cacheManager.clear():await this.cacheManager.clear(e),this.cookieStorage.remove(this.orgHintCookieName,{cookieDomain:this.options.cookieDomain}),this.cookieStorage.remove(this.isAuthenticatedCookieName,{cookieDomain:this.options.cookieDomain}),this.userCache.remove(St);try{await this.dpop?.clear()}catch{}if(this.worker)try{await mt({type:`clear`},this.worker)}catch{}}async _isSessionCeilingReached(){let e=(this.userCache.get(St)??await this.cacheManager.getIdToken(new O({clientId:this.options.clientId})))?.decodedToken?.claims?.session_expiry;if(e===void 0)return!1;let t=await this.nowProvider();return Math.floor(t/1e3)>=e-30&&(await this._clearLocalSession(),!0)}async _getIdTokenFromCache(){let e=this.options.authorizationParams.audience||T,t=this.scope[e],n=await this.cacheManager.getIdToken(new O({clientId:this.options.clientId,audience:e,scope:t})),r=this.userCache.get(St);return n&&n.id_token===r?.id_token?r:(this.userCache.set(St,n),n)}async _getEntryFromCache(e){let t=e.scope,n=e.audience,r=e.clientId,i=e.cacheMode,a=await this.cacheManager.get(new O({scope:t,audience:n,clientId:r}),60,this.options.useMrrt,i);if(a&&a.access_token){let e=a.token_type,t=a.access_token,n=a.oauthTokenScope,r=a.expires_in,i=await this._getIdTokenFromCache();return i&&Object.assign(Object.assign({id_token:i.id_token,token_type:e||`Bearer`,access_token:t},n?{scope:n}:null),{expires_in:r})}}_storeMfaContext(e,t,n){e instanceof ye&&this.mfa.setMFAAuthDetails(e.mfa_token,t,n,e.mfa_requirements)}async _requestToken(e,t){var n;let r=t||{},i=r.nonceIn,a=r.organization,o=r.scopesToRequest;try{let t=await vt(Object.assign(Object.assign({baseUrl:this.domainUrl,client_id:this.options.clientId,auth0Client:this.options.auth0Client,useFormData:this.options.useFormData,timeout:this.httpTimeoutMs,useMrrt:this.options.useMrrt,dpop:this.dpop,preserveRefreshToken:this.onlineAccess},e),{scope:o||e.scope}),this.worker),r=await this._verifyIdToken(t.id_token,i,a);if(e.grant_type===`authorization_code`){let e=await this._getIdTokenFromCache();(n=e?.decodedToken?.claims)!=null&&n.sub&&e.decodedToken.claims.sub!==r.claims.sub&&(await this.cacheManager.clear(this.options.clientId),this.userCache.remove(St))}if(e.grant_type!==`authorization_code`){let e=(await this._getIdTokenFromCache())?.decodedToken?.claims?.session_expiry;e!==void 0&&(r=Object.assign(Object.assign({},r),{claims:Object.assign(Object.assign({},r.claims),{session_expiry:e})}))}return!t.refresh_token&&this.onlineAccess&&(t.refresh_token=e.refresh_token??(await this.cacheManager.get(new O({scope:o||e.scope,audience:e.audience||T,clientId:this.options.clientId}),void 0,this.options.useMrrt))?.refresh_token),await this._saveEntryInCache(Object.assign(Object.assign(Object.assign(Object.assign({},t),{decodedToken:r,scope:e.scope,audience:e.audience||T}),t.scope?{oauthTokenScope:t.scope}:null),{client_id:this.options.clientId})),this.cookieStorage.save(this.isAuthenticatedCookieName,!0,{daysUntilExpire:this.sessionCheckExpiryDays,cookieDomain:this.options.cookieDomain}),this._processOrgHint(a||r.claims.org_id),Object.assign(Object.assign({},t),{decodedToken:r})}catch(t){throw e.grant_type!==`authorization_code`&&this._storeMfaContext(t,o||e.scope,e.audience),t}}_buildTokenExchangeParams(e){return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},e),{grant_type:`urn:ietf:params:oauth:grant-type:token-exchange`,subject_token:e.subject_token,subject_token_type:e.subject_token_type}),e.actor_token&&{actor_token:e.actor_token}),e.actor_token_type&&{actor_token_type:e.actor_token_type}),{scope:bt(this.scope,e.scope,e.audience||this.options.authorizationParams.audience),audience:e.audience||this.options.authorizationParams.audience,organization:e.organization||this.options.authorizationParams.organization})}async loginWithCustomTokenExchange(e){return this._requestToken(this._buildTokenExchangeParams(e))}async customTokenExchange(e){let t=this._buildTokenExchangeParams(e);try{let n=await vt(Object.assign(Object.assign({},t),{baseUrl:this.domainUrl,client_id:this.options.clientId,auth0Client:this.options.auth0Client,useFormData:this.options.useFormData,timeout:this.httpTimeoutMs,dpop:this.dpop}),this.worker,!0);return n.id_token&&await this._verifyIdToken(n.id_token,void 0,e.organization),n}catch(e){throw this._storeMfaContext(e,t.scope,t.audience),e}}async exchangeToken(e){return this.loginWithCustomTokenExchange(e)}_assertDpop(e){if(!e)throw Error("`useDpop` option must be enabled before using DPoP.")}getDpopNonce(e){return this._assertDpop(this.dpop),this.dpop.getNonce(e)}setDpopNonce(e,t){return this._assertDpop(this.dpop),this.dpop.setNonce(e,t)}generateDpopProof(e){return this._assertDpop(this.dpop),this.dpop.generateProof(e)}createFetcher(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return new sn(e,{isDpopEnabled:()=>!!this.options.useDpop,getAccessToken:e=>this.getTokenSilently({authorizationParams:{scope:(e?.scope)?.join(` `),audience:e?.audience},detailedResponse:!0}),getDpopNonce:()=>this.getDpopNonce(e.dpopNonceId),setDpopNonce:t=>this.setDpopNonce(t,e.dpopNonceId),generateDpopProof:e=>this.generateDpopProof(e)})}async connectAccountWithRedirect(e){let t=e.openUrl,n=e.appState,r=e.connection,i=e.scopes,a=e.authorization_params,o=e.redirectUri,s=o===void 0?this.options.authorizationParams.redirect_uri||window.location.origin:o;if(!r)throw Error(`connection is required`);let c=Ee(Te()),l=Te(),u=Me(await Ae(l)),d=await this.myAccount.connectAccount({connection:r,scopes:i,redirect_uri:s,state:c,code_challenge:u,code_challenge_method:`S256`,authorization_params:a}),f=d.connect_uri,p=d.connect_params,m=d.auth_session;this.transactionManager.create({state:c,code_verifier:l,auth_session:m,redirect_uri:s,appState:n,connection:r,response_type:Ht.ConnectCode});let h=new URL(f);h.searchParams.set(`ticket`,p.ticket),t?await t(h.toString()):window.location.assign(h)}async _requestTokenForPasskey(e){let t=e.audience||this.options.authorizationParams.audience,n=e.organization||this.options.authorizationParams.organization;return this._requestToken(Object.assign(Object.assign(Object.assign({grant_type:`urn:okta:params:oauth:grant-type:webauthn`,auth_session:e.authSession,authn_response:e.credential},e.realm&&{realm:e.realm}),n&&{organization:n}),{scope:bt(this.scope,e.scope,t),audience:t}))}async _requestTokenForMfa(e,t){let n=e.mfaToken,r=f(e,[`mfaToken`]);return this._requestToken(Object.assign(Object.assign({},r),{mfa_token:n}),t)}},tc={isAuthenticated:!1,isLoading:!0,error:void 0,user:void 0},$=function(){throw Error(`You forgot to wrap your component in <Auth0Provider>.`)},nc=s(s({},tc),{buildAuthorizeUrl:$,buildLogoutUrl:$,getAccessTokenSilently:$,getAccessTokenWithPopup:$,getIdTokenClaims:$,loginWithCustomTokenExchange:$,customTokenExchange:$,exchangeToken:$,loginWithRedirect:$,loginWithPopup:$,connectAccountWithRedirect:$,logout:$,revokeRefreshToken:$,handleRedirectCallback:$,getDpopNonce:$,setDpopNonce:$,generateDpopProof:$,createFetcher:$,getConfiguration:$,mfa:{getAuthenticators:$,enroll:$,challenge:$,verify:$,getEnrollmentFactors:$},passkey:{signup:$,login:$},myAccount:{getFactors:$,getAuthenticationMethods:$,getAuthenticationMethod:$,updateAuthenticationMethod:$,deleteAuthenticationMethod:$,enrollmentChallenge:$,enrollmentVerify:$}}),rc=(0,i.createContext)(nc),ic=function(e){o(t,e);function t(n,r){var i=e.call(this,r??n)||this;return i.error=n,i.error_description=r,Object.setPrototypeOf(i,t.prototype),i}return t}(Error),ac=/[?&](?:connect_)?code=[^&]+/,oc=/[?&]state=[^&]+/,sc=/[?&]error=[^&]+/,cc=function(e){return e===void 0&&(e=window.location.search),(ac.test(e)||sc.test(e))&&oc.test(e)},lc=function(e){return function(t){if(t instanceof Error)return t;if(typeof t==`object`&&t&&`error`in t&&typeof t.error==`string`){if(`error_description`in t&&typeof t.error_description==`string`){var n=t;return new ic(n.error,n.error_description)}return new ic(t.error)}return Error(e)}},uc=lc(`Login failed`),dc=lc(`Get access token failed`),fc=function(e){e?.redirectUri&&(console.warn("Using `redirectUri` has been deprecated, please use `authorizationParams.redirect_uri` instead as `redirectUri` will be no longer supported in a future version"),e.authorizationParams=e.authorizationParams??{},e.authorizationParams.redirect_uri=e.redirectUri,delete e.redirectUri),e?.authorizationParams?.redirectUri&&(console.warn("Using `authorizationParams.redirectUri` has been deprecated, please use `authorizationParams.redirect_uri` instead as `authorizationParams.redirectUri` will be removed in a future version"),e.authorizationParams.redirect_uri=e.authorizationParams.redirectUri,delete e.authorizationParams.redirectUri)},pc=function(e,t){switch(t.type){case`LOGIN_POPUP_STARTED`:return s(s({},e),{isLoading:!0});case`LOGIN_POPUP_COMPLETE`:case`INITIALISED`:return s(s({},e),{isAuthenticated:!!t.user,user:t.user,isLoading:!1,error:void 0});case`HANDLE_REDIRECT_COMPLETE`:case`GET_ACCESS_TOKEN_COMPLETE`:case`SYNC_USER`:return e.user===t.user?e:s(s({},e),{isAuthenticated:!!t.user,user:t.user});case`LOGOUT`:return s(s({},e),{isAuthenticated:!1,user:void 0});case`ERROR`:return s(s({},e),{isLoading:!1,error:t.error})}},mc=function(e){return fc(e),s(s({},e),{auth0Client:{name:`auth0-react`,version:`2.22.0`}})},hc=function(e){window.history.replaceState({},document.title,e.returnTo??window.location.pathname)},gc=function(e){var t=e,n=t.children,r=t.skipRedirectCallback,a=t.onRedirectCallback,o=a===void 0?hc:a,f=t.context,p=f===void 0?rc:f,m=t.client,h=c(t,[`children`,`skipRedirectCallback`,`onRedirectCallback`,`context`,`client`]);m&&(h.domain||h.clientId)&&console.warn("Auth0Provider: the `client` prop takes precedence over `domain`/`clientId` and other configuration options. Remove `domain`, `clientId`, and any other Auth0Client configuration props when using the `client` prop.");var g=(0,i.useState)(function(){return m??new ec(mc(h))})[0],_=(0,i.useReducer)(pc,tc),ee=_[0],v=_[1],y=(0,i.useRef)(!1),b=(0,i.useCallback)(function(e){return v({type:`ERROR`,error:e}),e},[]);(0,i.useEffect)(function(){y.current||(y.current=!0,(function(){return l(void 0,void 0,void 0,function(){var e,t,n,i,a,s,l;return u(this,function(u){switch(u.label){case 0:return u.trys.push([0,7,,8]),e=void 0,cc()&&!r?[4,g.handleRedirectCallback()]:[3,3];case 1:return t=u.sent(),n=t.appState,i=n===void 0?{}:n,a=t.response_type,s=c(t,[`appState`,`response_type`]),[4,g.getUser()];case 2:return e=u.sent(),i.response_type=a,a===Ht.ConnectCode&&(i.connectedAccount=s),o(i,e),[3,6];case 3:return[4,g.checkSession()];case 4:return u.sent(),[4,g.getUser()];case 5:e=u.sent(),u.label=6;case 6:return v({type:`INITIALISED`,user:e}),[3,8];case 7:return l=u.sent(),b(uc(l)),[3,8];case 8:return[2]}})})})())},[g,o,r,b]);var x=(0,i.useCallback)(function(e){return fc(e),g.loginWithRedirect(e)},[g]),te=(0,i.useCallback)(function(e,t){return l(void 0,void 0,void 0,function(){var n,r;return u(this,function(i){switch(i.label){case 0:v({type:`LOGIN_POPUP_STARTED`}),i.label=1;case 1:return i.trys.push([1,3,,4]),[4,g.loginWithPopup(e,t)];case 2:return i.sent(),[3,4];case 3:return n=i.sent(),b(uc(n)),[2];case 4:return[4,g.getUser()];case 5:return r=i.sent(),v({type:`LOGIN_POPUP_COMPLETE`,user:r}),[2]}})})},[g,b]),S=(0,i.useCallback)(function(){return l(void 0,d([],[...arguments],!0),void 0,function(e){return e===void 0&&(e={}),u(this,function(t){switch(t.label){case 0:return[4,g.logout(e)];case 1:return t.sent(),(e.openUrl||e.openUrl===!1)&&v({type:`LOGOUT`}),[2]}})})},[g]),ne=(0,i.useCallback)(function(e){return l(void 0,void 0,void 0,function(){var t,n;return u(this,function(r){switch(r.label){case 0:return r.trys.push([0,,2,4]),[4,g.revokeRefreshToken(e)];case 1:return r.sent(),[3,4];case 2:return t=v,n={type:`SYNC_USER`},[4,g.getUser()];case 3:return t.apply(void 0,[(n.user=r.sent(),n)]),[7];case 4:return[2]}})})},[g]),C=(0,i.useCallback)(function(e){return l(void 0,void 0,void 0,function(){var t,n,r,i;return u(this,function(a){switch(a.label){case 0:return a.trys.push([0,2,3,5]),[4,g.getTokenSilently(e)];case 1:return t=a.sent(),[3,5];case 2:throw n=a.sent(),dc(n);case 3:return r=v,i={type:`GET_ACCESS_TOKEN_COMPLETE`},[4,g.getUser()];case 4:return r.apply(void 0,[(i.user=a.sent(),i)]),[7];case 5:return[2,t]}})})},[g]),re=(0,i.useCallback)(function(e,t){return l(void 0,void 0,void 0,function(){var n,r,i,a;return u(this,function(o){switch(o.label){case 0:return o.trys.push([0,2,3,5]),[4,g.getTokenWithPopup(e,t)];case 1:return n=o.sent(),[3,5];case 2:throw r=o.sent(),dc(r);case 3:return i=v,a={type:`GET_ACCESS_TOKEN_COMPLETE`},[4,g.getUser()];case 4:return i.apply(void 0,[(a.user=o.sent(),a)]),[7];case 5:return[2,n]}})})},[g]),w=(0,i.useCallback)(function(e){return g.connectAccountWithRedirect(e)},[g]),ie=(0,i.useCallback)(function(){return g.getIdTokenClaims()},[g]),ae=(0,i.useCallback)(function(e){return l(void 0,void 0,void 0,function(){var t,n,r,i;return u(this,function(a){switch(a.label){case 0:return a.trys.push([0,2,3,5]),[4,g.loginWithCustomTokenExchange(e)];case 1:return t=a.sent(),[3,5];case 2:throw n=a.sent(),dc(n);case 3:return r=v,i={type:`GET_ACCESS_TOKEN_COMPLETE`},[4,g.getUser()];case 4:return r.apply(void 0,[(i.user=a.sent(),i)]),[7];case 5:return[2,t]}})})},[g]),oe=(0,i.useCallback)(function(e){return g.customTokenExchange(e)},[g]),se=(0,i.useCallback)(function(e){return l(void 0,void 0,void 0,function(){return u(this,function(t){return[2,ae(e)]})})},[ae]),ce=(0,i.useCallback)(function(e){return l(void 0,void 0,void 0,function(){var t,n,r;return u(this,function(i){switch(i.label){case 0:return i.trys.push([0,2,3,5]),[4,g.handleRedirectCallback(e)];case 1:return[2,i.sent()];case 2:throw t=i.sent(),dc(t);case 3:return n=v,r={type:`HANDLE_REDIRECT_COMPLETE`},[4,g.getUser()];case 4:return n.apply(void 0,[(r.user=i.sent(),r)]),[7];case 5:return[2]}})})},[g]),le=(0,i.useCallback)(function(e){return g.getDpopNonce(e)},[g]),ue=(0,i.useCallback)(function(e,t){return g.setDpopNonce(e,t)},[g]),de=(0,i.useCallback)(function(e){return g.generateDpopProof(e)},[g]),T=(0,i.useCallback)(function(e){return g.createFetcher(e)},[g]),E=(0,i.useCallback)(function(){return g.getConfiguration()},[g]),fe=(0,i.useMemo)(function(){return g.mfa},[g]),pe=(0,i.useMemo)(function(){return g.myAccount},[g]),me=(0,i.useCallback)(function(e){return l(void 0,void 0,void 0,function(){var t,n,r,i;return u(this,function(a){switch(a.label){case 0:return a.trys.push([0,2,3,5]),[4,g.passkey.signup(e)];case 1:return t=a.sent(),[3,5];case 2:throw n=a.sent(),dc(n);case 3:return r=v,i={type:`GET_ACCESS_TOKEN_COMPLETE`},[4,g.getUser()];case 4:return r.apply(void 0,[(i.user=a.sent(),i)]),[7];case 5:return[2,t]}})})},[g]),he=(0,i.useCallback)(function(e){return l(void 0,void 0,void 0,function(){var t,n,r,i;return u(this,function(a){switch(a.label){case 0:return a.trys.push([0,2,3,5]),[4,g.passkey.login(e)];case 1:return t=a.sent(),[3,5];case 2:throw n=a.sent(),dc(n);case 3:return r=v,i={type:`GET_ACCESS_TOKEN_COMPLETE`},[4,g.getUser()];case 4:return r.apply(void 0,[(i.user=a.sent(),i)]),[7];case 5:return[2,t]}})})},[g]),ge=(0,i.useMemo)(function(){return{signup:me,login:he}},[me,he]),_e=(0,i.useMemo)(function(){return s(s({},ee),{getAccessTokenSilently:C,getAccessTokenWithPopup:re,getIdTokenClaims:ie,loginWithCustomTokenExchange:ae,customTokenExchange:oe,exchangeToken:se,loginWithRedirect:x,loginWithPopup:te,connectAccountWithRedirect:w,logout:S,revokeRefreshToken:ne,handleRedirectCallback:ce,getDpopNonce:le,setDpopNonce:ue,generateDpopProof:de,createFetcher:T,getConfiguration:E,mfa:fe,passkey:ge,myAccount:pe})},[ee,C,re,ie,ae,oe,se,x,te,w,S,ne,ce,le,ue,de,T,E,fe,ge,pe]);return i.createElement(p.Provider,{value:_e},n)},_c=function(e){return e===void 0&&(e=rc),(0,i.useContext)(e)};export{_c as n,gc as t};