@muze-nl/metro-oidc 0.8.0 → 0.9.0

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.
@@ -1,4 +1,4 @@
1
- (()=>{var Gt=Object.defineProperty;var at=(e,t)=>{for(var r in t)Gt(e,r,{get:t[r],enumerable:!0})};var D={};at(D,{Client:()=>ue,client:()=>C,deepClone:()=>le,metroError:()=>m,request:()=>J,response:()=>X,url:()=>b});var G="https://metro.muze.nl/details/";Symbol.metroProxy||(Symbol.metroProxy=Symbol("isProxy"));Symbol.metroSource||(Symbol.metroSource=Symbol("source"));var ue=class e{clientOptions={url:b(typeof window<"u"?window.location:"https://localhost"),verbs:["get","post","put","delete","patch","head","options","query"]};static tracers={};constructor(...t){for(let r of t)if(typeof r=="string"||r instanceof String)this.clientOptions.url=b(this.clientOptions.url.href,r);else if(r instanceof e)Object.assign(this.clientOptions,r.clientOptions);else if(r instanceof Function)this.#e([r]);else if(r&&typeof r=="object")for(let n in r)n=="middlewares"?this.#e(r[n]):n=="url"?this.clientOptions.url=b(this.clientOptions.url.href,r[n]):typeof r[n]=="function"?this.clientOptions[n]=r[n](this.clientOptions[n],this.clientOptions):this.clientOptions[n]=r[n];for(let r of this.clientOptions.verbs)this[r]=async function(...n){return this.fetch(J(this.clientOptions,...n,{method:r.toUpperCase()}),qt(...n))}}#e(t){typeof t=="function"&&(t=[t]);let r=t.findIndex(n=>typeof n!="function");if(r>=0)throw m("metro.client: middlewares must be a function or an array of functions "+G+"client/invalid-middlewares/",t[r]);Array.isArray(this.clientOptions.middlewares)||(this.clientOptions.middlewares=[]),this.clientOptions.middlewares=this.clientOptions.middlewares.concat(t)}fetch(t,r){if(t=J(t,r),!t.url)throw m("metro.client."+t.method.toLowerCase()+": Missing url parameter "+G+"client/fetch-missing-url/",t);if(r||(r={}),typeof r!="object"||r instanceof String)throw m("metro.client.fetch: Invalid options parameter "+G+"client/fetch-invalid-options/",r);let o=[async function(l){l[Symbol.metroProxy]&&(l=l[Symbol.metroSource]);let d=await fetch(l);return X(d)}].concat(this.clientOptions?.middlewares?.slice()||[]);r=Object.assign({},this.clientOptions,r);let i=Zt(t,r),s=tr(this,r,i),a;for(let p of o)a=(function(l,d){return async function(w){let T,A=i.tracers;fe(A,"request",w,d,i);try{T=await d(w,l,s)}catch(c){throw fe(A,"error",c,w,d,i),c}return fe(A,"response",T,d,i),T}})(a,p);return a(t)}with(...t){return new e(le(this.clientOptions),...t)}get location(){return this.clientOptions.url}},Xt=0,Yt=["trace","tracer","tracers"];function qt(...e){let t={};for(let r of e)if(ut(r))for(let n of Yt)n in r&&(t[n]=r[n]);return t}function Zt(e,t={}){let r=Qt(t.trace||t.tracer||t.tracers),n=[];r?n=r.localTracers||[]:n=ce(t.trace).concat(ce(t.tracer)).concat(ce(t.tracers));let o=Object.values(ue.tracers||{});return{__metroTraceContext:!0,id:"metro-trace-context-"+ ++Xt,parent:r,request:e,options:t,globalTracers:o,localTracers:n,tracers:o.concat(n)}}function Qt(e){return e?e.context?.__metroTraceContext?e.context:e.__metroTraceContext?e:null:null}function ce(e){return!e||e.__metroTraceContext||e.context?.__metroTraceContext?[]:Array.isArray(e)?e.flatMap(ce):er(e)?[e]:ut(e)?Object.values(e).flatMap(ce):[]}function er(e){return e&&typeof e=="object"&&["request","response","error","event","diagnostic","span","link","current"].some(t=>typeof e[t]=="function")}function tr(e,t,r){let n=rr(r);return Object.freeze({client:e,options:t,trace:n,fetch(o,i={}){return e.fetch(o,Object.assign({},i,{trace:n}))}})}function rr(e){let t={__metroTraceContext:!0,context:e,event(r,n={}){fe(e.tracers,"event",r,n,e)},diagnostic(r={}){fe(e.tracers,"diagnostic",r,e)},current(){for(let r of e.tracers)if(typeof r.current=="function"){let n=r.current(e);if(n)return n}return{traceId:null,spanId:null}},async span(r,n,o={}){let i=e.tracers.find(s=>typeof s.span=="function");return i?i.span(r,n,o,e):n()},link(r){let n=null;for(let o of e.tracers)typeof o.link=="function"&&(n=o.link(r,void 0,e)||n);return n},options(r={}){return Object.assign({},r,{trace:t})}};return t}function fe(e,t,...r){for(let n of e)n&&typeof n[t]=="function"&&n[t].call(n,...r)}function ut(e){return e&&typeof e=="object"&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null)}function C(...e){return new ue(...le(e))}function nr(e,t){let r=t||{};!r.url&&t.url&&(r.url=t.url);for(let n of["method","headers","body","mode","credentials","cache","redirect","referrer","referrerPolicy","integrity","keepalive","signal","priority","url"]){let o=e[n];if(!(typeof o>"u"||o==null))if(o?.[Symbol.metroProxy]&&(o=o[Symbol.metroSource]),typeof o=="function")r[n]=o(r[n],r);else if(n=="url")r.url=b(r.url,o);else if(n=="headers"){r.headers=new Headers(t.headers),o instanceof Headers||(o=new Headers(e.headers));for(let[i,s]of o.entries())r.headers.set(i,s)}else r[n]=o}return e instanceof Request&&e.data&&(r.body=e.data),r}function J(...e){let t={url:b(typeof window<"u"?window.location:"https://localhost/"),duplex:"half"};for(let o of e)typeof o=="string"||o instanceof URL||o instanceof URLSearchParams?t.url=b(t.url,o):o&&(o instanceof FormData||o instanceof ReadableStream||o instanceof Blob||o instanceof ArrayBuffer||o instanceof DataView)?t.body=o:o&&typeof o=="object"&&Object.assign(t,nr(o,t));let r=new Request(t.url,t),n=t.body;return n&&typeof n=="object"&&!(n instanceof String)&&!(n instanceof ReadableStream)&&!(n instanceof Blob)&&!(n instanceof ArrayBuffer)&&!(n instanceof DataView)&&!(n instanceof FormData)&&!(n instanceof URLSearchParams)&&globalThis.ArrayBuffer&&ArrayBuffer.isView(n)&&typeof n.toString=="function"&&(t.body=n.toString({headers:r.headers}),r=new Request(t.url,t)),Object.freeze(r),new Proxy(r,{get(o,i){let s;switch(i){case Symbol.metroSource:s=o;break;case Symbol.metroProxy:s=!0;break;case"with":s=function(...a){return typeof n<"u"&&a.unshift({body:n}),J(o,...a)};break;case"data":s=n;break;default:o[i]instanceof Function?i==="clone"?s=function(){let a=o.clone();return typeof n<"u"&&!(typeof ReadableStream<"u"&&n instanceof ReadableStream)?J(a,{body:n}):J(a)}:s=o[i].bind(o):s=o[i];break}return s}})}function ct(e,t){let r=t||{};!r.url&&t.url&&(r.url=t.url);for(let n of["status","statusText","headers","body","url","type","redirected"]){let o=e[n];typeof o>"u"||o==null||(o?.[Symbol.metroProxy]&&(o=o[Symbol.metroSource]),typeof o=="function"?r[n]=o(r[n],r):n=="url"?r.url=new URL(o,r.url||"https://localhost/"):r[n]=o)}return e instanceof Response&&e.data&&(r.body=e.data),r}function X(...e){let t={};for(let o of e)typeof o=="string"?t.body=o:o instanceof Response?Object.assign(t,ct(o,t)):o&&typeof o=="object"&&(o instanceof FormData||o instanceof Blob||o instanceof ArrayBuffer||o instanceof DataView||o instanceof ReadableStream||o instanceof URLSearchParams||o instanceof String||typeof globalThis.TypedArray<"u"&&o instanceof globalThis.TypedArray?t.body=o:Object.assign(t,ct(o,t)));let r;t.body&&(r=t.body),[101,204,205,304].includes(t.status)&&(t.body=null);let n=new Response(t.body,t);return Object.freeze(n),new Proxy(n,{get(o,i){let s;switch(i){case Symbol.metroProxy:s=!0;break;case Symbol.metroSource:s=o;break;case"with":s=function(...a){return X(o,...a)};break;case"data":s=r;break;case"ok":s=o.status>=200&&o.status<300;break;default:typeof o[i]=="function"?s=o[i].bind(o):s=o[i];break}return s}})}function ft(e,t){typeof t=="function"?t(e.searchParams,e):(t=new URLSearchParams(t),t.forEach((r,n)=>{e.searchParams.append(n,r)}))}function or(e,t){let r=e[Symbol.metroSource]||e;t instanceof URLSearchParams||(t=new URLSearchParams(t));let n=r.hash||"#";return n+="?"+t,b(r,{hash:n})}function b(...e){let t=["hash","fragment","host","hostname","href","password","pathname","port","protocol","username","search","searchParams","hashParams"],r=new URL("https://localhost/"),n=null;for(let o of e)if(typeof o=="string"||o instanceof String)r=new URL(o,r);else if(o instanceof URL||typeof Location<"u"&&o instanceof Location)r=new URL(o);else if(o instanceof URLSearchParams)ft(r,o);else if(o&&typeof o=="object")for(let i in o)switch(i){case"search":typeof o.search=="function"?o.search(r.search,r):r.search=new URLSearchParams(o.search);break;case"searchParams":ft(r,o.searchParams);break;default:if(!t.includes(i))throw m("metro.url: unknown url parameter "+G+"url/unknown-param-name/",i);if(i=="fragment"){let s=o.fragment;s&&typeof s=="string"&&s[0]!="#"&&(s="#"+s),o.hash=s,i="hash"}else i=="hashParams"&&(n=o.hashParams);if(typeof o[i]=="function")o[i](r[i],r);else if(typeof o[i]=="string"||o[i]instanceof String||typeof o[i]=="number"||o[i]instanceof Number||typeof o[i]=="boolean"||o[i]instanceof Boolean)r[i]=""+o[i];else if(typeof o[i]=="object"&&o[i].toString)r[i]=o[i].toString();else throw m("metro.url: unsupported value for "+i+" "+G+"url/unsupported-param-value/",e[i]);break}else throw m("metro.url: unsupported option value "+G+"url/unsupported-option-value/",o);return n&&(r.hash||(r.hash="#"),typeof n=="string"?r.hash+=n:r=or(r,n)),Object.freeze(r),new Proxy(r,{get(o,i){let s;switch(i){case Symbol.metroProxy:s=!0;break;case Symbol.metroSource:s=o;break;case"with":s=function(...a){return b(o,...a)};break;case"filename":s=o.pathname.split("/").pop();break;case"folderpath":s=o.pathname.substring(0,o.pathname.lastIndexOf("/")+1);break;case"authority":s=o.username??"",s+=o.password?":"+o.password:"",s+=s?"@":"",s+=o.hostname,s+=o.port?":"+o.port:"",s+="/",s=o.protocol+"//"+s;break;case"fragment":s=o.hash.substring(1);break;case"scheme":o.protocol?s=o.protocol.substring(0,o.protocol.length-1):s="";break;default:o[i]instanceof Function?s=o[i].bind(o):s=o[i];break}return s}})}var ir={error:(e,...t)=>{console.error("\u24C2\uFE0F ",e,...t)},info:(e,...t)=>{console.info("\u24C2\uFE0F ",e,...t)},group:e=>{console.group("\u24C2\uFE0F "+e)},groupEnd:e=>{console.groupEnd("\u24C2\uFE0F "+e)}};function m(e,...t){return ir.error(e,...t),new Error(e,...t)}function le(e){if(Array.isArray(e))return e.slice().map(le);if(e&&typeof e=="object")if(e.__proto__?.constructor==Object||!e.__proto__){let t=Object.assign({},e);return Object.keys(t).forEach(r=>{t[r]=le(e[r])}),t}else return e;return e}var We={};at(We,{Optional:()=>f,Recommended:()=>q,Required:()=>_,allOf:()=>ve,anyOf:()=>V,assert:()=>P,disable:()=>ar,enable:()=>sr,error:()=>S,fails:()=>K,formatIssue:()=>pt,formatIssues:()=>mt,instanceOf:()=>F,issues:()=>pr,not:()=>Z,oneOf:()=>R,validEmail:()=>Ie,validURL:()=>y,warn:()=>ht});var ke=!1;function sr(){ke=!0}function ar(){ke=!1}function z(e="",t){return(typeof e>"u"||e==null)&&(e=""),typeof t=="number"?`${e}[${t}]`:`${e}.${t}`}function lt(e=""){if(Array.isArray(e))return e;if(!e)return[];let t=[],r=/(?:^|\.)([^.\[\]]+)|\[(\d+)\]/g,n;for(;n=r.exec(e);)typeof n[1]<"u"?t.push(n[1]):typeof n[2]<"u"&&t.push(Number(n[2]));return t}function Oe(e=[]){return typeof e=="string"?e.startsWith(".")?e.slice(1):e:e.map((t,r)=>typeof t=="number"?`[${t}]`:`${r?".":""}${t}`).join("")}function Ke(e){return e===String?"string":e===Number?"number":e===Boolean?"boolean":e.name||"function"}function dt(e,t=60){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}function cr(e){return`'${dt(String(e).replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n"))}'`}function fr(e){try{let r=JSON.stringify(e);if(typeof r=="string")return dt(r)}catch{}let t=e?.constructor?.name;return t&&t!="Object"?t:Object.prototype.toString.call(e)}function Y(e){return typeof e=="string"?cr(e):typeof e>"u"?"undefined":e===null?"null":typeof e=="function"?Ke(e):e instanceof RegExp?e.toString():typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"?String(e):typeof e=="symbol"?e.toString():fr(e)}function B(e){return e===String||e===Number||e===Boolean||typeof e=="function"?Ke(e):e instanceof RegExp?e.toString():Array.isArray(e)?"["+e.map(B).join(", ")+"]":Y(e)}function ur(e){return e.map(B).join(", ")}function lr(e,t,r){return e=="data and pattern are not equal"?`expected ${Y(r)}, found ${Y(t)}`:e=="data does not match pattern"||/^data\[\d+\] does not match pattern$/.test(e)?`expected ${B(r)}, found ${Y(t)}`:e=="data is undefined, should match pattern"?`missing; expected ${B(r)}`:e=="data is required"?"required":e=="data is an empty string, which is not allowed"?"empty string is not allowed":e=="data is not an object, pattern is"?"data is not an object":e=="data is not an instanceof pattern"?`expected instance of ${B(r)}, found ${Y(t)}`:e=="data does not match oneOf patterns"||e=="data does not match anyOf patterns"?`expected one of ${ur(r)}, found ${Y(t)}`:e=="data matches pattern, when required not to"?`must not match ${B(r)}`:e}function pt(e,t={}){if(!e||typeof e!="object")return String(e);let r=e.pathString||Oe(e.path||[])||"value";return`${t.indent??""}${r}: ${e.message}`}function mt(e,t={}){if(!e)return!1;let r=t.indent??" - ";return(Array.isArray(e)?e:[e]).map(n=>pt(n,{...t,indent:r}))}function dr(e){if(!e||typeof e!="object")return{path:[],pathString:"",message:String(e),expected:void 0,actual:void 0};let t=lt(e.path),r=Oe(t),n=e.actual??e.found,o=B(e.expected),i=lr(e.message,n,e.expected);return{path:t,pathString:r,message:i,expected:o,actual:n}}function Ce(e){if(!e)return[];let t=[];for(let r of Array.isArray(e)?e:[e])if(r){if(r&&typeof r=="object"&&r.problems){let n=Ce(r.problems);if(n.length){t=t.concat(n);continue}}t.push(dr(r))}return t}function P(e,t){if(ke){let r=K(e,t);if(r){let n=Ce(r),i=`Assertions failed:
2
- `+mt(n).join(`
3
- `);throw console.error("\u{1F170}\uFE0F "+i),new Error(i,{cause:{problems:r,issues:n,source:e}})}}}function f(e){return function(r,n,o){if(typeof r<"u"&&r!=null&&typeof e<"u")return K(r,e,n,o)}}function _(e){return function(r,n,o){return r==null||typeof r>"u"?S("data is required",r,e||"any value",o):typeof e<"u"?K(r,e,n,o):!1}}function q(e){return function(r,n,o){return r==null||typeof r>"u"?(ht("data does not contain recommended value",r,e,o),!1):K(r,e,n,o)}}function R(...e){return function(r,n,o){for(let i of e)if(!K(r,i,n,o))return!1;return S("data does not match oneOf patterns",r,e,o)}}function V(...e){return function(r,n,o){if(!Array.isArray(r))return S("data is not an array",r,"anyOf",o);for(let[i,s]of r.entries()){let a=z(o,i);if(R(...e)(s,n,a))return S("data does not match anyOf patterns",s,e,a)}return!1}}function ve(...e){return function(r,n,o){let i=[];for(let s of e)i=i.concat(K(r,s,n,o));if(i=i.filter(Boolean),i.length)return S("data does not match all given patterns",r,e,o,i)}}function y(e,t,r){try{e instanceof URL&&(e=e.href);let n=new URL(e);if(n.href!=e&&!(n.href+"/"==e||n.href==e+"/"))return S("data is not a valid url",e,"validURL",r)}catch{return S("data is not a valid url",e,"validURL",r)}}function Ie(e,t,r){if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e))return S("data is not a valid email",e,"validEmail",r)}function F(e){return function(r,n,o){if(!(r instanceof e))return S("data is not an instanceof pattern",r,e,o)}}function Z(e){return function(r,n,o){if(!K(r,e,n,o))return S("data matches pattern, when required not to",r,e,o)}}function pr(e,t,r){let n=K(e,t,r);return n?Ce(n):!1}function K(e,t,r,n=""){typeof r>"u"&&(r=e);let o=[];if(t===Boolean)typeof e!="boolean"&&!(e instanceof Boolean)&&o.push(S("data is not a boolean",e,t,n));else if(t===Number)typeof e!="number"&&!(e instanceof Number)&&o.push(S("data is not a number",e,t,n));else if(t===String)typeof e!="string"&&!(e instanceof String)&&o.push(S("data is not a string",e,t,n)),e==""&&o.push(S("data is an empty string, which is not allowed",e,t,n));else if(t instanceof RegExp)if(Array.isArray(e)){let i=e.findIndex((s,a)=>K(s,t,r,z(n,a)));i>-1&&o.push(S("data["+i+"] does not match pattern",e[i],t,z(n,i)))}else typeof e>"u"?o.push(S("data is undefined, should match pattern",e,t,n)):t.test(e)||o.push(S("data does not match pattern",e,t,n));else if(t instanceof Function){let i=t(e,r,n);i&&(Array.isArray(i)?o=o.concat(i):o.push(i))}else if(Array.isArray(t))if(!Array.isArray(e))o.push(S("data is not an array",e,[],n));else for(let i of t)for(let s of e.keys()){let a=K(e[s],i,r,z(n,s));Array.isArray(a)?o=o.concat(a):a&&o.push(a)}else if(t&&typeof t=="object")if(Array.isArray(e)){let i=e.findIndex((s,a)=>K(s,t,r,z(n,a)));i>-1&&o.push(S("data["+i+"] does not match pattern",e[i],t,z(n,i)))}else if(!e||typeof e!="object")o.push(S("data is not an object, pattern is",e,t,n));else if(e instanceof URLSearchParams&&(e=Object.fromEntries(e)),t instanceof Function){let i=K(e,t,r,n);i&&(o=o.concat(i))}else for(let[i,s]of Object.entries(t)){let a=K(e[i],s,r,z(n,i));a&&(o=o.concat(a))}else t!=e&&o.push(S("data and pattern are not equal",e,t,n));return o.length?o:!1}function S(e,t,r,n="",o){let i=lt(n),s={path:n,pathString:Oe(i),pathParts:i,message:e,found:t,expected:r};return o&&(s.problems=o),s}function ht(e,t,r,n){console.warn("\u{1F170}\uFE0F Assert: "+n,e,r,t)}globalThis.assert={...We};function yt(e){let t,r;if(typeof localStorage<"u")t={get:()=>localStorage.getItem("metro/state:"+e),set:n=>localStorage.setItem("metro/state:"+e,n),has:()=>localStorage.getItem("metro/state:"+e)!==null,delete:()=>localStorage.removeItem("metro/state:"+e)},r={get:n=>JSON.parse(localStorage.getItem(e+":"+n)),set:(n,o)=>localStorage.setItem(e+":"+n,JSON.stringify(o)),has:n=>localStorage.getItem(e+":"+n)!==null,delete:n=>localStorage.removeItem(e+":"+n)};else{let n=new Map;t={get:()=>n.get("metro/state:"+e),set:o=>n.set("metro/state:"+e,o),has:()=>n.has("metro/state:"+e),delete:()=>n.delete("metro/state:"+e)},r=new Map}return{state:t,tokens:r}}var mr=new Map([["bearer","Bearer"],["dpop","DPoP"]]),hr=new Set(["none","client_secret_post","client_secret_basic"]);function Je(e){let t={client:C(),force_authorization:!1,site:"default",oauth2_configuration:{authorization_endpoint:"/authorize",token_endpoint:"/token",redirect_uri:globalThis.document?.location.href,grant_type:"authorization_code",code_verifier:De(64)},authorize_callback:async c=>(window.location.href!=c.href&&window.location.replace(c.href),!1)};P(e,{});let r=Object.assign({},t.oauth2_configuration,e?.oauth2_configuration);e=Object.assign({},t,e),e.oauth2_configuration=r;let n=yt(e.site);e.tokens||(e.tokens=n.tokens),e.state||(e.state=n.state),P(e,{oauth2_configuration:{client_id:_(/.+/),grant_type:"authorization_code",authorization_endpoint:_(y),token_endpoint:_(y),redirect_uri:_(y)}});for(let c in r)switch(c){case"access_token":case"authorization_code":case"refresh_token":e.tokens.set(c,_r(c,r[c]));break}return async function(c,u){if(e.force_authorization)return o(c,u);let h=await u(c);return h.ok||!yr(h)?h:o(c,u)};async function o(c,u){i();let h=e.tokens.get("access_token"),g=e.tokens.get("refresh_token"),k=xr(h);return!h||k&&!g?await s()?o(c,u):X("false"):k&&g?await a()?o(c,u):X("false"):(c=J(c,{headers:{Authorization:h.type+" "+h.value}}),u(c))}function i(){if(typeof window<"u"&&window?.location){let c=b(window.location),u,h,g;if(c.searchParams.has("code")||c.searchParams.has("error"))g=c.searchParams,c=c.with({search:""}),history.pushState({},"",c.href);else if(c.hash){let k=c.hash.substr(1);g=new URLSearchParams("?"+k),c=c.with({hash:""}),history.pushState({},"",c.href)}if(g){if(g.has("error"))throw m("oauth2mw: authorization failed: "+g.get("error")+(g.get("error_description")?" ("+g.get("error_description")+")":""));u=g.get("code"),h=g.get("state"),T(h),u&&e.tokens.set("authorization_code",u)}}}async function s(){if(r.grant_type==="authorization_code"&&!e.tokens.has("authorization_code")){let g=await p();if(!e.authorize_callback||typeof e.authorize_callback!="function")throw m("oauth2mw: oauth2 with grant_type:authorization_code requires a callback function in client options.authorize_callback");let k=await e.authorize_callback(g);if(k)w(k);else return!1}let c=l(),u=await e.client.post(c);if(!u.ok){let g=await u.text();throw m("OAuth2mw: fetch access_token: "+u.status+": "+u.statusText+" ("+g+")",{cause:c})}let h=await u.json();return A(h),e.tokens.delete("authorization_code"),h}async function a(){let c=l("refresh_token"),u=await e.client.post(c);if(!u.ok){let g=await u.text();throw m("OAuth2mw: refresh access_token: "+u.status+": "+u.statusText+" ("+g+")",{cause:c})}let h=await u.json();return A(h),h}async function p(){if(!r.authorization_endpoint)throw m("oauth2mw: Missing options.oauth2_configuration.authorization_endpoint");let c=b(r.authorization_endpoint,{hash:""});P(r,{client_id:/.+/,redirect_uri:/.+/,scope:/.*/});let u={response_type:"code",client_id:r.client_id,redirect_uri:r.redirect_uri,state:r.state||Rr(40)};return r.response_type&&(u.response_type=r.response_type),r.response_mode&&(u.response_mode=r.response_mode),e.state.set(u.state),r.code_verifier&&(e.tokens.set("code_verifier",r.code_verifier),u.code_challenge=await Tr(r.code_verifier),u.code_challenge_method="S256"),r.scope&&(u.scope=r.scope),r.prompt&&(u.prompt=r.prompt),r.nonce&&(u.nonce=r.nonce),b(c,{search:u})}function l(c=null){if(P(r,{client_id:/.+/,redirect_uri:/.+/}),!r.token_endpoint)throw m("oauth2mw: Missing options.endpoints.token url");let u=b(r.token_endpoint,{hash:""}),h={grant_type:c||r.grant_type},g={};switch(d(h,g),r.scope&&(h.scope=r.scope),h.grant_type){case"authorization_code":h.redirect_uri=r.redirect_uri,h.code=e.tokens.get("authorization_code");let k=e.tokens.get("code_verifier");k&&(h.code_verifier=k);break;case"client_credentials":break;case"refresh_token":h.refresh_token=Ar(e.tokens.get("refresh_token"));break;default:throw new Error("Unknown grant_type: "+h.grant_type)}return J(u,{method:"POST",headers:g,body:new URLSearchParams(h)})}function d(c,u){let h=Sr(r);if(h==="none"){c.client_id=r.client_id;return}if(!r.client_secret)throw m("oauth2mw: token_endpoint_auth_method "+h+" requires oauth2_configuration.client_secret");if(h==="client_secret_post"){c.client_id=r.client_id,c.client_secret=r.client_secret;return}if(h==="client_secret_basic"){u.Authorization=br(r.client_id,r.client_secret);return}}function w(c){let u=c;if(c&&typeof c=="object"){if(c.error)throw m("oauth2mw: authorization failed: "+c.error);T(c.state),u=c.authorization_code||c.code}if(!u)throw m("oauth2mw: authorization callback did not return an authorization code");e.tokens.set("authorization_code",u)}function T(c){let u=e.state.get();if(!c||c!==u)throw m("oauth2mw: authorization state mismatch")}function A(c){let u=wr(c);e.tokens.set("access_token",u),c.refresh_token&&e.tokens.set("refresh_token",{value:c.refresh_token})}}function yr(e){return e?e.status===400?!0:Kr(e.headers?.get("WWW-Authenticate"))?.error==="insufficient_scope"?!1:e.status===401:!1}function _r(e,t){return e==="access_token"&&t&&typeof t=="object"?t:e==="access_token"?{value:t,type:"Bearer",expires:null}:t}function wr(e){if(!e||typeof e!="object")throw m("OAuth2mw: token endpoint did not return a JSON object");if(!e.access_token)throw m("OAuth2mw: token response did not include access_token");if(!e.token_type)throw m("OAuth2mw: token response did not include token_type");let t=gr(e.token_type);return{value:e.access_token,expires:e.expires_in===void 0?null:Pr(e.expires_in),type:t,scope:e.scope}}function gr(e){let t=mr.get(String(e).toLowerCase());if(!t)throw m("OAuth2mw: unsupported token_type "+e);return t}function Sr(e){let t=e.token_endpoint_auth_method||(e.client_secret?"client_secret_post":"none");if(!hr.has(t))throw m("oauth2mw: unsupported token_endpoint_auth_method "+t);return t}function br(e,t){let r=_t(e)+":"+_t(t);return"Basic "+Er(r)}function _t(e){return encodeURIComponent(e).replace(/%20/g,"+")}function Er(e){return typeof btoa=="function"?btoa(e):Buffer.from(e,"binary").toString("base64")}function Ar(e){return e&&typeof e=="object"?e.value:e}function xr(e){if(!e)return!0;if(!e.expires)return!1;let t=new Date(e.expires);return new Date().getTime()>t.getTime()}function Pr(e){if(e instanceof Date)return new Date(e.getTime());if(typeof e=="number"){let t=new Date;return t.setSeconds(t.getSeconds()+e),t}throw new TypeError("Unknown expires type "+e)}function De(e=64){let t=new Uint8Array(e);return globalThis.crypto.getRandomValues(t),Ue(t)}async function Tr(e){let r=new TextEncoder().encode(e),n=await globalThis.crypto.subtle.digest("SHA-256",r);return Ue(n)}function Ue(e){let t=Array.from(new Uint8Array(e),r=>String.fromCharCode(r)).join("");return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Rr(e){let t=new Uint8Array(Math.ceil(e*3/4)+1);if(globalThis.crypto?.getRandomValues)return globalThis.crypto.getRandomValues(t),Ue(t).slice(0,e);let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n="",o=0;for(;o<e;)n+=r.charAt(Math.floor(Math.random()*r.length)),o++;return n}function wt(){let e=new URL(document.location.href);if(!e.searchParams.has("code")){if(e.hash){let t=e.hash.substr(1);if(new URLSearchParams("?"+t).has("code"))return!0}return!1}return!0}function Kr(e){if(!e||typeof e!="string")return null;let t=e.trim(),r=t.search(/\s/),n=r<0?t:t.slice(0,r),o=r<0?"":t.slice(r+1);if(!["bearer","dpop"].includes(n.toLowerCase()))return null;let i={scheme:n},s=/([A-Za-z][A-Za-z0-9_-]*)=("(?:[^"\\]|\\.)*"|[^,\s]*)/g,a;for(;a=s.exec(o);){let p=a[2];p.startsWith('"')&&p.endsWith('"')&&(p=p.slice(1,-1).replace(/\\"/g,'"')),i[a[1]]=p}return i}var Or=new TextEncoder,Cr=new TextDecoder;function _e(e){return typeof e=="string"?Or.encode(e):Cr.decode(e)}function gt(e){if(typeof e.modulusLength!="number"||e.modulusLength<2048)throw new He(`${e.name} modulusLength must be at least 2048 bits`)}function vr(e){switch(e.algorithm.name){case"ECDSA":return{name:e.algorithm.name,hash:"SHA-256"};case"RSA-PSS":return gt(e.algorithm),{name:e.algorithm.name,saltLength:32};case"RSASSA-PKCS1-v1_5":return gt(e.algorithm),{name:e.algorithm.name};case"Ed25519":return{name:e.algorithm.name}}throw new N}async function Ir(e,t,r){if(r.usages.includes("sign")===!1)throw new TypeError('private CryptoKey instances used for signing assertions must include "sign" in their "usages"');let n=`${we(_e(JSON.stringify(e)))}.${we(_e(JSON.stringify(t)))}`,o=we(await crypto.subtle.sign(vr(r),r,_e(n)));return`${n}.${o}`}var Le;Uint8Array.prototype.toBase64?Le=e=>(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e.toBase64({alphabet:"base64url",omitPadding:!0})):Le=t=>{t instanceof ArrayBuffer&&(t=new Uint8Array(t));let r=[];for(let n=0;n<t.byteLength;n+=32768)r.push(String.fromCharCode.apply(null,t.subarray(n,n+32768)));return btoa(r.join("")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")};function we(e){return Le(e)}var N=class extends Error{constructor(t){var r;super(t??"operation not supported"),this.name=this.constructor.name,(r=Error.captureStackTrace)===null||r===void 0||r.call(Error,this,this.constructor)}},He=class extends Error{constructor(t){var r;super(t),this.name=this.constructor.name,(r=Error.captureStackTrace)===null||r===void 0||r.call(Error,this,this.constructor)}};function Wr(e){if(e.algorithm.hash.name==="SHA-256")return"PS256";throw new N("unsupported RsaHashedKeyAlgorithm hash name")}function Jr(e){if(e.algorithm.hash.name==="SHA-256")return"RS256";throw new N("unsupported RsaHashedKeyAlgorithm hash name")}function Dr(e){if(e.algorithm.namedCurve==="P-256")return"ES256";throw new N("unsupported EcKeyAlgorithm namedCurve")}function Ur(e){switch(e.algorithm.name){case"RSA-PSS":return Wr(e);case"RSASSA-PKCS1-v1_5":return Jr(e);case"ECDSA":return Dr(e);case"Ed25519":return"Ed25519";default:throw new N("unsupported CryptoKey algorithm name")}}function St(e){return e instanceof CryptoKey}function Lr(e){return St(e)&&e.type==="private"}function Hr(e){return St(e)&&e.type==="public"}function Nr(){return Math.floor(Date.now()/1e3)}async function Ne(e,t,r,n,o,i){let s=e?.privateKey,a=e?.publicKey;if(!Lr(s))throw new TypeError('"keypair.privateKey" must be a private CryptoKey');if(!Hr(a))throw new TypeError('"keypair.publicKey" must be a public CryptoKey');if(a.extractable!==!0)throw new TypeError('"keypair.publicKey.extractable" must be true');if(typeof t!="string")throw new TypeError('"htu" must be a string');if(typeof r!="string")throw new TypeError('"htm" must be a string');if(n!==void 0&&typeof n!="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 Ir({alg:Ur(s),typ:"dpop+jwt",jwk:await Mr(a)},Object.assign(Object.assign({},i),{iat:Nr(),jti:crypto.randomUUID(),htm:r,nonce:n,htu:t,ath:o?we(await crypto.subtle.digest("SHA-256",_e(o))):void 0}),s)}async function Mr(e){let{kty:t,e:r,n,x:o,y:i,crv:s}=await crypto.subtle.exportKey("jwk",e);return{kty:t,crv:s,e:r,n,x:o,y:i}}async function bt(e,t){var r;let n;if(typeof e!="string"||e.length===0)throw new TypeError('"alg" must be a non-empty string');switch(e){case"PS256":n={name:"RSA-PSS",hash:"SHA-256",modulusLength:2048,publicExponent:new Uint8Array([1,0,1])};break;case"RS256":n={name:"RSASSA-PKCS1-v1_5",hash:"SHA-256",modulusLength:2048,publicExponent:new Uint8Array([1,0,1])};break;case"ES256":n={name:"ECDSA",namedCurve:"P-256"};break;case"Ed25519":n={name:"Ed25519"};break;default:throw new N}return crypto.subtle.generateKey(n,(r=t?.extractable)!==null&&r!==void 0?r:!1,["sign","verify"])}function Me(){return new Promise((e,t)=>{let r=globalThis.indexedDB.open("metro",1);r.onupgradeneeded=()=>r.result.createObjectStore("keyPairs",{keyPath:"domain"}),r.onerror=n=>{t(n)},r.onsuccess=n=>{let o=n.target.result;e({set:function(i,s){return new Promise((a,p)=>{let l=o.transaction("keyPairs","readwrite",{durability:"strict"}),d=l.objectStore("keyPairs");l.oncomplete=()=>{a()},l.onerror=p,d.put(i,s)})},get:function(i){return new Promise((s,a)=>{let p=o.transaction("keyPairs","readonly"),d=p.objectStore("keyPairs").get(i);d.onsuccess=()=>{s(d.result)},d.onerror=a,p.onerror=a})},clear:function(){return new Promise((i,s)=>{let a=o.transaction("keyPairs","readwrite"),l=a.objectStore("keyPairs").clear();l.onsuccess=()=>{i()},l.onerror=s,a.onerror=s})}})}})}function $e(e){return P(e,{site:_(y),authorization_endpoint:_(y),token_endpoint:_(y),dpop_signing_alg_values_supported:f([])}),async(t,r)=>{let n=await Me(),o=await n.get(e.site);if(!o){let a=await bt("ES256");o={domain:e.site,keyPair:a},await n.set(o)}let i=b(t.url);if(t.url.startsWith(e.authorization_endpoint)){let a=t.body;a instanceof URLSearchParams||a instanceof FormData?a.set("dpop_jkt",o.keyPair.publicKey):a.dpop_jkt=o.keyPair.publicKey}else if(t.url.startsWith(e.token_endpoint)){let a=await Ne(o.keyPair,t.url,t.method);t=t.with({headers:{DPoP:a}})}else if(t.headers.has("Authorization")){let a=localStorage.getItem(i.host+":nonce")||void 0,p=t.headers.get("Authorization").split(" ")[1],l=await Ne(o.keyPair,t.url,t.method,a,p);t=t.with({headers:{Authorization:"DPoP "+p,DPoP:l}})}let s=await r(t);return s.headers.get("DPoP-Nonce")&&localStorage.setItem(i.host+":nonce",s.headers.get("DPoP-Nonce")),s}}function U(e){return e=Object.assign({contentType:"application/json",reviver:null,replacer:null,space:""},e),async function(r,n){if(r.headers.get("Accept")||(r=r.with({headers:{Accept:e.accept??e.contentType}})),r.method!=="GET"&&r.method!=="HEAD"&&r.data&&typeof r.data=="object"&&!(r.data instanceof ReadableStream)){let i=r.headers.get("Content-Type");(!i||zr(i))&&(r=r.with({headers:{"Content-Type":e.contentType}})),Et(r.headers.get("Content-Type"))&&(r=r.with({body:JSON.stringify(r.data,e.replacer,e.space)}))}let o=await n(r);if(o&&Et(o.headers?.get("Content-Type"))){let s=await o.clone().text();try{let a=JSON.parse(s,e.reviver);return o.with({body:a})}catch{}}return o}}var jr=/^application\/([a-zA-Z0-9\-_]+\+)?json\b/;function Et(e){return jr.exec(e)}function zr(e){return/^text\/plain\b/.exec(e)}function L(e){return async function(r,n){let o=await n(r);if(!o.ok)if(e&&typeof e[o.status]=="function")o=e[o.status].apply(o,r);else throw new Error(o.status+": "+o.statusText,{cause:o});return o}}var de=(...e)=>(t,r)=>e.filter(n=>r.hasOwnKey(n)).length>0?!1:S("root data must have all of",r,e),M=(...e)=>t=>Array.isArray(t)&&e.filter(r=>!t.includes(r)).length==0?!1:S("data must be an array which includes",t,e);var I=["HS256","HS384","HS512","RS256","RS384","RS512","ES256","ES384","ES512"],ge=["none","client_secret_post","client_secret_basic","client_secret_jwt","private_key_jwt"];async function Q(e={}){P(e,{client:f(F(C().constructor)),issuer:_(y)});let t={client:C().with(L()).with(U()),requireDynamicRegistration:!1};e=Object.assign({},t,e),e.client=e.client.with(L()).with(U());let r=!1;function n(p){return r}let o={issuer:_(ve(e.issuer,n)),authorization_endpoint:_(y),token_endpoint:_(y),userinfo_endpoint:q(y),jwks_uri:_(y),registration_endpoint:e.requireDynamicRegistration?_(y):q(y),scopes_supported:q(M("openid")),response_types_supported:e.requireDynamicRegistration?_(M("code","id_token","id_token token")):_([]),response_modes_supported:f([]),grant_types_supported:e.requireDynamicRegistration?f(M("authorization_code")):f([]),acr_values_supported:f([]),subject_types_supported:_([]),id_token_signing_alg_values_supported:_(M("RS256")),id_token_encryption_alg_values_supported:f([]),id_token_encryption_enc_values_supported:f([]),userinfo_signing_alg_values_supported:f([]),userinfo_encryption_alg_values_supported:f([]),userinfo_encryption_enc_values_supported:f([]),request_object_signing_alg_values_supported:f(M("RS256")),request_object_encryption_alg_values_supported:f([]),request_object_encryption_enc_values_supported:f([]),token_endpoint_auth_methods_supported:f(V(...ge)),token_endpoint_auth_signing_alg_values_supported:f(M("RS256"),Z(M("none"))),display_values_supported:f(V("page","popup","touch","wap")),claim_types_supported:f(V("normal","aggregated","distributed")),claims_supported:q([]),service_documentation:f(y),claims_locales_supported:f([]),ui_locales_supported:f([]),claims_parameter_supported:f(Boolean),request_parameter_supported:f(Boolean),request_uri_parameter_supported:f(Boolean),op_policy_uri:f(y),op_tos_uri:f(y)},i=b(e.issuer,".well-known/openid-configuration"),a=(await e.client.get(i)).data;return P(a,o),P(a.issuer,e.issuer),a}async function ee(e){let t={redirect_uris:_([y]),response_types:f([]),grant_types:f(V("authorization_code","refresh_token")),application_type:f(R("native","web")),contacts:f([Ie]),client_name:f(String),logo_uri:f(y),client_uri:f(y),policy_uri:f(y),tos_uri:f(y),jwks_uri:f(y,Z(de("jwks"))),jwks:f(y,Z(de("jwks_uri"))),sector_identifier_uri:f(y),subject_type:f(String),id_token_signed_response_alg:f(R(...I)),id_token_encrypted_response_alg:f(R(...I)),id_token_encrypted_response_enc:f(R(...I),de("id_token_encrypted_response_alg")),userinfo_signed_response_alg:f(R(...I)),userinfo_encrypted_response_alg:f(R(...I)),userinfo_encrypted_response_enc:f(R(...I),de("userinfo_encrypted_response_alg")),request_object_signing_alg:f(R(...I)),request_object_encryption_alg:f(R(...I)),request_object_encryption_enc:f(R(...I)),token_endpoint_auth_method:f(R(...ge)),token_endpoint_auth_signing_alg:f(R(...I)),default_max_age:f(Number),require_auth_time:f(Boolean),default_acr_values:f([String]),initiate_login_uri:f([y]),request_uris:f([y])};P(e,{client:f(F(C().constructor)),registration_endpoint:y,client_info:t});let r={client:C().with(L()).with(U()),client_info:{redirect_uris:[globalThis.document?.location.href]}};e=Object.assign({},r,e),e.client=e.client.with(L()).with(U()),e.client_info||(e.client_info={}),e.client_info.redirect_uris||(e.client_info.redirect_uris=[globalThis.document?.location.href]);let n=await e.client.post(e.registration_endpoint,{body:e.client_info}),o=n.data;if(!o.client_id)throw m("metro.oidc: Error: dynamic registration of client failed, no client_id returned",n);return e.client_info=Object.assign(e.client_info,o),e.client_info}function te(e){let t;if(typeof localStorage<"u")t={get:r=>JSON.parse(localStorage.getItem("metro/oidc:"+e+":"+r)),set:(r,n)=>localStorage.setItem("metro/oidc:"+e+":"+r,JSON.stringify(n)),has:r=>localStorage.getItem("metro/oidc:"+e+":"+r)!==null};else{let r=new Map;t={get:n=>JSON.parse(r.get("metro/oidc:"+e+":"+n)||null),set:(n,o)=>r.set("metro/oidc:"+e+":"+n,JSON.stringify(o)),has:n=>r.has("metro/oidc:"+e+":"+n)}}return t}var pe=new TextEncoder,H=new TextDecoder,Fn=2**32;function At(...e){let t=e.reduce((o,{length:i})=>o+i,0),r=new Uint8Array(t),n=0;for(let o of e)r.set(o,n),n+=o.length;return r}function Se(e){let t=new Uint8Array(e.length);for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n>127)throw new TypeError("non-ASCII string encountered in encode()");t[r]=n}return t}function xt(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}function $(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof e=="string"?e:H.decode(e),{alphabet:"base64url"});let t=e;t instanceof Uint8Array&&(t=H.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/");try{return xt(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}}var j=(e,t="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`),re=(e,t)=>e.name===t;function Br(e){return parseInt(e.name.slice(4),10)}function je(e,t){if(Br(e.hash)!==t)throw j(`SHA-${t}`,"algorithm.hash")}function Vr(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Fr(e,t){if(t&&!e.usages.includes(t))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function Pt(e,t,r){switch(t){case"HS256":case"HS384":case"HS512":{if(!re(e.algorithm,"HMAC"))throw j("HMAC");je(e.algorithm,parseInt(t.slice(2),10));break}case"RS256":case"RS384":case"RS512":{if(!re(e.algorithm,"RSASSA-PKCS1-v1_5"))throw j("RSASSA-PKCS1-v1_5");je(e.algorithm,parseInt(t.slice(2),10));break}case"PS256":case"PS384":case"PS512":{if(!re(e.algorithm,"RSA-PSS"))throw j("RSA-PSS");je(e.algorithm,parseInt(t.slice(2),10));break}case"Ed25519":case"EdDSA":{if(!re(e.algorithm,"Ed25519"))throw j("Ed25519");break}case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":{if(!re(e.algorithm,t))throw j(t);break}case"ES256":case"ES384":case"ES512":{if(!re(e.algorithm,"ECDSA"))throw j("ECDSA");let n=Vr(t);if(e.algorithm.namedCurve!==n)throw j(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Fr(e,r)}function Tt(e,t,...r){if(r=r.filter(Boolean),r.length>2){let n=r.pop();e+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var Rt=(e,...t)=>Tt("Key must be ",e,...t),ze=(e,t,...r)=>Tt(`Key for the ${e} algorithm must be `,t,...r);var v=class extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(t,r){super(t,r),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}},O=class extends v{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(t,r,n="unspecified",o="unspecified"){super(t,{cause:{claim:n,reason:o,payload:r}}),this.claim=n,this.reason=o,this.payload=r}},me=class extends v{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(t,r,n="unspecified",o="unspecified"){super(t,{cause:{claim:n,reason:o,payload:r}}),this.claim=n,this.reason=o,this.payload=r}},be=class extends v{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},x=class extends v{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"};var E=class extends v{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"},ne=class extends v{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"};var he=class extends v{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"},Ee=class extends v{static code="ERR_JWKS_NO_MATCHING_KEY";code="ERR_JWKS_NO_MATCHING_KEY";constructor(t="no applicable key found in the JSON Web Key Set",r){super(t,r)}},Ae=class extends v{[Symbol.asyncIterator];static code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";constructor(t="multiple matching keys found in the JSON Web Key Set",r){super(t,r)}};var xe=class extends v{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(t="signature verification failed",r){super(t,r)}};var Be=e=>{if(e?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return e instanceof CryptoKey}catch{return!1}},Ve=e=>e?.[Symbol.toStringTag]==="KeyObject",Fe=e=>Be(e)||Ve(e);function Ge(e,t,r){try{return $(e)}catch{throw new r(`Failed to base64url decode the ${t}`)}}var Gr=e=>typeof e=="object"&&e!==null;function W(e){if(!Gr(e)||Object.prototype.toString.call(e)!=="[object Object]")return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function Kt(...e){let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(let n of t){let o=Object.keys(n);if(!r||r.size===0){r=new Set(o);continue}for(let i of o){if(r.has(i))return!1;r.add(i)}}return!0}var ye=e=>W(e)&&typeof e.kty=="string",kt=e=>e.kty!=="oct"&&(e.kty==="AKP"&&typeof e.priv=="string"||typeof e.d=="string"),Ot=e=>e.kty!=="oct"&&e.d===void 0&&e.priv===void 0,Ct=e=>e.kty==="oct"&&typeof e.k=="string";function Yr(e,t){if(e.startsWith("RS")||e.startsWith("PS")){let{modulusLength:r}=t.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}}function qr(e,t){let r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:parseInt(e.slice(-3),10)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"Ed25519":case"EdDSA":return{name:"Ed25519"};case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":return{name:e};default:throw new x(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function Zr(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(Rt(t,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}return Pt(t,e,r),t}async function vt(e,t,r,n){let o=await Zr(e,t,"verify");Yr(e,o);let i=qr(e,o.algorithm);try{return await crypto.subtle.verify(i,o,r,n)}catch{return!1}}var Pe='Invalid or unsupported JWK "alg" (Algorithm) Parameter value';function Qr(e){let t,r;switch(e.kty){case"AKP":{switch(e.alg){case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":t={name:e.alg},r=e.priv?["sign"]:["verify"];break;default:throw new x(Pe)}break}case"RSA":{switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new x(Pe)}break}case"EC":{switch(e.alg){case"ES256":case"ES384":case"ES512":t={name:"ECDSA",namedCurve:{ES256:"P-256",ES384:"P-384",ES512:"P-521"}[e.alg]},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new x(Pe)}break}case"OKP":{switch(e.alg){case"Ed25519":case"EdDSA":t={name:"Ed25519"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new x(Pe)}break}default:throw new x('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}async function oe(e){if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:t,keyUsages:r}=Qr(e),n={...e};return n.kty!=="AKP"&&delete n.alg,delete n.use,crypto.subtle.importKey("jwk",n,t,e.ext??!(e.d||e.priv),e.key_ops??r)}var ie="given KeyObject instance cannot be used for this algorithm",se,It=async(e,t,r,n=!1)=>{se||=new WeakMap;let o=se.get(e);if(o?.[r])return o[r];let i=await oe({...t,alg:r});return n&&Object.freeze(e),o?o[r]=i:se.set(e,{[r]:i}),i},en=(e,t)=>{se||=new WeakMap;let r=se.get(e);if(r?.[t])return r[t];let n=e.type==="public",o=!!n,i;if(e.asymmetricKeyType==="x25519"){switch(t){case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":break;default:throw new TypeError(ie)}i=e.toCryptoKey(e.asymmetricKeyType,o,n?[]:["deriveBits"])}if(e.asymmetricKeyType==="ed25519"){if(t!=="EdDSA"&&t!=="Ed25519")throw new TypeError(ie);i=e.toCryptoKey(e.asymmetricKeyType,o,[n?"verify":"sign"])}switch(e.asymmetricKeyType){case"ml-dsa-44":case"ml-dsa-65":case"ml-dsa-87":{if(t!==e.asymmetricKeyType.toUpperCase())throw new TypeError(ie);i=e.toCryptoKey(e.asymmetricKeyType,o,[n?"verify":"sign"])}}if(e.asymmetricKeyType==="rsa"){let s;switch(t){case"RSA-OAEP":s="SHA-1";break;case"RS256":case"PS256":case"RSA-OAEP-256":s="SHA-256";break;case"RS384":case"PS384":case"RSA-OAEP-384":s="SHA-384";break;case"RS512":case"PS512":case"RSA-OAEP-512":s="SHA-512";break;default:throw new TypeError(ie)}if(t.startsWith("RSA-OAEP"))return e.toCryptoKey({name:"RSA-OAEP",hash:s},o,n?["encrypt"]:["decrypt"]);i=e.toCryptoKey({name:t.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:s},o,[n?"verify":"sign"])}if(e.asymmetricKeyType==="ec"){let a=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(e.asymmetricKeyDetails?.namedCurve);if(!a)throw new TypeError(ie);let p={ES256:"P-256",ES384:"P-384",ES512:"P-521"};p[t]&&a===p[t]&&(i=e.toCryptoKey({name:"ECDSA",namedCurve:a},o,[n?"verify":"sign"])),t.startsWith("ECDH-ES")&&(i=e.toCryptoKey({name:"ECDH",namedCurve:a},o,n?[]:["deriveBits"]))}if(!i)throw new TypeError(ie);return r?r[t]=i:se.set(e,{[t]:i}),i};async function Wt(e,t){if(e instanceof Uint8Array||Be(e))return e;if(Ve(e)){if(e.type==="secret")return e.export();if("toCryptoKey"in e&&typeof e.toCryptoKey=="function")try{return en(e,t)}catch(n){if(n instanceof TypeError)throw n}let r=e.export({format:"jwk"});return It(e,r,t)}if(ye(e))return e.k?$(e.k):It(e,e,t,!0);throw new Error("unreachable")}async function Jt(e,t,r){if(!W(e))throw new TypeError("JWK must be an object");let n;switch(t??=e.alg,n??=r?.extractable??e.ext,e.kty){case"oct":if(typeof e.k!="string"||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return $(e.k);case"RSA":if("oth"in e&&e.oth!==void 0)throw new x('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');return oe({...e,alg:t,ext:n});case"AKP":{if(typeof e.alg!="string"||!e.alg)throw new TypeError('missing "alg" (Algorithm) Parameter value');if(t!==void 0&&t!==e.alg)throw new TypeError("JWK alg and alg option value mismatch");return oe({...e,ext:n})}case"EC":case"OKP":return oe({...e,alg:t,ext:n});default:throw new x('Unsupported "kty" (Key Type) Parameter value')}}function Dt(e,t,r,n,o){if(o.crit!==void 0&&n?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(s=>typeof s!="string"||s.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;r!==void 0?i=new Map([...Object.entries(r),...t.entries()]):i=t;for(let s of n.crit){if(!i.has(s))throw new x(`Extension Header Parameter "${s}" is not recognized`);if(o[s]===void 0)throw new e(`Extension Header Parameter "${s}" is missing`);if(i.get(s)&&n[s]===void 0)throw new e(`Extension Header Parameter "${s}" MUST be integrity protected`)}return new Set(n.crit)}function Ut(e,t){if(t!==void 0&&(!Array.isArray(t)||t.some(r=>typeof r!="string")))throw new TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)}var ae=e=>e?.[Symbol.toStringTag],Xe=(e,t,r)=>{if(t.use!==void 0){let n;switch(r){case"sign":case"verify":n="sig";break;case"encrypt":case"decrypt":n="enc";break}if(t.use!==n)throw new TypeError(`Invalid key for this operation, its "use" must be "${n}" when present`)}if(t.alg!==void 0&&t.alg!==e)throw new TypeError(`Invalid key for this operation, its "alg" must be "${e}" when present`);if(Array.isArray(t.key_ops)){let n;switch(!0){case(r==="sign"||r==="verify"):case e==="dir":case e.includes("CBC-HS"):n=r;break;case e.startsWith("PBES2"):n="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(e):!e.includes("GCM")&&e.endsWith("KW")?n=r==="encrypt"?"wrapKey":"unwrapKey":n=r;break;case(r==="encrypt"&&e.startsWith("RSA")):n="wrapKey";break;case r==="decrypt":n=e.startsWith("RSA")?"unwrapKey":"deriveBits";break}if(n&&t.key_ops?.includes?.(n)===!1)throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}return!0},tn=(e,t,r)=>{if(!(t instanceof Uint8Array)){if(ye(t)){if(Ct(t)&&Xe(e,t,r))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(!Fe(t))throw new TypeError(ze(e,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if(t.type!=="secret")throw new TypeError(`${ae(t)} instances for symmetric algorithms must be of type "secret"`)}},rn=(e,t,r)=>{if(ye(t))switch(r){case"decrypt":case"sign":if(kt(t)&&Xe(e,t,r))return;throw new TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if(Ot(t)&&Xe(e,t,r))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!Fe(t))throw new TypeError(ze(e,t,"CryptoKey","KeyObject","JSON Web Key"));if(t.type==="secret")throw new TypeError(`${ae(t)} instances for asymmetric algorithms must not be of type "secret"`);if(t.type==="public")switch(r){case"sign":throw new TypeError(`${ae(t)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw new TypeError(`${ae(t)} instances for asymmetric algorithm decryption must be of type "private"`)}if(t.type==="private")switch(r){case"verify":throw new TypeError(`${ae(t)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw new TypeError(`${ae(t)} instances for asymmetric algorithm encryption must be of type "public"`)}};function Lt(e,t,r){switch(e.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":tn(e,t,r);break;default:rn(e,t,r)}}async function Ht(e,t,r){if(!W(e))throw new E("Flattened JWS must be an object");if(e.protected===void 0&&e.header===void 0)throw new E('Flattened JWS must have either of the "protected" or "header" members');if(e.protected!==void 0&&typeof e.protected!="string")throw new E("JWS Protected Header incorrect type");if(e.payload===void 0)throw new E("JWS Payload missing");if(typeof e.signature!="string")throw new E("JWS Signature missing or incorrect type");if(e.header!==void 0&&!W(e.header))throw new E("JWS Unprotected Header incorrect type");let n={};if(e.protected)try{let h=$(e.protected);n=JSON.parse(H.decode(h))}catch{throw new E("JWS Protected Header is invalid")}if(!Kt(n,e.header))throw new E("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...n,...e.header},i=Dt(E,new Map([["b64",!0]]),r?.crit,n,o),s=!0;if(i.has("b64")&&(s=n.b64,typeof s!="boolean"))throw new E('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:a}=o;if(typeof a!="string"||!a)throw new E('JWS "alg" (Algorithm) Header Parameter missing or invalid');let p=r&&Ut("algorithms",r.algorithms);if(p&&!p.has(a))throw new be('"alg" (Algorithm) Header Parameter value not allowed');if(s){if(typeof e.payload!="string")throw new E("JWS Payload must be a string")}else if(typeof e.payload!="string"&&!(e.payload instanceof Uint8Array))throw new E("JWS Payload must be a string or an Uint8Array instance");let l=!1;typeof t=="function"&&(t=await t(n,e),l=!0),Lt(a,t,"verify");let d=At(e.protected!==void 0?Se(e.protected):new Uint8Array,Se("."),typeof e.payload=="string"?s?Se(e.payload):pe.encode(e.payload):e.payload),w=Ge(e.signature,"signature",E),T=await Wt(t,a);if(!await vt(a,T,w,d))throw new xe;let c;s?c=Ge(e.payload,"payload",E):typeof e.payload=="string"?c=pe.encode(e.payload):c=e.payload;let u={payload:c};return e.protected!==void 0&&(u.protectedHeader=n),e.header!==void 0&&(u.unprotectedHeader=e.header),l?{...u,key:T}:u}async function Nt(e,t,r){if(e instanceof Uint8Array&&(e=H.decode(e)),typeof e!="string")throw new E("Compact JWS must be a string or Uint8Array");let{0:n,1:o,2:i,length:s}=e.split(".");if(s!==3)throw new E("Invalid Compact JWS");let a=await Ht({payload:o,protected:n,signature:i},t,r),p={payload:a.payload,protectedHeader:a.protectedHeader};return typeof t=="function"?{...p,key:a.key}:p}var nn=e=>Math.floor(e.getTime()/1e3),jt=60,zt=jt*60,Ye=zt*24,on=Ye*7,sn=Ye*365.25,an=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function Mt(e){let t=an.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");let r=parseFloat(t[2]),n=t[3].toLowerCase(),o;switch(n){case"sec":case"secs":case"second":case"seconds":case"s":o=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":o=Math.round(r*jt);break;case"hour":case"hours":case"hr":case"hrs":case"h":o=Math.round(r*zt);break;case"day":case"days":case"d":o=Math.round(r*Ye);break;case"week":case"weeks":case"w":o=Math.round(r*on);break;default:o=Math.round(r*sn);break}return t[1]==="-"||t[4]==="ago"?-o:o}var $t=e=>e.includes("/")?e.toLowerCase():`application/${e.toLowerCase()}`,cn=(e,t)=>typeof e=="string"?t.includes(e):Array.isArray(e)?t.some(Set.prototype.has.bind(new Set(e))):!1;function Bt(e,t,r={}){let n;try{n=JSON.parse(H.decode(t))}catch{}if(!W(n))throw new ne("JWT Claims Set must be a top-level JSON object");let{typ:o}=r;if(o&&(typeof e.typ!="string"||$t(e.typ)!==$t(o)))throw new O('unexpected "typ" JWT header value',n,"typ","check_failed");let{requiredClaims:i=[],issuer:s,subject:a,audience:p,maxTokenAge:l}=r,d=[...i];l!==void 0&&d.push("iat"),p!==void 0&&d.push("aud"),a!==void 0&&d.push("sub"),s!==void 0&&d.push("iss");for(let c of new Set(d.reverse()))if(!(c in n))throw new O(`missing required "${c}" claim`,n,c,"missing");if(s&&!(Array.isArray(s)?s:[s]).includes(n.iss))throw new O('unexpected "iss" claim value',n,"iss","check_failed");if(a&&n.sub!==a)throw new O('unexpected "sub" claim value',n,"sub","check_failed");if(p&&!cn(n.aud,typeof p=="string"?[p]:p))throw new O('unexpected "aud" claim value',n,"aud","check_failed");let w;switch(typeof r.clockTolerance){case"string":w=Mt(r.clockTolerance);break;case"number":w=r.clockTolerance;break;case"undefined":w=0;break;default:throw new TypeError("Invalid clockTolerance option type")}let{currentDate:T}=r,A=nn(T||new Date);if((n.iat!==void 0||l)&&typeof n.iat!="number")throw new O('"iat" claim must be a number',n,"iat","invalid");if(n.nbf!==void 0){if(typeof n.nbf!="number")throw new O('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>A+w)throw new O('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(n.exp!==void 0){if(typeof n.exp!="number")throw new O('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=A-w)throw new me('"exp" claim timestamp check failed',n,"exp","check_failed")}if(l){let c=A-n.iat,u=typeof l=="number"?l:Mt(l);if(c-w>u)throw new me('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(c<0-w)throw new O('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n}async function qe(e,t,r){let n=await Nt(e,t,r);if(n.protectedHeader.crit?.includes("b64")&&n.protectedHeader.b64===!1)throw new ne("JWTs MUST NOT use unencoded payload");let i={payload:Bt(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return typeof t=="function"?{...i,key:n.key}:i}function fn(e){switch(typeof e=="string"&&e.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";case"ML":return"AKP";default:throw new x('Unsupported "alg" value for a JSON Web Key Set')}}function un(e){return e&&typeof e=="object"&&Array.isArray(e.keys)&&e.keys.every(ln)}function ln(e){return W(e)}var Ze=class{#e;#t=new WeakMap;constructor(t){if(!un(t))throw new he("JSON Web Key Set malformed");this.#e=structuredClone(t)}jwks(){return this.#e}async getKey(t,r){let{alg:n,kid:o}={...t,...r?.header},i=fn(n),s=this.#e.keys.filter(l=>{let d=i===l.kty;if(d&&typeof o=="string"&&(d=o===l.kid),d&&(typeof l.alg=="string"||i==="AKP")&&(d=n===l.alg),d&&typeof l.use=="string"&&(d=l.use==="sig"),d&&Array.isArray(l.key_ops)&&(d=l.key_ops.includes("verify")),d)switch(n){case"ES256":d=l.crv==="P-256";break;case"ES384":d=l.crv==="P-384";break;case"ES512":d=l.crv==="P-521";break;case"Ed25519":case"EdDSA":d=l.crv==="Ed25519";break}return d}),{0:a,length:p}=s;if(p===0)throw new Ee;if(p!==1){let l=new Ae,d=this.#t;throw l[Symbol.asyncIterator]=async function*(){for(let w of s)try{yield await Vt(d,w,n)}catch{}},l}return Vt(this.#t,a,n)}};async function Vt(e,t,r){let n=e.get(t)||e.set(t,{}).get(t);if(n[r]===void 0){let o=await Jt({...t,ext:!0},r);if(o instanceof Uint8Array||o.type!=="public")throw new he("JSON Web Key Set members must be public keys");n[r]=o}return n[r]}function Qe(e){let t=new Ze(e),r=async(n,o)=>t.getKey(n,o);return Object.defineProperties(r,{jwks:{value:()=>structuredClone(t.jwks()),enumerable:!1,configurable:!1,writable:!1}}),r}var et=new WeakMap;function dn(e){if(!e||!Array.isArray(e.keys))throw m("metro.oidc: Error: jwks must be an object with a keys array");return et.has(e)||et.set(e,Qe(e)),et.get(e)}function pn(e={}){let t=e.id_token_signing_alg_values_supported;return Array.isArray(t)&&t.length?t.filter(r=>r!=="none"):["RS256"]}async function tt(e,t={}){if(!e)throw m("metro.oidc: Error: token response did not include an id_token");if(!t.jwks)throw m("metro.oidc: Error: cannot validate id_token without jwks");if(!t.issuer)throw m("metro.oidc: Error: cannot validate id_token without issuer");if(!t.client_id)throw m("metro.oidc: Error: cannot validate id_token without client_id");let{payload:r,protectedHeader:n}=await qe(e,dn(t.jwks),{issuer:t.issuer,audience:t.client_id,algorithms:t.algorithms||pn(t.openid_configuration),clockTolerance:t.clockTolerance??60,requiredClaims:["iss","sub","aud","exp","iat"]});if(t.nonce!==void 0&&r.nonce!==t.nonce)throw m("metro.oidc: Error: id_token nonce mismatch");return{header:n,claims:r}}function Te(e={}){let t={client:C(),force_authorization:!1,use_dpop:!0,authorize_callback:async r=>(window.location.href!=r.href&&window.location.replace(r.href),!1)};return e=Object.assign({},t,e),P(e,{client:_(F(C().constructor)),client_info:_(),issuer:_(y),oauth2:f({}),openid_configuration:f()}),e.store||(e.store=te(e.issuer)),!e.openid_configuration&&e.store.has("openid_configuration")&&(e.openid_configuration=e.store.get("openid_configuration")),!e.client_info?.client_id&&e.store.has("client_info")&&(e.client_info=e.store.get("client_info")),async(r,n)=>{let o;if(!e.force_authorization){try{o=await n(r)}catch(w){if(o=w?.cause,!o||o.status!=401&&o.status!=403)throw w}if(o.ok||o.status!=401&&o.status!=403)return o}if(e.openid_configuration||(e.openid_configuration=await Q({issuer:e.issuer,client:e.client.with(e.issuer)}),e.store.set("openid_configuration",e.openid_configuration)),!e.client_info?.client_id){if(!e.openid_configuration.registration_endpoint)throw m("metro.oidcmw: Error: issuer "+e.issuer+" does not support dynamic client registration, but you haven't specified a client_id");e.client_info=await ee({registration_endpoint:e.openid_configuration.registration_endpoint,client:e.client,client_info:e.client_info}),e.store.set("client_info",e.client_info)}let i=e.scope||"openid",s=e.nonce||De(32);e.store.set("pending_nonce",s);let a=Object.assign({site:e.issuer,client:e.client,force_authorization:!0,authorize_callback:e.authorize_callback,oauth2_configuration:{client_id:e.client_info?.client_id,client_secret:e.client_info?.client_secret,grant_type:"authorization_code",response_type:"code",response_mode:"query",authorization_endpoint:e.openid_configuration.authorization_endpoint,token_endpoint:e.openid_configuration.token_endpoint,scope:i,redirect_uri:e.client_info.redirect_uris[0],nonce:s}}),p=async(w,T)=>{let A=await T(w),c=b(e.openid_configuration.token_endpoint,{hash:""}).href;if(b(w.url,{hash:""}).href!==c||!A.headers.get("content-type")?.startsWith("application/json"))return A;let g=A.data&&typeof A.data=="object"?A.data:null;g||(g=await A.clone().json());let k=g?.id_token,Re=await l(),Ft=await tt(k,{issuer:e.openid_configuration.issuer,client_id:e.client_info.client_id,jwks:Re,openid_configuration:e.openid_configuration,nonce:e.store.get("pending_nonce")});return e.store.set("id_token",k),e.store.set("id_token_claims",Ft.claims),A},l=async()=>{if(!e.jwks){let T=await e.client.with(L()).with(U()).get(e.openid_configuration.jwks_uri);e.jwks=T.data}return e.jwks},d=e.client.with(e.issuer).with(p);if(e.use_dpop){let w={site:e.issuer,authorization_endpoint:e.openid_configuration.authorization_endpoint,token_endpoint:e.openid_configuration.token_endpoint,dpop_signing_alg_values_supported:e.openid_configuration.dpop_signing_alg_values_supported};d=d.with($e(w))}return a.client=d,d=d.with(Je(a)),o=await d.fetch(r),o}}function rt(){return wt()}function nt(e){if(!e.store){if(!e.issuer)throw m("Must supply options.issuer or options.store to get the id_token");e.store=te(e.issuer)}return e.store.get("id_token")}function ot(e){if(!e.store){if(!e.issuer)throw m("Must supply options.issuer or options.store to get the id_token claims");e.store=te(e.issuer)}return e.store.get("id_token_claims")}var mn={oidcmw:Te,discover:Q,register:ee,isRedirected:rt,idToken:nt,idTokenClaims:ot},it=mn;var st=Object.assign({},D,globalThis.metro||{});st.oidc||(st.oidc=it);globalThis.metro=st;var Oi=it;})();
1
+ (()=>{var Yt=Object.defineProperty;var ft=(e,t)=>{for(var r in t)Yt(e,r,{get:t[r],enumerable:!0})};var D={};ft(D,{Client:()=>de,client:()=>C,deepClone:()=>pe,metroError:()=>m,request:()=>J,response:()=>z,url:()=>b});var q="https://metro.muze.nl/details/";Symbol.metroProxy||(Symbol.metroProxy=Symbol("isProxy"));Symbol.metroSource||(Symbol.metroSource=Symbol("source"));var de=class e{clientOptions={url:b(typeof window<"u"?window.location:"https://localhost"),verbs:["get","post","put","delete","patch","head","options","query"]};static tracers={};constructor(...t){for(let r of t)if(typeof r=="string"||r instanceof String)this.clientOptions.url=b(this.clientOptions.url.href,r);else if(r instanceof e)Object.assign(this.clientOptions,r.clientOptions);else if(r instanceof Function)this.#e([r]);else if(r&&typeof r=="object")for(let n in r)n=="middlewares"?this.#e(r[n]):n=="url"?this.clientOptions.url=b(this.clientOptions.url.href,r[n]):typeof r[n]=="function"?this.clientOptions[n]=r[n](this.clientOptions[n],this.clientOptions):this.clientOptions[n]=r[n];for(let r of this.clientOptions.verbs)this[r]=async function(...n){return this.fetch(J(this.clientOptions,...n,{method:r.toUpperCase()}),er(...n))}}#e(t){typeof t=="function"&&(t=[t]);let r=t.findIndex(n=>typeof n!="function");if(r>=0)throw m("metro.client: middlewares must be a function or an array of functions "+q+"client/invalid-middlewares/",t[r]);Array.isArray(this.clientOptions.middlewares)||(this.clientOptions.middlewares=[]),this.clientOptions.middlewares=this.clientOptions.middlewares.concat(t)}fetch(t,r){if(t=J(t,r),!t.url)throw m("metro.client."+t.method.toLowerCase()+": Missing url parameter "+q+"client/fetch-missing-url/",t);if(r||(r={}),typeof r!="object"||r instanceof String)throw m("metro.client.fetch: Invalid options parameter "+q+"client/fetch-invalid-options/",r);let o=[async function(l){l[Symbol.metroProxy]&&(l=l[Symbol.metroSource]);let p=await fetch(l);return z(p)}].concat(this.clientOptions?.middlewares?.slice()||[]);r=Object.assign({},this.clientOptions,r);let i=tr(t,r),s=or(this,r,i),a;for(let d of o)a=(function(l,p){return async function(g){let A,R=i.tracers;le(R,"request",g,p,i);try{A=await p(g,l,s)}catch(c){throw le(R,"error",c,g,p,i),c}return le(R,"response",A,p,i),A}})(a,d);return a(t)}with(...t){return new e(pe(this.clientOptions),...t)}get location(){return this.clientOptions.url}},Zt=0,Qt=["trace","tracer","tracers"];function er(...e){let t={};for(let r of e)if(dt(r))for(let n of Qt)n in r&&(t[n]=r[n]);return t}function tr(e,t={}){let r=rr(t.trace||t.tracer||t.tracers),n=[];r?n=r.localTracers||[]:n=ue(t.trace).concat(ue(t.tracer)).concat(ue(t.tracers));let o=Object.values(de.tracers||{});return{__metroTraceContext:!0,id:"metro-trace-context-"+ ++Zt,parent:r,request:e,options:t,globalTracers:o,localTracers:n,tracers:o.concat(n)}}function rr(e){return e?e.context?.__metroTraceContext?e.context:e.__metroTraceContext?e:null:null}function ue(e){return!e||e.__metroTraceContext||e.context?.__metroTraceContext?[]:Array.isArray(e)?e.flatMap(ue):nr(e)?[e]:dt(e)?Object.values(e).flatMap(ue):[]}function nr(e){return e&&typeof e=="object"&&["request","response","error","event","diagnostic","span","link","current"].some(t=>typeof e[t]=="function")}function or(e,t,r){let n=ir(r);return Object.freeze({client:e,options:t,trace:n,fetch(o,i={}){return e.fetch(o,Object.assign({},i,{trace:n}))}})}function ir(e){let t={__metroTraceContext:!0,context:e,event(r,n={}){le(e.tracers,"event",r,n,e)},diagnostic(r={}){le(e.tracers,"diagnostic",r,e)},current(){for(let r of e.tracers)if(typeof r.current=="function"){let n=r.current(e);if(n)return n}return{traceId:null,spanId:null}},async span(r,n,o={}){let i=e.tracers.find(s=>typeof s.span=="function");return i?i.span(r,n,o,e):n()},link(r){let n=null;for(let o of e.tracers)typeof o.link=="function"&&(n=o.link(r,void 0,e)||n);return n},options(r={}){return Object.assign({},r,{trace:t})}};return t}function le(e,t,...r){for(let n of e)n&&typeof n[t]=="function"&&n[t].call(n,...r)}function dt(e){return e&&typeof e=="object"&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null)}function C(...e){return new de(...pe(e))}function sr(e,t){let r=t||{};!r.url&&t.url&&(r.url=t.url);for(let n of["method","headers","body","mode","credentials","cache","redirect","referrer","referrerPolicy","integrity","keepalive","signal","priority","url"]){let o=e[n];if(!(typeof o>"u"||o==null))if(o?.[Symbol.metroProxy]&&(o=o[Symbol.metroSource]),typeof o=="function")r[n]=o(r[n],r);else if(n=="url")r.url=b(r.url,o);else if(n=="headers"){r.headers=new Headers(t.headers),o instanceof Headers||(o=new Headers(e.headers));for(let[i,s]of o.entries())r.headers.set(i,s)}else r[n]=o}return e instanceof Request&&e.data&&(r.body=e.data),r}function J(...e){let t={url:b(typeof window<"u"?window.location:"https://localhost/"),duplex:"half"};for(let o of e)typeof o=="string"||o instanceof URL||o instanceof URLSearchParams?t.url=b(t.url,o):o&&(o instanceof FormData||o instanceof ReadableStream||o instanceof Blob||o instanceof ArrayBuffer||o instanceof DataView)?t.body=o:o&&typeof o=="object"&&Object.assign(t,sr(o,t));let r=new Request(t.url,t),n=t.body;return n&&typeof n=="object"&&!(n instanceof String)&&!(n instanceof ReadableStream)&&!(n instanceof Blob)&&!(n instanceof ArrayBuffer)&&!(n instanceof DataView)&&!(n instanceof FormData)&&!(n instanceof URLSearchParams)&&globalThis.ArrayBuffer&&ArrayBuffer.isView(n)&&typeof n.toString=="function"&&(t.body=n.toString({headers:r.headers}),r=new Request(t.url,t)),Object.freeze(r),new Proxy(r,{get(o,i){let s;switch(i){case Symbol.metroSource:s=o;break;case Symbol.metroProxy:s=!0;break;case"with":s=function(...a){return typeof n<"u"&&a.unshift({body:n}),J(o,...a)};break;case"data":s=n;break;default:o[i]instanceof Function?i==="clone"?s=function(){let a=o.clone();return typeof n<"u"&&!(typeof ReadableStream<"u"&&n instanceof ReadableStream)?J(a,{body:n}):J(a)}:s=o[i].bind(o):s=o[i];break}return s}})}function ut(e,t){let r=t||{};!r.url&&t.url&&(r.url=t.url);for(let n of["status","statusText","headers","body","url","type","redirected"]){let o=e[n];typeof o>"u"||o==null||(o?.[Symbol.metroProxy]&&(o=o[Symbol.metroSource]),typeof o=="function"?r[n]=o(r[n],r):n=="url"?r.url=new URL(o,r.url||"https://localhost/"):r[n]=o)}return e instanceof Response&&e.data&&(r.body=e.data),r}function z(...e){let t={};for(let o of e)typeof o=="string"?t.body=o:o instanceof Response?Object.assign(t,ut(o,t)):o&&typeof o=="object"&&(o instanceof FormData||o instanceof Blob||o instanceof ArrayBuffer||o instanceof DataView||o instanceof ReadableStream||o instanceof URLSearchParams||o instanceof String||typeof globalThis.TypedArray<"u"&&o instanceof globalThis.TypedArray?t.body=o:Object.assign(t,ut(o,t)));let r;t.body&&(r=t.body),[101,204,205,304].includes(t.status)&&(t.body=null);let n=new Response(t.body,t);return Object.freeze(n),new Proxy(n,{get(o,i){let s;switch(i){case Symbol.metroProxy:s=!0;break;case Symbol.metroSource:s=o;break;case"with":s=function(...a){return z(o,...a)};break;case"data":s=r;break;case"ok":s=o.status>=200&&o.status<300;break;default:typeof o[i]=="function"?s=o[i].bind(o):s=o[i];break}return s}})}function lt(e,t){typeof t=="function"?t(e.searchParams,e):(t=new URLSearchParams(t),t.forEach((r,n)=>{e.searchParams.append(n,r)}))}function ar(e,t){let r=e[Symbol.metroSource]||e;t instanceof URLSearchParams||(t=new URLSearchParams(t));let n=r.hash||"#";return n+="?"+t,b(r,{hash:n})}function b(...e){let t=["hash","fragment","host","hostname","href","password","pathname","port","protocol","username","search","searchParams","hashParams"],r=new URL("https://localhost/"),n=null;for(let o of e)if(typeof o=="string"||o instanceof String)r=new URL(o,r);else if(o instanceof URL||typeof Location<"u"&&o instanceof Location)r=new URL(o);else if(o instanceof URLSearchParams)lt(r,o);else if(o&&typeof o=="object")for(let i in o)switch(i){case"search":typeof o.search=="function"?o.search(r.search,r):r.search=new URLSearchParams(o.search);break;case"searchParams":lt(r,o.searchParams);break;default:if(!t.includes(i))throw m("metro.url: unknown url parameter "+q+"url/unknown-param-name/",i);if(i=="fragment"){let s=o.fragment;s&&typeof s=="string"&&s[0]!="#"&&(s="#"+s),o.hash=s,i="hash"}else i=="hashParams"&&(n=o.hashParams);if(typeof o[i]=="function")o[i](r[i],r);else if(typeof o[i]=="string"||o[i]instanceof String||typeof o[i]=="number"||o[i]instanceof Number||typeof o[i]=="boolean"||o[i]instanceof Boolean)r[i]=""+o[i];else if(typeof o[i]=="object"&&o[i].toString)r[i]=o[i].toString();else throw m("metro.url: unsupported value for "+i+" "+q+"url/unsupported-param-value/",e[i]);break}else throw m("metro.url: unsupported option value "+q+"url/unsupported-option-value/",o);return n&&(r.hash||(r.hash="#"),typeof n=="string"?r.hash+=n:r=ar(r,n)),Object.freeze(r),new Proxy(r,{get(o,i){let s;switch(i){case Symbol.metroProxy:s=!0;break;case Symbol.metroSource:s=o;break;case"with":s=function(...a){return b(o,...a)};break;case"filename":s=o.pathname.split("/").pop();break;case"folderpath":s=o.pathname.substring(0,o.pathname.lastIndexOf("/")+1);break;case"authority":s=o.username??"",s+=o.password?":"+o.password:"",s+=s?"@":"",s+=o.hostname,s+=o.port?":"+o.port:"",s+="/",s=o.protocol+"//"+s;break;case"fragment":s=o.hash.substring(1);break;case"scheme":o.protocol?s=o.protocol.substring(0,o.protocol.length-1):s="";break;default:o[i]instanceof Function?s=o[i].bind(o):s=o[i];break}return s}})}var cr={error:(e,...t)=>{console.error("\u24C2\uFE0F ",e,...t)},info:(e,...t)=>{console.info("\u24C2\uFE0F ",e,...t)},group:e=>{console.group("\u24C2\uFE0F "+e)},groupEnd:e=>{console.groupEnd("\u24C2\uFE0F "+e)}};function m(e,...t){return cr.error(e,...t),new Error(e,...t)}function pe(e){if(Array.isArray(e))return e.slice().map(pe);if(e&&typeof e=="object")if(e.__proto__?.constructor==Object||!e.__proto__){let t=Object.assign({},e);return Object.keys(t).forEach(r=>{t[r]=pe(e[r])}),t}else return e;return e}var De={};ft(De,{Optional:()=>f,Recommended:()=>Y,Required:()=>_,allOf:()=>We,anyOf:()=>F,assert:()=>P,disable:()=>ur,enable:()=>fr,error:()=>w,fails:()=>K,formatIssue:()=>ht,formatIssues:()=>yt,instanceOf:()=>G,issues:()=>yr,not:()=>Z,oneOf:()=>k,validEmail:()=>Je,validURL:()=>h,warn:()=>_t});var Ce=!1;function fr(){Ce=!0}function ur(){Ce=!1}function B(e="",t){return(typeof e>"u"||e==null)&&(e=""),typeof t=="number"?`${e}[${t}]`:`${e}.${t}`}function pt(e=""){if(Array.isArray(e))return e;if(!e)return[];let t=[],r=/(?:^|\.)([^.\[\]]+)|\[(\d+)\]/g,n;for(;n=r.exec(e);)typeof n[1]<"u"?t.push(n[1]):typeof n[2]<"u"&&t.push(Number(n[2]));return t}function ve(e=[]){return typeof e=="string"?e.startsWith(".")?e.slice(1):e:e.map((t,r)=>typeof t=="number"?`[${t}]`:`${r?".":""}${t}`).join("")}function Oe(e){return e===String?"string":e===Number?"number":e===Boolean?"boolean":e.name||"function"}function mt(e,t=60){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}function lr(e){return`'${mt(String(e).replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n"))}'`}function dr(e){try{let r=JSON.stringify(e);if(typeof r=="string")return mt(r)}catch{}let t=e?.constructor?.name;return t&&t!="Object"?t:Object.prototype.toString.call(e)}function X(e){return typeof e=="string"?lr(e):typeof e>"u"?"undefined":e===null?"null":typeof e=="function"?Oe(e):e instanceof RegExp?e.toString():typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"?String(e):typeof e=="symbol"?e.toString():dr(e)}function V(e){return e===String||e===Number||e===Boolean||typeof e=="function"?Oe(e):e instanceof RegExp?e.toString():Array.isArray(e)?"["+e.map(V).join(", ")+"]":X(e)}function pr(e){return e.map(V).join(", ")}function mr(e,t,r){return e=="data and pattern are not equal"?`expected ${X(r)}, found ${X(t)}`:e=="data does not match pattern"||/^data\[\d+\] does not match pattern$/.test(e)?`expected ${V(r)}, found ${X(t)}`:e=="data is undefined, should match pattern"?`missing; expected ${V(r)}`:e=="data is required"?"required":e=="data is an empty string, which is not allowed"?"empty string is not allowed":e=="data is not an object, pattern is"?"data is not an object":e=="data is not an instanceof pattern"?`expected instance of ${V(r)}, found ${X(t)}`:e=="data does not match oneOf patterns"||e=="data does not match anyOf patterns"?`expected one of ${pr(r)}, found ${X(t)}`:e=="data matches pattern, when required not to"?`must not match ${V(r)}`:e}function ht(e,t={}){if(!e||typeof e!="object")return String(e);let r=e.pathString||ve(e.path||[])||"value";return`${t.indent??""}${r}: ${e.message}`}function yt(e,t={}){if(!e)return!1;let r=t.indent??" - ";return(Array.isArray(e)?e:[e]).map(n=>ht(n,{...t,indent:r}))}function hr(e){if(!e||typeof e!="object")return{path:[],pathString:"",message:String(e),expected:void 0,actual:void 0};let t=pt(e.path),r=ve(t),n=e.actual??e.found,o=V(e.expected),i=mr(e.message,n,e.expected);return{path:t,pathString:r,message:i,expected:o,actual:n}}function Ie(e){if(!e)return[];let t=[];for(let r of Array.isArray(e)?e:[e])if(r){if(r&&typeof r=="object"&&r.problems){let n=Ie(r.problems);if(n.length){t=t.concat(n);continue}}t.push(hr(r))}return t}function P(e,t){if(Ce){let r=K(e,t);if(r){let n=Ie(r),i=`Assertions failed:
2
+ `+yt(n).join(`
3
+ `);throw console.error("\u{1F170}\uFE0F "+i),new Error(i,{cause:{problems:r,issues:n,source:e}})}}}function f(e){return function(r,n,o){if(typeof r<"u"&&r!=null&&typeof e<"u")return K(r,e,n,o)}}function _(e){return function(r,n,o){return r==null||typeof r>"u"?w("data is required",r,e||"any value",o):typeof e<"u"?K(r,e,n,o):!1}}function Y(e){return function(r,n,o){return r==null||typeof r>"u"?(_t("data does not contain recommended value",r,e,o),!1):K(r,e,n,o)}}function k(...e){return function(r,n,o){for(let i of e)if(!K(r,i,n,o))return!1;return w("data does not match oneOf patterns",r,e,o)}}function F(...e){return function(r,n,o){if(!Array.isArray(r))return w("data is not an array",r,"anyOf",o);for(let[i,s]of r.entries()){let a=B(o,i);if(k(...e)(s,n,a))return w("data does not match anyOf patterns",s,e,a)}return!1}}function We(...e){return function(r,n,o){let i=[];for(let s of e)i=i.concat(K(r,s,n,o));if(i=i.filter(Boolean),i.length)return w("data does not match all given patterns",r,e,o,i)}}function h(e,t,r){try{e instanceof URL&&(e=e.href);let n=new URL(e);if(n.href!=e&&!(n.href+"/"==e||n.href==e+"/"))return w("data is not a valid url",e,"validURL",r)}catch{return w("data is not a valid url",e,"validURL",r)}}function Je(e,t,r){if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e))return w("data is not a valid email",e,"validEmail",r)}function G(e){return function(r,n,o){if(!(r instanceof e))return w("data is not an instanceof pattern",r,e,o)}}function Z(e){return function(r,n,o){if(!K(r,e,n,o))return w("data matches pattern, when required not to",r,e,o)}}function yr(e,t,r){let n=K(e,t,r);return n?Ie(n):!1}function K(e,t,r,n=""){typeof r>"u"&&(r=e);let o=[];if(t===Boolean)typeof e!="boolean"&&!(e instanceof Boolean)&&o.push(w("data is not a boolean",e,t,n));else if(t===Number)typeof e!="number"&&!(e instanceof Number)&&o.push(w("data is not a number",e,t,n));else if(t===String)typeof e!="string"&&!(e instanceof String)&&o.push(w("data is not a string",e,t,n)),e==""&&o.push(w("data is an empty string, which is not allowed",e,t,n));else if(t instanceof RegExp)if(Array.isArray(e)){let i=e.findIndex((s,a)=>K(s,t,r,B(n,a)));i>-1&&o.push(w("data["+i+"] does not match pattern",e[i],t,B(n,i)))}else typeof e>"u"?o.push(w("data is undefined, should match pattern",e,t,n)):t.test(e)||o.push(w("data does not match pattern",e,t,n));else if(t instanceof Function){let i=t(e,r,n);i&&(Array.isArray(i)?o=o.concat(i):o.push(i))}else if(Array.isArray(t))if(!Array.isArray(e))o.push(w("data is not an array",e,[],n));else for(let i of t)for(let s of e.keys()){let a=K(e[s],i,r,B(n,s));Array.isArray(a)?o=o.concat(a):a&&o.push(a)}else if(t&&typeof t=="object")if(Array.isArray(e)){let i=e.findIndex((s,a)=>K(s,t,r,B(n,a)));i>-1&&o.push(w("data["+i+"] does not match pattern",e[i],t,B(n,i)))}else if(!e||typeof e!="object")o.push(w("data is not an object, pattern is",e,t,n));else if(e instanceof URLSearchParams&&(e=Object.fromEntries(e)),t instanceof Function){let i=K(e,t,r,n);i&&(o=o.concat(i))}else for(let[i,s]of Object.entries(t)){let a=K(e[i],s,r,B(n,i));a&&(o=o.concat(a))}else t!=e&&o.push(w("data and pattern are not equal",e,t,n));return o.length?o:!1}function w(e,t,r,n="",o){let i=pt(n),s={path:n,pathString:ve(i),pathParts:i,message:e,found:t,expected:r};return o&&(s.problems=o),s}function _t(e,t,r,n){console.warn("\u{1F170}\uFE0F Assert: "+n,e,r,t)}globalThis.assert={...De};function wt(e){let t,r;if(typeof localStorage<"u")t={get:()=>localStorage.getItem("metro/state:"+e),set:n=>localStorage.setItem("metro/state:"+e,n),has:()=>localStorage.getItem("metro/state:"+e)!==null,delete:()=>localStorage.removeItem("metro/state:"+e)},r={get:n=>JSON.parse(localStorage.getItem(e+":"+n)),set:(n,o)=>localStorage.setItem(e+":"+n,JSON.stringify(o)),has:n=>localStorage.getItem(e+":"+n)!==null,delete:n=>localStorage.removeItem(e+":"+n)};else{let n=new Map;t={get:()=>n.get("metro/state:"+e),set:o=>n.set("metro/state:"+e,o),has:()=>n.has("metro/state:"+e),delete:()=>n.delete("metro/state:"+e)},r=new Map}return{state:t,tokens:r}}var _r=new Map([["bearer","Bearer"],["dpop","DPoP"]]),wr=new Set(["none","client_secret_post","client_secret_basic"]);function Ue(e){let t={client:C(),force_authorization:!1,site:"default",oauth2_configuration:{authorization_endpoint:"/authorize",token_endpoint:"/token",redirect_uri:globalThis.document?.location.href,grant_type:"authorization_code",code_verifier:Le(64)},authorize_callback:async c=>(window.location.href!=c.href&&window.location.replace(c.href),!1)};P(e,{});let r=Object.assign({},t.oauth2_configuration,e?.oauth2_configuration);e=Object.assign({},t,e),e.oauth2_configuration=r;let n=wt(e.site);e.tokens||(e.tokens=n.tokens),e.state||(e.state=n.state),P(e,{oauth2_configuration:{client_id:_(/.+/),grant_type:"authorization_code",authorization_endpoint:_(h),token_endpoint:_(h),redirect_uri:_(h)}});for(let c in r)switch(c){case"access_token":case"authorization_code":case"refresh_token":e.tokens.set(c,gr(c,r[c]));break}return async function(c,u){if(e.force_authorization)return o(c,u);let y=await u(c);return y.ok||!gt(y)?y:o(c,u)};async function o(c,u,y={}){i();let S=e.tokens.get("access_token"),T=e.tokens.get("refresh_token"),ce=Rr(S);if(!S||ce&&!T)return await s()?o(c,u):z("false");if(ce&&T)return await a()?o(c,u):z("false");{let fe=J(c,{headers:{Authorization:S.type+" "+S.value}}),ge=await u(fe);return!gt(ge)||y.handledRejectedToken?ge:(e.tokens.delete("access_token"),(T?await a():await s())?o(c,u,{handledRejectedToken:!0}):z("false"))}}function i(){if(typeof window<"u"&&window?.location){let c=b(window.location),u,y,S;if(c.searchParams.has("code")||c.searchParams.has("error"))S=c.searchParams,c=c.with({search:""}),history.pushState({},"",c.href);else if(c.hash){let T=c.hash.substr(1);S=new URLSearchParams("?"+T),c=c.with({hash:""}),history.pushState({},"",c.href)}if(S){if(S.has("error"))throw m("oauth2mw: authorization failed: "+S.get("error")+(S.get("error_description")?" ("+S.get("error_description")+")":""));u=S.get("code"),y=S.get("state"),A(y),u&&e.tokens.set("authorization_code",u)}}}async function s(){if(r.grant_type==="authorization_code"&&!e.tokens.has("authorization_code")){let S=await d();if(!e.authorize_callback||typeof e.authorize_callback!="function")throw m("oauth2mw: oauth2 with grant_type:authorization_code requires a callback function in client options.authorize_callback");let T=await e.authorize_callback(S);if(T)g(T);else return!1}let c=l(),u=await e.client.post(c);if(!u.ok){let S=await u.text();throw m("OAuth2mw: fetch access_token: "+u.status+": "+u.statusText+" ("+S+")",{cause:c})}let y=await u.json();return R(y),e.tokens.delete("authorization_code"),y}async function a(){let c=l("refresh_token"),u=await e.client.post(c);if(!u.ok){let S=await u.text();throw m("OAuth2mw: refresh access_token: "+u.status+": "+u.statusText+" ("+S+")",{cause:c})}let y=await u.json();return R(y),y}async function d(){if(!r.authorization_endpoint)throw m("oauth2mw: Missing options.oauth2_configuration.authorization_endpoint");let c=b(r.authorization_endpoint,{hash:""});P(r,{client_id:/.+/,redirect_uri:/.+/,scope:/.*/});let u={response_type:"code",client_id:r.client_id,redirect_uri:r.redirect_uri,state:r.state||Kr(40)};return r.response_type&&(u.response_type=r.response_type),r.response_mode&&(u.response_mode=r.response_mode),e.state.set(u.state),r.code_verifier&&(e.tokens.set("code_verifier",r.code_verifier),u.code_challenge=await kr(r.code_verifier),u.code_challenge_method="S256"),r.scope&&(u.scope=r.scope),r.prompt&&(u.prompt=r.prompt),r.nonce&&(u.nonce=r.nonce),b(c,{search:u})}function l(c=null){if(P(r,{client_id:/.+/,redirect_uri:/.+/}),!r.token_endpoint)throw m("oauth2mw: Missing options.endpoints.token url");let u=b(r.token_endpoint,{hash:""}),y={grant_type:c||r.grant_type},S={};switch(p(y,S),r.scope&&(y.scope=r.scope),y.grant_type){case"authorization_code":y.redirect_uri=r.redirect_uri,y.code=e.tokens.get("authorization_code");let T=e.tokens.get("code_verifier");T&&(y.code_verifier=T);break;case"client_credentials":break;case"refresh_token":y.refresh_token=Pr(e.tokens.get("refresh_token"));break;default:throw new Error("Unknown grant_type: "+y.grant_type)}return J(u,{method:"POST",headers:S,body:new URLSearchParams(y)})}function p(c,u){let y=Er(r);if(y==="none"){c.client_id=r.client_id;return}if(!r.client_secret)throw m("oauth2mw: token_endpoint_auth_method "+y+" requires oauth2_configuration.client_secret");if(y==="client_secret_post"){c.client_id=r.client_id,c.client_secret=r.client_secret;return}if(y==="client_secret_basic"){u.Authorization=Ar(r.client_id,r.client_secret);return}}function g(c){let u=c;if(c&&typeof c=="object"){if(c.error)throw m("oauth2mw: authorization failed: "+c.error);A(c.state),u=c.authorization_code||c.code}if(!u)throw m("oauth2mw: authorization callback did not return an authorization code");e.tokens.set("authorization_code",u)}function A(c){let u=e.state.get();if(!c||c!==u)throw m("oauth2mw: authorization state mismatch")}function R(c){let u=Sr(c);e.tokens.set("access_token",u),c.refresh_token&&e.tokens.set("refresh_token",{value:c.refresh_token})}}function gt(e){return e?e.status===400?!0:Or(e.headers?.get("WWW-Authenticate"))?.error==="insufficient_scope"?!1:e.status===401:!1}function gr(e,t){return e==="access_token"&&t&&typeof t=="object"?t:e==="access_token"?{value:t,type:"Bearer",expires:null}:t}function Sr(e){if(!e||typeof e!="object")throw m("OAuth2mw: token endpoint did not return a JSON object");if(!e.access_token)throw m("OAuth2mw: token response did not include access_token");if(!e.token_type)throw m("OAuth2mw: token response did not include token_type");let t=br(e.token_type);return{value:e.access_token,expires:e.expires_in===void 0?null:Tr(e.expires_in),type:t,scope:e.scope}}function br(e){let t=_r.get(String(e).toLowerCase());if(!t)throw m("OAuth2mw: unsupported token_type "+e);return t}function Er(e){let t=e.token_endpoint_auth_method||(e.client_secret?"client_secret_post":"none");if(!wr.has(t))throw m("oauth2mw: unsupported token_endpoint_auth_method "+t);return t}function Ar(e,t){let r=St(e)+":"+St(t);return"Basic "+xr(r)}function St(e){return encodeURIComponent(e).replace(/%20/g,"+")}function xr(e){return typeof btoa=="function"?btoa(e):Buffer.from(e,"binary").toString("base64")}function Pr(e){return e&&typeof e=="object"?e.value:e}function Rr(e){if(!e)return!0;if(!e.expires)return!1;let t=new Date(e.expires);return new Date().getTime()>t.getTime()}function Tr(e){if(e instanceof Date)return new Date(e.getTime());if(typeof e=="number"){let t=new Date;return t.setSeconds(t.getSeconds()+e),t}throw new TypeError("Unknown expires type "+e)}function Le(e=64){let t=new Uint8Array(e);return globalThis.crypto.getRandomValues(t),He(t)}async function kr(e){let r=new TextEncoder().encode(e),n=await globalThis.crypto.subtle.digest("SHA-256",r);return He(n)}function He(e){let t=Array.from(new Uint8Array(e),r=>String.fromCharCode(r)).join("");return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Kr(e){let t=new Uint8Array(Math.ceil(e*3/4)+1);if(globalThis.crypto?.getRandomValues)return globalThis.crypto.getRandomValues(t),He(t).slice(0,e);let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n="",o=0;for(;o<e;)n+=r.charAt(Math.floor(Math.random()*r.length)),o++;return n}function bt(){let e=new URL(document.location.href);if(!e.searchParams.has("code")){if(e.hash){let t=e.hash.substr(1);if(new URLSearchParams("?"+t).has("code"))return!0}return!1}return!0}function Or(e){if(!e||typeof e!="string")return null;let t=e.trim(),r=t.search(/\s/),n=r<0?t:t.slice(0,r),o=r<0?"":t.slice(r+1);if(!["bearer","dpop"].includes(n.toLowerCase()))return null;let i={scheme:n},s=/([A-Za-z][A-Za-z0-9_-]*)=("(?:[^"\\]|\\.)*"|[^,\s]*)/g,a;for(;a=s.exec(o);){let d=a[2];d.startsWith('"')&&d.endsWith('"')&&(d=d.slice(1,-1).replace(/\\"/g,'"')),i[a[1]]=d}return i}var vr=new TextEncoder,Ir=new TextDecoder;function Se(e){return typeof e=="string"?vr.encode(e):Ir.decode(e)}function Et(e){if(typeof e.modulusLength!="number"||e.modulusLength<2048)throw new Me(`${e.name} modulusLength must be at least 2048 bits`)}function Wr(e){switch(e.algorithm.name){case"ECDSA":return{name:e.algorithm.name,hash:"SHA-256"};case"RSA-PSS":return Et(e.algorithm),{name:e.algorithm.name,saltLength:32};case"RSASSA-PKCS1-v1_5":return Et(e.algorithm),{name:e.algorithm.name};case"Ed25519":return{name:e.algorithm.name}}throw new N}async function Jr(e,t,r){if(r.usages.includes("sign")===!1)throw new TypeError('private CryptoKey instances used for signing assertions must include "sign" in their "usages"');let n=`${be(Se(JSON.stringify(e)))}.${be(Se(JSON.stringify(t)))}`,o=be(await crypto.subtle.sign(Wr(r),r,Se(n)));return`${n}.${o}`}var Ne;Uint8Array.prototype.toBase64?Ne=e=>(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e.toBase64({alphabet:"base64url",omitPadding:!0})):Ne=t=>{t instanceof ArrayBuffer&&(t=new Uint8Array(t));let r=[];for(let n=0;n<t.byteLength;n+=32768)r.push(String.fromCharCode.apply(null,t.subarray(n,n+32768)));return btoa(r.join("")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")};function be(e){return Ne(e)}var N=class extends Error{constructor(t){var r;super(t??"operation not supported"),this.name=this.constructor.name,(r=Error.captureStackTrace)===null||r===void 0||r.call(Error,this,this.constructor)}},Me=class extends Error{constructor(t){var r;super(t),this.name=this.constructor.name,(r=Error.captureStackTrace)===null||r===void 0||r.call(Error,this,this.constructor)}};function Dr(e){if(e.algorithm.hash.name==="SHA-256")return"PS256";throw new N("unsupported RsaHashedKeyAlgorithm hash name")}function Ur(e){if(e.algorithm.hash.name==="SHA-256")return"RS256";throw new N("unsupported RsaHashedKeyAlgorithm hash name")}function Lr(e){if(e.algorithm.namedCurve==="P-256")return"ES256";throw new N("unsupported EcKeyAlgorithm namedCurve")}function Hr(e){switch(e.algorithm.name){case"RSA-PSS":return Dr(e);case"RSASSA-PKCS1-v1_5":return Ur(e);case"ECDSA":return Lr(e);case"Ed25519":return"Ed25519";default:throw new N("unsupported CryptoKey algorithm name")}}function At(e){return e instanceof CryptoKey}function Nr(e){return At(e)&&e.type==="private"}function Mr(e){return At(e)&&e.type==="public"}function jr(){return Math.floor(Date.now()/1e3)}async function je(e,t,r,n,o,i){let s=e?.privateKey,a=e?.publicKey;if(!Nr(s))throw new TypeError('"keypair.privateKey" must be a private CryptoKey');if(!Mr(a))throw new TypeError('"keypair.publicKey" must be a public CryptoKey');if(a.extractable!==!0)throw new TypeError('"keypair.publicKey.extractable" must be true');if(typeof t!="string")throw new TypeError('"htu" must be a string');if(typeof r!="string")throw new TypeError('"htm" must be a string');if(n!==void 0&&typeof n!="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 Jr({alg:Hr(s),typ:"dpop+jwt",jwk:await $r(a)},Object.assign(Object.assign({},i),{iat:jr(),jti:crypto.randomUUID(),htm:r,nonce:n,htu:t,ath:o?be(await crypto.subtle.digest("SHA-256",Se(o))):void 0}),s)}async function $r(e){let{kty:t,e:r,n,x:o,y:i,crv:s}=await crypto.subtle.exportKey("jwk",e);return{kty:t,crv:s,e:r,n,x:o,y:i}}async function xt(e,t){var r;let n;if(typeof e!="string"||e.length===0)throw new TypeError('"alg" must be a non-empty string');switch(e){case"PS256":n={name:"RSA-PSS",hash:"SHA-256",modulusLength:2048,publicExponent:new Uint8Array([1,0,1])};break;case"RS256":n={name:"RSASSA-PKCS1-v1_5",hash:"SHA-256",modulusLength:2048,publicExponent:new Uint8Array([1,0,1])};break;case"ES256":n={name:"ECDSA",namedCurve:"P-256"};break;case"Ed25519":n={name:"Ed25519"};break;default:throw new N}return crypto.subtle.generateKey(n,(r=t?.extractable)!==null&&r!==void 0?r:!1,["sign","verify"])}function $e(){return new Promise((e,t)=>{let r=globalThis.indexedDB.open("metro",1);r.onupgradeneeded=()=>r.result.createObjectStore("keyPairs",{keyPath:"domain"}),r.onerror=n=>{t(n)},r.onsuccess=n=>{let o=n.target.result;e({set:function(i,s){return new Promise((a,d)=>{let l=o.transaction("keyPairs","readwrite",{durability:"strict"}),p=l.objectStore("keyPairs");l.oncomplete=()=>{a()},l.onerror=d,p.put(i,s)})},get:function(i){return new Promise((s,a)=>{let d=o.transaction("keyPairs","readonly"),p=d.objectStore("keyPairs").get(i);p.onsuccess=()=>{s(p.result)},p.onerror=a,d.onerror=a})},clear:function(){return new Promise((i,s)=>{let a=o.transaction("keyPairs","readwrite"),l=a.objectStore("keyPairs").clear();l.onsuccess=()=>{i()},l.onerror=s,a.onerror=s})}})}})}function ze(e){return P(e,{site:_(h),authorization_endpoint:_(h),token_endpoint:_(h),dpop_signing_alg_values_supported:f([])}),async(t,r)=>{let n=await $e(),o=await n.get(e.site);if(!o){let a=await xt("ES256");o={domain:e.site,keyPair:a},await n.set(o)}let i=b(t.url);if(t.url.startsWith(e.authorization_endpoint)){let a=t.body;a instanceof URLSearchParams||a instanceof FormData?a.set("dpop_jkt",o.keyPair.publicKey):a.dpop_jkt=o.keyPair.publicKey}else if(t.url.startsWith(e.token_endpoint)){let a=await je(o.keyPair,t.url,t.method);t=t.with({headers:{DPoP:a}})}else if(t.headers.has("Authorization")){let a=localStorage.getItem(i.host+":nonce")||void 0,d=t.headers.get("Authorization").split(" ")[1],l=await je(o.keyPair,t.url,t.method,a,d);t=t.with({headers:{Authorization:"DPoP "+d,DPoP:l}})}let s=await r(t);return s.headers.get("DPoP-Nonce")&&localStorage.setItem(i.host+":nonce",s.headers.get("DPoP-Nonce")),s}}function U(e){return e=Object.assign({contentType:"application/json",reviver:null,replacer:null,space:""},e),async function(r,n){if(r.headers.get("Accept")||(r=r.with({headers:{Accept:e.accept??e.contentType}})),r.method!=="GET"&&r.method!=="HEAD"&&r.data&&typeof r.data=="object"&&!(r.data instanceof ReadableStream)){let i=r.headers.get("Content-Type");(!i||Fr(i))&&(r=r.with({headers:{"Content-Type":e.contentType}})),Pt(r.headers.get("Content-Type"))&&(r=r.with({body:JSON.stringify(r.data,e.replacer,e.space)}))}let o=await n(r);if(o&&Pt(o.headers?.get("Content-Type"))){let s=await o.clone().text();if(s==="")return o;try{let a=JSON.parse(s,e.reviver);return o.with({body:a})}catch(a){if(!o.ok)return o;throw Br(r,o,a)}}return o}}function Br(e,t,r){let n="jsonmw: could not parse "+t.headers.get("Content-Type")+" response from "+e.url,o=new Error(n,{cause:r});return o.request=e,o.response=t,o}var Vr=/^application\/([a-zA-Z0-9\-_]+\+)?json\b/;function Pt(e){return Vr.exec(e)}function Fr(e){return/^text\/plain\b/.exec(e)}function L(e){return async function(r,n){let o=await n(r);if(!o.ok)if(e&&typeof e[o.status]=="function")o=e[o.status].apply(o,r);else throw new Error(o.status+": "+o.statusText,{cause:o});return o}}var me=(...e)=>(t,r)=>e.filter(n=>r.hasOwnKey(n)).length>0?!1:w("root data must have all of",r,e),M=(...e)=>t=>Array.isArray(t)&&e.filter(r=>!t.includes(r)).length==0?!1:w("data must be an array which includes",t,e);var I=["HS256","HS384","HS512","RS256","RS384","RS512","ES256","ES384","ES512"],Ee=["none","client_secret_post","client_secret_basic","client_secret_jwt","private_key_jwt"];async function Q(e={}){P(e,{client:f(G(C().constructor)),issuer:_(h)});let t={client:C().with(L()).with(U()),requireDynamicRegistration:!1};e=Object.assign({},t,e),e.client=e.client.with(L()).with(U());let r=!1;function n(d){return r}let o={issuer:_(We(e.issuer,n)),authorization_endpoint:_(h),token_endpoint:_(h),userinfo_endpoint:Y(h),jwks_uri:_(h),registration_endpoint:e.requireDynamicRegistration?_(h):Y(h),scopes_supported:Y(M("openid")),response_types_supported:e.requireDynamicRegistration?_(M("code","id_token","id_token token")):_([]),response_modes_supported:f([]),grant_types_supported:e.requireDynamicRegistration?f(M("authorization_code")):f([]),acr_values_supported:f([]),subject_types_supported:_([]),id_token_signing_alg_values_supported:_(M("RS256")),id_token_encryption_alg_values_supported:f([]),id_token_encryption_enc_values_supported:f([]),userinfo_signing_alg_values_supported:f([]),userinfo_encryption_alg_values_supported:f([]),userinfo_encryption_enc_values_supported:f([]),request_object_signing_alg_values_supported:f(M("RS256")),request_object_encryption_alg_values_supported:f([]),request_object_encryption_enc_values_supported:f([]),token_endpoint_auth_methods_supported:f(F(...Ee)),token_endpoint_auth_signing_alg_values_supported:f(M("RS256"),Z(M("none"))),display_values_supported:f(F("page","popup","touch","wap")),claim_types_supported:f(F("normal","aggregated","distributed")),claims_supported:Y([]),service_documentation:f(h),claims_locales_supported:f([]),ui_locales_supported:f([]),claims_parameter_supported:f(Boolean),request_parameter_supported:f(Boolean),request_uri_parameter_supported:f(Boolean),op_policy_uri:f(h),op_tos_uri:f(h)},i=b(e.issuer,".well-known/openid-configuration"),a=(await e.client.get(i)).data;return P(a,o),P(a.issuer,e.issuer),a}async function ee(e){let t={redirect_uris:_([h]),response_types:f([]),grant_types:f(F("authorization_code","refresh_token")),application_type:f(k("native","web")),contacts:f([Je]),client_name:f(String),logo_uri:f(h),client_uri:f(h),policy_uri:f(h),tos_uri:f(h),jwks_uri:f(h,Z(me("jwks"))),jwks:f(h,Z(me("jwks_uri"))),sector_identifier_uri:f(h),subject_type:f(String),id_token_signed_response_alg:f(k(...I)),id_token_encrypted_response_alg:f(k(...I)),id_token_encrypted_response_enc:f(k(...I),me("id_token_encrypted_response_alg")),userinfo_signed_response_alg:f(k(...I)),userinfo_encrypted_response_alg:f(k(...I)),userinfo_encrypted_response_enc:f(k(...I),me("userinfo_encrypted_response_alg")),request_object_signing_alg:f(k(...I)),request_object_encryption_alg:f(k(...I)),request_object_encryption_enc:f(k(...I)),token_endpoint_auth_method:f(k(...Ee)),token_endpoint_auth_signing_alg:f(k(...I)),default_max_age:f(Number),require_auth_time:f(Boolean),default_acr_values:f([String]),initiate_login_uri:f([h]),request_uris:f([h])};P(e,{client:f(G(C().constructor)),registration_endpoint:h,client_info:t});let r={client:C().with(L()).with(U()),client_info:{redirect_uris:[globalThis.document?.location.href]}};e=Object.assign({},r,e),e.client=e.client.with(L()).with(U()),e.client_info||(e.client_info={}),e.client_info.redirect_uris||(e.client_info.redirect_uris=[globalThis.document?.location.href]);let n=await e.client.post(e.registration_endpoint,{body:e.client_info}),o=n.data;if(!o.client_id)throw m("metro.oidc: Error: dynamic registration of client failed, no client_id returned",n);return e.client_info=Object.assign(e.client_info,o),e.client_info}function te(e){let t;if(typeof localStorage<"u")t={get:r=>JSON.parse(localStorage.getItem("metro/oidc:"+e+":"+r)),set:(r,n)=>localStorage.setItem("metro/oidc:"+e+":"+r,JSON.stringify(n)),has:r=>localStorage.getItem("metro/oidc:"+e+":"+r)!==null};else{let r=new Map;t={get:n=>JSON.parse(r.get("metro/oidc:"+e+":"+n)||null),set:(n,o)=>r.set("metro/oidc:"+e+":"+n,JSON.stringify(o)),has:n=>r.has("metro/oidc:"+e+":"+n)}}return t}var he=new TextEncoder,H=new TextDecoder,Xn=2**32;function Rt(...e){let t=e.reduce((o,{length:i})=>o+i,0),r=new Uint8Array(t),n=0;for(let o of e)r.set(o,n),n+=o.length;return r}function Ae(e){let t=new Uint8Array(e.length);for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n>127)throw new TypeError("non-ASCII string encountered in encode()");t[r]=n}return t}function Tt(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}function j(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof e=="string"?e:H.decode(e),{alphabet:"base64url"});let t=e;t instanceof Uint8Array&&(t=H.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/");try{return Tt(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}}var $=(e,t="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`),re=(e,t)=>e.name===t;function Gr(e){return parseInt(e.name.slice(4),10)}function Be(e,t){if(Gr(e.hash)!==t)throw $(`SHA-${t}`,"algorithm.hash")}function qr(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Xr(e,t){if(t&&!e.usages.includes(t))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function kt(e,t,r){switch(t){case"HS256":case"HS384":case"HS512":{if(!re(e.algorithm,"HMAC"))throw $("HMAC");Be(e.algorithm,parseInt(t.slice(2),10));break}case"RS256":case"RS384":case"RS512":{if(!re(e.algorithm,"RSASSA-PKCS1-v1_5"))throw $("RSASSA-PKCS1-v1_5");Be(e.algorithm,parseInt(t.slice(2),10));break}case"PS256":case"PS384":case"PS512":{if(!re(e.algorithm,"RSA-PSS"))throw $("RSA-PSS");Be(e.algorithm,parseInt(t.slice(2),10));break}case"Ed25519":case"EdDSA":{if(!re(e.algorithm,"Ed25519"))throw $("Ed25519");break}case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":{if(!re(e.algorithm,t))throw $(t);break}case"ES256":case"ES384":case"ES512":{if(!re(e.algorithm,"ECDSA"))throw $("ECDSA");let n=qr(t);if(e.algorithm.namedCurve!==n)throw $(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Xr(e,r)}function Kt(e,t,...r){if(r=r.filter(Boolean),r.length>2){let n=r.pop();e+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var Ot=(e,...t)=>Kt("Key must be ",e,...t),Ve=(e,t,...r)=>Kt(`Key for the ${e} algorithm must be `,t,...r);var v=class extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(t,r){super(t,r),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}},O=class extends v{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(t,r,n="unspecified",o="unspecified"){super(t,{cause:{claim:n,reason:o,payload:r}}),this.claim=n,this.reason=o,this.payload=r}},ye=class extends v{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(t,r,n="unspecified",o="unspecified"){super(t,{cause:{claim:n,reason:o,payload:r}}),this.claim=n,this.reason=o,this.payload=r}},xe=class extends v{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},x=class extends v{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"};var E=class extends v{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"},ne=class extends v{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"};var _e=class extends v{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"},Pe=class extends v{static code="ERR_JWKS_NO_MATCHING_KEY";code="ERR_JWKS_NO_MATCHING_KEY";constructor(t="no applicable key found in the JSON Web Key Set",r){super(t,r)}},Re=class extends v{[Symbol.asyncIterator];static code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";constructor(t="multiple matching keys found in the JSON Web Key Set",r){super(t,r)}};var Te=class extends v{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(t="signature verification failed",r){super(t,r)}};var Fe=e=>{if(e?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return e instanceof CryptoKey}catch{return!1}},Ge=e=>e?.[Symbol.toStringTag]==="KeyObject",qe=e=>Fe(e)||Ge(e);function Xe(e,t,r){try{return j(e)}catch{throw new r(`Failed to base64url decode the ${t}`)}}var Yr=e=>typeof e=="object"&&e!==null;function W(e){if(!Yr(e)||Object.prototype.toString.call(e)!=="[object Object]")return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function Ct(...e){let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(let n of t){let o=Object.keys(n);if(!r||r.size===0){r=new Set(o);continue}for(let i of o){if(r.has(i))return!1;r.add(i)}}return!0}var we=e=>W(e)&&typeof e.kty=="string",vt=e=>e.kty!=="oct"&&(e.kty==="AKP"&&typeof e.priv=="string"||typeof e.d=="string"),It=e=>e.kty!=="oct"&&e.d===void 0&&e.priv===void 0,Wt=e=>e.kty==="oct"&&typeof e.k=="string";function Qr(e,t){if(e.startsWith("RS")||e.startsWith("PS")){let{modulusLength:r}=t.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}}function en(e,t){let r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:parseInt(e.slice(-3),10)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"Ed25519":case"EdDSA":return{name:"Ed25519"};case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":return{name:e};default:throw new x(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function tn(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(Ot(t,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}return kt(t,e,r),t}async function Jt(e,t,r,n){let o=await tn(e,t,"verify");Qr(e,o);let i=en(e,o.algorithm);try{return await crypto.subtle.verify(i,o,r,n)}catch{return!1}}var ke='Invalid or unsupported JWK "alg" (Algorithm) Parameter value';function rn(e){let t,r;switch(e.kty){case"AKP":{switch(e.alg){case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":t={name:e.alg},r=e.priv?["sign"]:["verify"];break;default:throw new x(ke)}break}case"RSA":{switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new x(ke)}break}case"EC":{switch(e.alg){case"ES256":case"ES384":case"ES512":t={name:"ECDSA",namedCurve:{ES256:"P-256",ES384:"P-384",ES512:"P-521"}[e.alg]},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new x(ke)}break}case"OKP":{switch(e.alg){case"Ed25519":case"EdDSA":t={name:"Ed25519"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new x(ke)}break}default:throw new x('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}async function oe(e){if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:t,keyUsages:r}=rn(e),n={...e};return n.kty!=="AKP"&&delete n.alg,delete n.use,crypto.subtle.importKey("jwk",n,t,e.ext??!(e.d||e.priv),e.key_ops??r)}var ie="given KeyObject instance cannot be used for this algorithm",se,Dt=async(e,t,r,n=!1)=>{se||=new WeakMap;let o=se.get(e);if(o?.[r])return o[r];let i=await oe({...t,alg:r});return n&&Object.freeze(e),o?o[r]=i:se.set(e,{[r]:i}),i},nn=(e,t)=>{se||=new WeakMap;let r=se.get(e);if(r?.[t])return r[t];let n=e.type==="public",o=!!n,i;if(e.asymmetricKeyType==="x25519"){switch(t){case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":break;default:throw new TypeError(ie)}i=e.toCryptoKey(e.asymmetricKeyType,o,n?[]:["deriveBits"])}if(e.asymmetricKeyType==="ed25519"){if(t!=="EdDSA"&&t!=="Ed25519")throw new TypeError(ie);i=e.toCryptoKey(e.asymmetricKeyType,o,[n?"verify":"sign"])}switch(e.asymmetricKeyType){case"ml-dsa-44":case"ml-dsa-65":case"ml-dsa-87":{if(t!==e.asymmetricKeyType.toUpperCase())throw new TypeError(ie);i=e.toCryptoKey(e.asymmetricKeyType,o,[n?"verify":"sign"])}}if(e.asymmetricKeyType==="rsa"){let s;switch(t){case"RSA-OAEP":s="SHA-1";break;case"RS256":case"PS256":case"RSA-OAEP-256":s="SHA-256";break;case"RS384":case"PS384":case"RSA-OAEP-384":s="SHA-384";break;case"RS512":case"PS512":case"RSA-OAEP-512":s="SHA-512";break;default:throw new TypeError(ie)}if(t.startsWith("RSA-OAEP"))return e.toCryptoKey({name:"RSA-OAEP",hash:s},o,n?["encrypt"]:["decrypt"]);i=e.toCryptoKey({name:t.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:s},o,[n?"verify":"sign"])}if(e.asymmetricKeyType==="ec"){let a=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(e.asymmetricKeyDetails?.namedCurve);if(!a)throw new TypeError(ie);let d={ES256:"P-256",ES384:"P-384",ES512:"P-521"};d[t]&&a===d[t]&&(i=e.toCryptoKey({name:"ECDSA",namedCurve:a},o,[n?"verify":"sign"])),t.startsWith("ECDH-ES")&&(i=e.toCryptoKey({name:"ECDH",namedCurve:a},o,n?[]:["deriveBits"]))}if(!i)throw new TypeError(ie);return r?r[t]=i:se.set(e,{[t]:i}),i};async function Ut(e,t){if(e instanceof Uint8Array||Fe(e))return e;if(Ge(e)){if(e.type==="secret")return e.export();if("toCryptoKey"in e&&typeof e.toCryptoKey=="function")try{return nn(e,t)}catch(n){if(n instanceof TypeError)throw n}let r=e.export({format:"jwk"});return Dt(e,r,t)}if(we(e))return e.k?j(e.k):Dt(e,e,t,!0);throw new Error("unreachable")}async function Lt(e,t,r){if(!W(e))throw new TypeError("JWK must be an object");let n;switch(t??=e.alg,n??=r?.extractable??e.ext,e.kty){case"oct":if(typeof e.k!="string"||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return j(e.k);case"RSA":if("oth"in e&&e.oth!==void 0)throw new x('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');return oe({...e,alg:t,ext:n});case"AKP":{if(typeof e.alg!="string"||!e.alg)throw new TypeError('missing "alg" (Algorithm) Parameter value');if(t!==void 0&&t!==e.alg)throw new TypeError("JWK alg and alg option value mismatch");return oe({...e,ext:n})}case"EC":case"OKP":return oe({...e,alg:t,ext:n});default:throw new x('Unsupported "kty" (Key Type) Parameter value')}}function Ht(e,t,r,n,o){if(o.crit!==void 0&&n?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(s=>typeof s!="string"||s.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;r!==void 0?i=new Map([...Object.entries(r),...t.entries()]):i=t;for(let s of n.crit){if(!i.has(s))throw new x(`Extension Header Parameter "${s}" is not recognized`);if(o[s]===void 0)throw new e(`Extension Header Parameter "${s}" is missing`);if(i.get(s)&&n[s]===void 0)throw new e(`Extension Header Parameter "${s}" MUST be integrity protected`)}return new Set(n.crit)}function Nt(e,t){if(t!==void 0&&(!Array.isArray(t)||t.some(r=>typeof r!="string")))throw new TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)}var ae=e=>e?.[Symbol.toStringTag],Ye=(e,t,r)=>{if(t.use!==void 0){let n;switch(r){case"sign":case"verify":n="sig";break;case"encrypt":case"decrypt":n="enc";break}if(t.use!==n)throw new TypeError(`Invalid key for this operation, its "use" must be "${n}" when present`)}if(t.alg!==void 0&&t.alg!==e)throw new TypeError(`Invalid key for this operation, its "alg" must be "${e}" when present`);if(Array.isArray(t.key_ops)){let n;switch(!0){case(r==="sign"||r==="verify"):case e==="dir":case e.includes("CBC-HS"):n=r;break;case e.startsWith("PBES2"):n="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(e):!e.includes("GCM")&&e.endsWith("KW")?n=r==="encrypt"?"wrapKey":"unwrapKey":n=r;break;case(r==="encrypt"&&e.startsWith("RSA")):n="wrapKey";break;case r==="decrypt":n=e.startsWith("RSA")?"unwrapKey":"deriveBits";break}if(n&&t.key_ops?.includes?.(n)===!1)throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}return!0},on=(e,t,r)=>{if(!(t instanceof Uint8Array)){if(we(t)){if(Wt(t)&&Ye(e,t,r))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(!qe(t))throw new TypeError(Ve(e,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if(t.type!=="secret")throw new TypeError(`${ae(t)} instances for symmetric algorithms must be of type "secret"`)}},sn=(e,t,r)=>{if(we(t))switch(r){case"decrypt":case"sign":if(vt(t)&&Ye(e,t,r))return;throw new TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if(It(t)&&Ye(e,t,r))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!qe(t))throw new TypeError(Ve(e,t,"CryptoKey","KeyObject","JSON Web Key"));if(t.type==="secret")throw new TypeError(`${ae(t)} instances for asymmetric algorithms must not be of type "secret"`);if(t.type==="public")switch(r){case"sign":throw new TypeError(`${ae(t)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw new TypeError(`${ae(t)} instances for asymmetric algorithm decryption must be of type "private"`)}if(t.type==="private")switch(r){case"verify":throw new TypeError(`${ae(t)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw new TypeError(`${ae(t)} instances for asymmetric algorithm encryption must be of type "public"`)}};function Mt(e,t,r){switch(e.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":on(e,t,r);break;default:sn(e,t,r)}}async function jt(e,t,r){if(!W(e))throw new E("Flattened JWS must be an object");if(e.protected===void 0&&e.header===void 0)throw new E('Flattened JWS must have either of the "protected" or "header" members');if(e.protected!==void 0&&typeof e.protected!="string")throw new E("JWS Protected Header incorrect type");if(e.payload===void 0)throw new E("JWS Payload missing");if(typeof e.signature!="string")throw new E("JWS Signature missing or incorrect type");if(e.header!==void 0&&!W(e.header))throw new E("JWS Unprotected Header incorrect type");let n={};if(e.protected)try{let y=j(e.protected);n=JSON.parse(H.decode(y))}catch{throw new E("JWS Protected Header is invalid")}if(!Ct(n,e.header))throw new E("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...n,...e.header},i=Ht(E,new Map([["b64",!0]]),r?.crit,n,o),s=!0;if(i.has("b64")&&(s=n.b64,typeof s!="boolean"))throw new E('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:a}=o;if(typeof a!="string"||!a)throw new E('JWS "alg" (Algorithm) Header Parameter missing or invalid');let d=r&&Nt("algorithms",r.algorithms);if(d&&!d.has(a))throw new xe('"alg" (Algorithm) Header Parameter value not allowed');if(s){if(typeof e.payload!="string")throw new E("JWS Payload must be a string")}else if(typeof e.payload!="string"&&!(e.payload instanceof Uint8Array))throw new E("JWS Payload must be a string or an Uint8Array instance");let l=!1;typeof t=="function"&&(t=await t(n,e),l=!0),Mt(a,t,"verify");let p=Rt(e.protected!==void 0?Ae(e.protected):new Uint8Array,Ae("."),typeof e.payload=="string"?s?Ae(e.payload):he.encode(e.payload):e.payload),g=Xe(e.signature,"signature",E),A=await Ut(t,a);if(!await Jt(a,A,g,p))throw new Te;let c;s?c=Xe(e.payload,"payload",E):typeof e.payload=="string"?c=he.encode(e.payload):c=e.payload;let u={payload:c};return e.protected!==void 0&&(u.protectedHeader=n),e.header!==void 0&&(u.unprotectedHeader=e.header),l?{...u,key:A}:u}async function $t(e,t,r){if(e instanceof Uint8Array&&(e=H.decode(e)),typeof e!="string")throw new E("Compact JWS must be a string or Uint8Array");let{0:n,1:o,2:i,length:s}=e.split(".");if(s!==3)throw new E("Invalid Compact JWS");let a=await jt({payload:o,protected:n,signature:i},t,r),d={payload:a.payload,protectedHeader:a.protectedHeader};return typeof t=="function"?{...d,key:a.key}:d}var an=e=>Math.floor(e.getTime()/1e3),Vt=60,Ft=Vt*60,Ze=Ft*24,cn=Ze*7,fn=Ze*365.25,un=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function zt(e){let t=un.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");let r=parseFloat(t[2]),n=t[3].toLowerCase(),o;switch(n){case"sec":case"secs":case"second":case"seconds":case"s":o=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":o=Math.round(r*Vt);break;case"hour":case"hours":case"hr":case"hrs":case"h":o=Math.round(r*Ft);break;case"day":case"days":case"d":o=Math.round(r*Ze);break;case"week":case"weeks":case"w":o=Math.round(r*cn);break;default:o=Math.round(r*fn);break}return t[1]==="-"||t[4]==="ago"?-o:o}var Bt=e=>e.includes("/")?e.toLowerCase():`application/${e.toLowerCase()}`,ln=(e,t)=>typeof e=="string"?t.includes(e):Array.isArray(e)?t.some(Set.prototype.has.bind(new Set(e))):!1;function Gt(e,t,r={}){let n;try{n=JSON.parse(H.decode(t))}catch{}if(!W(n))throw new ne("JWT Claims Set must be a top-level JSON object");let{typ:o}=r;if(o&&(typeof e.typ!="string"||Bt(e.typ)!==Bt(o)))throw new O('unexpected "typ" JWT header value',n,"typ","check_failed");let{requiredClaims:i=[],issuer:s,subject:a,audience:d,maxTokenAge:l}=r,p=[...i];l!==void 0&&p.push("iat"),d!==void 0&&p.push("aud"),a!==void 0&&p.push("sub"),s!==void 0&&p.push("iss");for(let c of new Set(p.reverse()))if(!(c in n))throw new O(`missing required "${c}" claim`,n,c,"missing");if(s&&!(Array.isArray(s)?s:[s]).includes(n.iss))throw new O('unexpected "iss" claim value',n,"iss","check_failed");if(a&&n.sub!==a)throw new O('unexpected "sub" claim value',n,"sub","check_failed");if(d&&!ln(n.aud,typeof d=="string"?[d]:d))throw new O('unexpected "aud" claim value',n,"aud","check_failed");let g;switch(typeof r.clockTolerance){case"string":g=zt(r.clockTolerance);break;case"number":g=r.clockTolerance;break;case"undefined":g=0;break;default:throw new TypeError("Invalid clockTolerance option type")}let{currentDate:A}=r,R=an(A||new Date);if((n.iat!==void 0||l)&&typeof n.iat!="number")throw new O('"iat" claim must be a number',n,"iat","invalid");if(n.nbf!==void 0){if(typeof n.nbf!="number")throw new O('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>R+g)throw new O('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(n.exp!==void 0){if(typeof n.exp!="number")throw new O('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=R-g)throw new ye('"exp" claim timestamp check failed',n,"exp","check_failed")}if(l){let c=R-n.iat,u=typeof l=="number"?l:zt(l);if(c-g>u)throw new ye('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(c<0-g)throw new O('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n}async function Qe(e,t,r){let n=await $t(e,t,r);if(n.protectedHeader.crit?.includes("b64")&&n.protectedHeader.b64===!1)throw new ne("JWTs MUST NOT use unencoded payload");let i={payload:Gt(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return typeof t=="function"?{...i,key:n.key}:i}function dn(e){switch(typeof e=="string"&&e.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";case"ML":return"AKP";default:throw new x('Unsupported "alg" value for a JSON Web Key Set')}}function pn(e){return e&&typeof e=="object"&&Array.isArray(e.keys)&&e.keys.every(mn)}function mn(e){return W(e)}var et=class{#e;#t=new WeakMap;constructor(t){if(!pn(t))throw new _e("JSON Web Key Set malformed");this.#e=structuredClone(t)}jwks(){return this.#e}async getKey(t,r){let{alg:n,kid:o}={...t,...r?.header},i=dn(n),s=this.#e.keys.filter(l=>{let p=i===l.kty;if(p&&typeof o=="string"&&(p=o===l.kid),p&&(typeof l.alg=="string"||i==="AKP")&&(p=n===l.alg),p&&typeof l.use=="string"&&(p=l.use==="sig"),p&&Array.isArray(l.key_ops)&&(p=l.key_ops.includes("verify")),p)switch(n){case"ES256":p=l.crv==="P-256";break;case"ES384":p=l.crv==="P-384";break;case"ES512":p=l.crv==="P-521";break;case"Ed25519":case"EdDSA":p=l.crv==="Ed25519";break}return p}),{0:a,length:d}=s;if(d===0)throw new Pe;if(d!==1){let l=new Re,p=this.#t;throw l[Symbol.asyncIterator]=async function*(){for(let g of s)try{yield await qt(p,g,n)}catch{}},l}return qt(this.#t,a,n)}};async function qt(e,t,r){let n=e.get(t)||e.set(t,{}).get(t);if(n[r]===void 0){let o=await Lt({...t,ext:!0},r);if(o instanceof Uint8Array||o.type!=="public")throw new _e("JSON Web Key Set members must be public keys");n[r]=o}return n[r]}function tt(e){let t=new et(e),r=async(n,o)=>t.getKey(n,o);return Object.defineProperties(r,{jwks:{value:()=>structuredClone(t.jwks()),enumerable:!1,configurable:!1,writable:!1}}),r}var rt=new WeakMap;function hn(e){if(!e||!Array.isArray(e.keys))throw m("metro.oidc: Error: jwks must be an object with a keys array");return rt.has(e)||rt.set(e,tt(e)),rt.get(e)}function yn(e={}){let t=e.id_token_signing_alg_values_supported;return Array.isArray(t)&&t.length?t.filter(r=>r!=="none"):["RS256"]}async function nt(e,t={}){if(!e)throw m("metro.oidc: Error: token response did not include an id_token");if(!t.jwks)throw m("metro.oidc: Error: cannot validate id_token without jwks");if(!t.issuer)throw m("metro.oidc: Error: cannot validate id_token without issuer");if(!t.client_id)throw m("metro.oidc: Error: cannot validate id_token without client_id");let{payload:r,protectedHeader:n}=await Qe(e,hn(t.jwks),{issuer:t.issuer,audience:t.client_id,algorithms:t.algorithms||yn(t.openid_configuration),clockTolerance:t.clockTolerance??60,requiredClaims:["iss","sub","aud","exp","iat"]});if(t.nonce!==void 0&&r.nonce!==t.nonce)throw m("metro.oidc: Error: id_token nonce mismatch");return{header:n,claims:r}}function Ke(e={}){let t={client:C(),force_authorization:!1,use_dpop:!0,authorize_callback:async n=>(window.location.href!=n.href&&window.location.replace(n.href),!1)};e=Object.assign({},t,e);let r=e.client_info;if(P(e,{client:_(G(C().constructor)),client_info:_(),issuer:_(h),oauth2:f({}),openid_configuration:f()}),e.store||(e.store=te(e.issuer)),!e.openid_configuration&&e.store.has("openid_configuration")&&(e.openid_configuration=e.store.get("openid_configuration")),!e.client_info?.client_id&&e.store.has("client_info")){let n=e.store.get("client_info");_n(n,r)&&(e.client_info=n)}return async(n,o)=>{let i;if(!e.force_authorization){try{i=await o(n)}catch(A){if(i=A?.cause,!i||i.status!=401&&i.status!=403)throw A}if(i.ok||i.status!=401&&i.status!=403)return i}if(e.openid_configuration||(e.openid_configuration=await Q({issuer:e.issuer,client:e.client.with(e.issuer)}),e.store.set("openid_configuration",e.openid_configuration)),!e.client_info?.client_id){if(!e.openid_configuration.registration_endpoint)throw m("metro.oidcmw: Error: issuer "+e.issuer+" does not support dynamic client registration, but you haven't specified a client_id");e.client_info=await ee({registration_endpoint:e.openid_configuration.registration_endpoint,client:e.client,client_info:e.client_info}),e.store.set("client_info",e.client_info)}let s=e.scope||"openid",a=e.nonce||Le(32);e.store.set("pending_nonce",a);let d=Object.assign({site:e.issuer,client:e.client,force_authorization:!0,authorize_callback:e.authorize_callback,oauth2_configuration:{client_id:e.client_info?.client_id,client_secret:e.client_info?.client_secret,grant_type:"authorization_code",response_type:"code",response_mode:"query",authorization_endpoint:e.openid_configuration.authorization_endpoint,token_endpoint:e.openid_configuration.token_endpoint,scope:s,redirect_uri:e.client_info.redirect_uris[0],nonce:a}}),l=async(A,R)=>{let c=await R(A),u=b(e.openid_configuration.token_endpoint,{hash:""}).href;if(b(A.url,{hash:""}).href!==u||!c.headers.get("content-type")?.startsWith("application/json"))return c;let T=c.data&&typeof c.data=="object"?c.data:null;T||(T=await c.clone().json());let ce=T?.id_token,fe=await p(),ge=await nt(ce,{issuer:e.openid_configuration.issuer,client_id:e.client_info.client_id,jwks:fe,openid_configuration:e.openid_configuration,nonce:e.store.get("pending_nonce")});return e.store.set("id_token",ce),e.store.set("id_token_claims",ge.claims),c},p=async()=>{if(!e.jwks){let R=await e.client.with(L()).with(U()).get(e.openid_configuration.jwks_uri);e.jwks=R.data}return e.jwks},g=e.client.with(e.issuer).with(l);if(e.use_dpop){let A={site:e.issuer,authorization_endpoint:e.openid_configuration.authorization_endpoint,token_endpoint:e.openid_configuration.token_endpoint,dpop_signing_alg_values_supported:e.openid_configuration.dpop_signing_alg_values_supported};g=g.with(ze(A))}return d.client=g,g=g.with(Ue(d)),i=await g.fetch(n),i}}function _n(e,t){if(!e?.client_id)return!1;if(!Array.isArray(t?.redirect_uris))return!0;let r=new Set(e.redirect_uris||[]);return t.redirect_uris.every(n=>r.has(n))}function ot(){return bt()}function it(e){if(!e.store){if(!e.issuer)throw m("Must supply options.issuer or options.store to get the id_token");e.store=te(e.issuer)}return e.store.get("id_token")}function st(e){if(!e.store){if(!e.issuer)throw m("Must supply options.issuer or options.store to get the id_token claims");e.store=te(e.issuer)}return e.store.get("id_token_claims")}var wn={oidcmw:Ke,discover:Q,register:ee,isRedirected:ot,idToken:it,idTokenClaims:st},at=wn;var ct=Object.assign({},D,globalThis.metro||{});ct.oidc||(ct.oidc=at);globalThis.metro=ct;var Ii=at;})();
4
4
  //# sourceMappingURL=browser.min.js.map