foundation-sdk 0.2.2 → 0.2.4

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