PageSourceSearch

https://www.researchretreat.org/_next/static/chunks/942-d80af7b3f9…?dpl=dpl_32YzwEHc53JeUBK7QBz7ixx7div8

js researchretreat.org collected 2026-10-07 20:34:36 UTC 207,493 bytes, 1 lines download raw bytes

1"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[942],{488:e=>{e.exports=function(e){return null==e}},1154:e=>{e.exports=function(e){try{return!!e()}catch(e){return!0}}},8632:(e,t)=>{var r={}.propertyIsEnumerable,s=Object.getOwnPropertyDescriptor;t.f=s&&!r.call({1:2},1)?function(e){var t=s(this,e);return!!t&&t.enumerable}:r},11827:(e,t,r)=>{var s=r(94156),i=r(488);e.exports=function(e,t){var r=e[t];return i(r)?void 0:s(r)}},14766:(e,t,r)=>{r.d(t,{_Q:()=>u,yE:()=>h});var s=r(70663);let i=function(e,t){if(e.length>=255)throw TypeError("Alphabet too long");for(var r=new Uint8Array(256),s=0;s<r.length;s++)r[s]=255;for(var i=0;i<e.length;i++){var a=e.charAt(i),n=a.charCodeAt(0);if(255!==r[n])throw TypeError(a+" is ambiguous");r[n]=i}var o=e.length,l=e.charAt(0),c=Math.log(o)/Math.log(256),d=Math.log(256)/Math.log(o);function u(e){if("string"!=typeof e)throw TypeError("Expected String");if(0===e.length)return new Uint8Array;var t=0;if(" "!==e[0]){for(var s=0,i=0;e[t]===l;)s++,t++;for(var a=(e.length-t)*c+1>>>0,n=new Uint8Array(a);e[t];){var d=r[e.charCodeAt(t)];if(255===d)return;for(var u=0,h=a-1;(0!==d||u<i)&&-1!==h;h--,u++)d+=o*n[h]>>>0,n[h]=d%256>>>0,d=d/256>>>0;if(0!==d)throw Error("Non-zero carry");i=u,t++}if(" "!==e[t]){for(var p=a-i;p!==a&&0===n[p];)p++;for(var f=new Uint8Array(s+(a-p)),m=s;p!==a;)f[m++]=n[p++];return f}}}return{encode:function(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw TypeError("Expected Uint8Array");if(0===t.length)return"";for(var r=0,s=0,i=0,a=t.length;i!==a&&0===t[i];)i++,r++;for(var n=(a-i)*d+1>>>0,c=new Uint8Array(n);i!==a;){for(var u=t[i],h=0,p=n-1;(0!==u||h<s)&&-1!==p;p--,h++)u+=256*c[p]>>>0,c[p]=u%o>>>0,u=u/o>>>0;if(0!==u)throw Error("Non-zero carry");s=h,i++}for(var f=n-s;f!==n&&0===c[f];)f++;for(var m=l.repeat(r);f<n;++f)m+=e.charAt(c[f]);return m},decodeUnsafe:u,decode:function(e){var r=u(e);if(r)return r;throw Error(`Non-${t} character`)}}};class a{name;prefix;baseEncode;constructor(e,t,r){this.name=e,this.prefix=t,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class n{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,r){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(void 0===s)throw Error("Invalid prefix character");this.prefixCodePoint=s,this.baseDecode=r}decode(e){if("string"==typeof e){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}throw Error("Can only multibase decode strings")}or(e){return l(this,e)}}class o{decoders;constructor(e){this.decoders=e}or(e){return l(this,e)}decode(e){let t=e[0],r=this.decoders[t];if(null!=r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}function l(e,t){return new o({...e.decoders??{[e.prefix]:e},...t.decoders??{[t.prefix]:t}})}class c{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,r,s){this.name=e,this.prefix=t,this.baseEncode=r,this.baseDecode=s,this.encoder=new a(e,t,r),this.decoder=new n(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}function d({name:e,prefix:t,encode:r,decode:s}){return new c(e,t,r,s)}function u({name:e,prefix:t,alphabet:r}){let{encode:a,decode:n}=i(r,e);return d({prefix:t,name:e,encode:a,decode:e=>(0,s.au)(n(e))})}function h({name:e,prefix:t,bitsPerChar:r,alphabet:s}){let i=function(e){let t={};for(let r=0;r<e.length;++r)t[e[r]]=r;return t}(s);return d({prefix:t,name:e,encode:e=>(function(e,t,r){let s="="===t[t.length-1],i=(1<<r)-1,a="",n=0,o=0;for(let s=0;s<e.length;++s)for(o=o<<8|e[s],n+=8;n>r;)n-=r,a+=t[i&o>>n];if(0!==n&&(a+=t[i&o<<r-n]),s)for(;(a.length*r&7)!=0;)a+="=";return a})(e,s,r),decode:t=>(function(e,t,r,s){let i=e.length;for(;"="===e[i-1];)--i;let a=new Uint8Array(i*r/8|0),n=0,o=0,l=0;for(let c=0;c<i;++c){let i=t[e[c]];if(void 0===i)throw SyntaxError(`Non-${s} character`);o=o<<r|i,(n+=r)>=8&&(n-=8,a[l++]=255&o>>n)}if(n>=r||(255&o<<8-n)!=0)throw SyntaxError("Unexpected end of data");return a})(t,i,r,e)})}},16730:e=>{var t=String;e.exports=function(e){try{return t(e)}catch(e){return"Object"}}},20161:(e,t,r)=>{e.exports=!r(1154)(function(){return 7!==Object.defineProperty({},1,{get:function(){return 7}}
1)[1]})},20666:(e,t,r)=>{var s=r(31989),i=r(92855),a=s.document,n=i(a)&&i(a.createElement);e.exports=function(e){return n?a.createElement(e):{}}},20885:(e,t,r)=>{var s=r(80997),i=s({}.toString),a=s("".slice);e.exports=function(e){return a(i(e),8,-1)}},21413:(e,t,r)=>{r(53569),e.exports=r(72194).f("dispose")},22856:(e,t,r)=>{var s=r(28891),i=Object;e.exports=function(e){return i(s(e))}},25942:(e,t,r)=>{let s,i;r.d(t,{fdI:()=>iC,HfL:()=>r3});var a,n={};r.r(n),r.d(n,{Rb:()=>ec,i4:()=>en,T0:()=>ed,Ye:()=>ep,h2:()=>e_,ie:()=>eo,n:()=>el,Dp:()=>ef}),r(92152),r(21413);let o="ERR_JWK_NOT_FOUND",l="ERR_JWT_INVALID";class c extends TypeError{constructor(e="JWK error",t="ERR_JWK_INVALID",r){super(e,r),this.code=t}}class d extends Error{constructor(e="Unable to create JWT",t="ERR_JWT_CREATE",r){super(e,r),this.code=t}static from(e,t,r){return e instanceof d?e:e instanceof c?new d(r,e.code,{cause:e}):new d(r,t,{cause:e})}}class u extends Error{constructor(e="Invalid JWT",t="ERR_JWT_VERIFY",r){super(e,r),this.code=t}static from(e,t,r){return e instanceof u?e:e instanceof c?new u(r,e.code,{cause:e}):new u(r,t,{cause:e})}}var h=r(98734),p=r(85828),f=r(44193);let m=e=>void 0!==e,y=(e,t)=>function(){let t=e.call(this);return Object.defineProperty(this,e.name,{get:()=>t,enumerable:!0,configurable:!0}),t},g=new TextDecoder;function v(e){let t=p.r0.baseDecode(e);return JSON.parse(g.decode(t))}let w=(e,t)=>{let r;for(let s=0;s<e.length;s++)if(65<=(r=e.charCodeAt(s))&&r<=90||97<=r&&r<=122||48<=r&&r<=57||45===r||95===r||46===r);else{let r=String.fromCodePoint(e.codePointAt(s));return t.addIssue({code:f.eq.custom,message:`Invalid character "${r}" in JWT at position ${s}`})}},_=(e,t=2)=>{if(!Number.isFinite(e)||e<1||(0|e)!==e)throw TypeError(`Count must be a natural number (got ${e})`);let r=e*t+(e-1),s="Invalid JWT format";return(i,a)=>{if(i.length<r)return a.addIssue({code:f.eq.custom,message:`${s}: too short`}),!1;let n=0;for(let r=0;r<e-1;r++){let o=i.indexOf(".",n);if(-1===o)return a.addIssue({code:f.eq.custom,message:`${s}: expected ${e} segments, got ${r+1}`}),!1;if(o-n<t)return a.addIssue({code:f.eq.custom,message:`${s}: segment ${r+1} is too short`}),!1;n=o+1}return -1!==i.indexOf(".",n)?(a.addIssue({code:f.eq.custom,message:`${s}: too many segments`}),!1):!(i.length-n<t)||(a.addIssue({code:f.eq.custom,message:`${s}: last segment is too short`}),!1)}};function b(e,t,r){return -1===r.indexOf(e,t+1)}let k=["verify","encrypt","wrapKey"];function S(e){return k.includes(e)}function x(e){return"verify"===e}function E(e){return"encrypt"===e||"wrapKey"===e}h.k5(k);let A=["sign","decrypt","unwrapKey","deriveKey","deriveBits"];function j(e){return A.includes(e)}h.k5(A);let I=[...A,...k],T=h.k5(I),R=h.Ik({kty:h.Yj().min(1),alg:h.Yj().min(1).optional(),kid:h.Yj().min(1).optional(),use:h.k5(["sig","enc"]).optional(),key_ops:h.YO(T).min(1,{message:"At least one key usage must be specified"}).refine(e=>e.every(b),{message:"key_ops must not contain duplicates"}).optional(),x5c:h.YO(h.Yj()).optional(),x5t:h.Yj().min(1).optional(),"x5t#S256":h.Yj().min(1).optional(),x5u:h.Yj().url().optional(),ext:h.zM().optional(),iat:h.ai().int().optional(),exp:h.ai().int().optional(),nbf:h.ai().int().optional(),revoked:h.Ik({revoked_at:h.ai().int(),reason:h.Yj().optional()}).optional()}),O=R.extend({kty:h.eu("RSA"),alg:h.k5(["RS256","RS384","RS512","PS256","PS384","PS512"]).optional(),n:h.Yj().min(1),e:h.Yj().min(1),d:h.Yj().min(1).optional(),p:h.Yj().min(1).optional(),q:h.Yj().min(1).optional(),dp:h.Yj().min(1).optional(),dq:h.Yj().min(1).optional(),qi:h.Yj().min(1).optional(),oth:h.YO(h.Ik({r:h.Yj().optional(),d:h.Yj().optional(),t:h.Yj().optional()})).min(1).optional()}),C=R.extend({kty:h.eu("EC"),alg:h.k5(["ES256","ES384","ES512"]).optional(),crv:h.k5(["P-256","P-384","P-521"]),x:h.Yj().min(1),y:h.Yj().min(1),d:h.Yj().min(1).optional()}),P=R.extend({kty:h.eu("EC"),alg:h.k5(["ES256K"]).optional(),crv:h.k5(["secp256k1"]),x:h.Yj().min(1),y:h.Yj().min(1),d:h.Yj().min(1).optional()}),D=R.extend({kty:h.eu("OKP"),alg:h.k5(["EdDSA"]).optional(),crv:h.k5(["Ed25519","Ed448"]),x:h.Yj().min(1),d:h.Yj().min(1).optional()}),$=R.extend({kty:h.eu("oct"),alg:h.k5(["HS256","HS384","HS512"]).optional(),k:h.Yj()}),L=h.KC([O,C,P,D,$]).refine(e=>null==e.use||Y(e),{message:'"use" can only be used with public keys',path:["use"]}).refine(e=>!e.key_ops?.some(j)||M(e),{message:"private key usage not allowed for public keys",path:["key_ops"]}).refine(e=>null==e.use||null==e.key_ops||"sig"===e.use&&e.key_ops.every(x)||"enc"===e.use&&e.key_ops.every(E),{message:'"key_ops" must be consistent with "use"',path:["key_ops"]}),z=L.refine(function(e){return"kid"in e&&null!=e.kid},{message:'"kid" is required',path:["kid"]}).refine(Y,{message:"private key not allowed"}).refine(e=>!e.key_ops||e.key_ops.every(S),{message:'"key_ops" must not contain private key usage for public keys',path:["key_ops"]});function K(e){return"k"in e&&null!=e.k}function q(e){return"d"in e&&null!=e.d}function M(e){return q(e)||K(e)}function Y(e){return!q(e)&&!K(e)}
1L.refine(M,{message:"private key required"});let{process:N}=globalThis,W=void 0!==N&&"string"==typeof N?.versions?.node;function Z(e){return e.key_ops?.some(E)??(null==e.use||"enc"===e.use)}function U(e){return e.key_ops?.some(x)??(null==e.use||"sig"===e.use)}h.Ik({keys:h.YO(h.L5()).transform(e=>e.map(e=>L.safeParse(e)).filter(e=>e.success).map(e=>e.data))});let F=h.Ik({keys:h.YO(h.L5()).transform(e=>e.map(e=>z.safeParse(e)).filter(e=>e.success).map(e=>e.data))}),H=h.Yj().superRefine(w).superRefine(_(3)),J=h.Yj().superRefine(w).superRefine(_(2)),B=h.Ik({alg:h.Yj(),jku:h.Yj().url().optional(),jwk:h.Ik({kty:h.Yj(),crv:h.Yj().optional(),x:h.Yj().optional(),y:h.Yj().optional(),e:h.Yj().optional(),n:h.Yj().optional()}).optional(),kid:h.Yj().optional(),x5u:h.Yj().optional(),x5c:h.YO(h.Yj()).optional(),x5t:h.Yj().optional(),"x5t#S256":h.Yj().optional(),typ:h.Yj().optional(),cty:h.Yj().optional(),crit:h.YO(h.Yj()).optional()}).passthrough(),V=h.Yj().superRefine((e,t)=>{try{let r=new URL(e);"http:"!==r.protocol&&"https:"!==r.protocol&&t.addIssue({code:f.eq.custom,message:"Only http: and https: protocols are allowed"}),(r.username||r.password)&&t.addIssue({code:f.eq.custom,message:"Credentials not allowed"}),r.search&&t.addIssue({code:f.eq.custom,message:"Query string not allowed"}),r.hash&&t.addIssue({code:f.eq.custom,message:"Fragment not allowed"})}catch(e){t.addIssue({code:f.eq.invalid_string,validation:"url"})}return e}),G=h.Ik({iss:h.Yj().optional(),aud:h.KC([h.Yj(),h.YO(h.Yj()).nonempty()]).optional(),sub:h.Yj().optional(),exp:h.ai().int().optional(),nbf:h.ai().int().optional(),iat:h.ai().int().optional(),jti:h.Yj().optional(),htm:h.Yj().optional(),htu:V.optional(),ath:h.Yj().optional(),acr:h.Yj().optional(),azp:h.Yj().optional(),amr:h.YO(h.Yj()).optional(),cnf:h.Ik({kid:h.Yj().optional(),jwk:z.optional(),jwe:h.Yj().optional(),jku:h.Yj().url().optional(),jkt:h.Yj().optional(),"x5t#S256":h.Yj().optional(),osc:h.Yj().optional()}).optional(),client_id:h.Yj().optional(),scope:h.Yj().optional(),nonce:h.Yj().optional(),at_hash:h.Yj().optional(),c_hash:h.Yj().optional(),s_hash:h.Yj().optional(),auth_time:h.ai().int().optional(),name:h.Yj().optional(),family_name:h.Yj().optional(),given_name:h.Yj().optional(),middle_name:h.Yj().optional(),nickname:h.Yj().optional(),preferred_username:h.Yj().optional(),gender:h.Yj().optional(),picture:h.Yj().url().optional(),profile:h.Yj().url().optional(),website:h.Yj().url().optional(),birthdate:h.Yj().regex(/\d{4}-\d{2}-\d{2}/).optional(),zoneinfo:h.Yj().regex(/^[A-Za-z0-9_/]+$/).optional(),locale:h.Yj().regex(/^[a-z]{2,3}(-[A-Z]{2})?$/).optional(),updated_at:h.ai().int().optional(),email:h.Yj().optional(),email_verified:h.zM().optional(),phone_number:h.Yj().optional(),phone_number_verified:h.zM().optional(),address:h.Ik({formatted:h.Yj().optional(),street_address:h.Yj().optional(),locality:h.Yj().optional(),region:h.Yj().optional(),postal_code:h.Yj().optional(),country:h.Yj().optional()}).optional(),authorization_details:h.YO(h.Ik({type:h.Yj(),locations:h.YO(h.Yj()).optional(),actions:h.YO(h.Yj()).optional(),datatypes:h.YO(h.Yj()).optional(),identifier:h.Yj().optional(),privileges:h.YO(h.Yj()).optional()}).passthrough()).optional()}).passthrough();var X=function(e,t,r){for(var s=arguments.length>2,i=0;i<t.length;i++)r=s?t[i].call(e,r):t[i].call(e);return s?r:void 0},Q=function(e,t,r,s,i,a){function n(e){if(void 0!==e&&"function"!=typeof e)throw TypeError("Function expected");return e}for(var o,l=s.kind,c="getter"===l?"get":"setter"===l?"set":"value",d=!t&&e?s.static?e:e.prototype:null,u=t||(d?Object.getOwnPropertyDescriptor(d,s.name):{}),h=!1,p=r.length-1;p>=0;p--){var f={};for(var m in s)f[m]="access"===m?{}:s[m];for(var m in s.access)f.access[m]=s.access[m];f.addInitializer=function(e){if(h)throw TypeError("Cannot add initializers after decoration has completed");a.push(n(e||null))};var y=(0,r[p])("accessor"===l?{get:u.get,set:u.set}:u[c],f);if("accessor"===l){if(void 0===y)continue;if(null===y||"object"!=typeof y)throw TypeError("Object expected");(o=n(y.get))&&(u.get=o),(o=n(y.set))&&(u.set=o),(o=n(y.init))&&i.unshift(o)}else(o=n(y))&&("field"===l?i.unshift(o):u[c]=o)}d&&Object.defineProperty(d,s.name,u),h=!0};let ee=(()=>{let e,t,r,s,i,a=[];return class{static{let n="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;e=[y],t=[y],r=[y],s=[y],i=[y],Q(this,null,e,{kind:"getter",name:"isPrivate",static:!1,private:!1,access:{has:e=>"isPrivate"in e,get:e=>e.isPrivate},metadata:n},null,a),Q(this,null,t,{kind:"getter",name:"isSymetric",static:!1,private:!1,access:{has:e=>"isSymetric"in e,get:e=>e.isSymetric},metadata:n},null,a),Q(this,null,r,{kind:"getter",name:"publicJwk",static:!1,private:!1,access:{has:e=>"publicJwk"in e,get:e=>e.publicJwk},metadata:n},null,a),Q(this,null,s,{kind:"getter",name:"bareJwk",static:!1,private:!1,access:{has:e=>"bareJwk"in e,get:e=>e.bareJwk},metadata:n},null,a),Q(this,null,i,{kind:"getter",name:"algorithms",static:!1,private:!1,access:{has:e=>"algorithms"in e,get:e=>e.algorithms},metadata:n},null,a),n&&Object.defineProperty(this,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:n})}constructor(e){this.jwk=(X(this,a),e)}get isPrivate(){return M(this.jwk)}get isSymetric(){return K(this.jwk)}get privateJwk(){if(this.isPrivate)return this.jwk}get publicJwk(){if(this.isSymetric)return;if(!this.isPrivate)return this.jwk;let e=z.safeParse({...this.jwk,d:void 0,k:void 0,use:void 0,key_ops:function(e){if(null==e)return;let t=new Set(e.filter(S));return e.includes("sign")&&t.add("verify"),e.includes("decrypt")&&t.add("encrypt"),e.includes("unwrapKey")&&t.add("wrapKey"),Array.from(t)}(this.keyOps)??k});if(e.success)return Object.freeze(e.data)}get bareJwk(){if(this.isSymetric)return;let{kty:e,crv:t,e:r,n:s,x:i,y:a}=this.jwk;return Object.freeze(L.parse({crv:t,e:r,kty:e,n:s,x:i,y:a}))}get use(){return this.jwk.use}get keyOps(){return this.jwk.key_ops}get alg(){return this.jwk.alg}get kid(){return this.jwk.kid}get crv(){return this.jwk.crv}get algorithms(){return Object.freeze(Array.from(function*(e){if("string"==typeof e.alg)return void(yield e.alg);switch(e.kty){case"EC":if(Z(e)&&(yield"ECDH-ES",yield"ECDH-ES+A128KW",yield"ECDH-ES+A192KW",yield"ECDH-ES+A256KW"),U(e)){let t="crv"in e?e.crv:void 0;switch(t){case"P-256":case"P-384":yield`ES${t.slice(-3)}`;break;case"P-521":yield"ES512";break;case"secp256k1":W&&(yield"ES256K");break;default:throw new c(`Unsupported crv "${t}"`)}}return;case"OKP":if(!e.use)throw new c('Missing "use" Parameter value');yield"ECDH-ES",yield"ECDH-ES+A128KW",yield"ECDH-ES+A192KW",yield"ECDH-ES+A256KW";return;case"RSA":Z(e)&&(yield"RSA-OAEP",yield"RSA-OAEP-256",yield"RSA-OAEP-384",yield"RSA-OAEP-512",W&&(yield"RSA1_5")),U(e)&&(yield"PS256",yield"PS384",yield"PS512",yield"RS256",yield"RS384",yield"RS512");return;case"oct":Z(e)&&(yield"A128GCMKW",yield"A192GCMKW",yield"A256GCMKW",yield"A128KW",yield"A192KW",
1yield"A256KW"),U(e)&&(yield"HS256",yield"HS384",yield"HS512");return;default:throw new c(`Unsupported kty "${e.kty}"`)}}(this.jwk)))}get isRevoked(){return null!=this.jwk.revoked}isActive(e){if(!e?.allowRevoked&&this.isRevoked)return!1;let t=e?.clockTolerance??0;if(t!==1/0){let r=e?.currentDate?.getTime()??Date.now(),{exp:s,nbf:i}=this.jwk;if(null!=i&&!(r>=1e3*i-t)||null!=s&&!(r<1e3*s+t))return!1}return!0}matches(e){return(null==e.kid||!!(Array.isArray(e.kid)?null!=this.kid&&e.kid.includes(this.kid):this.kid===e.kid))&&(null==e.alg||!!(Array.isArray(e.alg)?e.alg.some(e=>this.algorithms.includes(e)):this.algorithms.includes(e.alg)))&&(null==e.usage||!!(null==this.keyOps||this.keyOps.includes(e.usage)||"verify"===e.usage&&this.keyOps.includes("sign")||"encrypt"===e.usage&&this.keyOps.includes("decrypt")||"wrapKey"===e.usage&&this.keyOps.includes("unwrapKey"))&&!!(null==this.use||"sig"===this.use&&x(e.usage)||"enc"===this.use&&E(e.usage))&&!!(this.isPrivate||S(e.usage)))&&!0}}})();var et=function(e,t,r){for(var s=arguments.length>2,i=0;i<t.length;i++)r=s?t[i].call(e,r):t[i].call(e);return s?r:void 0},er=function(e,t,r,s,i,a){function n(e){if(void 0!==e&&"function"!=typeof e)throw TypeError("Function expected");return e}for(var o,l=s.kind,c="getter"===l?"get":"setter"===l?"set":"value",d=!t&&e?s.static?e:e.prototype:null,u=t||(d?Object.getOwnPropertyDescriptor(d,s.name):{}),h=!1,p=r.length-1;p>=0;p--){var f={};for(var m in s)f[m]="access"===m?{}:s[m];for(var m in s.access)f.access[m]=s.access[m];f.addInitializer=function(e){if(h)throw TypeError("Cannot add initializers after decoration has completed");a.push(n(e||null))};var y=(0,r[p])("accessor"===l?{get:u.get,set:u.set}:u[c],f);if("accessor"===l){if(void 0===y)continue;if(null===y||"object"!=typeof y)throw TypeError("Object expected");(o=n(y.get))&&(u.get=o),(o=n(y.set))&&(u.set=o),(o=n(y.init))&&i.unshift(o)}else(o=n(y))&&("field"===l?i.unshift(o):u[c]=o)}d&&Object.defineProperty(d,s.name,u),h=!0};let es=e=>e.privateJwk,ei=e=>e.publicJwk,ea=(()=>{let e,t,r,s=[];return class i{static{let i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;er(this,null,e,{kind:"getter",name:"signAlgorithms",static:!1,private:!1,access:{has:e=>"signAlgorithms"in e,get:e=>e.signAlgorithms},metadata:i},null,s),er(this,null,t,{kind:"getter",name:"publicJwks",static:!1,private:!1,access:{has:e=>"publicJwks"in e,get:e=>e.publicJwks},metadata:i},null,s),er(this,null,r,{kind:"getter",name:"privateJwks",static:!1,private:!1,access:{has:e=>"privateJwks"in e,get:e=>e.privateJwks},metadata:i},null,s),i&&Object.defineProperty(this,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i})}constructor(e,t=e instanceof i?[...e.preferredSigningAlgorithms]:["EdDSA","ES256K","ES256","PS256","PS384","PS512","HS256","HS384","HS512"]){this.preferredSigningAlgorithms=(et(this,s),t);let r=[],a=new Set;for(let t of e)if(t&&(r.push(t),t.kid))if(a.has(t.kid))throw new c(`Duplicate key: ${t.kid}`);else a.add(t.kid);this.keys=Object.freeze(r)}get size(){return this.keys.length}get signAlgorithms(){let e,t=new Set;for(let e of this)if("sig"===e.use)for(let r of e.algorithms)t.add(r);return Object.freeze([...t].sort((e=this.preferredSigningAlgorithms,(t,r)=>{let s=e.indexOf(t),i=e.indexOf(r);return s===i?0:-1===s?1:-1===i?-1:s-i})))}get publicJwks(){return Object.freeze({keys:Object.freeze(Array.from(this,ei).filter(m))})}get privateJwks(){return Object.freeze({keys:Object.freeze(Array.from(this,es).filter(m))})}has(e){return this.keys.some(t=>t.kid===e)}get(e){let t=this.find(e);if(t)return t;throw new c(`Key not found ${e.kid??e.alg??e.usage??"<unknown>"}`,o)}find(e){for(let t of this.list(e))return t}*list(e){for(let t of this)t.isActive(e)&&t.matches(e)&&(yield t)}findPrivateKey({kid:e,alg:t,usage:r,...s}){var i;let a=[];for(let i of(Array.isArray(t)&&1===t.length&&(t=t[0]),this.list({...s,kid:e,alg:t,usage:r}))){if("string"==typeof t)return{key:i,alg:t};a.push(i)}let n=null==(i=t)?e=>!0:Array.isArray(i)?e=>i.includes(e):e=>e===i,l=a.map(e=>[e,e.algorithms.filter(n)]);for(let e of this.preferredSigningAlgorithms)for(let[t,r]of l)if(r.includes(e))return{key:t,alg
1:e};for(let[e,t]of l)for(let r of t)return{key:e,alg:r};throw new c(`No private key found for ${e||t||r}`,o)}[(e=[y],t=[y],r=[y],Symbol.iterator)](){return this.keys.values()}async createJwt({alg:e,kid:t,...r},s){try{let{key:i,alg:a}=this.findPrivateKey({alg:e,kid:t,usage:"sign",allowRevoked:!1}),n={...r,alg:a,kid:i.kid};return"function"==typeof s&&(s=await s(n,i)),await i.createJwt(n,s)}catch(e){throw d.from(e)}}async verifyJwt(e,t){let{header:r}=function(e){let{0:t,1:r,length:s}=e.split(".");if(s>3||s<2)throw new u(void 0,l);let i=B.parse(v(t));if(2===s&&i?.alg!=="none")throw new u(void 0,l);return{header:i,payload:G.parse(v(r))}}(e),{kid:s,alg:i}=r,a=[];for(let r of this.list({...t,kid:s,alg:i,usage:"verify"}))try{return{...await r.verifyJwt(e,t),key:r}}catch(e){a.push(e)}switch(a.length){case 0:throw new u("No key matched","ERR_JWKS_NO_MATCHING_KEY");case 1:throw u.from(a[0],l);default:throw u.from(a,l)}}toJSON(){return structuredClone(this.publicJwks)}}})();class en extends Error{constructor(e,t){super(e,t),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}en.code="ERR_JOSE_GENERIC";class eo extends en{constructor(e,t,r="unspecified",s="unspecified"){super(e,{cause:{claim:r,reason:s,payload:t}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=r,this.reason=s,this.payload=t}}eo.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class el extends en{constructor(e,t,r="unspecified",s="unspecified"){super(e,{cause:{claim:r,reason:s,payload:t}}),this.code="ERR_JWT_EXPIRED",this.claim=r,this.reason=s,this.payload=t}}el.code="ERR_JWT_EXPIRED";class ec extends en{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}ec.code="ERR_JOSE_ALG_NOT_ALLOWED";class ed extends en{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}ed.code="ERR_JOSE_NOT_SUPPORTED";class eu extends en{constructor(e="decryption operation failed",t){super(e,t),this.code="ERR_JWE_DECRYPTION_FAILED"}}eu.code="ERR_JWE_DECRYPTION_FAILED";class eh extends en{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}eh.code="ERR_JWE_INVALID";class ep extends en{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}ep.code="ERR_JWS_INVALID";class ef extends en{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}ef.code="ERR_JWT_INVALID";class em extends en{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}em.code="ERR_JWK_INVALID";class ey extends en{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}ey.code="ERR_JWKS_INVALID";class eg extends en{constructor(e="no applicable key found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_NO_MATCHING_KEY"}}eg.code="ERR_JWKS_NO_MATCHING_KEY";class ev extends en{constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}Symbol.asyncIterator,ev.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class ew extends en{constructor(e="request timed out",t){super(e,t),this.code="ERR_JWKS_TIMEOUT"}}ew.code="ERR_JWKS_TIMEOUT";class e_ extends en{constructor(e="signature verification failed",t){super(e,t),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}e_.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";let eb=new TextEncoder,ek=new TextDecoder;function eS(...e){let t=new Uint8Array(e.reduce((e,{length:t})=>e+t,0)),r=0;for(let s of e)t.set(s,r),r+=s.length;return t}let ex=e=>(e=>{let t=e;"string"==typeof t&&(t=eb.encode(t));let r=[];for(let e=0;e<t.length;e+=32768)r.push(String.fromCharCode.apply(null,t.subarray(e,e+32768)));return btoa(r.join(""))})(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"),eE=e=>{let t=e;t instanceof Uint8Array&&(t=ek.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return(e=>{let t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r})(t)}catch{throw TypeError("The input to be decoded is not correctly encoded.")}},eA=crypto,ej=(e,t,r=0)=>{0===r&&(t.unshift(t.length),t.unshift(6));let s=e.indexOf(t[0],r);if(-1===s)return!1;let i=e.subarray(s,s+t.length);return i.length===t.length&&(i.every((e,r)=>e===t[r])||ej(e,t,s+1))},eI=e=>{switch(!0){case ej(e,[42,134,72,206,61,3,1,7]):return"P-256";case ej(e,[43,129,4,0,34]):return"P-384";case ej(e,[43,129,4,0,35]):return"P-521";case ej(e,[43,101,110]):return"X25519";case ej(e,[43,101,111]):return"X448";case ej(e,[43,101,112]):return"Ed25519";case ej(e,[43,101,113]):return"Ed448";default:throw new ed("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}},eT=async(e,t,r,s,i)=>{let a,n,o=new Uint8Array(atob(r.replace(e,"")).split("").map(e=>e.charCodeAt(0))),l="spki"===t;switch(s){case"PS256":case"PS384":case"PS512":a={name:"RSA-PSS",hash:`SHA-${s.slice(-3)}`},n=l?["verify"]:["sign"];break;case"RS256":case"RS384":case"RS512":a={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${s.slice(-3)}`},n=l?["verify"]:["sign"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":a={name:"RSA-OAEP",hash:`SHA-${parseInt(s.slice(-3),10)||1}`},n=l?["encrypt","wrapKey"]:["decrypt","unwrapKey"];break;case"ES256":a={name:"ECDSA",namedCurve:"P-256"},n=l?["verify"]:["sign"];break;case"ES384":a={name:"ECDSA",namedCurve:"P-384"},n=l?["verify"]:["sign"];break;case"ES512":a={name:"ECDSA",namedCurve:"P-521"},n=l?["verify"]:["sign"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{let e=eI(o);a=e.startsWith("P-")?{name:"ECDH",namedCurve:e}:{name:e},n=l?[]:["deriveBits"];break}
1case"Ed25519":a={name:"Ed25519"},n=l?["verify"]:["sign"];break;case"EdDSA":a={name:eI(o)},n=l?["verify"]:["sign"];break;default:throw new ed('Invalid or unsupported "alg" (Algorithm) value')}return eA.subtle.importKey(t,o,a,i?.extractable??!1,n)},eR=async e=>{if(!e.alg)throw TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:t,keyUsages:r}=function(e){let t,r;switch(e.kty){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 ed('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"EC":switch(e.alg){case"ES256":t={name:"ECDSA",namedCurve:"P-256"},r=e.d?["sign"]:["verify"];break;case"ES384":t={name:"ECDSA",namedCurve:"P-384"},r=e.d?["sign"]:["verify"];break;case"ES512":t={name:"ECDSA",namedCurve:"P-521"},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 ed('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"OKP":switch(e.alg){case"Ed25519":t={name:"Ed25519"},r=e.d?["sign"]:["verify"];break;case"EdDSA":t={name:e.crv},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 ed('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;default:throw new ed('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}(e),s=[t,e.ext??!1,e.key_ops??r],i={...e};return delete i.alg,delete i.use,eA.subtle.importKey("jwk",i,...s)};function eO(e){if("object"!=typeof e||null===e||"[object Object]"!==Object.prototype.toString.call(e))return!1;if(null===Object.getPrototypeOf(e))return!0;let t=e;for(;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}async function eC(e,t,r){if("string"!=typeof e||0!==e.indexOf("-----BEGIN PRIVATE KEY-----"))throw TypeError('"pkcs8" must be PKCS#8 formatted string');return eT(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",e,t,r)}async function eP(e,t){if(!eO(e))throw TypeError("JWK must be an object");switch(t||(t=e.alg),e.kty){case"oct":if("string"!=typeof e.k||!e.k)throw TypeError('missing "k" (Key Value) Parameter value');return eE(e.k);case"RSA":if("oth"in e&&void 0!==e.oth)throw new ed('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return eR({...e,alg:t});default:throw new ed('Unsupported "kty" (Key Type) Parameter value')}}function eD(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:e.slice(-3)>>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":return{name:"Ed25519"};case"EdDSA":return{name:t.name};default:throw new ed(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}let e$=(e,t)=>{if(e.startsWith("RS")||e.startsWith("PS")){let{modulusLength:r}=t.algorithm;if("number"!=typeof r||r<2048)throw TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}};function eL(e,t="algorithm.name"){return TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function ez(e,t){return e.name===t}function eK(e){return parseInt(e.name.slice(4),10)}function eq(e,t,...r){if((r=r.filter(Boolean)).length>2){let t=r.pop();e+=`one of type ${r.join(", ")}, or ${t}.`}else 2===r.length?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return null==t?e+=` Received ${t}`:"function"==typeof t&&t.name?e+=` Received function ${t.name}`:"object"==typeof t&&null!=t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}let eM=(e,...t)=>eq("Key must be ",e,...t);function eY(e,t,...r){return eq(`Key for the ${e} algorithm must be `,t,...r)}let eN=e=>e instanceof CryptoKey||e?.[Symbol.toStringTag]==="KeyObject",eW=["CryptoKey"];function eZ(e){return eO(e)&&"string"==typeof e.kty}let eU=e=>eE(e),eF=e=>e?.[Symbol.toStringTag]==="KeyObject",eH=async(e,t,r,s,i=!1)=>{let a=e.get(t);if(a?.[s])return a[s];let n=await eR({...r,alg:s});return i&&Object.freeze(t),a?a[s]=n:e.set(t,{[s]:n}),n},eJ={normalizePublicKey:(e,t)=>{if(eF(e)){let r=e.export({format:"jwk"});return(delete r.d,delete r.dp,delete r.dq,delete r.p,delete r.q,delete r.qi,r.k)?eU(r.k):(i||(i=new WeakMap),eH(i,e,r,t))}return eZ(e)?e.k?eE(e.k):(i||(i=new WeakMap),eH(i,e,e,t,!0)):e},normalizePrivateKey:(e,t)=>{if(eF(e)){let r=e.export({format:"jwk"});return r.k?eU(r.k):(s||(s=new WeakMap),eH(s,e,r,t))}return eZ(e)?e.k?eE(e.k):(s||(s=new WeakMap),eH(s,e,e,t,!0)):e}};async function eB(e,t,r){if("sign"===r&&(t=await eJ.normalizePrivateKey(t,e)),"verify"===r&&(t=await eJ.normalizePublicKey(t,e)),t instanceof CryptoKey)return!function(e,t,...r){switch(t){case"HS256":case"HS384"
1:case"HS512":{if(!ez(e.algorithm,"HMAC"))throw eL("HMAC");let r=parseInt(t.slice(2),10);if(eK(e.algorithm.hash)!==r)throw eL(`SHA-${r}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!ez(e.algorithm,"RSASSA-PKCS1-v1_5"))throw eL("RSASSA-PKCS1-v1_5");let r=parseInt(t.slice(2),10);if(eK(e.algorithm.hash)!==r)throw eL(`SHA-${r}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!ez(e.algorithm,"RSA-PSS"))throw eL("RSA-PSS");let r=parseInt(t.slice(2),10);if(eK(e.algorithm.hash)!==r)throw eL(`SHA-${r}`,"algorithm.hash");break}case"EdDSA":if("Ed25519"!==e.algorithm.name&&"Ed448"!==e.algorithm.name)throw eL("Ed25519 or Ed448");break;case"Ed25519":if(!ez(e.algorithm,"Ed25519"))throw eL("Ed25519");break;case"ES256":case"ES384":case"ES512":{if(!ez(e.algorithm,"ECDSA"))throw eL("ECDSA");let r=function(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw Error("unreachable")}}(t);if(e.algorithm.namedCurve!==r)throw eL(r,"algorithm.namedCurve");break}default:throw TypeError("CryptoKey does not support this operation")}if(r.length&&!r.some(t=>e.usages.includes(t))){let e="CryptoKey does not support this operation, its usages must include ";if(r.length>2){let t=r.pop();e+=`one of ${r.join(", ")}, or ${t}.`}else 2===r.length?e+=`one of ${r[0]} or ${r[1]}.`:e+=`${r[0]}.`;throw TypeError(e)}}(t,e,r),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw TypeError(eM(t,...eW));return eA.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}throw TypeError(eM(t,...eW,"Uint8Array","JSON Web Key"))}let eV=async(e,t,r)=>{let s=await eB(e,t,"sign");return e$(e,s),new Uint8Array(await eA.subtle.sign(eD(e,s.algorithm),s,r))},eG=(...e)=>{let t,r=e.filter(Boolean);if(0===r.length||1===r.length)return!0;for(let e of r){let r=Object.keys(e);if(!t||0===t.size){t=new Set(r);continue}for(let e of r){if(t.has(e))return!1;t.add(e)}}return!0},eX=e=>e?.[Symbol.toStringTag],eQ=(e,t,r)=>{if(void 0!==t.use&&"sig"!==t.use)throw TypeError("Invalid key for this operation, when present its use must be sig");if(void 0!==t.key_ops&&t.key_ops.includes?.(r)!==!0)throw TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(void 0!==t.alg&&t.alg!==e)throw TypeError(`Invalid key for this operation, when present its alg must be ${e}`);return!0};function e0(e,t,r,s){t.startsWith("HS")||"dir"===t||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?((e,t,r,s)=>{if(!(t instanceof Uint8Array)){if(s&&eZ(t)){var i;if(eZ(i=t)&&"oct"===i.kty&&"string"==typeof i.k&&eQ(e,t,r))return;throw TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!eN(t))throw TypeError(eY(e,t,...eW,"Uint8Array",s?"JSON Web Key":null));if("secret"!==t.type)throw TypeError(`${eX(t)} instances for symmetric algorithms must be of type "secret"`)}})(t,r,s,e):((e,t,r,s)=>{var i,a;if(s&&eZ(t))switch(r){case"sign":if("oct"!==(i=t).kty&&"string"==typeof i.d&&eQ(e,t,r))return;throw TypeError("JSON Web Key for this operation be a private JWK");case"verify":if("oct"!==(a=t).kty&&void 0===a.d&&eQ(e,t,r))return;throw TypeError("JSON Web Key for this operation be a public JWK")}if(!eN(t))throw TypeError(eY(e,t,...eW,s?"JSON Web Key":null));if("secret"===t.type)throw TypeError(`${eX(t)} instances for asymmetric algorithms must not be of type "secret"`);if("sign"===r&&"public"===t.type)throw TypeError(`${eX(t)} instances for asymmetric algorithm signing must be of type "private"`);if("decrypt"===r&&"public"===t.type)throw TypeError(`${eX(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&"verify"===r&&"private"===t.type)throw TypeError(`${eX(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&"encrypt"===r&&"private"===t.type)throw TypeError(`${eX(t)} instances for asymmetric algorithm encryption must be of type "public"`)})(t,r,s,e)}e0.bind(void 0,!1);let e1=e0.bind(void 0,!0),e2=function(e,t,r,s,i){let a;if(void 0!==i.crit&&s?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!s||void 0===s.crit)return new Set;if(!Array.isArray(s.crit)||0===s.crit.length||s.crit.some(e=>"string"!=typeof e||0===e.length))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');for(let n of(a=void 0!==r?new Map([...Object.entries(r),...t.entries()]):t,s.crit)){if(!a.has(n))throw new ed(`Extension Header Parameter "${n}" is not recognized`);if(void 0===i[n])throw new e(`Extension Header Parameter "${n}" is missing`);if(a.get(n)&&void 0===s[n])throw new e(`Extension Header Parameter "${n}" MUST be integrity protected`)}return new Set(s.crit)};class e5{constructor(e){if(!(e instanceof Uint8Array))throw TypeError("payload must be an instance of Uint8Array");this._payload=e}setProtectedHeader(e){if(this._protectedHeader)throw TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}async sign(e,t){let r;if(!this._protectedHeader&&!this._unprotectedHeader)throw new ep("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!eG(this._protectedHeader,this._unprotectedHeader))throw new ep("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let s={...this._protectedHeader,...this._unprotectedHeader},i=e2(ep,new Map([["b64",!0]]),t?.crit,this._protectedHeader,s),a=!0;if(i.has("b64")&&"boolean"!=typeof(a=this._protectedHeader.b64))throw new ep('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:n}=s;if("string"!=typeof n||!n)throw new ep('JWS "alg" (Algorithm) Header Parameter missing or invalid');e1(n,e,"sign");let o=this._payload;a&&(o=eb.encode(ex(o)));
1let l=eS(r=this._protectedHeader?eb.encode(ex(JSON.stringify(this._protectedHeader))):eb.encode(""),eb.encode("."),o),c={signature:ex(await eV(n,e,l)),payload:""};return a&&(c.payload=ek.decode(o)),this._unprotectedHeader&&(c.header=this._unprotectedHeader),this._protectedHeader&&(c.protected=ek.decode(r)),c}}class e4{constructor(e){this._flattened=new e5(e)}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}async sign(e,t){let r=await this._flattened.sign(e,t);if(void 0===r.payload)throw TypeError("use the flattened module for creating JWS with b64: false");return`${r.protected}.${r.payload}.${r.signature}`}}let e8=e=>Math.floor(e.getTime()/1e3),e9=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,e6=e=>{let t,r=e9.exec(e);if(!r||r[4]&&r[1])throw TypeError("Invalid time period format");let s=parseFloat(r[2]);switch(r[3].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":t=Math.round(s);break;case"minute":case"minutes":case"min":case"mins":case"m":t=Math.round(60*s);break;case"hour":case"hours":case"hr":case"hrs":case"h":t=Math.round(3600*s);break;case"day":case"days":case"d":t=Math.round(86400*s);break;case"week":case"weeks":case"w":t=Math.round(604800*s);break;default:t=Math.round(0x1e187e0*s)}return"-"===r[1]||"ago"===r[4]?-t:t};function e3(e,t){if(!Number.isFinite(t))throw TypeError(`Invalid ${e} input`);return t}class e7{constructor(e={}){if(!eO(e))throw TypeError("JWT Claims Set MUST be an object");this._payload=e}setIssuer(e){return this._payload={...this._payload,iss:e},this}setSubject(e){return this._payload={...this._payload,sub:e},this}setAudience(e){return this._payload={...this._payload,aud:e},this}setJti(e){return this._payload={...this._payload,jti:e},this}setNotBefore(e){return"number"==typeof e?this._payload={...this._payload,nbf:e3("setNotBefore",e)}:e instanceof Date?this._payload={...this._payload,nbf:e3("setNotBefore",e8(e))}:this._payload={...this._payload,nbf:e8(new Date)+e6(e)},this}setExpirationTime(e){return"number"==typeof e?this._payload={...this._payload,exp:e3("setExpirationTime",e)}:e instanceof Date?this._payload={...this._payload,exp:e3("setExpirationTime",e8(e))}:this._payload={...this._payload,exp:e8(new Date)+e6(e)},this}setIssuedAt(e){return void 0===e?this._payload={...this._payload,iat:e8(new Date)}:e instanceof Date?this._payload={...this._payload,iat:e3("setIssuedAt",e8(e))}:"string"==typeof e?this._payload={...this._payload,iat:e3("setIssuedAt",e8(new Date)+e6(e))}:this._payload={...this._payload,iat:e3("setIssuedAt",e)},this}}class te extends e7{setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,t){let r=new e4(eb.encode(JSON.stringify(this._payload)));if(r.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&!1===this._protectedHeader.b64)throw new ef("JWTs MUST NOT use unencoded payload");return r.sign(e,t)}}let tt=async(e,t,r,s)=>{let i=await eB(e,t,"verify");e$(e,i);let a=eD(e,i.algorithm);try{return await eA.subtle.verify(a,i,r,s)}catch{return!1}};async function tr(e,t,r){let s,i;if(!eO(e))throw new ep("Flattened JWS must be an object");if(void 0===e.protected&&void 0===e.header)throw new ep('Flattened JWS must have either of the "protected" or "header" members');if(void 0!==e.protected&&"string"!=typeof e.protected)throw new ep("JWS Protected Header incorrect type");if(void 0===e.payload)throw new ep("JWS Payload missing");if("string"!=typeof e.signature)throw new ep("JWS Signature missing or incorrect type");if(void 0!==e.header&&!eO(e.header))throw new ep("JWS Unprotected Header incorrect type");let a={};if(e.protected)try{let t=eE(e.protected);a=JSON.parse(ek.decode(t))}catch{throw new ep("JWS Protected Header is invalid")}if(!eG(a,e.header))throw new ep("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let n={...a,...e.header},o=e2(ep,new Map([["b64",!0]]),r?.crit,a,n),l=!0;if(o.has("b64")&&"boolean"!=typeof(l=a.b64))throw new ep('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:c}=n;if("string"!=typeof c||!c)throw new ep('JWS "alg" (Algorithm) Header Parameter missing or invalid');let d=r&&((e,t)=>{if(void 0!==t&&(!Array.isArray(t)||t.some(e=>"string"!=typeof e)))throw TypeError(`"${e}
1" option must be an array of strings`);if(t)return new Set(t)})("algorithms",r.algorithms);if(d&&!d.has(c))throw new ec('"alg" (Algorithm) Header Parameter value not allowed');if(l){if("string"!=typeof e.payload)throw new ep("JWS Payload must be a string")}else if("string"!=typeof e.payload&&!(e.payload instanceof Uint8Array))throw new ep("JWS Payload must be a string or an Uint8Array instance");let u=!1;"function"==typeof t?(t=await t(a,e),u=!0,e1(c,t,"verify"),eZ(t)&&(t=await eP(t,c))):e1(c,t,"verify");let h=eS(eb.encode(e.protected??""),eb.encode("."),"string"==typeof e.payload?eb.encode(e.payload):e.payload);try{s=eE(e.signature)}catch{throw new ep("Failed to base64url decode the signature")}if(!await tt(c,t,s,h))throw new e_;if(l)try{i=eE(e.payload)}catch{throw new ep("Failed to base64url decode the payload")}else i="string"==typeof e.payload?eb.encode(e.payload):e.payload;let p={payload:i};return(void 0!==e.protected&&(p.protectedHeader=a),void 0!==e.header&&(p.unprotectedHeader=e.header),u)?{...p,key:t}:p}async function ts(e,t,r){if(e instanceof Uint8Array&&(e=ek.decode(e)),"string"!=typeof e)throw new ep("Compact JWS must be a string or Uint8Array");let{0:s,1:i,2:a,length:n}=e.split(".");if(3!==n)throw new ep("Invalid Compact JWS");let o=await tr({payload:i,protected:s,signature:a},t,r),l={payload:o.payload,protectedHeader:o.protectedHeader};return"function"==typeof t?{...l,key:o.key}:l}let ti=e=>e.toLowerCase().replace(/^application\//,"");async function ta(e,t,r){let s=await ts(e,t,r);if(s.protectedHeader.crit?.includes("b64")&&!1===s.protectedHeader.b64)throw new ef("JWTs MUST NOT use unencoded payload");let i={payload:((e,t,r={})=>{let s,i,a,n;try{s=JSON.parse(ek.decode(t))}catch{}if(!eO(s))throw new ef("JWT Claims Set must be a top-level JSON object");let{typ:o}=r;if(o&&("string"!=typeof e.typ||ti(e.typ)!==ti(o)))throw new eo('unexpected "typ" JWT header value',s,"typ","check_failed");let{requiredClaims:l=[],issuer:c,subject:d,audience:u,maxTokenAge:h}=r,p=[...l];for(let e of(void 0!==h&&p.push("iat"),void 0!==u&&p.push("aud"),void 0!==d&&p.push("sub"),void 0!==c&&p.push("iss"),new Set(p.reverse())))if(!(e in s))throw new eo(`missing required "${e}" claim`,s,e,"missing");if(c&&!(Array.isArray(c)?c:[c]).includes(s.iss))throw new eo('unexpected "iss" claim value',s,"iss","check_failed");if(d&&s.sub!==d)throw new eo('unexpected "sub" claim value',s,"sub","check_failed");if(u&&(a=s.aud,n="string"==typeof u?[u]:u,"string"==typeof a?!n.includes(a):!(!!Array.isArray(a)&&n.some(Set.prototype.has.bind(new Set(a))))))throw new eo('unexpected "aud" claim value',s,"aud","check_failed");switch(typeof r.clockTolerance){case"string":i=e6(r.clockTolerance);break;case"number":i=r.clockTolerance;break;case"undefined":i=0;break;default:throw TypeError("Invalid clockTolerance option type")}let{currentDate:f}=r,m=e8(f||new Date);if((void 0!==s.iat||h)&&"number"!=typeof s.iat)throw new eo('"iat" claim must be a number',s,"iat","invalid");if(void 0!==s.nbf){if("number"!=typeof s.nbf)throw new eo('"nbf" claim must be a number',s,"nbf","invalid");if(s.nbf>m+i)throw new eo('"nbf" claim timestamp check failed',s,"nbf","check_failed")}if(void 0!==s.exp){if("number"!=typeof s.exp)throw new eo('"exp" claim must be a number',s,"exp","invalid");if(s.exp<=m-i)throw new el('"exp" claim timestamp check failed',s,"exp","check_failed")}if(h){let e=m-s.iat;if(e-i>("number"==typeof h?h:e6(h)))throw new el('"iat" claim timestamp check failed (too far in the past)',s,"iat","check_failed");if(e<0-i)throw new eo('"iat" claim timestamp check failed (it should be in the past)',s,"iat","check_failed")}return s})(s.protectedHeader,s.payload,r),protectedHeader:s.protectedHeader};return"function"==typeof t?{...i,key:s.key}:i}function tn(e){let t=e?.modulusLength??2048;if("number"!=typeof t||t<2048)throw new ed("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return t}async function to(e,t){let r,s;switch(e){case"PS256":case"PS384":case"PS512":r={name:"RSA-PSS",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:tn(t)},s=["sign","verify"];break;case"RS256":case"RS384":case"RS512":r={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:tn(t)},s=["sign","verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":r={name:"RSA-OAEP",hash:`SHA-${parseInt(e.slice(-3),10)||1}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:tn(t)},s=["decrypt","unwrapKey","encrypt","wrapKey"];break;case"ES256":r={name:"ECDSA",namedCurve:"P-256"},s=["sign","verify"];break;case"ES384":r={name:"ECDSA",namedCurve:"P-384"},s=["sign","verify"];break;case"ES512":r={name:"ECDSA",namedCurve:"P-521"},s=["sign","verify"];break;case"Ed25519":r={name:"Ed25519"},s=["sign","verify"];break;case"EdDSA":{s=["sign","verify"];let e=t?.crv??"Ed25519";
1switch(e){case"Ed25519":case"Ed448":r={name:e};break;default:throw new ed("Invalid or unsupported crv option provided")}break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{s=["deriveKey","deriveBits"];let e=t?.crv??"P-256";switch(e){case"P-256":case"P-384":case"P-521":r={name:"ECDH",namedCurve:e};break;case"X25519":case"X448":r={name:e};break;default:throw new ed("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448")}break}default:throw new ed('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return eA.subtle.generateKey(r,t?.extractable??!1,s)}async function tl(e,t){return to(e,t)}let tc=async e=>{if(e instanceof Uint8Array)return{kty:"oct",k:ex(e)};if(!(e instanceof CryptoKey))throw TypeError(eM(e,...eW,"Uint8Array"));if(!e.extractable)throw TypeError("non-extractable CryptoKey cannot be exported as a JWK");let{ext:t,key_ops:r,alg:s,use:i,...a}=await eA.subtle.exportKey("jwk",e);return a};async function td(e){return tc(e)}let{i4:tu}=n;class th extends ee{async getKeyObj(e){if(!this.algorithms.includes(e))throw new c(`Key cannot be used with algorithm "${e}"`);try{return await eP(this.jwk,e)}catch(e){throw new c("Failed to import JWK",void 0,{cause:e})}}async createJwt(e,t){try{let{kid:r}=e;if(r&&r!==this.kid)throw new d(`Invalid "kid" (${r}) used to sign with key "${this.kid}"`);let{alg:s}=e;if(!s)throw new d('Missing "alg" in JWT header');let i=await this.getKeyObj(s),a=new te(t).setProtectedHeader({...e,alg:s,kid:this.kid});return await a.sign(i)}catch(e){if(e instanceof tu)throw new d(e.message,e.code,{cause:e});throw d.from(e)}}async verifyJwt(e,t){try{let r=await ta(e,async({alg:e})=>this.getKeyObj(e),{...t,algorithms:this.algorithms}),s=B.safeParse(r.protectedHeader);if(!s.success)throw new u("Invalid JWT header",void 0,{cause:s.error});let i=G.safeParse(r.payload);if(!i.success)throw new u("Invalid JWT payload",void 0,{cause:i.error});return{protectedHeader:s.data,payload:i.data}}catch(e){if(e instanceof tu)throw new u(e.message,e.code,{cause:e});throw u.from(e)}}static async generateKeyPair(e=["ES256"],t){if(!e.length)throw new c("No algorithms provided for key generation");let r=[];for(let s of e)try{return await tl(s,t)}catch(e){r.push(e)}throw new c("Failed to generate key pair",void 0,{cause:AggregateError(r,"None of the algorithms worked")})}static async generate(e=["ES256"],t,r){let s=await this.generateKeyPair(e,{...r,extractable:!0});return this.fromKeyLike(s.privateKey,t)}static async fromImportable(e,t){if("string"==typeof e){if(e.startsWith("-----"))return this.fromPKCS8(e,"",t);if(e.startsWith("{"))return this.fromJWK(e,t);throw new c("Invalid input")}if("object"==typeof e)return"kty"in e||"alg"in e?this.fromJWK(e,t):this.fromKeyLike(e,t);throw new c("Invalid input")}static async fromKeyLike(e,t,r){let s=await td(e);if(r)if(s.alg){if(s.alg!==r)throw new c('Invalid "alg" in JWK')}else s.alg=r;return this.fromJWK(s,t)}static async fromPKCS8(e,t,r){let s=await eC(e,t,{extractable:!0});return this.fromKeyLike(s,r)}static async fromJWK(e,t){let r="string"==typeof e?JSON.parse(e):e;if(!r||"object"!=typeof r)throw new c("Invalid JWK");let s=function(e,t){if(null!=e&&null!=t&&e!==t)throw TypeError(`Expected "${t}", got "${e}"`);return e??t??void 0}(r.kid,t);return null!=r.use&&M(r)&&(console.warn('Deprecation warning: Private JWK with a "use" property will be rejected in the future. Please remove replace "use" with (valid) "key_ops".'),r.key_ops??="sig"===r.use?["sign"]:["encrypt"],delete r.use),new th(L.parse({...r,kid:s}))}}class tp extends th{static async generate(e=["ES256"],t=crypto.randomUUID(),r){let s=await this.generateKeyPair(e,r);if(!("object"==typeof s&&null!==s&&"privateKey"in s&&s.privateKey instanceof CryptoKey&&"private"===s.privateKey.type&&s.privateKey.usages.includes("sign")&&"publicKey"in s&&s.publicKey instanceof CryptoKey&&"public"===s.publicKey.type&&!0===s.publicKey.extractable&&s.publicKey.usages.includes("verify")))throw TypeError("Invalid CryptoKeyPair");return this.fromKeypair(s,t)}static async fromKeypair(e,t){let{alg:r=function(e){switch(e.name){case"RSA-PSS":case"RSASSA-PKCS1-v1_5":{let t=e.hash.name;switch(t){case"SHA-256":case"SHA-384":case"SHA-512":{let r="RSA-PSS"===e.name?"PS":"RS";return`${r}${t.slice(-3)}`}default:throw TypeError("unsupported RsaHashedKeyAlgorithm hash")}}case"ECDSA":{let t=e.namedCurve;switch(t){case"P-256":case"P-384":case"P-512":return`ES${t.slice(-3)}`;case"P-521":return"ES512";default:throw TypeError("unsupported EcKeyAlgorithm namedCurve")}}
1case"Ed448":case"Ed25519":return"EdDSA";default:throw TypeError(`Unexpected algorithm "${e.name}"`)}}(e.privateKey.algorithm),...s}=await crypto.subtle.exportKey("jwk",e.privateKey.extractable?e.privateKey:e.publicKey);return new tp(L.parse({...s,kid:t,alg:r}),e)}constructor(e,t){if(!e.alg)throw new c('JWK "alg" is required for Webcrypto keys');super(e),this.cryptoKeyPair=t}get isPrivate(){return!0}async getKeyObj(e){if(this.jwk.alg!==e)throw new c(`Key cannot be used with algorithm "${e}"`);return this.cryptoKeyPair.privateKey}}let tf=e=>"number"==typeof e?e:void 0;class tm extends Error{constructor(e,t,r,s=400,i){super(t,{cause:i}),this.did=e,this.code=r,this.status=s}get statusCode(){return this.status}toString(){return`${this.constructor.name} ${this.code} (${this.did}): ${this.message}`}static from(e,t){return e instanceof tm?e:new tm(t,e instanceof Error?e.message:"string"==typeof e?e:"An unknown error occurred","did-unknown-error","object"==typeof e&&null!=e?("statusCode"in e?tf(e.statusCode):void 0)??("status"in e?tf(e.status):void 0):void 0,e)}}class ty extends tm{constructor(e,t,r){super(e,t,"did-invalid",400,r)}}let tg="did:",tv=tg.length;function tw(e,t=0,r=e.length){let s;if(!Number.isFinite(r)||!Number.isFinite(t)||r<t||r>e.length)throw TypeError("Invalid start or end position");if(r===t)throw new ty(e,"DID method-specific id must not be empty");for(let i=t;i<r;i++)if(((s=e.charCodeAt(i))<97||s>122)&&(s<65||s>90)&&(s<48||s>57)&&46!==s&&45!==s&&95!==s){if(58===s){if(i===r-1)throw new ty(e,'DID cannot end with ":"');continue}if(37===s){if(((s=e.charCodeAt(++i))<48||s>57)&&(s<65||s>70)||((s=e.charCodeAt(++i))<48||s>57)&&(s<65||s>70))throw new ty(e,`Invalid pct-encoded character at position ${i}`);if(i>=r)throw new ty(e,`Incomplete pct-encoded character at position ${i-2}`);continue}throw new ty(e,`Disallowed character in DID at position ${i}`)}}let t_=h.Yj().superRefine((e,t)=>{try{return!function(e){if("string"!=typeof e)throw new ty(typeof e,"DID must be a string");let{length:t}=e;if(t>2048)throw new ty(e,"DID is too long (2048 chars max)");if(!e.startsWith(tg))throw new ty(e,`DID requires "${tg}" prefix`);let r=e.indexOf(":",tv);if(-1===r)throw new ty(e,"Missing colon after method name");!function(e,t=0,r=e.length){let s;if(!Number.isFinite(r)||!Number.isFinite(t)||r<t||r>e.length)throw TypeError("Invalid start or end position");if(r===t)throw new ty(e,"Empty method name");for(let i=t;i<r;i++)if(((s=e.charCodeAt(i))<97||s>122)&&(s<48||s>57))throw new ty(e,`Invalid character at position ${i} in DID method name`)}(e,tv,r),tw(e,r+1,t)}(e),!0}catch(e){return t.addIssue({code:f.eq.custom,message:e instanceof Error?e.message:"Unexpected error"}),!1}});function tb(e,t=0,r=e.length){let s;for(let i=t;i<r;i++)if((s=e.charCodeAt(i))>=65&&s<=90||s>=97&&s<=122||s>=48&&s<=57||45===s||46===s||95===s||126===s);else if(33===s||36===s||38===s||39===s||40===s||41===s||42===s||43===s||44===s||59===s||61===s);else if(58===s||64===s);else if(47===s||63===s);else{if(37!==s||i+2>=r||!tk(e.charCodeAt(i+1))||!tk(e.charCodeAt(i+2)))return!1;i+=2}return!0}function tk(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}let tS=URL.canParse?.bind(URL)??((e,t)=>{try{return new URL(e,t),!0}catch{return!1}}),tx="did:plc:",tE=tx.length;function tA(e){if("string"!=typeof e)throw new ty(typeof e,"DID must be a string");if(!e.startsWith(tx))throw new ty(e,"Invalid did:plc prefix");if(32!==e.length)throw new ty(e,"did:plc must be 32 characters long");for(let t=tE;t<32;t++)if(!tj(e.charCodeAt(t)))throw new ty(e,`Invalid character at position ${t}`)}let tj=e=>e>=97&&e<=122||e>=50&&e<=55,tI="did:web:";function tT(e){let t=tI.length,r=e.indexOf(":",t),s=(-1===r?e.slice(t):e.slice(t,r)).replaceAll("%3A",":"),i=-1===r?"":e.slice(r).replaceAll(":","/"),a=s.startsWith("localhost")&&(9===s.length||58===s.charCodeAt(9))?"http":"https";return`${a}://${s}${i}`}let tR=h.Yj().refine(tO,'Atproto only allows "plc" and "web" DID methods');function tO(e){var t;return function(e){if("string"!=typeof e||32!==e.length||!e.startsWith(tx))return!1;for(let t=tE;t<32;t++)if(!tj(e.charCodeAt(t)))return!1;return!0}(e)||!(!function(e){if("string"!=typeof e||!e.startsWith(tI)||":"===e.charAt(tI.length))return!1;try{tw(e,tI.length)}catch{return!1}return tS(tT(e))}(t=e)||tP(t)||tD(t))}function tC(e){if("string"!=typeof e)throw new ty(typeof e,"DID must be a string");if(e.startsWith(tx))tA(e);else if(e.startsWith(tI)){var t=e;if("string"!=typeof t)throw new ty(typeof t,"DID must be a string");if(!t.startsWith(tI))throw new ty(t,"Invalid did:web prefix");if(":"===t.charAt(tI.length))throw new ty(t,"did:web MSID must not start with a colon");if(tw(t,tI.length),!tS(tT(t)))throw new ty(t,"Invalid Web DID");if(tP(t))throw new ty(t,"Atproto does not allow path components in Web DIDs");if(tD(t))throw new ty(t,"Atproto does not allow port numbers in Web DIDs, except for localhost")}else throw new ty(e,'Atproto only allows "plc" and "web" DID methods')}function tP(e){return e.includes(":",tI.length)}
1function tD(e){if("did:web:localhost"===e||e.startsWith("did:web:localhost:")||e.startsWith("did:web:localhost%3A"))return!1;let t=e.indexOf(":",tI.length);return -1===t?e.includes("%3A",tI.length):-1!==e.lastIndexOf("%3A",t)}function t$(e){var t,r,s;return e?.type==="AtprotoPersonalDataServer"&&"string"==typeof e.serviceEndpoint&&tS(e.serviceEndpoint)&&(t=this.id,r="atproto_pds",35===(s=e.id).charCodeAt(0)?s.length===r.length+1&&s.endsWith(r):s.length===r.length+1+t.length&&35===s.charCodeAt(t.length)&&s.startsWith(t)&&s.endsWith(r))}Object.freeze(["EcdsaSecp256r1VerificationKey2019","EcdsaSecp256k1VerificationKey2019","Multikey"]);let tL=h.Yj().url("RFC3968 compliant URI"),tz=h.KC([t_,h.YO(t_)]),tK=h.KC([tL.refine(e=>{let t=e.indexOf("#");return -1!==t&&tb(e,t+1)},{message:"Missing or invalid fragment in RFC3968 URI"}),h.Yj().refine(e=>35===e.charCodeAt(0),{message:"Fragment must start with #"}).refine(e=>tb(e,1),{message:"Invalid char in URI fragment"})]),tq=h.Ik({id:tK,type:h.Yj().min(1),controller:tz,publicKeyJwk:h.g1(h.Yj(),h.L5()).optional(),publicKeyMultibase:h.Yj().optional()}),tM=h.KC([h.Yj(),h.YO(h.Yj())]),tY=h.KC([tL,h.g1(h.Yj(),tL),h.YO(h.KC([tL,h.g1(h.Yj(),tL)])).nonempty()]),tN=h.Ik({id:tK,type:tM,serviceEndpoint:tY}),tW=h.KC([tK,tq]),tZ=h.Ik({"@context":h.KC([h.eu("https://www.w3.org/ns/did/v1"),h.YO(h.Yj().url()).nonempty().refine(e=>"https://www.w3.org/ns/did/v1"===e[0],{message:"First @context must be https://www.w3.org/ns/did/v1"})]).optional(),id:t_,controller:tz.optional(),alsoKnownAs:h.YO(tL).optional(),service:h.YO(tN).optional(),authentication:h.YO(tW).optional(),verificationMethod:h.YO(tq).optional()}).superRefine(({id:e,service:t},r)=>{if(t){let s=new Set;for(let i=0;i<t.length;i++){let a=t[i],n=a.id.startsWith("#")?`${e}${a.id}`:a.id;s.has(n)?r.addIssue({code:f.eq.custom,message:`Duplicate service id (${a.id}) found in the document`,path:["service",i,"id"]}):s.add(n)}}});function tU(e,t="Assertion failed"){if(!e)throw Error(t)}let tF=()=>!0,tH=()=>!1;class tJ{#e=new Map;#t;#r;#s={};constructor(e,t,r={}){this.#t=e,this.#r=t,this.#s=r}async get(e,{signal:t,context:r,allowStale:s=!1,noCache:i=!1}={}){let a;t?.throwIfAborted();let{isStale:n,deleteOnError:o}=this.#s,l=i?tH:s||null==n?tF:async t=>!await n(e,t);for(;a=this.#e.get(e);){try{let{isFresh:e,value:t}=await a;if(e||await l(t))return t}catch{}t?.throwIfAborted()}let c=Promise.resolve().then(async()=>{t?.throwIfAborted();
1let s=await this.getStored(e,{signal:t});return void 0!==s&&await l(s)?{isFresh:!1,value:s}:(t?.throwIfAborted(),Promise.resolve().then(async()=>this.#t.call(null,e,{signal:t,noCache:i,context:r},s)).catch(async t=>{if(void 0!==s)try{await o?.(t,e,s)&&await this.delStored(e,t)}catch(e){throw AggregateError([t,e],"Error while deleting stored value")}throw t}).then(async t=>(await this.setStored(e,t),{isFresh:!0,value:t})))}).finally(()=>{tU(this.#e.get(e)===c,`Pending item for key "${e}" was replaced before it finished.`),this.#e.delete(e)});tU(!this.#e.has(e),`Concurrent execution flow for key "${e}" should not exist.`),this.#e.set(e,c);let{value:d}=await c;return d}async getStored(e,t){return this.#r.get(e,t)}async setStored(e,t){await this.#r.set(e,t)}async delStored(e,t){await this.#r.del(e)}}let tB=(e,t)=>{console.error(`SimpleStore error during "${t}"`,e)};function tV(e,t=tB){return{async get(r,s){s?.signal?.throwIfAborted();try{return await e.get(r,s)}catch(e){if(s?.signal?.aborted)throw e;t(e,"get",r);return}},async set(r,s){try{await e.set(r,s)}catch(e){t(e,"set",r)}},async del(r){try{await e.del(r)}catch(e){t(e,"del",r)}},async clear(){try{await e.clear?.()}catch(e){t(e,"clear")}}}}var tG=r(95704);let tX="object"==typeof performance&&performance&&"function"==typeof performance.now?performance:Date,tQ=new Set,t0="object"==typeof tG&&tG?tG:{},t1=(e,t,r,s)=>{"function"==typeof t0.emitWarning?t0.emitWarning(e,t,r,s):console.error(`[${r}] ${t}: ${e}`)},t2=globalThis.AbortController,t5=globalThis.AbortSignal;if(void 0===t2){t5=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(e,t){this._onabort.push(t)}},t2=class{constructor(){t()}signal=new t5;abort(e){if(!this.signal.aborted){for(let t of(this.signal.reason=e,this.signal.aborted=!0,this.signal._onabort))t(e);this.signal.onabort?.(e)}}};let e=t0.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",t=()=>{e&&(e=!1,t1("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",t))}}Symbol("type");let t4=e=>e&&e===Math.floor(e)&&e>0&&isFinite(e),t8=e=>t4(e)?e<=256?Uint8Array:e<=65536?Uint16Array:e<=0x100000000?Uint32Array:e<=Number.MAX_SAFE_INTEGER?t9:null:null;class t9 extends Array{constructor(e){super(e),this.fill(0)}}class t6{heap;length;static #i=!1;static create(e){let t=t8(e);if(!t)return[];t6.#i=!0;let r=new t6(e,t);return t6.#i=!1,r}constructor(e,t){if(!t6.#i)throw TypeError("instantiate Stack using Stack.create(n)");this.heap=new t(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}}class t3{#a;#n;#o;#l;#c;#d;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#u;#h;#p;#f;#m;#y;#g;#v;#w;#_;#b;#k;#S;#x;#E;#A;#j;static unsafeExposeInternals(e){return{starts:e.#S,ttls:e.#x,sizes:e.#k,keyMap:e.#p,keyList:e.#f,valList:e.#m,next:e.#y,prev:e.#g,get head(){return e.#v},get tail(){return e.#w},free:e.#_,isBackgroundFetch:t=>e.#I(t),backgroundFetch:(t,r,s,i)=>e.#T(t,r,s,i),moveToTail:t=>e.#R(t),indexes:t=>e.#O(t),rindexes:t=>e.#C(t),isStale:t=>e.#P(t)}}get max(){return this.#a}get maxSize(){return this.#n}get calculatedSize(){return this.#h}get size(){return this.#u}get fetchMethod(){return this.#c}get memoMethod(){return this.#d}get dispose(){return this.#o}get disposeAfter(){return this.#l}constructor(e){let{max:t=0,ttl:r,ttlResolution:s=1,ttlAutopurge:i,updateAgeOnGet:a,updateAgeOnHas:n,allowStale:o,dispose:l,disposeAfter:c,noDisposeOnSet:d,noUpdateTTL:u,maxSize:h=0,maxEntrySize:p=0,sizeCalculation:f,fetchMethod:m,memoMethod:y,noDeleteOnFetchRejection:g,noDeleteOnStaleGet:v,allowStaleOnFetchRejection:w,allowStaleOnFetchAbort:_,ignoreFetchAbort:b}=e;if(0!==t&&!t4(t))throw TypeError("max option must be a nonnegative integer");let k=t?t8(t):Array;if(!k)throw Error("invalid max value: "+t);if(this.#a=t,this.#n=h,this.maxEntrySize=p||this.#n,this.sizeCalculation=f,this.sizeCalculation){if(!this.#n&&!this.maxEntrySize)throw TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if("function"!=typeof this.sizeCalculation)throw TypeError("sizeCalculation set to non-function")}if(void 0!==y&&"function"!=typeof y)throw TypeError("memoMethod must be a function if defined");if(this.#d=y,void 0!==m&&"function"!=typeof m)throw TypeError("fetchMethod must be a function if specified");if(this.#c=m,this.#A=!!m,this.#p=new Map,this.#f=Array(t).fill(void 0),this.#m=Array(t).fill(void 0),this.#y=new k(t),this.#g=new k(t),this.#v=0,this.#w=0,this.#_=t6.create(t),this.#u=0,this.#h=0,"function"==typeof l&&(this.#o=l),"function"==typeof c?(this.#l=c,this.#b=[]):(this.#l=void 0,this.#b=void 0),this.#E=!!this.#o,this.#j=!!this.#l,this.noDisposeOnSet=!!d,this.noUpdateTTL=!!u,this.noDeleteOnFetchRejection=!!g,this.allowStaleOnFetchRejection=!!w,this.allowStaleOnFetchAbort=!!_,this.ignoreFetchAbort=!!b,0!==this.maxEntrySize){if(0!==this.#n&&!t4(this.#n))throw TypeError("maxSize must be a positive integer if specified");if(!t4(this.maxEntrySize))throw TypeError("maxEntrySize must be a positive integer if specified");this.#D()}if(this.allowStale=!!o,this.noDeleteOnStaleGet=!!v,this.updateAgeOnGet=!!a,this.updateAgeOnHas=!!n,this.ttlResolution=t4(s)||0===s?s:1,this.ttlAutopurge=!!i,this.ttl=r||0,this.ttl){if(!t4(this.ttl))throw TypeError("ttl must be a positive integer if specified");this.#$()}if(0===this.#a&&0===this.ttl&&0===this.#n)throw TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#a&&!this.#n){let e="LRU_CACHE_UNBOUNDED";tQ.has(e)||(tQ.add(e),t1("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",e,t3))}}getRemainingTTL(e){return this.#p.has(e)?1/0:0}#$(){let e=new t9(this.#a),t=new t9(this.#a);this.#x=e,this.#S=t,this.#L=(r,s,i=tX.now())=>{if(t[r]=0!==s?i:0,e[r]=s,0!==s&&this.ttlAutopurge){let e=setTimeout(()=>{this.#P(r)&&this.#z(this.#f[r],"expire")},s+1);e.unref&&e.unref()}},this.#K=r=>{t[r]=0!==e[r]?tX.now():0},this.#q=(i,a)=>
1{if(e[a]){let n=e[a],o=t[a];if(!n||!o)return;i.ttl=n,i.start=o,i.now=r||s();let l=i.now-o;i.remainingTTL=n-l}};let r=0,s=()=>{let e=tX.now();if(this.ttlResolution>0){r=e;let t=setTimeout(()=>r=0,this.ttlResolution);t.unref&&t.unref()}return e};this.getRemainingTTL=i=>{let a=this.#p.get(i);if(void 0===a)return 0;let n=e[a],o=t[a];return n&&o?n-((r||s())-o):1/0},this.#P=i=>{let a=t[i],n=e[i];return!!n&&!!a&&(r||s())-a>n}}#K=()=>{};#q=()=>{};#L=()=>{};#P=()=>!1;#D(){let e=new t9(this.#a);this.#h=0,this.#k=e,this.#M=t=>{this.#h-=e[t],e[t]=0},this.#Y=(e,t,r,s)=>{if(this.#I(t))return 0;if(!t4(r))if(s){if("function"!=typeof s)throw TypeError("sizeCalculation must be a function");if(!t4(r=s(t,e)))throw TypeError("sizeCalculation return invalid (expect positive integer)")}else throw TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return r},this.#N=(t,r,s)=>{if(e[t]=r,this.#n){let r=this.#n-e[t];for(;this.#h>r;)this.#W(!0)}this.#h+=e[t],s&&(s.entrySize=r,s.totalCalculatedSize=this.#h)}}#M=e=>{};#N=(e,t,r)=>{};#Y=(e,t,r,s)=>{if(r||s)throw TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#O({allowStale:e=this.allowStale}={}){if(this.#u)for(let t=this.#w;this.#Z(t)&&((e||!this.#P(t))&&(yield t),t!==this.#v);)t=this.#g[t]}*#C({allowStale:e=this.allowStale}={}){if(this.#u)for(let t=this.#v;this.#Z(t)&&((e||!this.#P(t))&&(yield t),t!==this.#w);)t=this.#y[t]}#Z(e){return void 0!==e&&this.#p.get(this.#f[e])===e}*entries(){for(let e of this.#O())void 0===this.#m[e]||void 0===this.#f[e]||this.#I(this.#m[e])||(yield[this.#f[e],this.#m[e]])}*rentries(){for(let e of this.#C())void 0===this.#m[e]||void 0===this.#f[e]||this.#I(this.#m[e])||(yield[this.#f[e],this.#m[e]])}*keys(){for(let e of this.#O()){let t=this.#f[e];void 0===t||this.#I(this.#m[e])||(yield t)}}*rkeys(){for(let e of this.#C()){let t=this.#f[e];void 0===t||this.#I(this.#m[e])||(yield t)}}*values(){for(let e of this.#O())void 0===this.#m[e]||this.#I(this.#m[e])||(yield this.#m[e])}*rvalues(){for(let e of this.#C())void 0===this.#m[e]||this.#I(this.#m[e])||(yield this.#m[e])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,t={}){for(let r of this.#O()){let s=this.#m[r],i=this.#I(s)?s.__staleWhileFetching:s;if(void 0!==i&&e(i,this.#f[r],this))return this.get(this.#f[r],t)}}forEach(e,t=this){for(let r of this.#O()){let s=this.#m[r],i=this.#I(s)?s.__staleWhileFetching:s;void 0!==i&&e.call(t,i,this.#f[r],this)}}rforEach(e,t=this){for(let r of this.#C()){let s=this.#m[r],i=this.#I(s)?s.__staleWhileFetching:s;void 0!==i&&e.call(t,i,this.#f[r],this)}}purgeStale(){let e=!1;for(let t of this.#C({allowStale:!0}))this.#P(t)&&(this.#z(this.#f[t],"expire"),e=!0);return e}info(e){let t=this.#p.get(e);if(void 0===t)return;let r=this.#m[t],s=this.#I(r)?r.__staleWhileFetching:r;if(void 0===s)return;let i={value:s};if(this.#x&&this.#S){let e=this.#x[t],r=this.#S[t];e&&r&&(i.ttl=e-(tX.now()-r),i.start=Date.now())}return this.#k&&(i.size=this.#k[t]),i}dump(){let e=[];for(let t of this.#O({allowStale:!0})){let r=this.#f[t],s=this.#m[t],i=this.#I(s)?s.__staleWhileFetching:s;if(void 0===i||void 0===r)continue;let a={value:i};if(this.#x&&this.#S){a.ttl=this.#x[t];let e=tX.now()-this.#S[t];a.start=Math.floor(Date.now()-e)}this.#k&&(a.size=this.#k[t]),e.unshift([r,a])}return e}load(e){for(let[t,r]of(this.clear(),e)){if(r.start){let e=Date.now()-r.start;r.start=tX.now()-e}this.set(t,r.value,r)}}set(e,t,r={}){if(void 0===t)return this.delete(e),this;let{ttl:s=this.ttl,start:i,noDisposeOnSet:a=this.noDisposeOnSet,sizeCalculation:n=this.sizeCalculation,status:o}=r,{noUpdateTTL:l=this.noUpdateTTL}=r,c=this.#Y(e,t,r.size||0,n);if(this.maxEntrySize&&c>this.maxEntrySize)return o&&(o.set="miss",o.maxEntrySizeExceeded=!0),this.#z(e,"set"),this;let d=0===this.#u?void 0:this.#p.get(e);if(void 0===d)d=0===this.#u?this.#w:0!==this.#_.length?this.#_.pop():this.#u===this.#a?this.#W(!1):this.#u,this.#f[d]=e,this.#m[d]=t,this.#p.set(e,d),this.#y[this.#w]=d,this.#g[d]=this.#w,this.#w=d,this.#u++,this.#N(d,c,o),o&&(o.set="add"),l=!1;else{this.#R(d);let r=this.#m[d];if(t!==r){if(this.#A&&this.#I(r)){r.__abortController.abort(Error("replaced"));let{__staleWhileFetching:t}=r;void 0!==t&&!a&&(this.#E&&this.#o?.(t,e,"set"),this.#j&&this.#b?.push([t,e,"set"]))}else!a&&(this.#E&&this.#o?.(r,e,"set"),this.#j&&this.#b?.push([r,e,"set"]));if(this.#M(d),this.#N(d,c,o),this.#m[d]=t,o){o.set="replace";let e=r&&this.#I(r)?r.__staleWhileFetching:r;void 0!==e&&(o.oldValue=e)}}else o&&(o.set="update")}if(0===s||this.#x||this.#$(),this.#x&&(l||this.#L(d,s,i),o&&this.#q(o,d)),!a&&this.#j&&this.#b){let e,t=this.#b;for(;e=t?.shift();)this.#l?.(...e)}return this}pop(){try{for(;this.#u;){let e=this.#m[this.#v];
1if(this.#W(!0),this.#I(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(void 0!==e)return e}}finally{if(this.#j&&this.#b){let e,t=this.#b;for(;e=t?.shift();)this.#l?.(...e)}}}#W(e){let t=this.#v,r=this.#f[t],s=this.#m[t];return this.#A&&this.#I(s)?s.__abortController.abort(Error("evicted")):(this.#E||this.#j)&&(this.#E&&this.#o?.(s,r,"evict"),this.#j&&this.#b?.push([s,r,"evict"])),this.#M(t),e&&(this.#f[t]=void 0,this.#m[t]=void 0,this.#_.push(t)),1===this.#u?(this.#v=this.#w=0,this.#_.length=0):this.#v=this.#y[t],this.#p.delete(r),this.#u--,t}has(e,t={}){let{updateAgeOnHas:r=this.updateAgeOnHas,status:s}=t,i=this.#p.get(e);if(void 0!==i){let e=this.#m[i];if(this.#I(e)&&void 0===e.__staleWhileFetching)return!1;if(!this.#P(i))return r&&this.#K(i),s&&(s.has="hit",this.#q(s,i)),!0;s&&(s.has="stale",this.#q(s,i))}else s&&(s.has="miss");return!1}peek(e,t={}){let{allowStale:r=this.allowStale}=t,s=this.#p.get(e);if(void 0===s||!r&&this.#P(s))return;let i=this.#m[s];return this.#I(i)?i.__staleWhileFetching:i}#T(e,t,r,s){let i=void 0===t?void 0:this.#m[t];if(this.#I(i))return i;let a=new t2,{signal:n}=r;n?.addEventListener("abort",()=>a.abort(n.reason),{signal:a.signal});let o={signal:a.signal,options:r,context:s},l=(s,i=!1)=>{let{aborted:n}=a.signal,l=r.ignoreFetchAbort&&void 0!==s;return(r.status&&(n&&!i?(r.status.fetchAborted=!0,r.status.fetchError=a.signal.reason,l&&(r.status.fetchAbortIgnored=!0)):r.status.fetchResolved=!0),!n||l||i)?(this.#m[t]===u&&(void 0===s?u.__staleWhileFetching?this.#m[t]=u.__staleWhileFetching:this.#z(e,"fetch"):(r.status&&(r.status.fetchUpdated=!0),this.set(e,s,o.options))),s):c(a.signal.reason)},c=s=>{let{aborted:i}=a.signal,n=i&&r.allowStaleOnFetchAbort,o=n||r.allowStaleOnFetchRejection,l=o||r.noDeleteOnFetchRejection;if(this.#m[t]===u&&(l&&void 0!==u.__staleWhileFetching?n||(this.#m[t]=u.__staleWhileFetching):this.#z(e,"fetch")),o)return r.status&&void 0!==u.__staleWhileFetching&&(r.status.returnedStale=!0),u.__staleWhileFetching;if(u.__returned===u)throw s},d=(t,s)=>{let n=this.#c?.(e,i,o);n&&n instanceof Promise&&n.then(e=>t(void 0===e?void 0:e),s),a.signal.addEventListener("abort",()=>{(!r.ignoreFetchAbort||r.allowStaleOnFetchAbort)&&(t(void 0),r.allowStaleOnFetchAbort&&(t=e=>l(e,!0)))})};r.status&&(r.status.fetchDispatched=!0);let u=new Promise(d).then(l,e=>(r.status&&(r.status.fetchRejected=!0,r.status.fetchError=e),c(e))),h=Object.assign(u,{__abortController:a,__staleWhileFetching:i,__returned:void 0});return void 0===t?(this.set(e,h,{...o.options,status:void 0}),t=this.#p.get(e)):this.#m[t]=h,h}#I(e){return!!this.#A&&!!e&&e instanceof Promise&&e.hasOwnProperty("__staleWhileFetching")&&e.__abortController instanceof t2}async fetch(e,t={}){let{allowStale:r=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,ttl:a=this.ttl,noDisposeOnSet:n=this.noDisposeOnSet,size:o=0,sizeCalculation:l=this.sizeCalculation,noUpdateTTL:c=this.noUpdateTTL,noDeleteOnFetchRejection:d=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:u=this.allowStaleOnFetchRejection,ignoreFetchAbort:h=this.ignoreFetchAbort,allowStaleOnFetchAbort:p=this.allowStaleOnFetchAbort,context:f,forceRefresh:m=!1,status:y,signal:g}=t;if(!this.#A)return y&&(y.fetch="get"),this.get(e,{allowStale:r,updateAgeOnGet:s,noDeleteOnStaleGet:i,status:y});let v={allowStale:r,updateAgeOnGet:s,noDeleteOnStaleGet:i,ttl:a,noDisposeOnSet:n,size:o,sizeCalculation:l,noUpdateTTL:c,noDeleteOnFetchRejection:d,allowStaleOnFetchRejection:u,allowStaleOnFetchAbort:p,ignoreFetchAbort:h,status:y,signal:g},w=this.#p.get(e);if(void 0===w){y&&(y.fetch="miss");let t=this.#T(e,w,v,f);return t.__returned=t}{let t=this.#m[w];if(this.#I(t)){let e=r&&void 0!==t.__staleWhileFetching;return y&&(y.fetch="inflight",e&&(y.returnedStale=!0)),e?t.__staleWhileFetching:t.__returned=t}let i=this.#P(w);if(!m&&!i)return y&&(y.fetch="hit"),this.#R(w),s&&this.#K(w),y&&this.#q(y,w),t;let a=this.#T(e,w,v,f),n=void 0!==a.__staleWhileFetching&&r;return y&&(y.fetch=i?"stale":"refresh",n&&i&&(y.returnedStale=!0)),n?a.__staleWhileFetching:a.__returned=a}}async forceFetch(e,t={}){let r=await this.fetch(e,t);if(void 0===r)throw Error("fetch() returned undefined");return r}memo(e,t={}){let r=this.#d;if(!r)throw Error("no memoMethod provided to constructor");let{context:s,forceRefresh:i,...a}=t,n=this.get(e,a);if(!i&&void 0!==n)return n;
1let o=r(e,n,{options:a,context:s});return this.set(e,o,a),o}get(e,t={}){let{allowStale:r=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,status:a}=t,n=this.#p.get(e);if(void 0!==n){let t=this.#m[n],o=this.#I(t);return(a&&this.#q(a,n),this.#P(n))?(a&&(a.get="stale"),o)?(a&&r&&void 0!==t.__staleWhileFetching&&(a.returnedStale=!0),r?t.__staleWhileFetching:void 0):(i||this.#z(e,"expire"),a&&r&&(a.returnedStale=!0),r?t:void 0):(a&&(a.get="hit"),o)?t.__staleWhileFetching:(this.#R(n),s&&this.#K(n),t)}a&&(a.get="miss")}#U(e,t){this.#g[t]=e,this.#y[e]=t}#R(e){e!==this.#w&&(e===this.#v?this.#v=this.#y[e]:this.#U(this.#g[e],this.#y[e]),this.#U(this.#w,e),this.#w=e)}delete(e){return this.#z(e,"delete")}#z(e,t){let r=!1;if(0!==this.#u){let s=this.#p.get(e);if(void 0!==s)if(r=!0,1===this.#u)this.#F(t);else{this.#M(s);let r=this.#m[s];if(this.#I(r)?r.__abortController.abort(Error("deleted")):(this.#E||this.#j)&&(this.#E&&this.#o?.(r,e,t),this.#j&&this.#b?.push([r,e,t])),this.#p.delete(e),this.#f[s]=void 0,this.#m[s]=void 0,s===this.#w)this.#w=this.#g[s];else if(s===this.#v)this.#v=this.#y[s];else{let e=this.#g[s];this.#y[e]=this.#y[s];let t=this.#y[s];this.#g[t]=this.#g[s]}this.#u--,this.#_.push(s)}}if(this.#j&&this.#b?.length){let e,t=this.#b;for(;e=t?.shift();)this.#l?.(...e)}return r}clear(){return this.#F("delete")}#F(e){for(let t of this.#C({allowStale:!0})){let r=this.#m[t];if(this.#I(r))r.__abortController.abort(Error("deleted"));else{let s=this.#f[t];this.#E&&this.#o?.(r,s,e),this.#j&&this.#b?.push([r,s,e])}}if(this.#p.clear(),this.#m.fill(void 0),this.#f.fill(void 0),this.#x&&this.#S&&(this.#x.fill(0),this.#S.fill(0)),this.#k&&this.#k.fill(0),this.#v=0,this.#w=0,this.#_.length=0,this.#h=0,this.#u=0,this.#j&&this.#b){let e,t=this.#b;for(;e=t?.shift();)this.#l?.(...e)}}}let t7=new WeakMap;function re(e){let t=new Set,r=[e],s=0;for(;r.length;){let e=r.pop();switch(typeof e){case"string":s+=12+4*Math.ceil(e.length/4);break;case"number":s+=12;break;case"boolean":s+=4;break;case"object":if(s+=4,null===e)break;if(t7.has(e)){s+=t7.get(e);break}if(t.has(e))continue;if(t.add(e),Array.isArray(e))s+=4,r.push(...e);else{s+=8;let t=Object.getOwnPropertyNames(e);for(let i=0;i<t.length;i++){s+=4;let a=t[i],n=e[a];void 0!==n&&r.push(n),r.push(a)}}break;case"function":case"symbol":s+=8;break;case"bigint":s+=16}}return"object"==typeof e&&null!==e&&t7.set(e,s),s}let rt=Symbol("nullItem"),rr=e=>e===rt?null:e;class rs{#H;constructor({sizeCalculation:e,...t}){this.#H=new t3({...t,allowStale:!1,updateAgeOnGet:!1,updateAgeOnHas:!1,sizeCalculation:e?(t,r)=>e(rr(t),r):null!=t.maxEntrySize||null!=t.maxSize?re:void 0})}get(e){let t=this.#H.get(e);if(void 0!==t)return rr(t)}set(e,t){this.#H.set(e,null===t?rt:t)}del(e){this.#H.delete(e)}clear(){this.#H.clear()}}class ri extends rs{constructor(e){super(e?.max==null?{ttl:36e5,maxSize:0x3200000,...e}:{ttl:36e5,...e})}}class ra{constructor(e,t=new ri,r){this.getter=new tJ((t,r)=>e.resolve(t,r),tV(t,r))}async resolve(e,t){return this.getter.get(e,t)}}class rn extends Error{constructor(e,t,r){super(t,r),this.statusCode=e}get expose(){return!0}}let ro=e=>"string"==typeof e?e:void 0;class rl extends TransformStream{constructor(e){if(!(e>=0))throw TypeError("maxBytes must be a non-negative number");let t=0;super({transform:(r,s)=>{(t+=r.length)<=e?s.enqueue(r):s.error(Error("Response too large"))}})}}async function rc(e,t){!e.body||e.bodyUsed||e.body.locked||"function"!=typeof e.body.cancel||("function"==typeof t?e.body.cancel().catch(t):"log"===t?e.body.cancel().catch(rd):await e.body.cancel())}function rd(e){console.warn("Failed to cancel response body",e)}class ru extends rn{constructor(e,t,r,s){if(null==t||!r){let e=function(e){if("string"==typeof e&&e.length>0)return[500,e];if(!(e instanceof Error))return[500,"Failed to fetch"];switch(e.message){case"failed to fetch the data URL":return[400,e.message];case"unexpected redirect":case"cors failure":case"blocked":case"proxy authentication required":return[502,e.message]}let t="code"in e?e.code:void 0;if("string"==typeof t)switch(!0){case"ENOTFOUND"===t:return[400,"Invalid hostname"];case"ECONNREFUSED"===t:return[502,"Connection refused"];case"DEPTH_ZERO_SELF_SIGNED_CERT"===t:return[502,"Self-signed certificate"];case t.startsWith("ERR_TLS"):return[502,"TLS error"];case t.startsWith("ECONN"):return[502,"Connection error"];default:return[500,`${t} error`]}return[500,e.message]}(function(e){return e instanceof TypeError&&"fetch failed"===e.message&&void 0!==e.cause?e.cause:e}(s?.cause));t??=e[0],r||=e[1]}super(t,r,s),this.request=e}get expose(){return 500!==this.statusCode}static from(e,t){return t instanceof ru?t:new ru(e,void 0,void 0,{cause:t})}}function rh(...e){return e.reduce(rp)}function rp(e,t){return async(...r)=>t(await e(...r))}class rf extends Response{#J;constructor(e,t){if(!e.body)throw TypeError("Response body is not available");if(e.bodyUsed)throw TypeError("Response body is already used");super(e.body.pipeThrough(t),{status:e.status,statusText:e.statusText,headers:e.headers}),this.#J=e}get url(){return this.#J.url}get redirected(){return this.#J.redirected}get type(){return this.#J.type}get statusText(){return this.#J.statusText}}let rm=/^application\/(?:[^()<>@,;:/[\]\\?={} \t]+\+)?json$/i;class ry extends rn{constructor(e,t=e.status,r=e.statusText,s){super(t,r,s),this.response=e}static async from(e,t=rg,r=e.status,s){let i="string"==typeof t?t:"function"==typeof t?await t(e):void 0;return new ry(e,r,i,s)}}let rg=async e=>{let t=rw(e);if(t)try{if("text/plain"===t)return await e.text();if(rm.test(t)){let t=await e.json();if("string"==typeof t)return t;if("object"==typeof t&&null!=t){if("error_description"in t){let e=ro(t.error_description);if(e)return e}if("error"in t){let e=ro(t.error);if(e)return e}if("message"in t){let e=ro(t.message);if(e)return e}}}}catch{}};async function rv(e,t=1/0){if("application/json"!==rw(e))return;var r=e,s=t;if(!(s>=0))throw TypeError("maxBytes must be a non-negative number");let i=function(e){let t=e.headers.get("Content-Length");if(null==t)return;if(!/^\d+$/.test(t))throw new ry(e,502,"Invalid Content-Length");let r=Number(t);if(!Number.isSafeInteger(r))throw new ry(e,502,"Content-Length too large");return r}(r);if(null!=i&&i>s)throw new ry(r,502,"Response too large");let a=e.clone();return(e.body&&t<1/0?new rf(a,new rl(t)):a).json()}function rw(e){let t=e.headers.get("Content-Type");if(null!=t)return t.split(";",1)[0].trim()}function r_(e,t=rd){return async r=>{try{return await e(r)}catch(e){throw await rc(r,t??void 0),e}}}function rb(e){return r_(t=>rk(t,e))}async function rk(e,t){if(e.ok)return e;throw await ry.from(e,t)}async function rS(e,t,r=!0){let s=rw(e);if(s){if(!t(s.toLowerCase()))throw await ry.from(e,`Unexpected response Content-Type (${s})`,502)}else if(r)throw await ry.from(e,"Missing response Content-Type header",502);return e}async function rx(e){try{let t=await e.json();return{response:e,json:t}}catch(t){throw new ry(e,502,"Unable to parse response as JSON",{cause:t})}}function rE(e=rm,t=!0){return rh(function(e,t=!0){let r="string"==typeof e?t=>t===e:e instanceof RegExp?t=>e.test(t):e;return r_(e=>rS(e,r,t))}(e,t),r_(rx))}let rA=function(e,t){if("parseAsync"in e&&"function"==typeof e.parseAsync)return async r=>e.parseAsync(r.json,t);if("parse"in e&&"function"==typeof e.parse)return async r=>e.parse(r.json,t);throw TypeError("Invalid schema")};function rj(e=globalThis.fetch,t=globalThis){var r;return r=async r=>{try{return await e.call(t,r)}catch(e){throw ru.from(r,e)}},function(e,t){var s,i;return r.call(this,(s=e,!(i=t)&&s instanceof Request?s:new Request
1(s,i)))}}class rI{constructor(e){this.methods=new Map(Object.entries(e))}async resolve(e,t){t?.signal?.throwIfAborted();let r=function(e){let t=e.indexOf(":",tv);return e.slice(tv,t)}(e),s=this.methods.get(r);if(!s)throw new tm(e,"Unsupported DID method","did-method-invalid",400);try{let r=await s.resolve(e,t);if(r.id!==e)throw new tm(e,`DID document id (${r.id}) does not match DID`,"did-document-id-mismatch",400);return r}catch(t){if(t instanceof ry){let r=t.response.status>=500?502:t.response.status;throw new tm(e,t.message,"did-fetch-error",r,t)}if(t instanceof rn)throw new tm(e,t.message,"did-fetch-error",400,t);if(t instanceof f.G)throw new tm(e,t.message,"did-document-format-error",503,t);throw tm.from(t,e)}}}let rT=rh(rb(),rE(/^application\/(did\+ld\+)?json$/),rA(tZ));class rR{constructor(e){this.plcDirectoryUrl=new URL(e?.plcDirectoryUrl||"https://plc.directory/"),this.fetch=rj(e?.fetch)}async resolve(e,t){tA(e);let r=new URL(`/${encodeURIComponent(e)}`,this.plcDirectoryUrl);return this.fetch(r,{redirect:"error",headers:{accept:"application/did+ld+json,application/json"},signal:t?.signal}).then(rT)}}let rO=rh(rb(),rE(/^application\/(did\+ld\+)?json$/),rA(tZ));class rC{constructor({fetch:e=globalThis.fetch,allowHttp:t=!0}={}){this.fetch=rj(e),this.allowHttp=t}async resolve(e,t){let r=function(e){let t=function(e){try{return new URL(tT(e))}catch(t){throw new ty(e,"Invalid Web DID",t)}}(e);return"/"===t.pathname?new URL("/.well-known/did.json",t):new URL(`${t.pathname}/did.json`,t)}(e);if(!this.allowHttp&&"http:"===r.protocol)throw new tm(e,'Resolution of "http" did:web is not allowed',"did-web-http-not-allowed");return this.fetch(r,{redirect:"error",headers:{accept:"application/did+ld+json,application/json"},signal:t?.signal}).then(rO)}}class rP extends rI{constructor(e){super({plc:new rR(e),web:new rC(e)})}}class rD extends Error{constructor(){super(...arguments),this.name="HandleResolverError"}}let r$=h.Ik({error:h.Yj(),message:h.Yj().optional()});class rL{constructor(e,t){this.serviceUrl=new URL(e),this.fetch=t?.fetch??globalThis.fetch}async resolve(e,t){let r=new URL("/xrpc/com.atproto.identity.resolveHandle",this.serviceUrl);r.searchParams.set("handle",e);let s=await this.fetch.call(null,r,{cache:t?.noCache?"no-cache":void 0,signal:t?.signal,redirect:"error"}),i=await s.json();if(400===s.status){let{error:e,data:t}=r$.safeParse(i);if(e)throw new rD(`Invalid response from resolveHandle method: ${e.message}`,{cause:e});if("InvalidRequest"===t.error&&"Unable to resolve handle"===t.message)return null}if(!s.ok)throw new rD("Invalid status code from resolveHandle method");let a=i?.did;if(!(null===a||tO(a)))throw new rD("Invalid DID returned from resolveHandle method");return a}}class rz{constructor(e,t=new rs({max:1e3,ttl:6e5}),r){this.getter=new tJ((t,r)=>e.resolve(t,r),tV(t,r))}async resolve(e,t){return this.getter.get(e,t)}}let rK="urn:ietf:params:oauth:client-assertion-type:jwt-bearer",rq=URL.canParse?.bind(URL)??(e=>{try{return new URL(e),!0}catch{return!1}});function rM(e){return!!(e.match(/^\d+\.\d+\.\d+\.\d+$/)||e.startsWith("[")&&e.endsWith("]"))}function rY(e){return"localhost"===e||"127.0.0.1"===e||"[::1]"===e}let rN=e=>{if("string"==typeof e&&e.startsWith("{")&&e.endsWith("}"))try{return JSON.parse(e)}catch{}return e},rW=h.Yj().refine(e=>e.includes(":")&&rq(e),{message:"Invalid URL"}),rZ=rW.superRefine((e,t)=>e.startsWith("http://")?!!rY(new URL(e).hostname)||(t.addIssue({code:f.eq.custom,message:'URL must use "localhost", "127.0.0.1" or "[::1]" as hostname'}),!1):(t.addIssue({code:f.eq.custom,message:'URL must use the "http:" protocol'}),!1)),rU=rW.superRefine((e,t)=>{if(!e.startsWith("https://"))return t.addIssue({code:f.eq.custom,message:'URL must use the "https:" protocol'}),!1;let r=new URL(e);if(rY(r.hostname))return t.addIssue({code:f.eq.custom,message:"https: URL must not use a loopback host"}),!1;if(rM(r.hostname));else{if(!r.hostname.includes("."))return t.addIssue({code:f.eq.custom,message:"Domain name must contain at least two segments"}),!1;if(r.hostname.endsWith(".local"))return t.addIssue({code:f.eq.custom,message:'Domain name must not end with ".local"'}),!1}return!0}),rF=h.Yj().superRefine((e,t)=>
1{if(e.startsWith("http://")){let r=rZ.safeParse(e);return r.success||r.error.issues.forEach(t.addIssue,t),r.success}if(e.startsWith("https://")){let r=rU.safeParse(e);return r.success||r.error.issues.forEach(t.addIssue,t),r.success}return t.addIssue({code:f.eq.custom,message:'URL must use the "http:" or "https:" protocol'}),!1}),rH=rW.superRefine((e,t)=>{let r=e.indexOf("."),s=e.indexOf(":");if(-1===r||-1===s||r>s)return t.addIssue({code:f.eq.custom,message:'Private-use URI scheme requires a "." as part of the protocol'}),!1;let i=new URL(e);return i.protocol.includes(".")?(function(e){let t=e.split(".");if(t.length<2)return!0;let r=t.at(-1).toLowerCase();return"test"===r||"local"===r||"localhost"===r||"invalid"===r||"example"===r}(i.protocol.slice(0,-1).split(".").reverse().join("."))&&t.addIssue({code:f.eq.custom,message:"Private-use URI Scheme redirect URI must not be a local hostname"}),!i.href.startsWith(`${i.protocol}//`)&&!i.username&&!i.password&&!i.hostname&&!i.port||(t.addIssue({code:f.eq.custom,message:"Private-Use URI Scheme must be in the form <scheme>:/{path} (notice the single slash!) as per RFC 8252"}),!1)):(t.addIssue({code:f.eq.custom,message:"Invalid private-use URI scheme"}),!1)}),rJ=Object.freeze(["http://127.0.0.1/","http://[::1]/"]),rB=/^[\x21\x23-\x5B\x5D-\x7E]+(?: [\x21\x23-\x5B\x5D-\x7E]+)*$/,rV=e=>rB.test(e),rG=h.Yj().refine(rV,{message:"Invalid OAuth scope"}),rX="atproto";function rQ(e){return rV(e)&&((e,t)=>{let r;if(0===e.length)throw TypeError("Value cannot be empty");if(e.includes(" "))throw TypeError("Value cannot contain spaces");let s=t.length,i=e.length;if(s<i)return!1;let a=t.indexOf(e);for(;-1!==a;){if(r=a+i,(0===a||32===t.charCodeAt(a-1))&&(r===s||32===t.charCodeAt(r)))return!0;a=t.indexOf(e,r+1)}return!1})(rX,e)}let r0=h.Yj().refine(rQ,{message:"Invalid ATProto OAuth scope"}),r1=h.Yj().min(1),r2=rZ.superRefine((e,t)=>!e.startsWith("http://localhost")||(t.addIssue({code:f.eq.custom,message:'Use of "localhost" hostname is not allowed (RFC 8252), use a loopback IP such as "127.0.0.1" instead'}),!1)),r5=h.Yj().superRefine((e,t)=>{if(e.startsWith("https:")){let r=rU.safeParse(e);return r.success||r.error.issues.forEach(t.addIssue,t),r.success}if(e.startsWith("http:")){let r=r2.safeParse(e);return r.success||r.error.issues.forEach(t.addIssue,t),r.success}if(!/^[^.:]+(?:\.[^.:]+)+:/.test(e))return t.addIssue({code:f.eq.custom,message:'URL must use the "https:" or "http:" protocol, or a private-use URI scheme (RFC 8252)'}),!1;{let r=rH.safeParse(e);return r.success||r.error.issues.forEach(t.addIssue,t),r.success}}),r4="http://localhost",r8=r1.superRefine((e,t)=>{let r=r6(e);return r.success||t.addIssue({code:"custom",message:r.message}),r.success});function r9(e){let t=r6(e);if(t.success)return t.value;throw TypeError(`Invalid loopback client ID: ${t.message}`)}function r6(e){if(!e.startsWith(r4))return{success:!1,message:`Value must start with "${r4}"`};if(e.includes("#",r4.length))return{success:!1,message:"Value must not contain a hash component"};let t=e.length>r4.length&&47===e.charCodeAt(r4.length)?r4.length+1:r4.length;return e.length!==t&&63!==e.charCodeAt(t)?{success:!1,message:"Value must not contain a path component"}:function(e){let t={};for(let[r,s]of"string"==typeof e?new URLSearchParams(e):e)if("scope"===r){if("scope"in t)return{success:!1,message:'Duplicate "scope" query parameter'};let e=rG.safeParse(s);if(!e.success){let t=e.error.issues.map(e=>e.message).join(", ");return{success:!1,message:`Invalid "scope" query parameter: ${t||"Validation failed"}`}}t.scope=e.data}else{if("redirect_uri"!==r)return{success:!1,message:`Unexpected query parameter "${r}"`};let e=r2.safeParse(s);if(!e.success){let t=e.error.issues.map(e=>e.message).join(", ");return{success:!1,message:`Invalid "redirect_uri" query parameter: ${t||"Validation failed"}`}}null==t.redirect_uris?t.redirect_uris=[e.data]:t.redirect_uris.push(e.data)}return{success:!0,value:t}}(e.slice(t+1))}function r3(e){var t;let r=function(e){let{scope:t=rX,redirect_uris:r}=r9(e);if(!rQ(t))throw TypeError('ATProto Loopback ClientID must include "atproto" scope');return{scope:t,redirect_uris:r??[...rJ]}}(e);return{client_id:e,scope:(t=r).scope,redirect_uris:t.redirect_uris,response_types:["code"],grant_types:["authorization_code","refresh_token"],token_endpoint_auth_method:"none",application_type:"native",dpop_bound_access_tokens:!0}}let r7=h.Ik({type:h.Yj(),locations:h.YO(rW).optional(),actions:h.YO(h.Yj()).optional(),datatypes:h.YO(h.Yj()).optional(),identifier:h.Yj().optional(),privileges:h.YO(h.Yj()).optional()}),se=h.YO(r7),st=h.KC([h.Yj().regex(/^DPoP$/i).transform(()=>"DPoP"),h.Yj().regex(/^Bearer$/i).transform(()=>"Bearer")]),sr=h.Ik({access_token:h.Yj(),token_type:st,scope:h.Yj().optional(),refresh_token:h.Yj().optional(),expires_in:h.ai().optional(),id_token:H.optional(),authorization_details:se.optional()}).passthrough().extend({token_type:h.eu("DPoP"),sub:tR,scope:r0,id_token:h.Zm().optional()}),ss=h.Yj().min(1),si=h.Ik({grant_type:h.eu("authorization_code"),code:h.Yj().min(1),redirect_uri:r5,code_verifier:h.Yj().min(43).max(128).regex(/^[a-zA-Z0-9-._~]+$/).optional()}),sa=h.Ik({request:h.KC([H,J])}),sn=h.k5(["S256","plain"]),so=h.k5(["none","login","consent","select_account","create"]),sl=h.k5(["query","fragment","form_post"]),sc=h.k5(["code","token","none","code id_token token","code id_token","code token","id_token token","id_token"]),sd=h.k5(["auth_time","nonce","acr","name","family_name","given_name","middle_name","nickname","preferred_username","gender","picture","profile","website","birthdate","zoneinfo","locale","updated_at","email","email_verified","phone_number","phone_number_verified","address"]),su=h.KC([h.Yj(),h.ai(),h.zM()]),sh=h.Ik({essential:h.zM().optional(),value:su.optional(),values:h.YO(su).optional()}),sp=h.k5(["userinfo","id_token"]),sf=h.Ik({client_id:r1,state:h.Yj().optional(),redirect_uri:r5.optional(),scope:rG.optional(),response_type:sc,code_challenge:h.Yj().optional(),code_challenge_method:sn.optional(),dpop_jkt:h.Yj().optional(),response_mode:sl.optional(),nonce:h.Yj().optional(),max_age:h.v
1k(e=>{if("string"==typeof e){let t=Number(e);if(!Number.isNaN(t))return t}return e},h.ai().int().min(0)).optional(),claims:h.vk(rN,h.g1(sp,h.g1(sd,h.KC([h.eu(null),sh])))).optional(),login_hint:h.Yj().min(1).optional(),ui_locales:h.Yj().regex(/^[a-z]{2,3}(-[A-Z]{2})?( [a-z]{2,3}(-[A-Z]{2})?)*$/).optional(),id_token_hint:H.optional(),display:h.k5(["page","popup","touch","wap"]).optional(),prompt:so.optional(),authorization_details:h.vk(rN,se).optional()});h.KC([sf,sa]);let sm=h.Yj().min(1),sy=h.Ik({request_uri:sm});h.E$(h.Ik({client_id:r1}),h.KC([sf,sa,sy])),h.k5(["invalid_request","unauthorized_client","access_denied","unsupported_response_type","invalid_scope","server_error","temporarily_unavailable"]);let sg=rF.superRefine((e,t)=>{if(e.endsWith("/"))return t.addIssue({code:f.eq.custom,message:"Issuer URL must not end with a slash"}),!1;let r=new URL(e);return r.username||r.password?(t.addIssue({code:f.eq.custom,message:"Issuer URL must not contain a username or password"}),!1):r.hash||r.search?(t.addIssue({code:f.eq.custom,message:"Issuer URL must not contain a query or fragment"}),!1):e===("/"===r.pathname?r.origin:r.href)||(t.addIssue({code:f.eq.custom,message:"Issuer URL must be in the canonical form"}),!1)}),sv=h.Ik({issuer:sg,claims_supported:h.YO(h.Yj()).optional(),claims_locales_supported:h.YO(h.Yj()).optional(),claims_parameter_supported:h.zM().optional(),request_parameter_supported:h.zM().optional(),request_uri_parameter_supported:h.zM().optional(),require_request_uri_registration:h.zM().optional(),scopes_supported:h.YO(h.Yj()).optional(),subject_types_supported:h.YO(h.Yj()).optional(),response_types_supported:h.YO(h.Yj()).optional(),response_modes_supported:h.YO(h.Yj()).optional(),grant_types_supported:h.YO(h.Yj()).optional(),code_challenge_methods_supported:h.YO(sn).min(1).optional(),ui_locales_supported:h.YO(h.Yj()).optional(),id_token_signing_alg_values_supported:h.YO(h.Yj()).optional(),display_values_supported:h.YO(h.Yj()).optional(),request_object_signing_alg_values_supported:h.YO(h.Yj()).optional(),authorization_response_iss_parameter_supported:h.zM().optional(),authorization_details_types_supported:h.YO(h.Yj()).optional(),request_object_encryption_alg_values_supported:h.YO(h.Yj()).optional(),request_object_encryption_enc_values_supported:h.YO(h.Yj()).optional(),jwks_uri:rF.optional(),authorization_endpoint:rF,token_endpoint:rF,token_endpoint_auth_methods_supported:h.YO(h.Yj()).default(["client_secret_basic"]),token_endpoint_auth_signing_alg_values_supported:h.YO(h.Yj()).optional(),revocation_endpoint:rF.optional(),introspection_endpoint:rF.optional(),pushed_authorization_request_endpoint:rF.optional(),require_pushed_authorization_requests:h.zM().optional(),userinfo_endpoint:rF.optional(),end_session_endpoint:rF.optional(),registration_endpoint:rF.optional(),dpop_signing_alg_values_supported:h.YO(h.Yj()).optional(),protected_resources:h.YO(rF).optional(),client_id_metadata_document_supported:h.zM().optional(),prompt_values_supported:h.YO(so).optional()}).superRefine((e,t)=>{e.require_pushed_authorization_requests&&!e.pushed_authorization_request_endpoint&&t.addIssue({code:f.eq.custom,message:'"pushed_authorization_request_endpoint" required when "require_pushed_authorization_requests" is true'})}).superRefine((e,t)=>{e.response_types_supported&&!e.response_types_supported.includes("code")&&t.addIssue({code:f.eq.custom,message:'Response type "code" is required'})}).superRefine((e,t)=>{e.token_endpoint_auth_signing_alg_values_supported?.includes("none")&&t.addIssue({code:f.eq.custom,message:'Client authentication method "none" is not allowed'})}),sw=h.Ik({grant_type:h.eu("client_credentials")}),s_=h.Ik({client_id:r1,client_assertion_type:h.eu(rK),client_assertion:H}),sb=h.Ik({client_id:r1,client_secret:h.Yj()}),sk=h.Ik({client_id:r1});h.KC([s_,sb,sk]);let sS=h.E$(r1,rU).superRefine((e,t)=>{let r=new URL(e);return r.username||r.password?(t.addIssue({code:f.eq.custom,message:"ClientID must not contain credentials"}),!1):r.hash?(t.addIssue({code:f.eq.custom,message:"ClientID must not contain a fragment"}),!1):"/"===r.pathname?(t.addIssue({code:f.eq.custom,message:'ClientID must contain a path component (e.g. "/client-metadata.json")'}),!1):r.pathname.endsWith("/")?(t.addIssue({code:f.eq.custom,message:"ClientID path must not end with a trailing slash"}),!1):rM(r.hostname)?(t.addIssue({code:f.eq.custom,message:"ClientID hostname must not be an IP address"}),!1):function(e){let t=e.startsWith("https://")?8:e.startsWith("http://")?7:-1;if(-1===t)throw TypeError('URL must use the "https:" or "http:" protocol');let r=e.indexOf("#",t),s=e.indexOf("?",t),i=-1!==s&&(-1===r||s<r)?s:-1,a=-1===r?-1===i?e.length:i:-1===i?r:Math.min(r,i),n=e.indexOf("/",t),o=-1===n||n>a?a:n;if(t===o)throw TypeError("URL must contain a host");return e.substring(o,a)}(e)===r.pathname||(t.addIssue({code:f.eq.custom,message:`ClientID must be in canonical form ("${r.href}", got "${e}")`}),!1)});sS.superRefine((e,t)=>
1{let r=new URL(e);return r.port?(t.addIssue({code:f.eq.custom,message:"ClientID must not contain a port"}),!1):r.search?(t.addIssue({code:f.eq.custom,message:"ClientID must not contain a query string"}),!1):"/oauth-client-metadata.json"===r.pathname||(t.addIssue({code:f.eq.custom,message:'ClientID must be "/oauth-client-metadata.json"'}),!1)});let sx=h.k5(["client_secret_basic","client_secret_jwt","client_secret_post","none","private_key_jwt","self_signed_tls_client_auth","tls_client_auth"]),sE=h.k5(["authorization_code","implicit","refresh_token","password","client_credentials","urn:ietf:params:oauth:grant-type:jwt-bearer","urn:ietf:params:oauth:grant-type:saml2-bearer"]),sA=h.Ik({redirect_uris:h.YO(r5).nonempty(),response_types:h.YO(sc).nonempty().default(["code"]),grant_types:h.YO(sE).nonempty().default(["authorization_code"]),scope:rG.optional(),token_endpoint_auth_method:sx.default("client_secret_basic"),token_endpoint_auth_signing_alg:h.Yj().optional(),userinfo_signed_response_alg:h.Yj().optional(),userinfo_encrypted_response_alg:h.Yj().optional(),jwks_uri:rF.optional(),jwks:F.optional(),application_type:h.k5(["web","native"]).default("web"),subject_type:h.k5(["public","pairwise"]).default("public"),request_object_signing_alg:h.Yj().optional(),id_token_signed_response_alg:h.Yj().optional(),authorization_signed_response_alg:h.Yj().default("RS256"),authorization_encrypted_response_enc:h.k5(["A128CBC-HS256"]).optional(),authorization_encrypted_response_alg:h.Yj().optional(),client_id:r1.optional(),client_name:h.Yj().optional(),client_uri:rF.optional(),policy_uri:rF.optional(),tos_uri:rF.optional(),logo_uri:rF.optional(),default_max_age:h.ai().optional(),require_auth_time:h.zM().optional(),contacts:h.YO(h.Yj().email()).optional(),tls_client_certificate_bound_access_tokens:h.zM().optional(),dpop_bound_access_tokens:h.zM().optional(),authorization_details_types:h.YO(h.Yj()).optional()}),sj=h.Ik({request_uri:h.Yj(),expires_in:h.ai().int().positive()}),sI=h.Ik({grant_type:h.eu("password"),username:h.Yj(),password:h.Yj()}),sT=h.Ik({resource:rF.refine(e=>!e.includes("?"),{message:"Resource URL must not contain query parameters"}).refine(e=>!e.includes("#"),{message:"Resource URL must not contain a fragment"}),authorization_servers:h.YO(sg).optional(),jwks_uri:rF.optional(),scopes_supported:h.YO(h.Yj()).optional(),bearer_methods_supported:h.YO(h.k5(["header","body","query"])).optional(),resource_signing_alg_values_supported:h.YO(h.Yj()).optional(),resource_documentation:rF.optional(),resource_policy_uri:rF.optional(),resource_tos_uri:rF.optional()}),sR=h.Yj().min(1),sO=h.Ik({grant_type:h.eu("refresh_token"),refresh_token:sR});h.Ik({token:h.KC([ss,sR]),token_type_hint:h.k5(["access_token","refresh_token"]).optional()}),h.gM("grant_type",[si,sO,sI,sw]),h.k5(["interaction_required","login_required","account_selection_required","consent_required","invalid_request_uri","invalid_request_object","request_not_supported","request_uri_not_supported","registration_not_supported"]),h.Ik({sub:h.Yj(),iss:h.Yj().url().optional(),aud:h.KC([h.Yj(),h.YO(h.Yj()).min(1)]).optional(),email:h.Yj().email().optional(),email_verified:h.zM().optional(),name:h.Yj().optional(),preferred_username:h.Yj().optional(),picture:h.Yj().url().optional()});let sC=new Map,sP=(e,t)=>(function(e){return new Promise(t=>{let r=(sC.get(e)??Promise.resolve()).then(()=>new Promise(s=>{t(()=>{sC.get(e)===r&&sC.delete(e),s()})}));sC.set(e,r)})})(e).then(async e=>{try{return await t()}finally{e()}}),sD=e=>"string"==typeof e?e:void 0;function s$(e){return e.get("content-type")?.split(";")[0].trim()}function sL(e){if("function"==typeof AbortSignal.timeout)return AbortSignal.timeout(e);let t=new AbortController;return setTimeout(()=>t.abort(function(e){let t=`The operation timed out after ${e} ms`;return"function"==typeof DOMException?new DOMException(t,"TimeoutError"):Error(t)}(e)),e),t.signal}class sz extends AbortController{[Symbol.dispose](){this.abort(Error("AbortController was disposed"))}}class sK extends tJ{constructor(e,t,r){super(async(e,t)=>this.fetchMetadata(e,t),tV(e,r?.onCacheError)),this.fetch=rj(t),this.allowHttpIssuer=r?.allowHttpIssuer===!0}async get(e,t){let r=sg.parse(String(e));if(!this.allowHttpIssuer&&r.startsWith("http:"))throw TypeError("Unsecure issuer URL protocol only allowed in development and test environments");return super.get(r,t)}async fetchMetadata(e,t){let r=new URL("/.well-known/oauth-authorization-server",e),s=new Request
1(r,{headers:{accept:"application/json"},cache:t?.noCache?"no-cache":void 0,signal:t?.signal,redirect:"manual"}),i=await this.fetch(s);if(200!==i.status)throw await rc(i,"log"),await ry.from(i,`Unexpected status code ${i.status} for "${r}"`,void 0,{cause:s});if("application/json"!==s$(i.headers))throw await rc(i,"log"),await ry.from(i,`Unexpected content type for "${r}"`,void 0,{cause:s});let a=sv.parse(await i.json());if(a.issuer!==e)throw TypeError(`Invalid issuer ${a.issuer}`);if(!0!==a.client_id_metadata_document_supported)throw TypeError(`Authorization server "${e}" does not support client_id_metadata_document`);return a}}class sq extends Error{static from(e,t,r){return e instanceof sq?e:new sq(t,e instanceof Error?e.message:void 0,r,e)}constructor(e,t=e.get("error_description")||"OAuth callback error",r,s){super(t,{cause:s}),this.params=e,this.state=r}}let sM="handle.invalid";class sY extends Error{constructor(){super(...arguments),this.name="IdentityResolverError"}}function sN(e){let t=function(e){if(e.alsoKnownAs){for(let t of e.alsoKnownAs)if(t.startsWith("at://"))return t.slice(5)}}(e);if(t)return sW(t)}function sW(e){var t;let r=e.toLowerCase();return(t=r).length>0&&t.length<254&&/^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/.test(t)?r:void 0}class sZ{constructor(e,t){this.didResolver=e,this.handleResolver=t}async resolve(e,t){return tO(e)?this.resolveFromDid(e,t):this.resolveFromHandle(e,t)}async resolveFromDid(e,t){let r=await this.getDocumentFromDid(e,t);t?.signal?.throwIfAborted();let s=sN(r),i=s?await this.handleResolver.resolve(s,t).catch(()=>void 0):void 0;return{did:r.id,didDoc:r,handle:s&&i===e?s:sM}}async resolveFromHandle(e,t){let r=await this.getDocumentFromHandle(e,t);return{did:r.id,didDoc:r,handle:sN(r)||sM}}async getDocumentFromDid(e,t){return this.didResolver.resolve(e,t)}async getDocumentFromHandle(e,t){let r=sW(e);if(!r)throw new sY(`Invalid handle "${e}" provided.`);let s=await this.handleResolver.resolve(r,t);if(!s)throw new sY(`Handle "${r}" does not resolve to a DID`);t?.signal?.throwIfAborted();let i=await this.didResolver.resolve(s,t);if(r!==sN(i))throw new sY(`Did document for "${s}" does not include the handle "${r}"`);return i}}let sU="ES256";class sF extends Error{}class sH extends Error{constructor(e,t=`The session for "${e}" was successfully revoked`,r){super(t,r),this.sub=e}}function sJ(e){return e.token_endpoint_auth_methods_supported}function sB(e){return e.token_endpoint_auth_signing_alg_values_supported??[sU]}class sV extends tJ{constructor(e,t=globalThis.fetch,r){super(async(e,t)=>this.fetchMetadata(e,t),tV(e,r?.onCacheError)),this.fetch=rj(t),this.allowHttpResource=r?.allowHttpResource===!0}
1async get(e,t){let{protocol:r,origin:s}=new URL(e);if("https:"!==r&&"http:"!==r)throw TypeError(`Invalid protected resource metadata URL protocol: ${r}`);if("http:"===r&&!this.allowHttpResource)throw TypeError(`Unsecure resource metadata URL (${r}) only allowed in development and test environments`);return super.get(s,t)}async fetchMetadata(e,t){let r=new URL("/.well-known/oauth-protected-resource",e),s=new Request(r,{signal:t?.signal,headers:{accept:"application/json"},cache:t?.noCache?"no-cache":void 0,redirect:"manual"}),i=await this.fetch(s);if(404===i.status)return await rc(i,"log"),null;if(200!==i.status)throw await rc(i,"log"),await ry.from(i,`Unexpected status code ${i.status} for "${r}"`,void 0,{cause:s});if("application/json"!==s$(i.headers))throw await rc(i,"log"),await ry.from(i,`Unexpected content type for "${r}"`,void 0,{cause:s});let a=sT.parse(await i.json());if(a.resource!==e)throw TypeError(`Invalid issuer ${a.resource}`);return a}}class sG extends Error{constructor(e,t){super(e,t)}static from(e,t){if(e instanceof sG)return e;let r=e instanceof f.G?`${e.errors[0].path} ${e.errors[0].message}`:null;return new sG((t??"Unable to resolve identity")+(r?` (${r})`:""),{cause:e})}}class sX{constructor(e,t,r){this.identityResolver=e,this.protectedResourceMetadataResolver=t,this.authorizationServerMetadataResolver=r}async resolve(e,t){return/^https?:\/\//.test(e)?this.resolveFromService(e,t):this.resolveFromIdentity(e,t)}async resolveFromService(e,t){try{return{metadata:await this.getResourceServerMetadata(e,t)}}catch(r){if(!t?.signal?.aborted&&r instanceof sG)try{let r=sg.safeParse(e);if(r.success)return{metadata:await this.getAuthorizationServerMetadata(r.data,t)}}catch{}throw r}}async resolveFromIdentity(e,t){let r=await this.resolveIdentity(e,t);t?.signal?.throwIfAborted();let s=function(e){let t=e.service?.find(t$,e);if(!t)throw new tm(e.id,`Document ${e.id} does not contain a (valid) #atproto_pds service URL`,"did-service-not-found");return new URL(t.serviceEndpoint)}(r.didDoc);return{identityInfo:r,metadata:await this.getResourceServerMetadata(s,t),pds:s}}async resolveIdentity(e,t){try{return await this.identityResolver.resolve(e,t)}catch(t){throw sG.from(t,`Failed to resolve identity: ${e}`)}}async getAuthorizationServerMetadata(e,t){try{return await this.authorizationServerMetadataResolver.get(e,t)}catch(t){throw sG.from(t,`Failed to resolve OAuth server metadata for issuer: ${e}`)}}async getResourceServerMetadata(e,t){try{let r=await this.protectedResourceMetadataResolver.get(e,t);if(!r)return this.getAuthorizationServerMetadata(e,t);if(r.authorization_servers?.length!==1)throw new sG(r.authorization_servers?.length?`Unable to determine authorization server for PDS: ${e}`:`No authorization servers found for PDS: ${e}`);let s=r.authorization_servers[0];t?.signal?.throwIfAborted();let i=await this.getAuthorizationServerMetadata(s,t);if(i.protected_resources&&!i.protected_resources.includes(r.resource))throw new sG(`PDS "${e}" not protected by issuer "${s}"`);return i}catch(t){throw sG.from(t,`Failed to resolve OAuth server metadata for resource: ${e}`)}}}class sQ extends Error{constructor(e,t,r){super(t,r),this.sub=e}}let s0=globalThis.crypto?.subtle,s1=globalThis.ReadableStream;function s2({key:e,supportedAlgs:t,nonces:r,sha256:s=void 0!==s0?s8:void 0,isAuthServer:i,fetch:a=globalThis.fetch}){if(!s)throw TypeError("crypto.subtle is not available in this environment. Please provide a sha256 function.");let n=function(e,t){if(t){let r=t.find(t=>e.algorithms.includes(t));if(r)return r}else{let[t]=e.algorithms;if(t)return t}throw Error("Key does not match any alg supported by the server")}(e,t);return async function(t,o){let l,c=null==o&&t instanceof Request?t:new Request(t,o),d=c.headers.get("Authorization"),u=d?.startsWith("DPoP ")?await s(d.slice(5)):void 0,{origin:h}=new URL(c.url),p=c.method,f=function(e){let t=e.indexOf("#"),r=e.indexOf("?"),s=-1===t?r:-1===r?t:Math.min(t,r);return -1===s?e:e.slice(0,s)}(c.url);try{l=await r.get(h)}catch{}let m=await s5(e,n,p,f,l,u);c.headers.set("DPoP",m);let y=await a.call(this,c),g=y.headers.get("DPoP-Nonce");if(!g||g===l)return y;try{await r.set(h,g)}catch{}if(!await s4(y,i)||t===c||s1&&o?.body instanceof s1)return y;await rc(y,"log");
1let v=await s5(e,n,p,f,g,u),w=new Request(t,o);w.headers.set("DPoP",v);let _=await a.call(this,w),b=_.headers.get("DPoP-Nonce");if(!b||b===l)return _;try{await r.set(h,b)}catch{}return _}}async function s5(e,t,r,s,i,a){let n=e.bareJwk;if(!n)throw Error("Only asymmetric keys can be used as DPoP proofs");let o=Math.floor(Date.now()/1e3);return e.createJwt({alg:t,typ:"dpop+jwt",jwk:n},{iat:o,jti:Math.random().toString(36).slice(2),htm:r,htu:s,nonce:i,ath:a})}async function s4(e,t){if((void 0===t||!1===t)&&401===e.status){let t=e.headers.get("WWW-Authenticate");if(t?.startsWith("DPoP"))return t.includes('error="use_dpop_nonce"')}if((void 0===t||!0===t)&&400===e.status)try{let t=await rv(e,10240);return t?.error==="use_dpop_nonce"}catch{}return!1}async function s8(e){if(null==s0)throw Error("crypto.subtle is not available in this environment. Please provide a sha256 function.");let t=new TextEncoder().encode(e),r=new Uint8Array(await s0.digest("SHA-256",t));return p.r0.baseEncode(r)}class s9 extends Error{constructor(e,t){let r=sD(t?.error),s=sD(t?.error_description);super(`OAuth ${r?`"${r}"`:"unknown"} error${s?`: ${s}`:""}`),this.response=e,this.payload=t,this.error=r,this.errorDescription=s}get status(){return this.response.status}get headers(){return this.response.headers}}class s6{constructor(e,t,r,s,i,a,n,o,l){this.authMethod=e,this.dpopKey=t,this.serverMetadata=r,this.clientMetadata=s,this.dpopNonces=i,this.oauthResolver=a,this.runtime=n,this.keyset=o,this.clientCredentialsFactory=function(e,t,r,s,i){if(!sJ(t).includes(e.method))throw new sF(`Client authentication method "${e.method}" no longer supported`);if("none"===e.method)return()=>({payload:{client_id:r.client_id}});if("private_key_jwt"===e.method)try{if(!i)throw Error("A keyset is required for private_key_jwt");let{key:a,alg:n}=i.findPrivateKey({usage:"sign",kid:e.kid,alg:sB(t)});return async()=>({payload:{client_id:r.client_id,client_assertion_type:rK,client_assertion:await a.createJwt({alg:n},{iss:r.client_id,sub:r.client_id,aud:t.issuer,jti:await s.generateNonce(),iat:Math.floor(Date.now()/1e3),exp:Math.floor(Date.now()/1e3)+60})}})}catch(e){throw new sF("Failed to load private key",{cause:e})}throw new sF(`Unsupported auth method ${e.method}`)}(e,r,s,n,o),this.dpopFetch=s2({fetch:rj(l),key:t,supportedAlgs:r.dpop_signing_alg_values_supported,sha256:async e=>n.sha256(e),nonces:i,isAuthServer:!0})}get issuer(){return this.serverMetadata.issuer}async revoke(e){try{await this.request("revocation",{token:e})}catch{}}async exchangeCode(e,t,r){let s=Date.now(),i=await this.request("token",{grant_type:"authorization_code",redirect_uri:r??this.clientMetadata.redirect_uris[0],code:e,code_verifier:t});try{return{aud:await this.verifyIssuer(i.sub),sub:i.sub,iss:this.issuer,scope:i.scope,refresh_token:i.refresh_token,access_token:i.access_token,token_type:i.token_type,expires_at:"number"==typeof i.expires_in?new Date(s+1e3*i.expires_in).toISOString():void 0}}catch(e){throw await this.revoke(i.access_token),e}}async refresh(e){if(!e.refresh_token)throw new sQ(e.sub,"No refresh token available");let t=await this.verifyIssuer(e.sub),r=Date.now(),s=await this.request("token",{grant_type:"refresh_token",refresh_token:e.refresh_token});return{aud:t,sub:e.sub,iss:this.issuer,scope:s.scope,refresh_token:s.refresh_token,access_token:s.access_token,token_type:s.token_type,expires_at:"number"==typeof s.expires_in?new Date(r+1e3*s.expires_in).toISOString():void 0}}async verifyIssuer(e){let t=await this.oauthResolver.resolveFromIdentity(e,{noCache:!0,allowStale:!1,signal:sL(1e4)});if(this.issuer!==t.metadata.issuer)throw TypeError("Issuer mismatch");return t.pds.href}async request(e,t){let r=this.serverMetadata[`${e}_endpoint`];if(!r)throw Error(`No ${e} endpoint available`);let s=await this.clientCredentialsFactory(),{response:i,json:a}=await this.dpopFetch(r,{method:"POST",headers:{...s.headers,"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(Object.entries({...t,...s.payload}).filter(s3).map(s7)).toString()}).then(rE());if(i.ok)switch(e){case"token":return sr.parse(a);case"pushed_authorization_request":return sj.parse(a);default:return a}throw new s9(i,a)}}function s3(e){return void 0!==e[1]}function s7(e){let t=e[0],r=e[1];switch(typeof r){case"string":return[t,r];case"number":case"boolean":return[t,String(r)];default:{let e=JSON.stringify(r);if(void 0===e)throw Error(`Unsupported value type for ${t}: ${String(r)}`);return[t,e]}}}class ie{constructor(e,t,r,s,i,a){this.clientMetadata=e,this.runtime=t,this.resolver=r,this.fetch=s,this.keyset=i,this.dpopNonceCache=a}async fromIssuer(e,t,r,s){let i=await this.resolver.getAuthorizationServerMetadata(e,s);return this.fromMetadata(i,t,r)}async fromMetadata(e,t,r){return new s6(t,r,e,this.clientMetadata,this.dpopNonceCache,this.resolver,this.runtime,this.keyset,this.fetch)}}
1class it extends Error{constructor(e,t=`The session for "${e}" is invalid`,r){super(t,r),this.sub=e}}let ir=globalThis.ReadableStream;class is{constructor(e,t,r,s=globalThis.fetch){this.server=e,this.sub=t,this.sessionGetter=r,this.dpopFetch=s2({fetch:rj(s),key:e.dpopKey,supportedAlgs:e.serverMetadata.dpop_signing_alg_values_supported,sha256:async t=>e.runtime.sha256(t),nonces:e.dpopNonces,isAuthServer:!1})}get did(){return this.sub}get serverMetadata(){return this.server.serverMetadata}async getTokenSet(e){let{tokenSet:t}=await this.sessionGetter.getSession(this.sub,e);return t}async getTokenInfo(e="auto"){let t=await this.getTokenSet(e),r=null==t.expires_at?void 0:new Date(t.expires_at);return{expiresAt:r,get expired(){return null==r?void 0:r.getTime()<Date.now()-5e3},scope:t.scope,iss:t.iss,aud:t.aud,sub:t.sub}}async signOut(){try{let e=await this.getTokenSet(!1);await this.server.revoke(e.access_token)}finally{await this.sessionGetter.delStored(this.sub,new sH(this.sub))}}async fetchHandler(e,t){let r,s=await this.getTokenSet("auto"),i=new URL(e,s.aud),a=`${s.token_type} ${s.access_token}`,n=new Headers(t?.headers);n.set("Authorization",a);let o=await this.dpopFetch(i,{...t,headers:n});if(!ii(o))return o;try{r=await this.getTokenSet(!0)}catch(e){return o}if(ir&&t?.body instanceof ir)return o;let l=`${r.token_type} ${r.access_token}`,c=new URL(e,r.aud);n.set("Authorization",l);let d=await this.dpopFetch(c,{...t,headers:n});return ii(d)&&await this.sessionGetter.delStored(this.sub,new it(this.sub)),d}}function ii(e){if(401!==e.status)return!1;let t=e.headers.get("WWW-Authenticate");return null!=t&&(t.startsWith("Bearer ")||t.startsWith("DPoP "))&&t.includes('error="invalid_token"')}class ia{constructor(e){this.implementation=e;let{requestLock:t}=e;this.hasImplementationLock=null!=t,this.usingLock=t?.bind(e)||sP}async generateKey(e){let t=Array.from(e).sort(io);return this.implementation.createKey(t)}async sha256(e){let t=new TextEncoder().encode(e),r=await this.implementation.digest(t,{name:"sha256"});return p.r0.baseEncode(r)}async generateNonce(e=16){let t=await this.implementation.getRandomValues(e);return p.r0.baseEncode(t)}async generatePKCE(e){let t=await this.generateVerifier(e);return{verifier:t,challenge:await this.sha256(t),method:"S256"}}async calculateJwkThumbprint(e){let t=JSON.stringify(function(e){let t=t=>{let r=e[t];if("string"!=typeof r||!r)throw TypeError(`"${t}" Parameter missing or invalid`);return r};switch(e.kty){case"EC":return{crv:t("crv"),kty:t("kty"),x:t("x"),y:t("y")};case"OKP":return{crv:t("crv"),kty:t("kty"),x:t("x")};case"RSA":return{e:t("e"),kty:t("kty"),n:t("n")};case"oct":return{k:t("k"),kty:t("kty")};default:throw TypeError('"kty" (Key Type) Parameter missing or unsupported')}}(e));return this.sha256(t)}async generateVerifier(e=32){if(e<32||e>96)throw TypeError("Invalid code_verifier length");let t=await this.implementation.getRandomValues(e);return p.r0.baseEncode(t)}}function io(e,t){if("ES256K"===e)return -1;if("ES256K"===t)return 1;for(let r of["ES","PS","RS"])if(e.startsWith(r)){if(t.startsWith(r))return parseInt(e.slice(2,5))-parseInt(t.slice(2,5));return -1}else if(t.startsWith(r))return 1;return 0}var il=function(e,t,r){if(null!=t){var s,i;if("object"!=typeof t&&"function"!=typeof t)throw TypeError("Object expected.");if(r){if(!Symbol.asyncDispose)throw TypeError("Symbol.asyncDispose is not defined.");s=t[Symbol.asyncDispose]}if(void 0===s){if(!Symbol.dispose)throw TypeError("Symbol.dispose is not defined.");s=t[Symbol.dispose],r&&(i=s)}if("function"!=typeof s)throw TypeError("Object not disposable.");i&&(s=function(){try{i.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:s,async:r})}else r&&e.stack.push({async:!0});return t},ic=(a="function"==typeof SuppressedError?SuppressedError:function(e,t,r){var s=Error(r);return s.name="SuppressedError",s.error=e,s.suppressed=t,s},function(e){function t(t){e.error=e.hasError?new a(t,e.error,"An error was suppressed during disposal."):t,e.hasError=!0}var r,s=0;return function i(){for(;r=e.stack.pop();)try{if(!r.async&&1===s)return s=0,e.stack.push(r),Promise.resolve().then(i);if(r.dispose){var a=r.dispose.call(r.value);if(r.async)return s|=2,Promise.resolve(a).then(i,function(e){return t(e),i()})}else s|=1}catch(e){t(e)}
1if(1===s)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}()});function id(e){return e instanceof sQ||e instanceof sH||e instanceof it||e instanceof sF||e instanceof TypeError}class iu extends tJ{#B;#V;#s;constructor(e,t,r,s={}){super(async(e,{signal:i},a)=>{if(void 0===a){let t=new sQ(e,"The session was deleted by another process");throw await s.onSessionDeleted?.call(null,e,t),t}let{dpopKey:n,authMethod:o,tokenSet:l}=a;if(e!==l.sub)throw new sQ(e,"Stored session sub mismatch");if(!l.refresh_token)throw new sQ(e,"No refresh token available");let c=await t.fromIssuer(l.iss,o,n,{signal:i});i?.throwIfAborted();try{let t=await c.refresh(l);if(e!==t.sub)throw new sQ(e,"Token set sub mismatch");return{dpopKey:n,tokenSet:t,authMethod:c.authMethod}}catch(t){if(t instanceof s9&&400===t.status&&"invalid_grant"===t.error){if(!r.hasImplementationLock){await new Promise(e=>setTimeout(e,1e3));let r=await this.getStored(e);if(void 0===r)throw new sQ(e,"The session was deleted by another process",{cause:t});if(r.tokenSet.access_token!==l.access_token||r.tokenSet.refresh_token!==l.refresh_token)return r}throw new sQ(e,t.errorDescription??"The session was revoked",{cause:t})}throw t}},e,{isStale:(e,{tokenSet:t})=>null!=t.expires_at&&new Date(t.expires_at).getTime()<Date.now()+1e4+3e4*Math.random(),deleteOnError:id}),this.#B=t,this.#V=r,this.#s=s}async setStored(e,t){if(e!==t.tokenSet.sub)throw Error("Token set does not match the expected sub");try{await super.setStored(e,t)}catch(s){let r=[s];try{let{tokenSet:e,dpopKey:r,authMethod:s}=t,i=await this.#B.fromIssuer(e.iss,s,r);await i.revoke(e.refresh_token??e.access_token)}catch(e){r.push(e)}try{await this.delStored(e,s)}catch(e){r.push(e)}throw AggregateError(r,`Failed to store session for ${e}`)}await this.#s.onSessionUpdated?.call(null,e,t)}async delStored(e,t){await super.delStored(e,t),await this.#s.onSessionDeleted?.call(null,e,t)}async get(e,t){let r=await this.#V.usingLock(`@atproto-oauth-client-${e}`,async()=>{let r={stack:[],error:void 0,hasError:!1};try{let s=sL(3e4),i=il(r,function(e){let t=new sz,r=function(e){let r=Error("This operation was aborted",{cause:this.reason});t.abort(r)};try{for(let s of e)s&&(s.throwIfAborted(),s.addEventListener("abort",r,{signal:t.signal}));return t}catch(e){throw t.abort(e),e}}([t?.signal,s]),!1);return await super.get(e,{...t,signal:i.signal})}catch(e){r.error=e,r.hasError=!0}finally{ic(r)}});if(e!==r.tokenSet.sub)throw Error("Token set does not match the expected sub");return r}async getSession(e,t="auto"){return this.get(e,{noCache:!0===t,allowStale:!1===t})}}let ih=sA.extend({client_id:h.KC([sS,r8])});class ip{static async fetchMetadata({clientId:e,fetch:t=globalThis.fetch,signal:r}){r?.throwIfAborted();let s=new Request(e,{redirect:"error",signal:r}),i=await t(s);if(200!==i.status)throw i.body?.cancel?.(),TypeError(`Failed to fetch client metadata: ${i.status}`);let a=i.headers.get("content-type")?.split(";")[0].trim();if("application/json"!==a)throw i.body?.cancel?.(),TypeError(`Invalid client metadata content type: ${a}`);let n=await i.json();return r?.throwIfAborted(),sA.parse(n)}constructor(e){let{stateStore:t,sessionStore:r,dpopNonceCache:s=new rs({ttl:6e4,max:100}),authorizationServerMetadataCache:i=new rs({ttl:6e4,max:100}),protectedResourceMetadataCache:a=new rs({ttl:6e4,max:100}),responseMode:n,clientMetadata:o,runtimeImplementation:l,keyset:c}=e;this.keyset=c?c instanceof ea?c:new ea(c):void 0,this.clientMetadata=function(e,t){!e.jwks&&!e.jwks_uri&&t?.size&&(e={...e,jwks:t.toJSON()});let r=ih.parse(e);if(r.client_id.startsWith("http:"))r9(r.client_id);else{var s;s=r.client_id,sS.parse(s)}let i=r.scope?.split(" ");if(!i?.includes("atproto"))throw TypeError('Client metadata must include the "atproto" scope');if(!r.response_types.includes("code"))throw TypeError('"response_types" must include "code"');if(!r.grant_types.includes("authorization_code"))throw TypeError('"grant_types" must include "authorization_code"');let a=r.token_endpoint_auth_method,n=r.token_endpoint_auth_signing_alg;switch(a){case"none":if(n)throw TypeError(`"token_endpoint_auth_signing_alg" must not be provided when "token_endpoint_auth_method" is "${a}"`);break;case"private_key_jwt":{if(!n)throw TypeError(`"token_endpoint_auth_signing_alg" must be provided when "token_endpoint_auth_method" is "${a}"`);if(!t)throw TypeError(`Client authentication method "${a}" requires a keyset`);let e=Array.from(t.list({usage:"sign"})).filter(e=>e.kid);if(!e.length)throw TypeError(`Client authentication method "${a}" requires at least one active signing key with a "kid" property`);
1if(!e.some(e=>e.algorithms.includes(sU)))throw TypeError(`Client authentication method "${a}" requires at least one active "${sU}" signing key`);if(r.jwks){for(let t of e)if(!r.jwks.keys.some(e=>e.kid===t.kid&&!e.revoked))throw TypeError(`Missing or inactive key "${t.kid}" in jwks. Make sure that every signing key of the Keyset is declared as an active key in the Metadata's JWKS.`)}else if(r.jwks_uri);else throw TypeError(`Client authentication method "${a}" requires a JWKS`);break}default:throw TypeError(`Unsupported "token_endpoint_auth_method" value: ${a}`)}return r}(o,this.keyset),this.responseMode=n,this.runtime=new ia(l),this.fetch=e.fetch??globalThis.fetch,this.oauthResolver=new sX(function(e){if("identityResolver"in e&&null!=e.identityResolver)return e.identityResolver;if("handleResolver"in e&&null!=e.handleResolver)return new sZ(function(e){let{didResolver:t,didCache:r,onDidCacheError:s}=e;return t instanceof ra&&!r?t:new ra(t??new rP(e),r,s)}(e),function(e){let{handleResolver:t,handleCache:r,onHandleCacheError:s}=e;return t instanceof rz&&!r?t:new rz("string"==typeof t||t instanceof URL?new rL(t,e):t,r,s)}(e));throw TypeError("identityResolver or handleResolver option is required")}(e),new sV(a,this.fetch,{allowHttpResource:e.allowHttp}),new sK(i,this.fetch,{allowHttpIssuer:e.allowHttp})),this.serverFactory=new ie(this.clientMetadata,this.runtime,this.oauthResolver,this.fetch,this.keyset,s),this.stateStore=t,this.sessionGetter=new iu(r,this.serverFactory,this.runtime,e)}get identityResolver(){return this.oauthResolver.identityResolver}get jwks(){return this.keyset?.publicJwks??{keys:[]}}async authorize(e,{signal:t,...r}={}){let s=r?.redirect_uri??this.clientMetadata.redirect_uris[0];if(!this.clientMetadata.redirect_uris.includes(s))throw TypeError("Invalid redirect_uri");let{identityInfo:i,metadata:a}=await this.oauthResolver.resolve(e,{signal:t}),n=await this.runtime.generatePKCE(),o=await this.runtime.generateKey(a.dpop_signing_alg_values_supported||[sU]),l=function(e,t,r){let s=t.token_endpoint_auth_method,i=sJ(e);if(!i.includes(s))throw Error(`The server does not support "${s}" authentication. Supported methods are: ${i.join(", ")}.`);if("private_key_jwt"===s){if(!r)throw Error("A keyset is required for private_key_jwt");let t=sB(e);for(let e of r.list({alg:t,usage:"sign"}))if(e.kid)return{method:"private_key_jwt",kid:e.kid};throw Error(t.includes(sU)?`Client authentication method "${s}" requires at least one "${sU}" signing key with a "kid" property`:`Authorization server requires "${s}" authentication method, but does not support "${sU}" algorithm.`)}if("none"===s)return{method:"none"};throw Error('The ATProto OAuth spec requires that client use either "none" or "private_key_jwt" authentication method.'+("client_secret_basic"===s?' You might want to explicitly set "token_endpoint_auth_method" to one of those values in the client metadata document.':` You set "${s}" which is not allowed.`))}(a,this.clientMetadata,this.keyset),c=await this.runtime.generateNonce();await this.stateStore.set(c,{iss:a.issuer,dpopKey:o,authMethod:l,verifier:n.verifier,appState:r?.state});let d={...r,client_id:this.clientMetadata.client_id,redirect_uri:s,code_challenge:n.challenge,code_challenge_method:n.method,state:c,login_hint:i?i.handle!==sM?i.handle:i.did:void 0,response_mode:this.responseMode,response_type:"code",scope:r?.scope??this.clientMetadata.scope},u=new URL(a.authorization_endpoint);if("https:"!==u.protocol&&"http:"!==u.protocol)throw TypeError(`Invalid authorization endpoint protocol: ${u.protocol}`);if(a.pushed_authorization_request_endpoint){let e=await this.serverFactory.fromMetadata(a,l,o),t=await e.request("pushed_authorization_request",d);return u.searchParams.set("client_id",this.clientMetadata.client_id),u.searchParams.set("request_uri",t.request_uri),u}if(a.require_pushed_authorization_requests)throw Error("Server requires pushed authorization requests (PAR) but no PAR endpoint is available");for(let[e,t]of Object.entries(d))t&&u.searchParams.set(e,String(t));if(u.pathname.length+u.search.length<2048)return u;if(!a.pushed_authorization_request_endpoint)throw Error("Login URL too long");throw Error("Server does not support pushed authorization requests (PAR)")}
1async abortRequest(e){if(!e.searchParams.get("request_uri"))return}async callback(e,t={}){if(null!=e.get("response"))throw new sq(e,"JARM not supported");let r=e.get("iss"),s=e.get("state"),i=e.get("error"),a=e.get("code");if(!s)throw new sq(e,'Missing "state" parameter');let n=await this.stateStore.get(s);if(n)await this.stateStore.del(s);else throw new sq(e,`Unknown authorization session "${s}"`);try{if(null!=i)throw new sq(e,void 0,n.appState);if(!a)throw new sq(e,'Missing "code" query param',n.appState);let s=await this.serverFactory.fromIssuer(n.iss,n.authMethod,n.dpopKey);if(null!=r){if(!s.issuer)throw new sq(e,"Issuer not found in metadata",n.appState);if(s.issuer!==r)throw new sq(e,"Issuer mismatch",n.appState)}else if(s.serverMetadata.authorization_response_iss_parameter_supported)throw new sq(e,"iss missing from the response",n.appState);let o=await s.exchangeCode(a,n.verifier,t?.redirect_uri??s.clientMetadata.redirect_uris[0]);try{await this.revoke(o.sub)}catch{}try{return await this.sessionGetter.setStored(o.sub,{dpopKey:n.dpopKey,authMethod:s.authMethod,tokenSet:o}),{session:this.createSession(s,o.sub),state:n.appState??null}}catch(e){throw await s.revoke(o.refresh_token||o.access_token),e}}catch(t){throw sq.from(t,e,n.appState)}}async restore(e,t="auto"){tC(e);let{dpopKey:r,authMethod:s,tokenSet:i}=await this.sessionGetter.getSession(e,t);try{let a=await this.serverFactory.fromIssuer(i.iss,s,r,{noCache:!0===t,allowStale:!1===t});return this.createSession(a,e)}catch(t){throw t instanceof sF&&await this.sessionGetter.delStored(e,t),t}}async revoke(e){tC(e);let t=await this.sessionGetter.getSession(e,!1).catch(e=>{if(id(e))return null;throw e});if(!t)return;let{dpopKey:r,authMethod:s,tokenSet:i}=t;try{let e=await this.serverFactory.fromIssuer(i.iss,s,r);await e.revoke(i.access_token)}finally{await this.sessionGetter.delStored(e,new sH(e))}}createSession(e,t){return new is(e,t,this.sessionGetter,this.fetch)}}function im(e){return new Promise((t,r)=>{let s=()=>{e.removeEventListener("success",i),e.removeEventListener("error",a)},i=()=>{t(e.result),s()},a=()=>{r(e.error||Error("Unknown error")),s()};e.addEventListener("success",i),e.addEventListener("error",a)})}class iy{constructor(e){this.idbIndex=e}count(e){return im(this.idbIndex.count(e))}get(e){return im(this.idbIndex.get(e))}getKey(e){return im(this.idbIndex.getKey(e))}getAll(e,t){return im(this.idbIndex.getAll(e,t))}getAllKeys(e,t){return im(this.idbIndex.getAllKeys(e,t))}deleteAll(e){return new Promise((t,r)=>{let s=this.idbIndex.openCursor(e);s.onsuccess=function(e){let r=e.target.result;r?(r.delete(),r.continue()):t()},s.onerror=function(e){r(e.target?.error||Error("Unexpected error"))}})}}class ig{constructor(e){this.idbObjStore=e}get name(){return this.idbObjStore.name}index(e){return new iy(this.idbObjStore.index(e))}get(e){return im(this.idbObjStore.get(e))}getKey(e){return im(this.idbObjStore.getKey(e))}getAll(e,t){return im(this.idbObjStore.getAll(e,t))}getAllKeys(e,t){return im(this.idbObjStore.getAllKeys(e,t))}add(e,t){return im(this.idbObjStore.add(e,t))}put(e,t){return im(this.idbObjStore.put(e,t))}delete(e){return im(this.idbObjStore.delete(e))}clear(){return im(this.idbObjStore.clear())}}class iv{#G;constructor(e){this.#G=e;let t=()=>{s()},r=()=>{s()},s=()=>{this.#G=null,e.removeEventListener("abort",t),e.removeEventListener("complete",r)};e.addEventListener("abort",t),e.addEventListener("complete",r)}get tx(){if(!this.#G)throw Error("Transaction already ended");return this.#G}async abort(){let{tx:e}=this;this.#G=null,e.abort()}async commit(){let{tx:e}=this;this.#G=null,e.commit?.()}objectStore(e){return new ig(this.tx.objectStore(e))}[Symbol.dispose](){this.#G&&this.commit()}}class iw{static async open(e,t,r){return new iw(await new Promise((r,s)=>{let i=indexedDB.open(e,t.length);i.onerror=()=>s(i.error),i.onsuccess=()=>r(i.result),i.onupgradeneeded=({oldVersion:e,newVersion:r})=>{let a=i.result;try{for(let s=e;s<(r??t.length);++s){let e=t[s];if(e)e(a);else throw Error(`Missing migration for version ${s}`)}}catch(e){a.close(),s(e)}}}),r)}#X;constructor(e,t){this.txOptions=t,this.#X=e;let r=()=>{this.#X=null,e.removeEventListener("versionchange",r),e.removeEventListener("close",r),e.close()};e.addEventListener("versionchange",r),e.addEventListener("close",r)}get db(){if(!this.#X)throw Error("Database closed");return this.#X}get name(){return this.db.name}get objectStoreNames(){return this.db.objectStoreNames}get version(){return this.db.version}async transaction(e,t,r){return new Promise(async(s,i)=>{try{let a=this.db.transaction(e,t,this.txOptions),n={done:!1};a.oncomplete=()=>{n.done?s(n.value):i(Error("Transaction completed without result"))},a.onerror=()=>i(a.error),a.onabort=()=>i(a.error||Error("Transaction aborted"));try{let e=await r(new iv(a));n={done:!0,value:e},a.commit()}catch(e){throw a.abort(),e}}catch(e){i(e)}})}close(){let{db:e}=this;this.#X=null,e.close()}async [Symbol.asyncDispose](){this.#X&&await this.close()}}function i_(e){if(!(e instanceof tp)||!e.kid)throw Error("Invalid key object");return{keyId:e.kid,keyPair:e.cryptoKeyPair}}async function ib(e){return tp.fromKeypair(e.keyPair,e.keyId)}let ik=["state","session","didCache","dpopNonceCache","handleCache","authorizationServerMetadataCache","protectedResourceMetadataCache"];class iS{#Q;#ee;constructor(e){this.#Q=iw.open(e?.name??"@atproto-oauth-client",[e=>{for(let t of ik)e.createObjectStore(t,{autoIncrement:!0}).createIndex("expiresAt","expiresAt",{unique:!1})}],{durability:e?.durability??"strict"}),this.#ee=setInterval(()=>{this.cleanup()},e?.cleanupInterval??3e4)}async run(e,t,r){let s=await this.#Q;return await s.transaction([e],t,t=>r(t.objectStore(e)))}createStore(e,{encode:t,decode:r,expiresAt:s}){return{get:async t=>{let s=await this.run(e,"readonly",e=>e.get(t));if(void 0!==s)return null!=s.expiresAt&&new Date(s.expiresAt)<new Date?void await this.run(e,"readwrite",e=>e.delete(t)):r(s.value)},set:async(r,i)=>{let a={value:await t(i),expiresAt:s(i)?.toISOString()};await this.run(e,"readwrite",e=>e.put(a,r))},del:async t=>{await this.run(e,"readwrite",e=>e.delete(t))}}}getSessionStore(){return this.createStore("session",{expiresAt:({tokenSet:e})=>e.refresh_token||null==e.expires_at?null:new Date(e.expires_at),encode:({dpopKey:e,...t})=>({...t,dpopKey:i_(e)}),decode:async({dpopKey:e,...t})=>({...t,dpopKey:await ib(e)})})}
1getStateStore(){return this.createStore("state",{expiresAt:e=>new Date(Date.now()+6e5),encode:({dpopKey:e,...t})=>({...t,dpopKey:i_(e)}),decode:async({dpopKey:e,...t})=>({...t,dpopKey:await ib(e)})})}getDpopNonceCache(){return this.createStore("dpopNonceCache",{expiresAt:e=>new Date(Date.now()+6e5),encode:e=>e,decode:e=>e})}getDidCache(){return this.createStore("didCache",{expiresAt:e=>new Date(Date.now()+6e4),encode:e=>e,decode:e=>e})}getHandleCache(){return this.createStore("handleCache",{expiresAt:e=>new Date(Date.now()+6e4),encode:e=>e,decode:e=>e})}getAuthorizationServerMetadataCache(){return this.createStore("authorizationServerMetadataCache",{expiresAt:e=>new Date(Date.now()+6e4),encode:e=>e,decode:e=>e})}getProtectedResourceMetadataCache(){return this.createStore("protectedResourceMetadataCache",{expiresAt:e=>new Date(Date.now()+6e4),encode:e=>e,decode:e=>e})}async cleanup(){let e=await this.#Q;for(let t of ik)await e.transaction([t],"readwrite",e=>e.objectStore(t).index("expiresAt").deleteAll(IDBKeyRange.upperBound(Date.now())))}async [Symbol.asyncDispose](){clearInterval(this.#ee),this.#ee=void 0;let e=this.#Q;this.#Q=Promise.reject(Error("Database has been disposed")),this.#Q.catch(()=>null);let t=await e.catch(()=>null);t&&await t[Symbol.asyncDispose]()}}let ix="undefined"!=typeof navigator&&navigator.locks?.request?(e,t)=>navigator.locks.request(e,{mode:"exclusive"},async()=>t()):void 0;class iE{constructor(){if(this.requestLock=ix,"object"!=typeof crypto||!crypto?.subtle)throw Error("Crypto with CryptoSubtle is required. If running in a browser, make sure the current page is loaded over HTTPS.");this.requestLock||console.warn("Locks API not available. You should consider using a more recent browser.")}async createKey(e){return tp.generate(e)}getRandomValues(e){return crypto.getRandomValues(new Uint8Array(e))}async digest(e,{name:t}){switch(t){case"sha256":case"sha384":case"sha512":return new Uint8Array(await crypto.subtle.digest(`SHA-${t.slice(3)}`,e));default:throw Error(`Unsupported digest algorithm: ${t}`)}}}class iA extends Error{constructor(){super("Login complete, please close the popup window."),this.code="LOGIN_CONTINUED_IN_PARENT_WINDOW"}}let ij="@@atproto/oauth-client-browser",iI=`${ij}(popup-channel)`,iT=`${ij}(popup-state):`,iR=new BroadcastChannel(`${ij}(synchronization-channel:2)`),iO=new iE;class iC extends ip{static async load({clientId:e,...t}){if(e.startsWith("http:"))return new iC({clientMetadata:r3(e),...t});if(e.startsWith("https:")){sS.parse(e);let r=await ip.fetchMetadata({clientId:e,...t});return new iC({...t,clientMetadata:r})}throw TypeError(`Invalid client id: ${e}`)}constructor({clientMetadata:e=r3(function(e,t="127.0.0.1"){if(!rY(e.hostname))throw TypeError(`Expected a loopback host, got ${e.hostname}`);let r=`http://${"localhost"===e.hostname?t:e.hostname}${e.port&&!e.port.startsWith(":")?`:${e.port}`:e.port}${e.pathname}`;return`http://localhost${"/"===e.pathname?"":e.pathname}?redirect_uri=${encodeURIComponent(r)}`}(window.location)),responseMode:t="fragment",...r}){if(!globalThis.crypto?.subtle)throw Error("WebCrypto API is required");if(!["query","fragment"].includes(t))throw TypeError(`Invalid response mode: ${t}`);let s=new iS;super({...r,clientMetadata:e,responseMode:t,keyset:void 0,runtimeImplementation:iO,sessionStore:s.getSessionStore(),stateStore:s.getStateStore(),didCache:s.getDidCache(),handleCache:s.getHandleCache(),dpopNonceCache:s.getDpopNonceCache(),authorizationServerMetadataCache:s.getAuthorizationServerMetadataCache(),protectedResourceMetadataCache:s.getProtectedResourceMetadataCache(),onSessionDeleted:async(e,t)=>(localStorage.getItem(`${ij}(sub)`)===e&&localStorage.removeItem(`${ij}(sub)`),iR.postMessage({name:"onSessionDeleted",args:[e,t]}),r.onSessionDeleted?.call(null,e,t)),onSessionUpdated:async(e,t)=>(iR.postMessage({name:"onSessionUpdated",args:[e,t]}),r.onSessionUpdated?.call(null,e,t))}),this.ac=new AbortController,this.database=s;let{signal:i}=this.ac;iR.addEventListener("message",e=>{if(e.source===window)return;let{name:t,args:s}=e.data,i=r[t];i?.(...s)},{signal:i})}async init(e){let t=this.readCallbackParams();if(t){let e=this.findRedirectUrl();if(e)return this.initCallback(t,e)}return this.initRestore(e)}async initRestore(e){await function(e){if(!r6(e.client_id).success||"localhost"!==window.location.hostname)return;let t=new URL(window.location.href);for(let r of e.redirect_uris){let e=new URL(r);if(("127.0.0.1"===e.hostname||"[::1]"===e.hostname)&&(!e.port||e.port===t.port)&&e.protocol===t.protocol&&e.pathname===t.pathname)throw e.port=t.port,window.location.href=e.href,Error("Redirecting to loopback IP...")}throw Error(`Please use the loopback IP address instead of ${t}`)}(this.clientMetadata);let t=localStorage.getItem(`${ij}(sub)`);if(t)try{return{session:await this.restore(t,e)}}catch(e){throw localStorage.removeItem(`${ij}(sub)`),e}}async restore(e,t){let r=await super.restore(e,t);return localStorage.setItem(`${ij}(sub)`,r.sub),r}async revoke(e){return localStorage.removeItem(`${ij}(sub)`),super.revoke(e)}async signIn(e,t){return t?.display==="popup"?this.signInPopup(e,t):this.signInRedirect(e,t)}async signInRedirect(e,t){let r=await this.authorize(e,t);return window.location.href=r.href,new Promise((e,t)=>
1{setTimeout(e=>{this.abortRequest(r).then(()=>t(e),r=>t(AggregateError([e,r])))},5e3,Error("User navigated back"))})}async signInPopup(e,t){let r=t?.popupName??"_blank",s=t?.popupFeatures??"width=600,height=600,menubar=no,toolbar=no",i=window.open("about:blank",r,s),a=`${Math.random().toString(36).slice(2)}`,n=await this.authorize(e,{...t,state:`${iT}${a}`,display:t?.display??"popup"});return t?.signal?.throwIfAborted(),i?i.window.location.href=n.href:i=window.open(n.href,r,s),i?.focus(),new Promise((e,r)=>{let s=new BroadcastChannel(iI),n=()=>{clearTimeout(l),s.removeEventListener("message",c),s.close(),t?.signal?.removeEventListener("abort",o),i?.close()},o=()=>{r(Error(t?.signal?.aborted?"Aborted":"Timeout")),n()};t?.signal?.addEventListener("abort",o);let l=setTimeout(o,3e5),c=async({data:i})=>{if(i.key!==a||!("result"in i))return;s.postMessage({key:a,ack:!0}),n();let{result:o}=i;if("fulfilled"===o.status){let s=o.value;try{t?.signal?.throwIfAborted(),e(await this.restore(s,!1))}catch(e){r(e),this.revoke(s)}}else{let{message:e,params:t}=o.reason;r(new sq(new URLSearchParams(t),e))}};s.addEventListener("message",c)})}findRedirectUrl(){for(let e of this.clientMetadata.redirect_uris){let t=new URL(e);if(location.origin===t.origin&&location.pathname===t.pathname)return e}}readCallbackParams(){let e=new URLSearchParams("fragment"===this.responseMode?location.hash.slice(1):location.search);return e.has("state")&&(e.has("code")||e.has("error"))?e:null}async initCallback(e=this.readCallbackParams(),t=this.findRedirectUrl()){if(!e)throw TypeError("No OAuth callback parameters found in the URL");"fragment"===this.responseMode?history.replaceState(null,"",location.pathname+location.search):"query"===this.responseMode&&history.replaceState(null,"",location.pathname);let r=e=>{let t=new BroadcastChannel(iI);return new Promise(r=>{let s=e=>{clearTimeout(a),t.removeEventListener("message",i),t.close(),r(e)},i=({data:t})=>{"ack"in t&&e.key===t.key&&s(!0)};t.addEventListener("message",i),t.postMessage(e);let a=setTimeout(s,500,!1)})};return this.callback(e,{redirect_uri:t}).then(async e=>{if(e.state?.startsWith(iT))throw await r({key:e.state.slice(iT.length),result:{status:"fulfilled",value:e.session.sub}})||await e.session.signOut(),new iA;return localStorage.setItem(`${ij}(sub)`,e.session.sub),e}).catch(async e=>{if(e instanceof sq&&e.state?.startsWith(iT))throw await r({key:e.state.slice(iT.length),result:{status:"rejected",reason:{message:e.message,params:Array.from(e.params.entries())}}}),new iA;throw e}).catch(e=>{throw e instanceof iA&&window.close(),e})}async [Symbol.asyncDispose](){try{this.ac.abort()}finally{await this.database[Symbol.asyncDispose]()}}async dispose(){await this[Symbol.asyncDispose]()}}},26396:(e,t,r)=>{var s=r(31989),i=Object.defineProperty;e.exports=function(e,t){try{i(s,e,{value:t,configurable:!0,writable:!0})}catch(r){s[e]=t}return t}},27612:(e,t,r)=>{var s=r(92412),i=r(96696);e.exports=function(e){var t=s(e,"string");return i(t)?t:t+""}},28891:(e,t,r)=>{var s=r(488),i=TypeError;e.exports=function(e){if(s(e))throw new i("Can't call method on "+e);return e}},30842:(e,t,r)=>{var s=r(31989),i=r(33608);e.exports=function(e,t){var r;return arguments.length<2?i(r=s[e])?r:void 0:s[e]&&s[e][t]}},30852:(e,t,r)=>{var s=r(20161),i=r(45120),a=r(53859),n=r(48074),o=r(27612),l=TypeError,c=Object.defineProperty,d=Object.getOwnPropertyDescriptor,u="enumerable",h="configurable",p="writable";t.f=s?a?function(e,t,r){if(n(e),t=o(t),n(r),"function"==typeof e&&"prototype"===t&&"value"in r&&p in r&&!r[p]){var s=d(e,t);s&&s[p]&&(e[t]=r.value,r={configurable:h in r?r[h]:s[h],enumerable:u in r?r[u]:s[u],writable:!1})}return c(e,t,r)}:c:function(e,t,r){if(n(e),t=o(t),n(r),i)try{return c(e,t,r)}catch(e){}if("get"in r||"set"in r)throw new l("Accessors not supported");return"value"in r&&(e[t]=r.value),e}},31877:(e,t,r)=>{var s=r(80997),i=0,a=Math.random(),n=s(1.1.toString);e.exports=function(e){return"Symbol("+(void 0===e?"":e)+")_"+n(++i+a,36)}},31989:function(e,t,r){var s=function(e){return e&&e.Math===Math&&e};e.exports=s("object"==typeof globalThis&&globalThis)||s("object"==typeof window&&window)||s("object"==typeof self&&self)||s("object"==typeof r.g&&r.g)||s("object"==typeof this&&this)||function(){return this}()||Function("return this")()},32725:(e,t,r)=>{e.exports=r(58738)&&!Symbol.sham&&"symbol"==typeof Symbol.iterator},33608:e=>{var t="object"==typeof document&&document.all;e.exports=void 0===t&&void 0!==t?function(e){return"function"==typeof e||e===t}:function(e){return"function"==typeof e}},40867:(e,t,r)=>{var s=r(92912),i=r(33608),a=r(92855),n=TypeError;e.exports=function(e,t){var r,o;
1if("string"===t&&i(r=e.toString)&&!a(o=s(r,e))||i(r=e.valueOf)&&!a(o=s(r,e))||"string"!==t&&i(r=e.toString)&&!a(o=s(r,e)))return o;throw new n("Can't convert object to primitive value")}},42996:(e,t,r)=>{var s=r(80997),i=r(22856),a=s({}.hasOwnProperty);e.exports=Object.hasOwn||function(e,t){return a(i(e),t)}},44193:(e,t,r)=>{r.d(t,{G:()=>a,eq:()=>i});var s=r(88658);let i=s.ZS.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class a extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(e){return e.message},r={_errors:[]},s=e=>{for(let i of e.issues)if("invalid_union"===i.code)i.unionErrors.map(s);else if("invalid_return_type"===i.code)s(i.returnTypeError);else if("invalid_arguments"===i.code)s(i.argumentsError);else if(0===i.path.length)r._errors.push(t(i));else{let e=r,s=0;for(;s<i.path.length;){let r=i.path[s];s===i.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(i))):e[r]=e[r]||{_errors:[]},e=e[r],s++}}};return s(this),r}static assert(e){if(!(e instanceof a))throw Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,s.ZS.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){let t={},r=[];for(let s of this.issues)if(s.path.length>0){let r=s.path[0];t[r]=t[r]||[],t[r].push(e(s))}else r.push(e(s));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}a.create=e=>new a(e)},45120:(e,t,r)=>{var s=r(20161),i=r(1154),a=r(20666);e.exports=!s&&!i(function(){return 7!==Object.defineProperty(a("div"),"a",{get:function(){return 7}}).a})},48074:(e,t,r)=>{var s=r(92855),i=String,a=TypeError;e.exports=function(e){if(s(e))return e;throw new a(i(e)+" is not an object")}},51422:e=>{e.exports=!1},52134:(e,t,r)=>{var s=r(31989),i=r(53988),a=r(42996),n=r(31877),o=r(58738),l=r(32725),c=s.Symbol,d=i("wks"),u=l?c.for||c:c&&c.withoutSetter||n;e.exports=function(e){return a(d,e)||(d[e]=o&&a(c,e)?c[e]:u("Symbol."+e)),d[e]}},53569:(e,t,r)=>{var s=r(31989),i=r(84498),a=r(30852).f,n=r(86198).f,o=s.Symbol;if(i("dispose"),o){var l=n(o,"dispose");l.enumerable&&l.configurable&&l.writable&&a(o,"dispose",{value:l.value,enumerable:!1,configurable:!1,writable:!1})}},53859:(e,t,r)=>{var s=r(20161),i=r(1154);e.exports=s&&i(function(){return 42!==Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype})},53988:(e,t,r)=>{var s=r(63792),i=Object.create||Object;e.exports=function(e,t){return s[e]||(s[e]=t||i(null))}},58738:(e,t,r)=>{var s=r(62402),i=r(1154),a=r(31989).String;e.exports=!!Object.getOwnPropertySymbols&&!i(function(){var e=Symbol("symbol detection");return!a(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&s&&s<41})},58777:e=>{e.exports=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}}},60616:(e,t,r)=>{var s=r(89810),i=r(28891);e.exports=function(e){return s(i(e))}},61693:(e,t,r)=>{e.exports=!r(1154)(function(){var e=(function(){}).bind();return"function"!=typeof e||e.hasOwnProperty("prototype")})},62402:(e,t,r)=>{var s,i,a=r(31989),n=r(82682),o=a.process,l=a.Deno,c=o&&o.versions||l&&l.version,d=c&&c.v8;d&&(i=(s=d.split("."))[0]>0&&s[0]<4?1:+(s[0]+s[1])),!i&&n&&(!(s=n.match(/Edge\/(\d+)/))||s[1]>=74)&&(s=n.match(/Chrome\/(\d+)/))&&(i=+s[1]),e.exports=i},63792:(e,t,r)=>{var s=r(51422),i=r(31989),a=r(26396),n="__core-js_shared__",o=e.exports=i[n]||a(n,{});(o.versions||(o.versions=[])).push({version:"3.50.0",mode:s?"pure":"global",copyright:"\xa9 2013–2025 Denis Pushkarev (zloirock.ru), 2025–2026 CoreJS Company (core-js.io). All rights reserved.",license:"https://github.com/zloirock/core-js/blob/v3.50.0/LICENSE",source:"https://github.com/zloirock/core-js"})},70663:(e,t,r)=>{function s(e,t){if(e===t)return!0;
1if(e.byteLength!==t.byteLength)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0}function i(e){if(e instanceof Uint8Array&&"Uint8Array"===e.constructor.name)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw Error("Unknown type, must be binary type")}r.d(t,{aI:()=>s,au:()=>i}),new Uint8Array(0)},71028:(e,t,r)=>{var s=r(31989),i=r(84498),a=r(30852).f,n=r(86198).f,o=s.Symbol;if(i("asyncDispose"),o){var l=n(o,"asyncDispose");l.enumerable&&l.configurable&&l.writable&&a(o,"asyncDispose",{value:l.value,enumerable:!1,configurable:!1,writable:!1})}},72194:(e,t,r)=>{t.f=r(52134)},80997:(e,t,r)=>{var s=r(61693),i=Function.prototype,a=i.call,n=s&&i.bind.bind(a,a);e.exports=s?n:function(e){return function(){return a.apply(e,arguments)}}},82682:(e,t,r)=>{var s=r(31989).navigator,i=s&&s.userAgent;e.exports=i?String(i):""},84130:(e,t,r)=>{e.exports=r(31989)},84498:(e,t,r)=>{var s=r(84130),i=r(42996),a=r(72194),n=r(30852).f;e.exports=function(e){var t=s.Symbol||(s.Symbol={});i(t,e)||n(t,e,{value:a.f(e)})}},85828:(e,t,r)=>{r.d(t,{GY:()=>o,K3:()=>i,r0:()=>n,x$:()=>a});var s=r(14766);let i=(0,s.yE)({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),a=(0,s.yE)({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),n=(0,s.yE)({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),o=(0,s.yE)({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6})},86198:(e,t,r)=>{var s=r(20161),i=r(92912),a=r(8632),n=r(58777),o=r(60616),l=r(27612),c=r(42996),d=r(45120),u=Object.getOwnPropertyDescriptor;t.f=s?u:function(e,t){if(e=o(e),t=l(t),d)try{return u(e,t)}catch(e){}if(c(e,t))return n(!i(a.f,e,t),e[t])}},88658:(e,t,r)=>{var s,i;r.d(t,{CR:()=>n,ZS:()=>s,Zp:()=>a}),function(e){e.assertEqual=e=>{},e.assertIs=function(e){},e.assertNever=function(e){throw Error()},e.arrayToEnum=e=>{let t={};for(let r of e)t[r]=r;return t},e.getValidEnumValues=t=>{let r=e.objectKeys(t).filter(e=>"number"!=typeof t[t[e]]),s={};for(let e of r)s[e]=t[e];return e.objectValues(s)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{let t=[];for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},e.find=(e,t)=>{for(let r of e)if(t(r))return r},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(s||(s={})),(i||(i={})).mergeShapes=(e,t)=>({...e,...t});let a=s.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),n=e=>{switch(typeof e){case"undefined":return a.undefined;case"string":return a.string;case"number":return Number.isNaN(e)?a.nan:a.number;case"boolean":return a.boolean;case"function":return a.function;case"bigint":return a.bigint;case"symbol":return a.symbol;case"object":if(Array.isArray(e))return a.array;if(null===e)return a.null;if(e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch)return a.promise;if("undefined"!=typeof Map&&e instanceof Map)return a.map;if("undefined"!=typeof Set&&e instanceof Set)return a.set;if("undefined"!=typeof Date&&e instanceof Date)return a.date;return a.object;default:return a.unknown}}},89810:(e,t,r)=>{var s=r(80997),i=r(1154),a=r(20885),n=Object,o=s("".split);e.exports=i(function(){return!n("z").propertyIsEnumerable(0)})?function(e){return"String"===a(e)?o(e,""):n(e)}:n},92152:(e,t,r)=>{r(71028),e.exports=r(72194).f("asyncDispose")},92412:(e,t,r)=>{var s=r(92912),i=r(92855),a=r(96696),n=r(11827),o=r(40867),l=r(52134),c=TypeError,d=l("toPrimitive");e.exports=function(e,t){if(!i(e)||a(e))return e;var r,l=n(e,d);if(l){if(void 0===t&&(t="default"),!i(r=s(l,e,t))||a(r))return r;throw new c("Can't convert object to primitive value")}return void 0===t&&(t="number"),o(e,t)}},92855:(e,t,r)=>{var s=r(33608);e.exports=function(e){return"object"==typeof e?null!==e:s(e)}},92912:(e,t,r)=>{var s=r(61693),i=Function.prototype.call;e.exports=s?i.bind(i):function(){return i.apply(i,arguments)}},94156:(e,t,r)=>{var s=r(33608),i=r(16730),a=TypeError;e.exports=function(e){if(s(e))return e;throw new a(i(e)+" is not a function")}},96696:(e,t,r)=>{var s=r(30842),i=r(33608),a=r(98220),n=r(32725),o=Object;e.exports=n?function(e){return"symbol"==typeof e}:function(e){var t=s("Symbol");return i(t)&&a(t.prototype,o(e))}},98220:(e,t,r)=>{e.exports=r(80997)({}.isPrototypeOf)},98734:(e,t,r)=>{let s;r.d(t,{tm:()=>ez,YO:()=>eI,zM:()=>eE,gM:()=>eO,k5:()=>e$,Nl:()=>ek,E$:()=>eC,eu:()=>eD,Zm:()=>ej,ai:()=>ex,Ik:()=>eT,vk:()=>eL,g1:()=>eP,Yj:()=>eS,KC:()=>eR,L5:()=>eA});var i,a,n=r(44193),o=r(88658);let l=(e,t)=>
1{let r;switch(e.code){case n.eq.invalid_type:r=e.received===o.Zp.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case n.eq.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,o.ZS.jsonStringifyReplacer)}`;break;case n.eq.unrecognized_keys:r=`Unrecognized key(s) in object: ${o.ZS.joinValues(e.keys,", ")}`;break;case n.eq.invalid_union:r="Invalid input";break;case n.eq.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${o.ZS.joinValues(e.options)}`;break;case n.eq.invalid_enum_value:r=`Invalid enum value. Expected ${o.ZS.joinValues(e.options)}, received '${e.received}'`;break;case n.eq.invalid_arguments:r="Invalid function arguments";break;case n.eq.invalid_return_type:r="Invalid function return type";break;case n.eq.invalid_date:r="Invalid date";break;case n.eq.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:o.ZS.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case n.eq.too_small:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type||"bigint"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case n.eq.too_big:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case n.eq.custom:r="Invalid input";break;case n.eq.invalid_intersection_types:r="Intersection results could not be merged";break;case n.eq.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case n.eq.not_finite:r="Number must be finite";break;default:r=t.defaultError,o.ZS.assertNever(e)}return{message:r}};!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:e?.message}(i||(i={}));let c=e=>{let{data:t,path:r,errorMaps:s,issueData:i}=e,a=[...r,...i.path||[]],n={...i,path:a};if(void 0!==i.message)return{...i,path:a,message:i.message};let o="";for(let e of s.filter(e=>!!e).slice().reverse())o=e(n,{data:t,defaultError:o}).message;return{...i,path:a,message:o}};function d(e,t){let r=c({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,l,void 0].filter(e=>!!e)});e.common.issues.push(r)}class u{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){let r=[];for(let s of t){if("aborted"===s.status)return h;"dirty"===s.status&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){let r=[];for(let e of t){let t=await e.key,s=await e.value;r.push({key:t,value:s})}return u.mergeObjectSync(e,r)}static mergeObjectSync(e,t){let r={};for(let s of t){let{key:t,value:i}=s;if("aborted"===t.status||"aborted"===i.status)return h;"dirty"===t.status&&e.dirty(),"dirty"===i.status&&e.dirty(),"__proto__"!==t.value&&(void 0!==i.value||s.alwaysSet)&&(r[t.value]=i.value)}return{status:e.value,value:r}}}let h=Object.freeze({status:"aborted"}),p=e=>({status:"dirty",value:e}),f=e=>
vendor: 5,499 bytes, line 1
1({status:"valid",value:e}),m=e=>"undefined"!=typeof Promise&&e instanceof Promise;class y{constructor(e,t,r,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}let g=(e,t)=>{if("valid"===t.status)return{success:!0,data:t.value};if(!e.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new n.G(e.common.issues);return this._error=t,this._error}}};function v(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:s,description:i}=e;if(t&&(r||s))throw Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');return t?{errorMap:t,description:i}:{errorMap:(t,i)=>{let{message:a}=e;return"invalid_enum_value"===t.code?{message:a??i.defaultError}:void 0===i.data?{message:a??s??i.defaultError}:"invalid_type"!==t.code?{message:i.defaultError}:{message:a??r??i.defaultError}},description:i}}class w{get description(){return this._def.description}_getType(e){return(0,o.CR)(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:(0,o.CR)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new u,ctx:{common:e.parent.common,data:e.data,parsedType:(0,o.CR)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(m(t))throw Error("Synchronous parse encountered promise.");return t}_parseAsync(e){return Promise.resolve(this._parse(e))}parse(e,t){let r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){let r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,o.CR)(e)},s=this._parseSync({data:e,path:r.path,parent:r});return g(r,s)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,o.CR)(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:t});return"valid"===r.status?{value:r.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>"valid"===e.status?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){let r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,o.CR)(e)},s=this._parse({data:e,path:r.path,parent:r});return g(r,await (m(s)?s:Promise.resolve(s)))}refine(e,t){return this._refinement((r,s)=>{let i=e(r),a=()=>s.addIssue({code:n.eq.custom,..."string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(r):t});return"undefined"!=typeof Promise&&i instanceof Promise?i.then(e=>!!e||(a(),!1)):!!i||(a(),!1)})}refinement(e,t){return this._refinement((r,s)=>!!e(r)||(s.addIssue("function"==typeof t?t(r,s):t),!1))}_refinement(e){return new eh({schema:this,typeName:a.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return ep.create(this,this._def)}nullable(){return ef.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return B.create(this)}promise(){return eu.create(this,this._def)}or(e){return G.create([this,e],this._def)}and(e){return ee.create(this,e,this._def)}transform(e){return new eh({...v(this._def),schema:this,typeName:a.ZodEffects,effect:{type:"transform",transform:e}})}default(e){return new em({...v(this._def),innerType:this,defaultValue:"function"==typeof e?e:()=>e,typeName:a.ZodDefault})}brand(){return new ev({typeName:a.ZodBranded,type:this,...v(this._def)})}catch(e){return new ey({...v(this._def),innerType:this,catchValue:"function"==typeof e?e:()=>e,typeName:a.ZodCatch})}describe(e){return new this.constructor({...this._def,description:e})}pipe(e){return ew.create(this,e)}readonly(){return e_.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}let _=/^c[^\s-]{8,}
1$/i,b=/^[0-9a-z]+$/,k=/^[0-9A-HJKMNP-TV-Z]{26}$/i,S=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,x=/^[a-z0-9_-]{21}$/i,E=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,A=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,j=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,I=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,T=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,R=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,O=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,C=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,P=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,D="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",$=RegExp(`^${D}$`);function L(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`);let r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}class z extends w{_parse(e){var t,r,i,a;let l;if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==o.Zp.string){let t=this._getOrReturnCtx(e);return d(t,{code:n.eq.invalid_type,expected:o.Zp.string,received:t.parsedType}),h}let c=new u;for(let u of this._def.checks)if("min"===u.kind)e.data.length<u.value&&(d(l=this._getOrReturnCtx(e,l),{code:n.eq.too_small,minimum:u.value,type:"string",inclusive:!0,exact:!1,message:u.message}),c.dirty());else if("max"===u.kind)e.data.length>u.value&&(d(l=this._getOrReturnCtx(e,l),{code:n.eq.too_big,maximum:u.value,type:"string",inclusive:!0,exact:!1,message:u.message}),c.dirty());else if("length"===u.kind){let t=e.data.length>u.value,r=e.data.length<u.value;(t||r)&&(l=this._getOrReturnCtx(e,l),t?d(l,{code:n.eq.too_big,maximum:u.value,type:"string",inclusive:!0,exact:!0,message:u.message}):r&&d(l,{code:n.eq.too_small,minimum:u.value,type:"string",inclusive:!0,exact:!0,message:u.message}),c.dirty())}else if("email"===u.kind)j.test(e.data)||(d(l=this._getOrReturnCtx(e,l),{validation:"email",code:n.eq.invalid_string,message:u.message}),c.dirty());else if("emoji"===u.kind)s||(s=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),s.test(e.data)||(d(l=this._getOrReturnCtx(e,l),{validation:"emoji",code:n.eq.invalid_string,message:u.message}),c.dirty());else if("uuid"===u.kind)S.test(e.data)||(d(l=this._getOrReturnCtx(e,l),{validation:"uuid",code:n.eq.invali
vendor: 11,721 bytes, line 1
1d_string,message:u.message}),c.dirty());else if("nanoid"===u.kind)x.test(e.data)||(d(l=this._getOrReturnCtx(e,l),{validation:"nanoid",code:n.eq.invalid_string,message:u.message}),c.dirty());else if("cuid"===u.kind)_.test(e.data)||(d(l=this._getOrReturnCtx(e,l),{validation:"cuid",code:n.eq.invalid_string,message:u.message}),c.dirty());else if("cuid2"===u.kind)b.test(e.data)||(d(l=this._getOrReturnCtx(e,l),{validation:"cuid2",code:n.eq.invalid_string,message:u.message}),c.dirty());else if("ulid"===u.kind)k.test(e.data)||(d(l=this._getOrReturnCtx(e,l),{validation:"ulid",code:n.eq.invalid_string,message:u.message}),c.dirty());else if("url"===u.kind)try{new URL(e.data)}catch{d(l=this._getOrReturnCtx(e,l),{validation:"url",code:n.eq.invalid_string,message:u.message}),c.dirty()}else"regex"===u.kind?(u.regex.lastIndex=0,u.regex.test(e.data)||(d(l=this._getOrReturnCtx(e,l),{validation:"regex",code:n.eq.invalid_string,message:u.message}),c.dirty())):"trim"===u.kind?e.data=e.data.trim():"includes"===u.kind?e.data.includes(u.value,u.position)||(d(l=this._getOrReturnCtx(e,l),{code:n.eq.invalid_string,validation:{includes:u.value,position:u.position},message:u.message}),c.dirty()):"toLowerCase"===u.kind?e.data=e.data.toLowerCase():"toUpperCase"===u.kind?e.data=e.data.toUpperCase():"startsWith"===u.kind?e.data.startsWith(u.value)||(d(l=this._getOrReturnCtx(e,l),{code:n.eq.invalid_string,validation:{startsWith:u.value},message:u.message}),c.dirty()):"endsWith"===u.kind?e.data.endsWith(u.value)||(d(l=this._getOrReturnCtx(e,l),{code:n.eq.invalid_string,validation:{endsWith:u.value},message:u.message}),c.dirty()):"datetime"===u.kind?(function(e){let t=`${D}T${L(e)}`,r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,RegExp(`^${t}$`)})(u).test(e.data)||(d(l=this._getOrReturnCtx(e,l),{code:n.eq.invalid_string,validation:"datetime",message:u.message}),c.dirty()):"date"===u.kind?$.test(e.data)||(d(l=this._getOrReturnCtx(e,l),{code:n.eq.invalid_string,validation:"date",message:u.message}),c.dirty()):"time"===u.kind?RegExp(`^${L(u)}$`).test(e.data)||(d(l=this._getOrReturnCtx(e,l),{code:n.eq.invalid_string,validation:"time",message:u.message}),c.dirty()):"duration"===u.kind?A.test(e.data)||(d(l=this._getOrReturnCtx(e,l),{validation:"duration",code:n.eq.invalid_string,message:u.message}),c.dirty()):"ip"===u.kind?(t=e.data,!(("v4"===(r=u.version)||!r)&&I.test(t)||("v6"===r||!r)&&R.test(t))&&1&&(d(l=this._getOrReturnCtx(e,l),{validation:"ip",code:n.eq.invalid_string,message:u.message}),c.dirty())):"jwt"===u.kind?!function(e,t){if(!E.test(e))return!1;try{let[r]=e.split(".");if(!r)return!1;let s=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(s));if("object"!=typeof i||null===i||"typ"in i&&i?.typ!=="JWT"||!i.alg||t&&i.alg!==t)return!1;return!0}catch{return!1}}(e.data,u.alg)&&(d(l=this._getOrReturnCtx(e,l),{validation:"jwt",code:n.eq.invalid_string,message:u.message}),c.dirty()):"cidr"===u.kind?(i=e.data,!(("v4"===(a=u.version)||!a)&&T.test(i)||("v6"===a||!a)&&O.test(i))&&1&&(d(l=this._getOrReturnCtx(e,l),{validation:"cidr",code:n.eq.invalid_string,message:u.message}),c.dirty())):"base64"===u.kind?C.test(e.data)||(d(l=this._getOrReturnCtx(e,l),{validation:"base64",code:n.eq.invalid_string,message:u.message}),c.dirty()):"base64url"===u.kind?P.test(e.data)||(d(l=this._getOrReturnCtx(e,l),{validation:"base64url",code:n.eq.invalid_string,message:u.message}),c.dirty()):o.ZS.assertNever(u);return{status:c.value,value:e.data}}_regex(e,t,r){return this.refinement(t=>e.test(t),{validation:t,code:n.eq.invalid_string,...i.errToObj(r)})}_addCheck(e){return new z({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...i.errToObj(e)})}url(e){return this._addCheck({kind:"url",...i.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...i.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...i.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...i.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...i.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...i.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...i.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...i.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...i.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...i.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...i.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...i.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...i.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,...i.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...i.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...i.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...i.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...i.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...i.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...i.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...i.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...i.errToObj(t)})}nonempty(e){return this.min(1,i.errToObj(e))}trim(){return new z({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new z({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new z({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this._def.checks.find(e=>"date"===e.kind)}get isTime(){return!!this._def.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this._def.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isNANOID(){return!!this._def.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this._def.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this._def.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this._def.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}z.create=e=>new z({checks:[],typeName:a.ZodString,coerce:e?.coerce??!1,...v(e)});class K extends w{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){let t;if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==o.Zp.number){let t=this._getOrReturnCtx(e);return d(t,{code:n.eq.invalid_type,expected:o.Zp.number,received:t.parsedType}),h}let r=new u;for(let s of this._def.checks)"int"===s.kind?o.ZS.isInteger(e.data)||(d(t=this._getOrReturnCtx(e,t),{code:n.eq.invalid_type,expected:"integer",received:"float",message:s.message}),r.dirty()):"min"===s.kind?(s.inclusive?e.data<s.value:e.data<=s.value)&&(d(t=this._getOrReturnCtx(e,t),{code:n.eq.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),r.dirty()):"max"===s.kind?(s.inclusive?e.data>s.value:e.data>=s.value)&&(d(t=this._getOrReturnCtx(e,t),{code:n.eq.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),r.dirty()):"multipleOf"===s.kind?0!==function(e,t){let r=(e.toString().split(".")[1]||"").length,s=(t.toString().split(".")[1]||"").length,i=r>s?r:s;return Number.parseInt(e.toFixed(i).replace(".",""))%Number.parseInt(t.toFixed(i).replace(".",""))/10**i}(e.data,s.value)&&(d(t=this._getOrReturnCtx(e,t),{code:n.eq.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):"finite"===s.kind?Number.isFinite(e.data)||(d(t=this._getOrReturnCtx(e,t),{code:n.eq.not_finite,message:s.message}),r.dirty()):o.ZS.assertNever(s);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,i.toString(t))}gt(e,t){return this.setLimit("min",e,!1,i.toString(t))}lte(e,t){return this.setLimit("max",e,!0,i.toString(t))}lt(e,t){return this.setLimit("max",e,!1,i.toString(t))}setLimit(e,t,r,s){return new K({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:i.toString(s)}]})}_addCheck(e){return new K({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:i.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:i.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:i.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:i.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:i.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:i.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:i.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:i.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:i.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>"int"===e.kind||"multipleOf"===e.kind&&o.ZS.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let r of this._def.checks)if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;else"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.value<e)&&(e=r.value);return Number.isFinite(t)&&Number.isFinite(e)}}K.create=e=>new K({checks:[],typeName:a.ZodNumber,coerce:e?.coerce||!1,...v(e)});class q extends w{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){let t;if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==o.Zp.bigint)return this._getInvalidInput(e);let r=new u;for(let s of this._def.checks)"min"===s.kind?(s.inclusive?e.data<s.value:e.data<=s.value)&&(d(t=this._getOrReturnCtx(e,t),{code:n.eq.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),r.dirty()):"max"===s.kind?(s.inclusive?e.data>s.value:e.data>=s.value)&&(d(t=this._getOrReturnCtx(e,t),{code:n.eq.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),r.dirty()):"multipleOf"===s.kind?e.data%s.value!==BigInt(0)&&(d(t=this._getOrReturnCtx(e,t),{code:n.eq.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()):o.ZS.assertNever(s);return{status:r.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);
1return d(t,{code:n.eq.invalid_type,expected:o.Zp.bigint,received:t.parsedType}),h}gte(e,t){return this.setLimit("min",e,!0,i.toString(t))}gt(e,t){return this.setLimit("min",e,!1,i.toString(t))}lte(e,t){return this.setLimit("max",e,!0,i.toString(t))}lt(e,t){return this.setLimit("max",e,!1,i.toString(t))}setLimit(e,t,r,s){return new q({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:i.toString(s)}]})}_addCheck(e){return new q({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:i.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:i.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:i.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:i.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:i.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}q.create=e=>new q({checks:[],typeName:a.ZodBigInt,coerce:e?.coerce??!1,...v(e)});class M extends w{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==o.Zp.boolean){let t=this._getOrReturnCtx(e);return d(t,{code:n.eq.invalid_type,expected:o.Zp.boolean,received:t.parsedType}),h}return f(e.data)}}M.create=e=>new M({typeName:a.ZodBoolean,coerce:e?.coerce||!1,...v(e)});class Y extends w{_parse(e){let t;if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==o.Zp.date){let t=this._getOrReturnCtx(e);return d(t,{code:n.eq.invalid_type,expected:o.Zp.date,received:t.parsedType}),h}if(Number.isNaN(e.data.getTime()))return d(this._getOrReturnCtx(e),{code:n.eq.invalid_date}),h;let r=new u;for(let s of this._def.checks)"min"===s.kind?e.data.getTime()<s.value&&(d(t=this._getOrReturnCtx(e,t),{code:n.eq.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):"max"===s.kind?e.data.getTime()>s.value&&(d(t=this._getOrReturnCtx(e,t),{code:n.eq.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):o.ZS.assertNever(s);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Y({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:i.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:i.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}Y.create=e=>new Y({checks:[],coerce:e?.coerce||!1,typeName:a.ZodDate,...v(e)});class N extends w{_parse(e){if(this._getType(e)!==o.Zp.symbol){let t=this._getOrReturnCtx(e);return d(t,{code:n.eq.invalid_type,expected:o.Zp.symbol,received:t.parsedType}),h}return f(e.data)}}N.create=e=>new N({typeName:a.ZodSymbol,...v(e)});class W extends w{_parse(e){if(this._getType(e)!==o.Zp.undefined){let t=this._getOrReturnCtx(e);return d(t,{code:n.eq.invalid_type,expected:o.Zp.undefined,received:t.parsedType}),h}return f(e.data)}}W.create=e=>new W({typeName:a.ZodUndefined,...v(e)});class Z extends w{_parse(e){if(this._getType(e)!==o.Zp.null){let t=this._getOrReturnCtx(e);return d(t,{code:n.eq.invalid_type,expected:o.Zp.null,received:t.parsedType}),h}return f(e.data)}}Z.create=e=>new Z({typeName:a.ZodNull,...v(e)});class U extends w{constructor(){super(...arguments),this._any=!0}_parse(e){return f(e.data)}}U.create=e=>new U({typeName:a.ZodAny,...v(e)});class F extends w{constructor(){super(...arguments),this._unknown=!0}_parse(e){return f(e.data)}}F.create=e=>new F({typeName:a.ZodUnknown,...v(e)});class H extends w{_parse(e){let t=this._getOrReturnCtx(e);
vendor: 5,217 bytes, line 1
1return d(t,{code:n.eq.invalid_type,expected:o.Zp.never,received:t.parsedType}),h}}H.create=e=>new H({typeName:a.ZodNever,...v(e)});class J extends w{_parse(e){if(this._getType(e)!==o.Zp.undefined){let t=this._getOrReturnCtx(e);return d(t,{code:n.eq.invalid_type,expected:o.Zp.void,received:t.parsedType}),h}return f(e.data)}}J.create=e=>new J({typeName:a.ZodVoid,...v(e)});class B extends w{_parse(e){let{ctx:t,status:r}=this._processInputParams(e),s=this._def;if(t.parsedType!==o.Zp.array)return d(t,{code:n.eq.invalid_type,expected:o.Zp.array,received:t.parsedType}),h;if(null!==s.exactLength){let e=t.data.length>s.exactLength.value,i=t.data.length<s.exactLength.value;(e||i)&&(d(t,{code:e?n.eq.too_big:n.eq.too_small,minimum:i?s.exactLength.value:void 0,maximum:e?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(null!==s.minLength&&t.data.length<s.minLength.value&&(d(t,{code:n.eq.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),null!==s.maxLength&&t.data.length>s.maxLength.value&&(d(t,{code:n.eq.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((e,r)=>s.type._parseAsync(new y(t,e,t.path,r)))).then(e=>u.mergeArray(r,e));let i=[...t.data].map((e,r)=>s.type._parseSync(new y(t,e,t.path,r)));return u.mergeArray(r,i)}get element(){return this._def.type}min(e,t){return new B({...this._def,minLength:{value:e,message:i.toString(t)}})}max(e,t){return new B({...this._def,maxLength:{value:e,message:i.toString(t)}})}length(e,t){return new B({...this._def,exactLength:{value:e,message:i.toString(t)}})}nonempty(e){return this.min(1,e)}}B.create=(e,t)=>new B({type:e,minLength:null,maxLength:null,exactLength:null,typeName:a.ZodArray,...v(t)});class V extends w{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;let e=this._def.shape(),t=o.ZS.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==o.Zp.object){let t=this._getOrReturnCtx(e);return d(t,{code:n.eq.invalid_type,expected:o.Zp.object,received:t.parsedType}),h}let{status:t,ctx:r}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof H&&"strip"===this._def.unknownKeys))for(let e in r.data)i.includes(e)||a.push(e);let l=[];for(let e of i){let t=s[e],i=r.data[e];l.push({key:{status:"valid",value:e},value:t._parse(new y(r,i,r.path,e)),alwaysSet:e in r.data})}if(this._def.catchall instanceof H){let e=this._def.unknownKeys;if("passthrough"===e)for(let e of a)l.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if("strict"===e)a.length>0&&(d(r,{code:n.eq.unrecognized_keys,keys:a}),t.dirty());else if("strip"===e);else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let e=this._def.catchall;for(let t of a){let s=r.data[t];l.push({key:{status:"valid",value:t},value:e._parse(new y(r,s,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of l){let r=await t.key,s=await t.value;e.push({key:r,value:s,alwaysSet:t.alwaysSet})}return e}).then(e=>u.mergeObjectSync(t,e)):u.mergeObjectSync(t,l)}get shape(){return this._def.shape()}strict(e){return i.errToObj,new V({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{let s=this._def.errorMap?.(t,r).message??r.defaultError;return"unrecognized_keys"===t.code?{message:i.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new V({...this._def,unknownKeys:"strip"})}passthrough(){return new V({...this._def,unknownKeys:"passthrough"})}extend(e){return new V({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new V({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:a.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new V({...this._def,catchall:e})}pick(e){let t={};for(let r of o.ZS.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new V({...this._def,shape:()=>t})}omit(e){let t={};for(let r of o.ZS.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new V({...this._def,shape:()=>t})}deepPartial(){return function e(t){if(t instanceof V){let r={};for(let s in t.shape){let i=t.shape[s];r[s]=ep.create(e(i))}return new V({...t._def,shape:()=>r})}if(t instanceof B)return new B({...t._def,type:e(t.element)});if(t instanceof ep)return ep.create(e(t.unwrap()));if(t instanceof ef)return ef.create(e(t.unwrap()));if(t instanceof et)return et.create(t.items.map(t=>e(t)));else return t}(this)}partial(e){let t={};for(let r of o.ZS.objectKeys(this.shape)){let s=this.shape[r];e&&!e[r]?t[r]=s:t[r]=s.optional()}return new V({...this._def,shape:()=>t})}required(e){let t={};for(let r of o.ZS.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof ep;)e=e._def.innerType;t[r]=e}return new V({...this._def,shape:()=>t})}keyof(){return el(o.ZS.objectKeys(this.shape))}}
1V.create=(e,t)=>new V({shape:()=>e,unknownKeys:"strip",catchall:H.create(),typeName:a.ZodObject,...v(t)}),V.strictCreate=(e,t)=>new V({shape:()=>e,unknownKeys:"strict",catchall:H.create(),typeName:a.ZodObject,...v(t)}),V.lazycreate=(e,t)=>new V({shape:e,unknownKeys:"strip",catchall:H.create(),typeName:a.ZodObject,...v(t)});class G extends w{_parse(e){let{ctx:t}=this._processInputParams(e),r=this._def.options;if(t.common.async)return Promise.all(r.map(async e=>{let r={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:r}),ctx:r}})).then(function(e){for(let t of e)if("valid"===t.result.status)return t.result;for(let r of e)if("dirty"===r.result.status)return t.common.issues.push(...r.ctx.common.issues),r.result;let r=e.map(e=>new n.G(e.ctx.common.issues));return d(t,{code:n.eq.invalid_union,unionErrors:r}),h});{let e,s=[];for(let i of r){let r={...t,common:{...t.common,issues:[]},parent:null},a=i._parseSync({data:t.data,path:t.path,parent:r});if("valid"===a.status)return a;"dirty"!==a.status||e||(e={result:a,ctx:r}),r.common.issues.length&&s.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let i=s.map(e=>new n.G(e));return d(t,{code:n.eq.invalid_union,unionErrors:i}),h}}get options(){return this._def.options}}G.create=(e,t)=>new G({options:e,typeName:a.ZodUnion,...v(t)});let X=e=>{if(e instanceof en)return X(e.schema);if(e instanceof eh)return X(e.innerType());if(e instanceof eo)return[e.value];if(e instanceof ec)return e.options;if(e instanceof ed)return o.ZS.objectValues(e.enum);else if(e instanceof em)return X(e._def.innerType);else if(e instanceof W)return[void 0];else if(e instanceof Z)return[null];else if(e instanceof ep)return[void 0,...X(e.unwrap())];else if(e instanceof ef)return[null,...X(e.unwrap())];else if(e instanceof ev)return X(e.unwrap());else if(e instanceof e_)return X(e.unwrap());else if(e instanceof ey)return X(e._def.innerType);else return[]};class Q extends w{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==o.Zp.object)return d(t,{code:n.eq.invalid_type,expected:o.Zp.object,received:t.parsedType}),h;let r=this.discriminator,s=t.data[r],i=this.optionsMap.get(s);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(d(t,{code:n.eq.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),h)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){let s=new Map;for(let r of t){let t=X(r.shape[e]);if(!t.length)throw Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let i of t){if(s.has(i))throw Error(`Discriminator property ${String(e)} has duplicate value ${String(i)}`);s.set(i,r)}}return new Q({typeName:a.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...v(r)})}}class ee extends w{_parse(e){let{status:t,ctx:r}=this._processInputParams(e),s=(e,s)=>{if("aborted"===e.status||"aborted"===s.status)return h;let i=function e(t,r){let s=(0,o.CR)(t),i=(0,o.CR)(r);if(t===r)return{valid:!0,data:t};if(s===o.Zp.object&&i===o.Zp.object){let s=o.ZS.objectKeys(r),i=o.ZS.objectKeys(t).filter(e=>-1!==s.indexOf(e)),a={...t,...r};for(let s of i){let i=e(t[s],r[s]);if(!i.valid)return{valid:!1};a[s]=i.data}return{valid:!0,data:a}}if(s===o.Zp.array&&i===o.Zp.array){if(t.length!==r.length)return{valid:!1};let s=[];for(let i=0;i<t.length;i++){let a=e(t[i],r[i]);if(!a.valid)return{valid:!1};s.push(a.data)}return{valid:!0,data:s}}if(s===o.Zp.date&&i===o.Zp.date&&+t==+r)return{valid:!0,data:t};return{valid:!1}}(e.value,s.value);return i.valid?(("dirty"===e.status||"dirty"===s.status)&&t.dirty(),{status:t.value,value:i.data}):(d(r,{code:n.eq.invalid_intersection_types}),h)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([e,t])=>s(e,t)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}ee.create=(e,t,r)=>new ee({left:e,right:t,typeName:a.ZodIntersection,...v(r)});class et extends w{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);
1if(r.parsedType!==o.Zp.array)return d(r,{code:n.eq.invalid_type,expected:o.Zp.array,received:r.parsedType}),h;if(r.data.length<this._def.items.length)return d(r,{code:n.eq.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),h;!this._def.rest&&r.data.length>this._def.items.length&&(d(r,{code:n.eq.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let s=[...r.data].map((e,t)=>{let s=this._def.items[t]||this._def.rest;return s?s._parse(new y(r,e,r.path,t)):null}).filter(e=>!!e);return r.common.async?Promise.all(s).then(e=>u.mergeArray(t,e)):u.mergeArray(t,s)}get items(){return this._def.items}rest(e){return new et({...this._def,rest:e})}}et.create=(e,t)=>{if(!Array.isArray(e))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new et({items:e,typeName:a.ZodTuple,rest:null,...v(t)})};class er extends w{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==o.Zp.object)return d(r,{code:n.eq.invalid_type,expected:o.Zp.object,received:r.parsedType}),h;let s=[],i=this._def.keyType,a=this._def.valueType;for(let e in r.data)s.push({key:i._parse(new y(r,e,r.path,e)),value:a._parse(new y(r,r.data[e],r.path,e)),alwaysSet:e in r.data});return r.common.async?u.mergeObjectAsync(t,s):u.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,r){return new er(t instanceof w?{keyType:e,valueType:t,typeName:a.ZodRecord,...v(r)}:{keyType:z.create(),valueType:e,typeName:a.ZodRecord,...v(t)})}}class es extends w{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==o.Zp.map)return d(r,{code:n.eq.invalid_type,expected:o.Zp.map,received:r.parsedType}),h;let s=this._def.keyType,i=this._def.valueType,a=[...r.data.entries()].map(([e,t],a)=>({key:s._parse(new y(r,e,r.path,[a,"key"])),value:i._parse(new y(r,t,r.path,[a,"value"]))}));if(r.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let r of a){let s=await r.key,i=await r.value;if("aborted"===s.status||"aborted"===i.status)return h;("dirty"===s.status||"dirty"===i.status)&&t.dirty(),e.set(s.value,i.value)}return{status:t.value,value:e}})}{let e=new Map;for(let r of a){let s=r.key,i=r.value;if("aborted"===s.status||"aborted"===i.status)return h;("dirty"===s.status||"dirty"===i.status)&&t.dirty(),e.set(s.value,i.value)}return{status:t.value,value:e}}}}es.create=(e,t,r)=>new es({valueType:t,keyType:e,typeName:a.ZodMap,...v(r)});class ei extends w{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==o.Zp.set)return d(r,{code:n.eq.invalid_type,expected:o.Zp.set,received:r.parsedType}),h;let s=this._def;null!==s.minSize&&r.data.size<s.minSize.value&&(d(r,{code:n.eq.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),null!==s.maxSize&&r.data.size>s.maxSize.value&&(d(r,{code:n.eq.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());let i=this._def.valueType;function a(e){let r=new Set;for(let s of e){if("aborted"===s.status)return h;"dirty"===s.status&&t.dirty(),r.add(s.value)}return{status:t.value,value:r}}let l=[...r.data.values()].map((e,t)=>i._parse(new y(r,e,r.path,t)));return r.common.async?Promise.all(l).then(e=>a(e)):a(l)}min(e,t){return new ei({...this._def,minSize:{value:e,message:i.toString(t)}})}max(e,t){return new ei({...this._def,maxSize:{value:e,message:i.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}ei.create=(e,t)=>new ei({valueType:e,minSize:null,maxSize:null,typeName:a.ZodSet,...v(t)});class ea extends w{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==o.Zp.function)return d(t,{code:n.eq.invalid_type,expected:o.Zp.function,received:t.parsedType}),h;function r(e,r){return c({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,l,l].filter(e=>
1!!e),issueData:{code:n.eq.invalid_arguments,argumentsError:r}})}function s(e,r){return c({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,l,l].filter(e=>!!e),issueData:{code:n.eq.invalid_return_type,returnTypeError:r}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof eu){let e=this;return f(async function(...t){let o=new n.G([]),l=await e._def.args.parseAsync(t,i).catch(e=>{throw o.addIssue(r(t,e)),o}),c=await Reflect.apply(a,this,l);return await e._def.returns._def.type.parseAsync(c,i).catch(e=>{throw o.addIssue(s(c,e)),o})})}{let e=this;return f(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new n.G([r(t,o.error)]);let l=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(l,i);if(!c.success)throw new n.G([s(l,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new ea({...this._def,args:et.create(e).rest(F.create())})}returns(e){return new ea({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new ea({args:e||et.create([]).rest(F.create()),returns:t||F.create(),typeName:a.ZodFunction,...v(r)})}}class en extends w{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}en.create=(e,t)=>new en({getter:e,typeName:a.ZodLazy,...v(t)});class eo extends w{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return d(t,{received:t.data,code:n.eq.invalid_literal,expected:this._def.value}),h}return{status:"valid",value:e.data}}get value(){return this._def.value}}function el(e,t){return new ec({values:e,typeName:a.ZodEnum,...v(t)})}eo.create=(e,t)=>new eo({value:e,typeName:a.ZodLiteral,...v(t)});class ec extends w{_parse(e){if("string"!=typeof e.data){let t=this._getOrReturnCtx(e),r=this._def.values;return d(t,{expected:o.ZS.joinValues(r),received:t.parsedType,code:n.eq.invalid_type}),h}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),r=this._def.values;return d(t,{received:t.data,code:n.eq.invalid_enum_value,options:r}),h}return f(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return ec.create(e,{...this._def,...t})}exclude(e,t=this._def){return ec.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}ec.create=el;class ed extends w{_parse(e){let t=o.ZS.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==o.Zp.string&&r.parsedType!==o.Zp.number){let e=o.ZS.objectValues(t);return d(r,{expected:o.ZS.joinValues(e),received:r.parsedType,code:n.eq.invalid_type}),h}if(this._cache||(this._cache=new Set(o.ZS.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let e=o.ZS.objectValues(t);return d(r,{received:r.data,code:n.eq.invalid_enum_value,options:e}),h}return f(e.data)}get enum(){return this._def.values}}ed.create=(e,t)=>new ed({values:e,typeName:a.ZodNativeEnum,...v(t)});class eu extends w{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==o.Zp.promise&&!1===t.common.async?(d(t,{code:n.eq.invalid_type,expected:o.Zp.promise,received:t.parsedType}),h):f((t.parsedType===o.Zp.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}eu.create=(e,t)=>new eu({type:e,typeName:a.ZodPromise,...v(t)});class eh extends w{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===a.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:r}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:e=>{d(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),"preprocess"===s.type){let e=s.transform(r.data,i);if(r.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===t.value)return h;let s=await this._def.schema._parseAsync({data:e,path:r.path,parent:r});return"aborted"===s.status?h:"dirty"===s.status||"dirty"===t.value?p(s.value):s});{if("aborted"===t.value)return h;let s=this._def.schema._parseSync({data:e,path:r.path,parent:r});return"aborted"===s.status?h:"dirty"===s.status||"dirty"===t.value?p(s.value):s}}if("refinement"===s.type){let e=e=>{let t=s.refinement(e,i);if(r.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1!==r.common.async)return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(r=>"aborted"===r.status?h:("dirty"===r.status&&t.dirty(),e(r.value).then(()=>({status:t.value,value:r.value}))));{let s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===s.status?h:("dirty"===s.status&&t.dirty(),e(s.value),{status:t.value,value:s.value})}}if("transform"===s.type)if(!1!==r.common.async)return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(e=>"valid"!==e.status?h:Promise.resolve(s.transform(e.value,i)).then(e=>({status:t.value,value:e})));else{let e=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if("valid"!==e.status)return h;let a=s.transform(e.value,i);if(a instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:a}}o.ZS.assertNever(s)}}eh.create=(e,t,r)=>new eh({schema:e,typeName:a.ZodEffects,effect:t,...v(r)}),eh.createWithPreprocess=(e,t,r)=>new eh({schema:t,effect:{type:"preprocess",transform:e},typeName:a.ZodEffects,...v(r)});class ep extends w{_parse(e){return this._getType(e)===o.Zp.undefined?f(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ep.create=(e,t)=>
1new ep({innerType:e,typeName:a.ZodOptional,...v(t)});class ef extends w{_parse(e){return this._getType(e)===o.Zp.null?f(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ef.create=(e,t)=>new ef({innerType:e,typeName:a.ZodNullable,...v(t)});class em extends w{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return t.parsedType===o.Zp.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}em.create=(e,t)=>new em({innerType:e,typeName:a.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...v(t)});class ey extends w{_parse(e){let{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return m(s)?s.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new n.G(r.common.issues)},input:r.data})})):{status:"valid",value:"valid"===s.status?s.value:this._def.catchValue({get error(){return new n.G(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}ey.create=(e,t)=>new ey({innerType:e,typeName:a.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...v(t)});class eg extends w{_parse(e){if(this._getType(e)!==o.Zp.nan){let t=this._getOrReturnCtx(e);return d(t,{code:n.eq.invalid_type,expected:o.Zp.nan,received:t.parsedType}),h}return{status:"valid",value:e.data}}}eg.create=e=>new eg({typeName:a.ZodNaN,...v(e)}),Symbol("zod_brand");class ev extends w{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class ew extends w{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?h:"dirty"===e.status?(t.dirty(),p(e.value)):this._def.out._parseAsync({data:e.value,path:r.path,parent:r})})();{let e=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?h:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:r.path,parent:r})}}static create(e,t){return new ew({in:e,out:t,typeName:a.ZodPipeline})}}class e_ extends w{_parse(e){let t=this._def.innerType._parse(e),r=e=>("valid"===e.status&&(e.value=Object.freeze(e.value)),e);return m(t)?t.then(e=>r(e)):r(t)}unwrap(){return this._def.innerType}}function eb(e,t){let r="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof r?{message:r}:r}e_.create=(e,t)=>new e_({innerType:e,typeName:a.ZodReadonly,...v(t)}),V.lazycreate,function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"}(a||(a={}));let ek=(e,t={message:`Input not instance of ${e.name}`})=>(function(e,t={},r){return e?U.create().superRefine((r,s)=>{let i=e(r);if(i instanceof Promise)return i.then(e=>{if(!e){let e=eb(t,r),i=e.fatal??void 0??!0;s.addIssue({code:"custom",...e,fatal:i})}});if(!i){let e=eb(t,r),i=e.fatal??void 0??!0;s.addIssue({code:"custom",...e,fatal:i})}}):U.create()})(t=>t instanceof e,t),eS=z.create,ex=K.create;eg.create,q.create;let eE=M.create;Y.create,N.create,W.create,Z.create,U.create;let eA=F.create,ej=H.create;J.create;let eI=B.create,eT=V.create;V.strictCreate;let eR=G.create,eO=Q.create,eC=ee.create;et.create;let eP=er.create;es.create,ei.create,ea.create,en.create;let eD=eo.create,e$=ec.create;
1ed.create,eu.create,eh.create,ep.create,ef.create;let eL=eh.createWithPreprocess;ew.create;let ez=h}}]);

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.