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