@muze-nl/metro-oidc 0.5.6 → 0.8.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,2 +1,4 @@
1
- (()=>{var Ae=Object.defineProperty;var Pe=(e,o)=>{for(var t in o)Ae(e,t,{get:o[t],enumerable:!0})};var I={};Pe(I,{Client:()=>v,client:()=>E,deepClone:()=>T,formdata:()=>ue,metroError:()=>g,request:()=>C,response:()=>H,trace:()=>je,url:()=>b});var L="https://metro.muze.nl/details/";Symbol.metroProxy||(Symbol.metroProxy=Symbol("isProxy"));Symbol.metroSource||(Symbol.metroSource=Symbol("source"));var v=class e{clientOptions={url:b(typeof window<"u"?window.location:"https://localhost"),verbs:["get","post","put","delete","patch","head","options","query"]};static tracers={};constructor(...o){for(let t of o)if(typeof t=="string"||t instanceof String)this.clientOptions.url=b(this.clientOptions.url.href,t);else if(t instanceof e)Object.assign(this.clientOptions,t.clientOptions);else if(t instanceof Function)this.#e([t]);else if(t&&typeof t=="object")for(let r in t)r=="middlewares"?this.#e(t[r]):r=="url"?this.clientOptions.url=b(this.clientOptions.url.href,t[r]):typeof t[r]=="function"?this.clientOptions[r]=t[r](this.clientOptions[r],this.clientOptions):this.clientOptions[r]=t[r];for(let t of this.clientOptions.verbs)this[t]=async function(...r){return this.fetch(C(this.clientOptions,...r,{method:t.toUpperCase()}))}}#e(o){typeof o=="function"&&(o=[o]);let t=o.findIndex(r=>typeof r!="function");if(t>=0)throw g("metro.client: middlewares must be a function or an array of functions "+L+"client/invalid-middlewares/",o[t]);Array.isArray(this.clientOptions.middlewares)||(this.clientOptions.middlewares=[]),this.clientOptions.middlewares=this.clientOptions.middlewares.concat(o)}fetch(o,t){if(o=C(o,t),!o.url)throw g("metro.client."+o.method.toLowerCase()+": Missing url parameter "+L+"client/fetch-missing-url/",o);if(t||(t={}),typeof t!="object"||t instanceof String)throw g("metro.client.fetch: Invalid options parameter "+L+"client/fetch-invalid-options/",t);let n=[async function(c){c[Symbol.metroProxy]&&(c=c[Symbol.metroSource]);let _=await fetch(c);return H(_)}].concat(this.clientOptions?.middlewares?.slice()||[]);t=Object.assign({},this.clientOptions,t);let i;for(let a of n)i=(function(c,_){return async function(y){let l,f=Object.values(e.tracers);for(let u of f)u.request&&u.request.call(u,y,_);l=await _(y,c);for(let u of f)u.response&&u.response.call(u,l,_);return l}})(i,a);return i(o)}with(...o){return new e(T(this.clientOptions),...o)}get location(){return this.clientOptions.url}};function E(...e){return new v(...T(e))}function Re(e,o){let t=o||{};!t.url&&o.url&&(t.url=o.url);for(let r of["method","headers","body","mode","credentials","cache","redirect","referrer","referrerPolicy","integrity","keepalive","signal","priority","url"]){let n=e[r];if(!(typeof n>"u"||n==null))if(n?.[Symbol.metroProxy]&&(n=n[Symbol.metroSource]),typeof n=="function")t[r]=n(t[r],t);else if(r=="url")t.url=b(t.url,n);else if(r=="headers"){t.headers=new Headers(o.headers),n instanceof Headers||(n=new Headers(e.headers));for(let[i,a]of n.entries())t.headers.set(i,a)}else t[r]=n}return e instanceof Request&&e.data&&(t.body=e.data),t}function C(...e){let o={url:b(typeof window<"u"?window.location:"https://localhost/"),duplex:"half"};for(let n of e)typeof n=="string"||n instanceof URL||n instanceof URLSearchParams?o.url=b(o.url,n):n&&(n instanceof FormData||n instanceof ReadableStream||n instanceof Blob||n instanceof ArrayBuffer||n instanceof DataView)?o.body=n:n&&typeof n=="object"&&Object.assign(o,Re(n,o));let t=new Request(o.url,o),r=o.body;return r&&typeof r=="object"&&!(r instanceof String)&&!(r instanceof ReadableStream)&&!(r instanceof Blob)&&!(r instanceof ArrayBuffer)&&!(r instanceof DataView)&&!(r instanceof FormData)&&!(r instanceof URLSearchParams)&&(typeof globalThis.TypedArray>"u"||!(r instanceof globalThis.TypedArray))&&typeof r.toString=="function"&&(o.body=r.toString({headers:t.headers}),t=new Request(o.url,o)),Object.freeze(t),new Proxy(t,{get(n,i){let a;switch(i){case Symbol.metroSource:a=n;break;case Symbol.metroProxy:a=!0;break;case"with":a=function(...c){return r&&c.unshift({body:r}),C(n,...c)};break;case"data":a=r;break;default:n[i]instanceof Function?a=n[i].bind(n):a=n[i];break}return a}})}function ce(e,o){let t=o||{};!t.url&&o.url&&(t.url=o.url);for(let r of["status","statusText","headers","body","url","type","redirected"]){let n=e[r];typeof n>"u"||n==null||(n?.[Symbol.metroProxy]&&(n=n[Symbol.metroSource]),typeof n=="function"?t[r]=n(t[r],t):r=="url"?t.url=new URL(n,t.url||"https://localhost/"):t[r]=n)}return e instanceof Response&&e.data&&(t.body=e.data),t}function H(...e){let o={};for(let n of e)typeof n=="string"?o.body=n:n instanceof Response?Object.assign(o,ce(n,o)):n&&typeof n=="object"&&(n instanceof FormData||n instanceof Blob||n instanceof ArrayBuffer||n instanceof DataView||n instanceof ReadableStream||n instanceof URLSearchParams||n instanceof String||typeof globalThis.TypedArray<"u"&&n instanceof globalThis.TypedArray?o.body=n:Object.assign(o,ce(n,o)));let t;o.body&&(t=o.body),[101,204,205,304].includes(o.status)&&(o.body=null);let r=new Response(o.body,o);return Object.freeze(r),new Proxy(r,{get(n,i){let a;switch(i){case Symbol.metroProxy:a=!0;break;case Symbol.metroSource:a=n;break;case"with":a=function(...c){return H(n,...c)};break;case"data":a=t;break;case"ok":a=n.status>=200&&n.status<400;break;default:typeof n[i]=="function"?a=n[i].bind(n):a=n[i];break}return a}})}function le(e,o){typeof o=="function"?o(e.searchParams,e):(o=new URLSearchParams(o),o.forEach((t,r)=>{e.searchParams.append(r,t)}))}function b(...e){let o=["hash","host","hostname","href","password","pathname","port","protocol","username","search","searchParams"],t=new URL("https://localhost/");for(let r of e)if(typeof r=="string"||r instanceof String)t=new URL(r,t);else if(r instanceof URL||typeof Location<"u"&&r instanceof Location)t=new URL(r);else if(r instanceof URLSearchParams)le(t,r);else if(r&&typeof r=="object")for(let n in r)switch(n){case"search":typeof r.search=="function"?r.search(t.search,t):t.search=new URLSearchParams(r.search);break;case"searchParams":le(t,r.searchParams);break;default:if(!o.includes(n))throw g("metro.url: unknown url parameter "+L+"url/unknown-param-name/",n);if(typeof r[n]=="function")r[n](t[n],t);else if(typeof r[n]=="string"||r[n]instanceof String||typeof r[n]=="number"||r[n]instanceof Number||typeof r[n]=="boolean"||r[n]instanceof Boolean)t[n]=""+r[n];else if(typeof r[n]=="object"&&r[n].toString)t[n]=r[n].toString();else throw g("metro.url: unsupported value for "+n+" "+L+"url/unsupported-param-value/",e[n]);break}else throw g("metro.url: unsupported option value "+L+"url/unsupported-option-value/",r);return Object.freeze(t),new Proxy(t,{get(r,n){let i;switch(n){case Symbol.metroProxy:i=!0;break;case Symbol.metroSource:i=r;break;case"with":i=function(...a){return b(r,...a)};break;case"filename":i=r.pathname.split("/").pop();break;case"folderpath":i=r.pathname.substring(0,r.pathname.lastIndexOf("\\")+1);break;case"authority":i=r.username??"",i+=r.password?":"+r.password:"",i+=i?"@":"",i+=r.hostname,i+=r.port?":"+r.port:"",i+="/",i=r.protocol+"//"+i;break;case"origin":i=r.protocol+"//"+r.hostname,i+=r.port?":"+r.port:"",i+="/";break;case"fragment":i=r.hash.substring(1);break;case"scheme":r.protocol?i=r.protocol.substring(0,r.protocol.length-1):i="";break;default:r[n]instanceof Function?i=r[n].bind(r):i=r[n];break}return i}})}function ue(...e){var o=new FormData;for(let t of e)if(t instanceof HTMLFormElement&&(t=new FormData(t)),t instanceof FormData)for(let r of t.entries())o.append(r[0],r[1]);else if(t&&typeof t=="object")for(let r of Object.entries(t))if(Array.isArray(r[1]))for(let n of r[1])o.append(r[0],n);else o.append(r[0],r[1]);else throw new g("metro.formdata: unknown option type "+L+"formdata/unknown-option-value/",t);return Object.freeze(o),new Proxy(o,{get(t,r){let n;switch(r){case Symbol.metroProxy:n=!0;break;case Symbol.metroSource:n=t;break;case"with":n=function(...i){return ue(t,...i)};break;default:t[r]instanceof Function?n=t[r].bind(t):n=t[r];break}return n}})}var J={error:(e,...o)=>{console.error("\u24C2\uFE0F ",e,...o)},info:(e,...o)=>{console.info("\u24C2\uFE0F ",e,...o)},group:e=>{console.group("\u24C2\uFE0F "+e)},groupEnd:e=>{console.groupEnd("\u24C2\uFE0F "+e)}};function g(e,...o){return J.error(e,...o),new Error(e,...o)}var je={add(e,o){v.tracers[e]=o},delete(e){delete v.tracers[e]},clear(){v.tracers={}},group(){let e=0;return{request:(o,t)=>{e++,J.group(e),J.info(o?.url,o,t)},response:(o,t)=>{J.info(o?.body?o.body[Symbol.metroSource]:null,o,t),J.groupEnd(e),e--}}}};function T(e){if(Array.isArray(e))return e.slice().map(T);if(e&&typeof e=="object")if(e.__proto__.constructor==Object||!e.__proto__){let o=Object.assign({},e);return Object.keys(o).forEach(t=>{o[t]=T(e[t])}),o}else return e;return e}function P(e){return e=Object.assign({contentType:"application/json",reviver:null,replacer:null,space:""},e),async function(t,r){if(t.headers.get("Accept")||(t=t.with({headers:{Accept:e.accept??e.contentType}})),t.method!=="GET"&&t.method!=="HEAD"&&t.data&&typeof t.data=="object"&&!(t.data instanceof ReadableStream)){let i=t.headers.get("Content-Type");(!i||Ee(i))&&(t=t.with({headers:{"Content-Type":e.contentType}})),fe(t.headers.get("Content-Type"))&&(t=t.with({body:JSON.stringify(t.data,e.replacer,e.space)}))}let n=await r(t);if(n&&fe(n.headers?.get("Content-Type"))){let a=await n.clone().text();try{let c=JSON.parse(a,e.reviver);return n.with({body:c})}catch{}}return n}}var Te=/^application\/([a-zA-Z0-9\-_]+\+)?json\b/;function fe(e){return Te.exec(e)}function Ee(e){return/^text\/plain\b/.exec(e)}function R(e){return async function(t,r){let n=await r(t);if(!n.ok)if(e&&typeof e[n.status]=="function")n=e[n.status].apply(n,t);else throw new Error(n.status+": "+n.statusText,{cause:n});return n}}function M(){return async function(o,t){let r=await t(o);return r.ok&&r.data?r.data:r}}var V=class extends v{constructor(o,t,r=null){o instanceof v?super(o.clientOptions,R(),M()):super(o,R(),M()),r||(r=this);for(let n in t)typeof t[n]=="function"?this[n]=t[n].bind(r):t[n]&&typeof t[n]=="object"?this[n]=new this.constructor(o,t[n],r):this[n]=t[n]}},Y=class extends V{constructor(o,t,r=null){o instanceof v?super(o.with(P()),t,r):super(E(o,P()),t,r)}};function de(...e){return new V(...T(e))}function pe(...e){return new Y(...T(e))}var he=Object.assign({},I,{mw:{json:P,thrower:R,getdata:M},api:de,jsonApi:pe});globalThis.metro||(globalThis.metro=he);var j=he;globalThis.assertEnabled=!1;function ze(){globalThis.assertEnabled=!0}function Ue(){globalThis.assertEnabled=!1}function w(e,o){if(globalThis.assertEnabled){let t=S(e,o);if(t)throw console.error("\u{1F170}\uFE0F Assertions failed because of:",t,"in this source:",e),new Error("Assertions failed",{cause:{problems:t,source:e}})}}function s(e){return function(t,r,n){if(typeof t<"u"&&t!=null&&typeof e<"u")return S(t,e,r,n)}}function p(e){return function(t,r,n){return t==null||typeof t>"u"?m("data is required",t,e||"any value",n):typeof e<"u"?S(t,e,r,n):!1}}function N(e){return function(t,r,n){return t==null||typeof t>"u"?(me("data does not contain recommended value",t,e,n),!1):S(t,e,r,n)}}function k(...e){return function(t,r,n){for(let i of e)if(!S(t,i,r,n))return!1;return m("data does not match oneOf patterns",t,e,n)}}function D(...e){return function(t,r,n){if(!Array.isArray(t))return m("data is not an array",t,"anyOf",n);for(let i of t)if(k(...e)(i))return m("data does not match anyOf patterns",i,e,n);return!1}}function q(...e){return function(t,r,n){let i=[];for(let a of e)i=i.concat(S(t,a,r,n));if(i=i.filter(Boolean),i.length)return m("data does not match all given patterns",t,e,n,i)}}function d(e,o,t){try{e instanceof URL&&(e=e.href);let r=new URL(e);if(r.href!=e&&!(r.href+"/"==e||r.href==e+"/"))return m("data is not a valid url",e,"validURL",t)}catch{return m("data is not a valid url",e,"validURL",t)}}function ee(e,o,t){if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e))return m("data is not a valid email",e,"validEmail",t)}function K(e){return function(t,r,n){if(!(t instanceof e))return m("data is not an instanceof pattern",t,e,n)}}function B(e){return function(t,r,n){if(!S(t,e,r,n))return m("data matches pattern, when required not to",t,e,n)}}function S(e,o,t,r=""){t||(t=e);let n=[];if(o===Boolean)typeof e!="boolean"&&!(e instanceof Boolean)&&n.push(m("data is not a boolean",e,o,r));else if(o===Number)typeof e!="number"&&!(e instanceof Number)&&n.push(m("data is not a number",e,o,r));else if(o===String)typeof e!="string"&&!(e instanceof String)&&n.push(m("data is not a string",e,o,r)),e==""&&n.push(m("data is an empty string, which is not allowed",e,o,r));else if(o instanceof RegExp)if(Array.isArray(e)){let i=e.findIndex((a,c)=>S(a,o,t,r+"["+c+"]"));i>-1&&n.push(m("data["+i+"] does not match pattern",e[i],o,r+"["+i+"]"))}else typeof e>"u"?n.push(m("data is undefined, should match pattern",e,o,r)):o.test(e)||n.push(m("data does not match pattern",e,o,r));else if(o instanceof Function){let i=o(e,t,r);i&&(Array.isArray(i)?n=n.concat(i):n.push(i))}else if(Array.isArray(o)){Array.isArray(e)||n.push(m("data is not an array",e,[],r));for(let i of o)for(let a of e.keys()){let c=S(e[a],i,t,r+"["+a+"]");Array.isArray(c)?n=n.concat(c):c&&n.push(c)}}else if(o&&typeof o=="object")if(Array.isArray(e)){let i=e.findIndex((a,c)=>S(a,o,t,r+"["+c+"]"));i>-1&&n.push(m("data["+i+"] does not match pattern",e[i],o,r+"["+i+"]"))}else if(!e||typeof e!="object")n.push(m("data is not an object, pattern is",e,o,r));else if(e instanceof URLSearchParams&&(e=Object.fromEntries(e)),o instanceof Function){let i=S(e,o,t,r);i&&(n=n.concat(i))}else for(let[i,a]of Object.entries(o)){let c=S(e[i],a,t,r+"."+i);c&&(n=n.concat(c))}else o!=e&&n.push(m("data and pattern are not equal",e,o,r));return n.length?n:!1}function m(e,o,t,r,n){let i={path:r,message:e,found:o,expected:t};return n&&(i.problems=n),i}function me(e,o,t,r){console.warn("\u{1F170}\uFE0F Assert: "+r,e,t,o)}globalThis.assert={warn:me,error:m,assert:w,enable:ze,disable:Ue,Required:p,Recommended:N,Optional:s,oneOf:k,anyOf:D,allOf:q,validURL:d,validEmail:ee,instanceOf:K,not:B,fails:S};function _e(e){let o,t;if(typeof localStorage<"u")o={get:()=>localStorage.getItem("metro/state:"+e),set:r=>localStorage.setItem("metro/state:"+e,r),has:()=>localStorage.getItem("metro/state:"+e)!==null,delete:()=>localStorage.remoteItem("metro/state:"+e)},t={get:r=>JSON.parse(localStorage.getItem(e+":"+r)),set:(r,n)=>localStorage.setItem(e+":"+r,JSON.stringify(n)),has:r=>localStorage.getItem(e+":"+r)!==null,delete:r=>localStorage.removeItem(e+":"+r)};else{let r=new Map;o={get:()=>r.get("metro/state:"+e),set:n=>r.set("metro/state:"+e,n),has:()=>r.has("metro/state:"+e),delete:()=>r.delete("metro/state:"+e)},t=new Map}return{state:o,tokens:t}}function te(e){let o={client:E(),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:Ce(64)},authorize_callback:async l=>(window.location.href!=l.href&&window.location.replace(l.href),!1)};w(e,{});let t=Object.assign({},o.oauth2_configuration,e?.oauth2_configuration);e=Object.assign({},o,e),e.oauth2_configuration=t;let r=_e(e.site);e.tokens||(e.tokens=r.tokens),e.state||(e.state=r.state),w(e,{oauth2_configuration:{client_id:p(/.+/),grant_type:"authorization_code",authorization_endpoint:p(d),token_endpoint:p(d),redirect_uri:p(d)}});for(let l in t)switch(l){case"access_token":case"authorization_code":case"refresh_token":e.tokens.set(l,t[l]);break}return async function(l,f){if(e.force_authorization)return n(l,f);let u;try{if(u=await f(l),u.ok)return u}catch(h){switch(u?.status){case 400:case 401:return n(l,f)}throw h}if(!u.ok)switch(u.status){case 400:case 401:return n(l,f)}return u};async function n(l,f){i();let u=e.tokens.get("access_token"),h=e.tokens.get("refresh_token"),x=Le(u);if(!u||x&&!h){try{if(!await a())return H("false")}catch(A){throw A}return n(l,f)}else if(x&&h){try{if(!await c())return H("false")}catch(A){throw A}return n(l,f)}else return l=C(l,{headers:{Authorization:u.type+" "+u.value}}),f(l)}function i(){if(typeof window<"u"&&window?.location){let l=b(window.location),f,u,h;if(l.searchParams.has("code"))h=l.searchParams,l=l.with({search:""}),history.pushState({},"",l.href);else if(l.hash){let x=l.hash.substr(1);h=new URLSearchParams("?"+x),l=l.with({hash:""}),history.pushState({},"",l.href)}if(h){f=h.get("code"),u=h.get("state");let x=e.state.get("metro/state");if(!u||u!==x)return;f&&e.tokens.set("authorization_code",f)}}}async function a(){if(t.grant_type==="authorization_code"&&!e.tokens.has("authorization_code")){let h=await _();if(!e.authorize_callback||typeof e.authorize_callback!="function")throw g("oauth2mw: oauth2 with grant_type:authorization_code requires a callback function in client options.authorize_callback");let x=await e.authorize_callback(h);if(x)e.tokens.set("authorization_code",x);else return!1}let l=y(),f=await e.client.post(l);if(!f.ok){let h=await f.text();throw g("OAuth2mw: fetch access_token: "+f.status+": "+f.statusText+" ("+h+")",{cause:l})}let u=await f.json();if(e.tokens.set("access_token",{value:u.access_token,expires:ye(u.expires_in),type:u.token_type,scope:u.scope}),u.refresh_token){let h={value:u.refresh_token};e.tokens.set("refresh_token",h)}return e.tokens.delete("authorization_code"),u}async function c(){let l=y("refresh_token"),f=await e.client.post(l);if(!f.ok)throw g("OAuth2mw: refresh access_token: "+f.status+": "+f.statusText,{cause:l});let u=await f.json();if(e.tokens.set("access_token",{value:u.access_token,expires:ye(u.expires_in),type:u.token_type,scope:u.scope}),u.refresh_token){let h={value:u.refresh_token};e.tokens.set("refresh_token",h)}else return!1;return u}async function _(){if(!t.authorization_endpoint)throw g("oauth2mw: Missing options.oauth2_configuration.authorization_endpoint");let l=b(t.authorization_endpoint,{hash:""});w(t,{client_id:/.+/,redirect_uri:/.+/,scope:/.*/});let f={response_type:"code",client_id:t.client_id,redirect_uri:t.redirect_uri,state:t.state||Ke(40)};return t.response_type&&(f.response_type=t.response_type),t.response_mode&&(f.response_mode=t.response_mode),e.state.set(f.state),t.client_secret&&(f.client_secret=t.client_secret),t.code_verifier&&(e.tokens.set("code_verifier",t.code_verifier),f.code_challenge=await De(t.code_verifier),f.code_challenge_method="S256"),t.scope&&(f.scope=t.scope),t.prompt&&(f.prompt=t.prompt),b(l,{search:f})}function y(l=null){if(w(t,{client_id:/.+/,redirect_uri:/.+/}),!t.token_endpoint)throw g("oauth2mw: Missing options.endpoints.token url");let f=b(t.token_endpoint,{hash:""}),u={grant_type:l||t.grant_type,client_id:t.client_id};switch(t.client_secret&&(u.client_secret=t.client_secret),t.scope&&(u.scope=t.scope),u.grant_type){case"authorization_code":u.redirect_uri=t.redirect_uri,u.code=e.tokens.get("authorization_code");let h=e.tokens.get("code_verifier");h&&(u.code_verifier=h);break;case"client_credentials":break;case"refresh_token":u.refresh_token=e.tokens.get("refresh_token");break;default:throw new Error("Unknown grant_type: ".oauth2.grant_type)}return C(f,{method:"POST",body:new URLSearchParams(u)})}}function Le(e){if(!e)return!0;let o=new Date(e.expires);return new Date().getTime()>o.getTime()}function ye(e){if(e instanceof Date)return new Date(e.getTime());if(typeof e=="number"){let o=new Date;return o.setSeconds(o.getSeconds()+e),o}throw new TypeError("Unknown expires type "+e)}function Ce(e=64){let o=new Uint8Array(e);return globalThis.crypto.getRandomValues(o),ge(o)}async function De(e){let t=new TextEncoder().encode(e),r=await globalThis.crypto.subtle.digest("SHA-256",t);return ge(r)}function ge(e){let o=Array.from(new Uint8Array(e),t=>String.fromCharCode(t)).join("");return btoa(o).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Ke(e){let o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t="",r=0;for(;r<e;)t+=o.charAt(Math.floor(Math.random()*o.length)),r++;return t}function we(){let e=new URL(document.location.href);if(!e.searchParams.has("code")){if(e.hash){let o=e.hash.substr(1);if(new URLSearchParams("?"+o).has("code"))return!0}return!1}return!0}function re(){return new Promise((e,o)=>{let t=globalThis.indexedDB.open("metro",1);t.onupgradeneeded=()=>t.result.createObjectStore("keyPairs",{keyPath:"domain"}),t.onerror=r=>{o(r)},t.onsuccess=r=>{let n=r.target.result;e({set:function(i,a){return new Promise((c,_)=>{let y=n.transaction("keyPairs","readwrite",{durability:"strict"}),l=y.objectStore("keyPairs");y.oncomplete=()=>{c()},y.onerror=_,l.put(i,a)})},get:function(i){return new Promise((a,c)=>{let _=n.transaction("keyPairs","readonly"),l=_.objectStore("keyPairs").get(i);l.onsuccess=()=>{a(l.result)},l.onerror=c,_.onerror=c})},clear:function(){return new Promise((i,a)=>{let c=n.transaction("keyPairs","readwrite"),y=c.objectStore("keyPairs").clear();y.onsuccess=()=>{i()},y.onerror=a,c.onerror=a})}})}})}var Ie=new TextEncoder,Me=new TextDecoder;function Z(e){return typeof e=="string"?Ie.encode(e):Me.decode(e)}function be(e){if(typeof e.modulusLength!="number"||e.modulusLength<2048)throw new oe(`${e.name} modulusLength must be at least 2048 bits`)}function Ne(e){switch(e.algorithm.name){case"ECDSA":return{name:e.algorithm.name,hash:"SHA-256"};case"RSA-PSS":return be(e.algorithm),{name:e.algorithm.name,saltLength:32};case"RSASSA-PKCS1-v1_5":return be(e.algorithm),{name:e.algorithm.name};case"Ed25519":return{name:e.algorithm.name}}throw new z}async function Be(e,o,t){if(t.usages.includes("sign")===!1)throw new TypeError('private CryptoKey instances used for signing assertions must include "sign" in their "usages"');let r=`${G(Z(JSON.stringify(e)))}.${G(Z(JSON.stringify(o)))}`,n=G(await crypto.subtle.sign(Ne(t),t,Z(r)));return`${r}.${n}`}var ne;Uint8Array.prototype.toBase64?ne=e=>(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e.toBase64({alphabet:"base64url",omitPadding:!0})):ne=o=>{o instanceof ArrayBuffer&&(o=new Uint8Array(o));let t=[];for(let r=0;r<o.byteLength;r+=32768)t.push(String.fromCharCode.apply(null,o.subarray(r,r+32768)));return btoa(t.join("")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")};function G(e){return ne(e)}var z=class extends Error{constructor(o){var t;super(o??"operation not supported"),this.name=this.constructor.name,(t=Error.captureStackTrace)===null||t===void 0||t.call(Error,this,this.constructor)}},oe=class extends Error{constructor(o){var t;super(o),this.name=this.constructor.name,(t=Error.captureStackTrace)===null||t===void 0||t.call(Error,this,this.constructor)}};function Je(e){if(e.algorithm.hash.name==="SHA-256")return"PS256";throw new z("unsupported RsaHashedKeyAlgorithm hash name")}function Fe(e){if(e.algorithm.hash.name==="SHA-256")return"RS256";throw new z("unsupported RsaHashedKeyAlgorithm hash name")}function We(e){if(e.algorithm.namedCurve==="P-256")return"ES256";throw new z("unsupported EcKeyAlgorithm namedCurve")}function $e(e){switch(e.algorithm.name){case"RSA-PSS":return Je(e);case"RSASSA-PKCS1-v1_5":return Fe(e);case"ECDSA":return We(e);case"Ed25519":return"Ed25519";default:throw new z("unsupported CryptoKey algorithm name")}}function ke(e){return e instanceof CryptoKey}function Ve(e){return ke(e)&&e.type==="private"}function Ze(e){return ke(e)&&e.type==="public"}function Ge(){return Math.floor(Date.now()/1e3)}async function ie(e,o,t,r,n,i){let a=e?.privateKey,c=e?.publicKey;if(!Ve(a))throw new TypeError('"keypair.privateKey" must be a private CryptoKey');if(!Ze(c))throw new TypeError('"keypair.publicKey" must be a public CryptoKey');if(c.extractable!==!0)throw new TypeError('"keypair.publicKey.extractable" must be true');if(typeof o!="string")throw new TypeError('"htu" must be a string');if(typeof t!="string")throw new TypeError('"htm" must be a string');if(r!==void 0&&typeof r!="string")throw new TypeError('"nonce" must be a string or undefined');if(n!==void 0&&typeof n!="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 Be({alg:$e(a),typ:"dpop+jwt",jwk:await Qe(c)},Object.assign(Object.assign({},i),{iat:Ge(),jti:crypto.randomUUID(),htm:t,nonce:r,htu:o,ath:n?G(await crypto.subtle.digest("SHA-256",Z(n))):void 0}),a)}async function Qe(e){let{kty:o,e:t,n:r,x:n,y:i,crv:a}=await crypto.subtle.exportKey("jwk",e);return{kty:o,crv:a,e:t,n:r,x:n,y:i}}async function Se(e,o){var t;let r;if(typeof e!="string"||e.length===0)throw new TypeError('"alg" must be a non-empty string');switch(e){case"PS256":r={name:"RSA-PSS",hash:"SHA-256",modulusLength:2048,publicExponent:new Uint8Array([1,0,1])};break;case"RS256":r={name:"RSASSA-PKCS1-v1_5",hash:"SHA-256",modulusLength:2048,publicExponent:new Uint8Array([1,0,1])};break;case"ES256":r={name:"ECDSA",namedCurve:"P-256"};break;case"Ed25519":r={name:"Ed25519"};break;default:throw new z}return crypto.subtle.generateKey(r,(t=o?.extractable)!==null&&t!==void 0?t:!1,["sign","verify"])}function se(e){return w(e,{site:p(d),authorization_endpoint:p(d),token_endpoint:p(d),dpop_signing_alg_values_supported:s([])}),async(o,t)=>{let r=await re(),n=await r.get(e.site);if(!n){let c=await Se("ES256");n={domain:e.site,keyPair:c},await r.set(n)}let i=j.url(o.url);if(o.url.startsWith(e.authorization_endpoint)){let c=o.body;c instanceof URLSearchParams||c instanceof FormData?c.set("dpop_jkt",n.keyPair.publicKey):c.dpop_jkt=n.keyPair.publicKey}else if(o.url.startsWith(e.token_endpoint)){let c=await ie(n.keyPair,o.url,o.method);o=o.with({headers:{DPoP:c}})}else if(o.headers.has("Authorization")){let c=localStorage.getItem(i.host+":nonce")||void 0,_=o.headers.get("Authorization").split(" ")[1],y=await ie(n.keyPair,o.url,o.method,c,_);o=o.with({headers:{Authorization:"DPoP "+_,DPoP:y}})}let a=await t(o);return a.headers.get("DPoP-Nonce")&&localStorage.setItem(i.host+":nonce",a.headers.get("DPoP-Nonce")),a}}var F=(...e)=>(o,t)=>e.filter(r=>t.hasOwnKey(r)).length>0?!1:m("root data must have all of",t,e),U=(...e)=>o=>Array.isArray(o)&&e.filter(t=>!o.includes(t)).length==0?!1:m("data must be an array which includes",o,e);var O=["HS256","HS384","HS512","RS256","RS384","RS512","ES256","ES384","ES512"],Q=["client_secret_post","client_secret_basic","client_secret_jwt","private_key_jwt"];async function W(e={}){w(e,{client:s(K(j.client().constructor)),issuer:p(d)});let o={client:j.client().with(R()).with(P()),requireDynamicRegistration:!1};e=Object.assign({},o,e);let t=!1;function r(_){return t}let n={issuer:p(q(e.issuer,r)),authorization_endpoint:p(d),token_endpoint:p(d),userinfo_endpoint:N(d),jwks_uri:p(d),registration_endpoint:e.requireDynamicRegistration?p(d):N(d),scopes_supported:N(U("openid")),response_types_supported:e.requireDynamicRegistration?p(U("code","id_token","id_token token")):p([]),response_modes_supported:s([]),grant_types_supported:e.requireDynamicRegistration?s(U("authorization_code")):s([]),acr_values_supported:s([]),subject_types_supported:p([]),id_token_signing_alg_values_supported:p(U("RS256")),id_token_encryption_alg_values_supported:s([]),id_token_encryption_enc_values_supported:s([]),userinfo_signing_alg_values_supported:s([]),userinfo_encryption_alg_values_supported:s([]),userinfo_encryption_enc_values_supported:s([]),request_object_signing_alg_values_supported:s(U("RS256")),request_object_encryption_alg_values_supported:s([]),request_object_encryption_enc_values_supported:s([]),token_endpoint_auth_methods_supported:s(D(...Q)),token_endpoint_auth_signing_alg_values_supported:s(U("RS256"),B(U("none"))),display_values_supported:s(D("page","popup","touch","wap")),claim_types_supported:s(D("normal","aggregated","distributed")),claims_supported:N([]),service_documentation:s(d),claims_locales_supported:s([]),ui_locales_supported:s([]),claims_parameter_supported:s(Boolean),request_parameter_supported:s(Boolean),request_uri_parameter_supported:s(Boolean),op_policy_uri:s(d),op_tos_uri:s(d)},i=j.url(e.issuer,".well-known/openid-configuration"),c=(await e.client.get(i)).data;return w(c,n),w(c.issuer,e.issuer),c}async function $(e){let o={redirect_uris:p([d]),response_types:s([]),grant_types:s(D("authorization_code","refresh_token")),application_type:s(k("native","web")),contacts:s([ee]),client_name:s(String),logo_uri:s(d),client_uri:s(d),policy_uri:s(d),tos_uri:s(d),jwks_uri:s(d,B(F("jwks"))),jwks:s(d,B(F("jwks_uri"))),sector_identifier_uri:s(d),subject_type:s(String),id_token_signed_response_alg:s(k(...O)),id_token_encrypted_response_alg:s(k(...O)),id_token_encrypted_response_enc:s(k(...O),F("id_token_encrypted_response_alg")),userinfo_signed_response_alg:s(k(...O)),userinfo_encrypted_response_alg:s(k(...O)),userinfo_encrypted_response_enc:s(k(...O),F("userinfo_encrypted_response_alg")),request_object_signing_alg:s(k(...O)),request_object_encryption_alg:s(k(...O)),request_object_encryption_enc:s(k(...O)),token_endpoint_auth_method:s(k(...Q)),token_endpoint_auth_signing_alg:s(k(...O)),default_max_age:s(Number),require_auth_time:s(Boolean),default_acr_values:s([String]),initiate_login_uri:s([d]),request_uris:s([d])};w(e,{client:s(K(j.client().constructor)),registration_endpoint:d,client_info:o});let t={client:j.client().with(R()).with(P()),client_info:{redirect_uris:[globalThis.document?.location.href]}};e=Object.assign({},t,e),e.client_info||(e.client_info={}),e.client_info.redirect_uris||(e.client_info.redirect_uris=[globalThis.document?.location.href]);let r=await e.client.post(e.registration_endpoint,{body:e.client_info}),n=r.data;if(!n.client_id||!n.client_secret)throw j.metroError("metro.oidc: Error: dynamic registration of client failed, no client_id or client_secret returned",r);return e.client_info=Object.assign(e.client_info,n),e.client_info}function X(e){let o;if(typeof localStorage<"u")o={get:t=>JSON.parse(localStorage.getItem("metro/oidc:"+e+":"+t)),set:(t,r)=>localStorage.setItem("metro/oidc:"+e+":"+t,JSON.stringify(r)),has:t=>localStorage.getItem("metro/oidc:"+e+":"+t)!==null};else{let t=new Map;o={get:r=>JSON.parse(t.get("metro/oidc:"+e+":"+r)||null),set:(r,n)=>t.set("metro/oidc:"+e+":"+r,JSON.stringify(n)),has:r=>t.has("metro/oidc:"+e+":"+r)}}return o}function ae(e={}){let o={client:E(),force_authorization:!1,use_dpop:!0,authorize_callback:async t=>(window.location.href!=t.href&&window.location.replace(t.href),!1)};return e=Object.assign({},o,e),w(e,{client:p(K(E().constructor)),client_info:p(),issuer:p(d),oauth2:s({}),openid_configuration:s()}),e.store||(e.store=X(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(t,r)=>{let n;if(!e.force_authorization){try{n=await r(t)}catch(y){if(n.status!=401&&n.status!=403)throw y}if(n.ok||n.status!=401&&n.status!=403)return n}if(e.openid_configuration||(e.openid_configuration=await W({issuer:e.issuer}),e.store.set("openid_configuration",e.openid_configuration)),!e.client_info?.client_id){if(!e.openid_configuration.registration_endpoint)throw g("metro.oidcmw: Error: issuer "+e.issuer+" does not support dynamic client registration, but you haven't specified a client_id");e.client_info=await $({registration_endpoint:e.openid_configuration.registration_endpoint,client_info:e.client_info}),e.store.set("client_info",e.client_info)}let i=e.scope||"openid",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]}}),c=async(y,l)=>{let f=await l(y);if(f.headers.get("content-type")?.startsWith("application/json")){let h=f.data?.id_token;if(!h){let x=f.clone();try{let A=await x.json();A&&A.id_token&&(h=A.id_token)}catch{}}h&&e.store.set("id_token",h)}return f},_=e.client.with(e.issuer).with(c);if(e.use_dpop){let y={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};_=_.with(se(y)),a.client=_}return _=_.with(te(a)),n=await _.fetch(t),n}}function xe(){return we()}function ve(e){if(!e.store){if(!e.issuer)throw g("Must supply options.issuer or options.store to get the id_token");e.store=X(e.issuer)}return e.store.get("id_token")}var Oe={oidcmw:ae,discover:W,register:$,isRedirected:xe,idToken:ve};globalThis.metro.oidc||(globalThis.metro.oidc=Oe);var Qt=Oe;})();
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;})();
2
4
  //# sourceMappingURL=browser.min.js.map