democlip-mcp 1.0.134 → 1.0.136
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/app/assets/{bluesky-2zxGS7t7.js → bluesky-a3DEo_Ep.js} +1 -1
- package/app/assets/{help-B-8EMI1T.js → help-D4J5iIJh.js} +1 -1
- package/app/assets/main-VCi5PISp.js +91 -0
- package/app/assets/prefs-DA-nHXSc.css +1 -0
- package/app/help.html +3 -3
- package/app/index.html +4 -6
- package/app/version.json +1 -1
- package/package.json +1 -1
- package/app/assets/main-CvITF10a.js +0 -91
- package/app/assets/prefs-B65035GX.css +0 -1
- /package/app/assets/{prefs-Bg51XGKs.js → prefs-DvFm87Vp.js} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{n as e,t}from"./main-CvITF10a.js";var n=t(((e,t,n)=>{var r=function(e){return e&&e.Math===Math&&e};t.exports=r(typeof globalThis==`object`&&globalThis)||r(typeof window==`object`&&window)||r(typeof self==`object`&&self)||r(typeof global==`object`&&global)||r(typeof n==`object`&&n)||(function(){return this})()||Function(`return this`)()})),r=t(((e,t)=>{t.exports=n()})),i=t(((e,t)=>{t.exports=function(e){try{return!!e()}catch{return!0}}})),a=t(((e,t)=>{t.exports=!i()(function(){var e=function(){}.bind();return typeof e!=`function`||e.hasOwnProperty(`prototype`)})})),o=t(((e,t)=>{var n=a(),r=Function.prototype,i=r.call,o=n&&r.bind.bind(i,i);t.exports=n?o:function(e){return function(){return i.apply(e,arguments)}}})),s=t(((e,t)=>{t.exports=function(e){return e==null}})),c=t(((e,t)=>{var n=s(),r=TypeError;t.exports=function(e){if(n(e))throw new r(`Can't call method on `+e);return e}})),l=t(((e,t)=>{var n=c(),r=Object;t.exports=function(e){return r(n(e))}})),u=t(((e,t)=>{var n=o(),r=l(),i=n({}.hasOwnProperty);t.exports=Object.hasOwn||function(e,t){return i(r(e),t)}})),d=t(((e,t)=>{t.exports=!1})),f=t(((e,t)=>{var r=n(),i=Object.defineProperty;t.exports=function(e,t){try{i(r,e,{value:t,configurable:!0,writable:!0})}catch{r[e]=t}return t}})),p=t(((e,t)=>{var r=d(),i=n(),a=f(),o=`__core-js_shared__`,s=t.exports=i[o]||a(o,{});(s.versions||=[]).push({version:`3.51.0`,mode:r?`pure`:`global`,copyright:`© 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.51.0/LICENSE`,source:`https://github.com/zloirock/core-js`})})),m=t(((e,t)=>{var n=p(),r=Object.create||Object;t.exports=function(e,t){return n[e]||(n[e]=t||r(null))}})),h=t(((e,t)=>{var n=o(),r=0,i=Math.random(),a=n(1.1.toString);t.exports=function(e){return`Symbol(`+(e===void 0?``:e)+`)_`+a(++r+i,36)}})),g=t(((e,t)=>{var r=n().navigator,i=r&&r.userAgent;t.exports=i?String(i):``})),ee=t(((e,t)=>{var r=n(),i=g(),a=r.process,o=r.Deno,s=a&&a.versions||o&&o.version,c=s&&s.v8,l,u;c&&(l=c.split(`.`),u=l[0]>0&&l[0]<4?1:+(l[0]+l[1])),!u&&i&&(l=i.match(/Edge\/(\d+)/),(!l||l[1]>=74)&&(l=i.match(/Chrome\/(\d+)/),l&&(u=+l[1]))),t.exports=u})),te=t(((e,t)=>{var r=ee(),a=i(),o=n().String;t.exports=!!Object.getOwnPropertySymbols&&!a(function(){var e=Symbol(`symbol detection`);return!o(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&r&&r<41})})),_=t(((e,t)=>{t.exports=te()&&!Symbol.sham&&typeof Symbol.iterator==`symbol`})),ne=t(((e,t)=>{var r=n(),i=m(),a=u(),o=h(),s=te(),c=_(),l=r.Symbol,d=i(`wks`),f=c?l.for||l:l&&l.withoutSetter||o;t.exports=function(e){return a(d,e)||(d[e]=s&&a(l,e)?l[e]:f(`Symbol.`+e)),d[e]}})),re=t((e=>{e.f=ne()})),ie=t(((e,t)=>{t.exports=!i()(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})})),ae=t(((e,t)=>{var n=typeof document==`object`&&document.all;t.exports=n===void 0&&n!==void 0?function(e){return typeof e==`function`||e===n}:function(e){return typeof e==`function`}})),oe=t(((e,t)=>{var n=ae();t.exports=function(e){return typeof e==`object`?e!==null:n(e)}})),se=t(((e,t)=>{var r=n(),i=oe(),a=r.document,o=i(a)&&i(a.createElement);t.exports=function(e){return o?a.createElement(e):{}}})),ce=t(((e,t)=>{var n=ie(),r=i(),a=se();t.exports=!n&&!r(function(){return Object.defineProperty(a(`div`),"a",{get:function(){return 7}}).a!==7})})),le=t(((e,t)=>{var n=ie(),r=i();t.exports=n&&r(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})})),ue=t(((e,t)=>{var n=oe(),r=String,i=TypeError;t.exports=function(e){if(n(e))return e;throw new i(r(e)+` is not an object`)}})),de=t(((e,t)=>{var n=a(),r=Function.prototype.call;t.exports=n?r.bind(r):function(){return r.apply(r,arguments)}})),fe=t(((e,t)=>{var r=n(),i=ae(),a=function(e){return i(e)?e:void 0};t.exports=function(e,t){return arguments.length<2?a(r[e]):r[e]&&r[e][t]}})),pe=t(((e,t)=>{t.exports=o()({}.isPrototypeOf)})),me=t(((e,t)=>{var n=fe(),r=ae(),i=pe(),a=_(),o=Object;t.exports=a?function(e){return typeof e==`symbol`}:function(e){var t=n(`Symbol`);return r(t)&&i(t.prototype,o(e))}})),he=t(((e,t)=>{var n=String;t.exports=function(e){try{return n(e)}catch{return`Object`}}})),ge=t(((e,t)=>{var n=ae(),r=he(),i=TypeError;t.exports=function(e){if(n(e))return e;throw new i(r(e)+` is not a function`)}})),_e=t(((e,t)=>{var n=ge(),r=s();t.exports=function(e,t){var i=e[t];return r(i)?void 0:n(i)}})),ve=t(((e,t)=>{var n=de(),r=ae(),i=oe(),a=TypeError;t.exports=function(e,t){var o,s;if(t===`string`&&r(o=e.toString)&&!i(s=n(o,e))||r(o=e.valueOf)&&!i(s=n(o,e))||t!==`string`&&r(o=e.toString)&&!i(s=n(o,e)))return s;throw new a(`Can't convert object to primitive value`)}})),ye=t(((e,t)=>{var n=de(),r=oe(),i=me(),a=_e(),o=ve(),s=ne(),c=TypeError,l=s(`toPrimitive`);t.exports=function(e,t){if(!r(e)||i(e))return e;var s=a(e,l),u;if(s){if(t===void 0&&(t=`default`),u=n(s,e,t),!r(u)||i(u))return u;throw new c(`Can't convert object to primitive value`)}return t===void 0&&(t=`number`),o(e,t)}})),be=t(((e,t)=>{var n=ye(),r=me();t.exports=function(e){var t=n(e,`string`);return r(t)?t:t+``}})),xe=t((e=>{var t=ie(),n=ce(),r=le(),i=ue(),a=be(),o=TypeError,s=Object.defineProperty,c=Object.getOwnPropertyDescriptor,l=`enumerable`,u=`configurable`,d=`writable`;e.f=t?r?function(e,t,n){if(i(e),t=a(t),i(n),typeof e==`function`&&t===`prototype`&&`value`in n&&d in n&&!n[d]){var r=c(e,t);r&&r[d]&&(e[t]=n.value,n={configurable:u in n?n[u]:r[u],enumerable:l in n?n[l]:r[l],writable:!1})}return s(e,t,n)}:s:function(e,t,r){if(i(e),t=a(t),i(r),n)try{return s(e,t,r)}catch{}if(`get`in r||`set`in r)throw new o(`Accessors not supported`);return`value`in r&&(e[t]=r.value),e}})),Se=t(((e,t)=>{var n=r(),i=u(),a=re(),o=xe().f;t.exports=function(e){var t=n.Symbol||={};i(t,e)||o(t,e,{value:a.f(e)})}})),Ce=t((e=>{var t={}.propertyIsEnumerable,n=Object.getOwnPropertyDescriptor;e.f=n&&!t.call({1:2},1)?function(e){var t=n(this,e);return!!t&&t.enumerable}:t})),we=t(((e,t)=>{t.exports=function(e,t){return{enumerable:!(e&1),configurable:!(e&2),writable:!(e&4),value:t}}})),Te=t(((e,t)=>{var n=o(),r=n({}.toString),i=n(``.slice);t.exports=function(e){return i(r(e),8,-1)}})),Ee=t(((e,t)=>{var n=o(),r=i(),a=Te(),s=Object,c=n(``.split);t.exports=r(function(){return!s(`z`).propertyIsEnumerable(0)})?function(e){return a(e)===`String`?c(e,``):s(e)}:s})),De=t(((e,t)=>{var n=Ee(),r=c();t.exports=function(e){return n(r(e))}})),Oe=t((e=>{var t=ie(),n=de(),r=Ce(),i=we(),a=De(),o=be(),s=u(),c=ce(),l=Object.getOwnPropertyDescriptor;e.f=t?l:function(e,t){if(e=a(e),t=o(t),c)try{return l(e,t)}catch{}if(s(e,t))return i(!n(r.f,e,t),e[t])}})),ke=t((()=>{var e=n(),t=Se(),r=xe().f,i=Oe().f,a=e.Symbol;if(t(`asyncDispose`),a){var o=i(a,`asyncDispose`);o.enumerable&&o.configurable&&o.writable&&r(a,`asyncDispose`,{value:o.value,enumerable:!1,configurable:!1,writable:!1})}})),Ae=t(((e,t)=>{ke(),t.exports=re().f(`asyncDispose`)})),je=t((()=>{var e=n(),t=Se(),r=xe().f,i=Oe().f,a=e.Symbol;if(t(`dispose`),a){var o=i(a,`dispose`);o.enumerable&&o.configurable&&o.writable&&r(a,`dispose`,{value:o.value,enumerable:!1,configurable:!1,writable:!1})}})),Me=t(((e,t)=>{je(),t.exports=re().f(`dispose`)})),v;(function(e){e.assertEqual=e=>{};function t(e){}e.assertIs=t;function n(e){throw Error()}e.assertNever=n,e.arrayToEnum=e=>{let t={};for(let n of e)t[n]=n;return t},e.getValidEnumValues=t=>{let n=e.objectKeys(t).filter(e=>typeof t[t[e]]!=`number`),r={};for(let e of n)r[e]=t[e];return e.objectValues(r)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys=typeof Object.keys==`function`?e=>Object.keys(e):e=>{let t=[];for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(let n of e)if(t(n))return n},e.isInteger=typeof Number.isInteger==`function`?e=>Number.isInteger(e):e=>typeof e==`number`&&Number.isFinite(e)&&Math.floor(e)===e;function r(e,t=` | `){return e.map(e=>typeof e==`string`?`'${e}'`:e).join(t)}e.joinValues=r,e.jsonStringifyReplacer=(e,t)=>typeof t==`bigint`?t.toString():t})(v||={});var Ne;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(Ne||={});var y=v.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),Pe=e=>{switch(typeof e){case`undefined`:return y.undefined;case`string`:return y.string;case`number`:return Number.isNaN(e)?y.nan:y.number;case`boolean`:return y.boolean;case`function`:return y.function;case`bigint`:return y.bigint;case`symbol`:return y.symbol;case`object`:return Array.isArray(e)?y.array:e===null?y.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?y.promise:typeof Map<`u`&&e instanceof Map?y.map:typeof Set<`u`&&e instanceof Set?y.set:typeof Date<`u`&&e instanceof Date?y.date:y.object;default:return y.unknown}},b=v.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`]),x=class e 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},n={_errors:[]},r=e=>{for(let i of e.issues)if(i.code===`invalid_union`)i.unionErrors.map(r);else if(i.code===`invalid_return_type`)r(i.returnTypeError);else if(i.code===`invalid_arguments`)r(i.argumentsError);else if(i.path.length===0)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){let n=i.path[r];r===i.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(i))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(this),n}static assert(t){if(!(t instanceof e))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,v.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=e=>e.message){let t={},n=[];for(let r of this.issues)if(r.path.length>0){let n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};x.create=e=>new x(e);var Fe=(e,t)=>{let n;switch(e.code){case b.invalid_type:n=e.received===y.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case b.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,v.jsonStringifyReplacer)}`;break;case b.unrecognized_keys:n=`Unrecognized key(s) in object: ${v.joinValues(e.keys,`, `)}`;break;case b.invalid_union:n=`Invalid input`;break;case b.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${v.joinValues(e.options)}`;break;case b.invalid_enum_value:n=`Invalid enum value. Expected ${v.joinValues(e.options)}, received '${e.received}'`;break;case b.invalid_arguments:n=`Invalid function arguments`;break;case b.invalid_return_type:n=`Invalid function return type`;break;case b.invalid_date:n=`Invalid date`;break;case b.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:v.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case b.too_small:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at least`:`more than`} ${e.minimum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at least`:`over`} ${e.minimum} character(s)`:e.type===`number`||e.type===`bigint`?`Number must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${e.minimum}`:e.type===`date`?`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 b.too_big:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at most`:`less than`} ${e.maximum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at most`:`under`} ${e.maximum} character(s)`:e.type===`number`?`Number must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`bigint`?`BigInt must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`date`?`Date must be ${e.exact?`exactly`:e.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(e.maximum))}`:`Invalid input`;break;case b.custom:n=`Invalid input`;break;case b.invalid_intersection_types:n=`Intersection results could not be merged`;break;case b.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case b.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,v.assertNever(e)}return{message:n}},Ie=Fe;function Le(){return Ie}var Re=e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,a=[...n,...i.path||[]],o={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let s=``,c=r.filter(e=>!!e).slice().reverse();for(let e of c)s=e(o,{data:t,defaultError:s}).message;return{...i,path:a,message:s}};function S(e,t){let n=Le(),r=Re({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Fe?void 0:Fe].filter(e=>!!e)});e.common.issues.push(r)}var C=class e{constructor(){this.value=`valid`}dirty(){this.value===`valid`&&(this.value=`dirty`)}abort(){this.value!==`aborted`&&(this.value=`aborted`)}static mergeArray(e,t){let n=[];for(let r of t){if(r.status===`aborted`)return w;r.status===`dirty`&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(t,n){let r=[];for(let e of n){let t=await e.key,n=await e.value;r.push({key:t,value:n})}return e.mergeObjectSync(t,r)}static mergeObjectSync(e,t){let n={};for(let r of t){let{key:t,value:i}=r;if(t.status===`aborted`||i.status===`aborted`)return w;t.status===`dirty`&&e.dirty(),i.status===`dirty`&&e.dirty(),t.value!==`__proto__`&&(i.value!==void 0||r.alwaysSet)&&(n[t.value]=i.value)}return{status:e.value,value:n}}},w=Object.freeze({status:`aborted`}),ze=e=>({status:`dirty`,value:e}),T=e=>({status:`valid`,value:e}),Be=e=>e.status===`aborted`,Ve=e=>e.status===`dirty`,He=e=>e.status===`valid`,Ue=e=>typeof Promise<`u`&&e instanceof Promise,E;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(E||={});var D=class{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}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}},We=(e,t)=>{if(He(t))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 x(e.common.issues);return this._error=t,this._error}}};function O(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))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 t.code===`invalid_enum_value`?{message:a??i.defaultError}:i.data===void 0?{message:a??r??i.defaultError}:t.code===`invalid_type`?{message:a??n??i.defaultError}:{message:i.defaultError}},description:i}}var k=class{get description(){return this._def.description}_getType(e){return Pe(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Pe(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new C,ctx:{common:e.parent.common,data:e.data,parsedType:Pe(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(Ue(t))throw Error(`Synchronous parse encountered promise.`);return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Pe(e)};return We(n,this._parseSync({data:e,path:n.path,parent:n}))}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Pe(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return He(n)?{value:n.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=>He(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Pe(e)},r=this._parse({data:e,path:n.path,parent:n});return We(n,await(Ue(r)?r:Promise.resolve(r)))}refine(e,t){let n=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,r)=>{let i=e(t),a=()=>r.addIssue({code:b.custom,...n(t)});return typeof Promise<`u`&&i instanceof Promise?i.then(e=>e?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t==`function`?t(n,r):t),!1))}_refinement(e){return new j({schema:this,typeName:M.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 Kt.create(this,this._def)}nullable(){return qt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ot.create(this)}promise(){return Gt.create(this,this._def)}or(e){return At.create([this,e],this._def)}and(e){return Pt.create(this,e,this._def)}transform(e){return new j({...O(this._def),schema:this,typeName:M.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new Jt({...O(this._def),innerType:this,defaultValue:t,typeName:M.ZodDefault})}brand(){return new Zt({typeName:M.ZodBranded,type:this,...O(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new Yt({...O(this._def),innerType:this,catchValue:t,typeName:M.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Qt.create(this,e)}readonly(){return $t.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Ge=/^c[^\s-]{8,}$/i,Ke=/^[0-9a-z]+$/,qe=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Je=/^[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,Ye=/^[a-z0-9_-]{21}$/i,Xe=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Ze=/^[-+]?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)?)??$/,Qe=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,$e=`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,et,tt=/^(?:(?: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])$/,nt=/^(?:(?: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])$/,rt=/^(([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]))$/,it=/^(([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])$/,at=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ot=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,st=`((\\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])))`,ct=RegExp(`^${st}$`);function lt(e){let t=`[0-5]\\d`;e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision??(t=`${t}(\\.\\d+)?`);let n=e.precision?`+`:`?`;return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function ut(e){return RegExp(`^${lt(e)}$`)}function dt(e){let t=`${st}T${lt(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function ft(e,t){return!((t!==`v4`&&t||!tt.test(e))&&(t!==`v6`&&t||!rt.test(e)))}function pt(e,t){if(!Xe.test(e))return!1;try{let[n]=e.split(`.`);if(!n)return!1;let r=n.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(n.length+(4-n.length%4)%4,`=`),i=JSON.parse(atob(r));return!(typeof i!=`object`||!i||`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&i.alg!==t)}catch{return!1}}function mt(e,t){return!((t!==`v4`&&t||!nt.test(e))&&(t!==`v6`&&t||!it.test(e)))}var ht=class e extends k{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==y.string){let t=this._getOrReturnCtx(e);return S(t,{code:b.invalid_type,expected:y.string,received:t.parsedType}),w}let t=new C,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),S(n,{code:b.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`max`)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),S(n,{code:b.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`length`){let i=e.data.length>r.value,a=e.data.length<r.value;(i||a)&&(n=this._getOrReturnCtx(e,n),i?S(n,{code:b.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&S(n,{code:b.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)Qe.test(e.data)||(n=this._getOrReturnCtx(e,n),S(n,{validation:`email`,code:b.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)et||=new RegExp($e,`u`),et.test(e.data)||(n=this._getOrReturnCtx(e,n),S(n,{validation:`emoji`,code:b.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)Je.test(e.data)||(n=this._getOrReturnCtx(e,n),S(n,{validation:`uuid`,code:b.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)Ye.test(e.data)||(n=this._getOrReturnCtx(e,n),S(n,{validation:`nanoid`,code:b.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)Ge.test(e.data)||(n=this._getOrReturnCtx(e,n),S(n,{validation:`cuid`,code:b.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)Ke.test(e.data)||(n=this._getOrReturnCtx(e,n),S(n,{validation:`cuid2`,code:b.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)qe.test(e.data)||(n=this._getOrReturnCtx(e,n),S(n,{validation:`ulid`,code:b.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),S(n,{validation:`url`,code:b.invalid_string,message:r.message}),t.dirty()}else r.kind===`regex`?(r.regex.lastIndex=0,r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),S(n,{validation:`regex`,code:b.invalid_string,message:r.message}),t.dirty())):r.kind===`trim`?e.data=e.data.trim():r.kind===`includes`?e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),S(n,{code:b.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty()):r.kind===`toLowerCase`?e.data=e.data.toLowerCase():r.kind===`toUpperCase`?e.data=e.data.toUpperCase():r.kind===`startsWith`?e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),S(n,{code:b.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),S(n,{code:b.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?dt(r).test(e.data)||(n=this._getOrReturnCtx(e,n),S(n,{code:b.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?ct.test(e.data)||(n=this._getOrReturnCtx(e,n),S(n,{code:b.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?ut(r).test(e.data)||(n=this._getOrReturnCtx(e,n),S(n,{code:b.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?Ze.test(e.data)||(n=this._getOrReturnCtx(e,n),S(n,{validation:`duration`,code:b.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?ft(e.data,r.version)||(n=this._getOrReturnCtx(e,n),S(n,{validation:`ip`,code:b.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?pt(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),S(n,{validation:`jwt`,code:b.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?mt(e.data,r.version)||(n=this._getOrReturnCtx(e,n),S(n,{validation:`cidr`,code:b.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?at.test(e.data)||(n=this._getOrReturnCtx(e,n),S(n,{validation:`base64`,code:b.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?ot.test(e.data)||(n=this._getOrReturnCtx(e,n),S(n,{validation:`base64url`,code:b.invalid_string,message:r.message}),t.dirty()):v.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:b.invalid_string,...E.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...E.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...E.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...E.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...E.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...E.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...E.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...E.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...E.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...E.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...E.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...E.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...E.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...E.errToObj(e)})}datetime(e){return typeof e==`string`?this._addCheck({kind:`datetime`,precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:`datetime`,precision:e?.precision===void 0?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...E.errToObj(e?.message)})}date(e){return this._addCheck({kind:`date`,message:e})}time(e){return typeof e==`string`?this._addCheck({kind:`time`,precision:null,message:e}):this._addCheck({kind:`time`,precision:e?.precision===void 0?null:e?.precision,...E.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...E.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...E.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...E.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...E.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...E.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...E.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...E.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...E.errToObj(t)})}nonempty(e){return this.min(1,E.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:`trim`}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toLowerCase`}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toUpperCase`}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind===`datetime`)}get isDate(){return!!this._def.checks.find(e=>e.kind===`date`)}get isTime(){return!!this._def.checks.find(e=>e.kind===`time`)}get isDuration(){return!!this._def.checks.find(e=>e.kind===`duration`)}get isEmail(){return!!this._def.checks.find(e=>e.kind===`email`)}get isURL(){return!!this._def.checks.find(e=>e.kind===`url`)}get isEmoji(){return!!this._def.checks.find(e=>e.kind===`emoji`)}get isUUID(){return!!this._def.checks.find(e=>e.kind===`uuid`)}get isNANOID(){return!!this._def.checks.find(e=>e.kind===`nanoid`)}get isCUID(){return!!this._def.checks.find(e=>e.kind===`cuid`)}get isCUID2(){return!!this._def.checks.find(e=>e.kind===`cuid2`)}get isULID(){return!!this._def.checks.find(e=>e.kind===`ulid`)}get isIP(){return!!this._def.checks.find(e=>e.kind===`ip`)}get isCIDR(){return!!this._def.checks.find(e=>e.kind===`cidr`)}get isBase64(){return!!this._def.checks.find(e=>e.kind===`base64`)}get isBase64url(){return!!this._def.checks.find(e=>e.kind===`base64url`)}get minLength(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};ht.create=e=>new ht({checks:[],typeName:M.ZodString,coerce:e?.coerce??!1,...O(e)});function gt(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=(t.toString().split(`.`)[1]||``).length,i=n>r?n:r;return Number.parseInt(e.toFixed(i).replace(`.`,``))%Number.parseInt(t.toFixed(i).replace(`.`,``))/10**i}var _t=class e extends k{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==y.number){let t=this._getOrReturnCtx(e);return S(t,{code:b.invalid_type,expected:y.number,received:t.parsedType}),w}let t,n=new C;for(let r of this._def.checks)r.kind===`int`?v.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),S(t,{code:b.invalid_type,expected:`integer`,received:`float`,message:r.message}),n.dirty()):r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),S(t,{code:b.too_small,minimum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),S(t,{code:b.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?gt(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),S(t,{code:b.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),S(t,{code:b.not_finite,message:r.message}),n.dirty()):v.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,E.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,E.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,E.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,E.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:E.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:E.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:E.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:E.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:E.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:E.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:E.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:E.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:E.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:E.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind===`int`||e.kind===`multipleOf`&&v.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks)if(n.kind===`finite`||n.kind===`int`||n.kind===`multipleOf`)return!0;else n.kind===`min`?(t===null||n.value>t)&&(t=n.value):n.kind===`max`&&(e===null||n.value<e)&&(e=n.value);return Number.isFinite(t)&&Number.isFinite(e)}};_t.create=e=>new _t({checks:[],typeName:M.ZodNumber,coerce:e?.coerce||!1,...O(e)});var vt=class e extends k{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==y.bigint)return this._getInvalidInput(e);let t,n=new C;for(let r of this._def.checks)r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),S(t,{code:b.too_small,type:`bigint`,minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),S(t,{code:b.too_big,type:`bigint`,maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`multipleOf`?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),S(t,{code:b.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):v.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return S(t,{code:b.invalid_type,expected:y.bigint,received:t.parsedType}),w}gte(e,t){return this.setLimit(`min`,e,!0,E.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,E.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,E.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,E.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:E.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!1,message:E.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:E.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:E.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:E.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:E.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};vt.create=e=>new vt({checks:[],typeName:M.ZodBigInt,coerce:e?.coerce??!1,...O(e)});var yt=class extends k{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==y.boolean){let t=this._getOrReturnCtx(e);return S(t,{code:b.invalid_type,expected:y.boolean,received:t.parsedType}),w}return T(e.data)}};yt.create=e=>new yt({typeName:M.ZodBoolean,coerce:e?.coerce||!1,...O(e)});var bt=class e extends k{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==y.date){let t=this._getOrReturnCtx(e);return S(t,{code:b.invalid_type,expected:y.date,received:t.parsedType}),w}if(Number.isNaN(e.data.getTime()))return S(this._getOrReturnCtx(e),{code:b.invalid_date}),w;let t=new C,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),S(n,{code:b.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:`date`}),t.dirty()):r.kind===`max`?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),S(n,{code:b.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):v.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:`min`,value:e.getTime(),message:E.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:E.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e==null?null:new Date(e)}get maxDate(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e==null?null:new Date(e)}};bt.create=e=>new bt({checks:[],coerce:e?.coerce||!1,typeName:M.ZodDate,...O(e)});var xt=class extends k{_parse(e){if(this._getType(e)!==y.symbol){let t=this._getOrReturnCtx(e);return S(t,{code:b.invalid_type,expected:y.symbol,received:t.parsedType}),w}return T(e.data)}};xt.create=e=>new xt({typeName:M.ZodSymbol,...O(e)});var St=class extends k{_parse(e){if(this._getType(e)!==y.undefined){let t=this._getOrReturnCtx(e);return S(t,{code:b.invalid_type,expected:y.undefined,received:t.parsedType}),w}return T(e.data)}};St.create=e=>new St({typeName:M.ZodUndefined,...O(e)});var Ct=class extends k{_parse(e){if(this._getType(e)!==y.null){let t=this._getOrReturnCtx(e);return S(t,{code:b.invalid_type,expected:y.null,received:t.parsedType}),w}return T(e.data)}};Ct.create=e=>new Ct({typeName:M.ZodNull,...O(e)});var wt=class extends k{constructor(){super(...arguments),this._any=!0}_parse(e){return T(e.data)}};wt.create=e=>new wt({typeName:M.ZodAny,...O(e)});var Tt=class extends k{constructor(){super(...arguments),this._unknown=!0}_parse(e){return T(e.data)}};Tt.create=e=>new Tt({typeName:M.ZodUnknown,...O(e)});var Et=class extends k{_parse(e){let t=this._getOrReturnCtx(e);return S(t,{code:b.invalid_type,expected:y.never,received:t.parsedType}),w}};Et.create=e=>new Et({typeName:M.ZodNever,...O(e)});var Dt=class extends k{_parse(e){if(this._getType(e)!==y.undefined){let t=this._getOrReturnCtx(e);return S(t,{code:b.invalid_type,expected:y.void,received:t.parsedType}),w}return T(e.data)}};Dt.create=e=>new Dt({typeName:M.ZodVoid,...O(e)});var Ot=class e extends k{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==y.array)return S(t,{code:b.invalid_type,expected:y.array,received:t.parsedType}),w;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(S(t,{code:e?b.too_big:b.too_small,minimum:i?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(S(t,{code:b.too_small,minimum:r.minLength.value,type:`array`,inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(S(t,{code:b.too_big,maximum:r.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new D(t,e,t.path,n)))).then(e=>C.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new D(t,e,t.path,n)));return C.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:E.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:E.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:E.toString(n)}})}nonempty(e){return this.min(1,e)}};Ot.create=(e,t)=>new Ot({type:e,minLength:null,maxLength:null,exactLength:null,typeName:M.ZodArray,...O(t)});function kt(e){if(e instanceof A){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=Kt.create(kt(r))}return new A({...e._def,shape:()=>t})}return e instanceof Ot?new Ot({...e._def,type:kt(e.element)}):e instanceof Kt?Kt.create(kt(e.unwrap())):e instanceof qt?qt.create(kt(e.unwrap())):e instanceof Ft?Ft.create(e.items.map(e=>kt(e))):e}var A=class e extends k{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=v.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==y.object){let t=this._getOrReturnCtx(e);return S(t,{code:b.invalid_type,expected:y.object,received:t.parsedType}),w}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Et&&this._def.unknownKeys===`strip`))for(let e in n.data)i.includes(e)||a.push(e);let o=[];for(let e of i){let t=r[e],i=n.data[e];o.push({key:{status:`valid`,value:e},value:t._parse(new D(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof Et){let e=this._def.unknownKeys;if(e===`passthrough`)for(let e of a)o.push({key:{status:`valid`,value:e},value:{status:`valid`,value:n.data[e]}});else if(e===`strict`)a.length>0&&(S(n,{code:b.unrecognized_keys,keys:a}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of a){let r=n.data[t];o.push({key:{status:`valid`,value:t},value:e._parse(new D(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of o){let n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>C.mergeObjectSync(t,e)):C.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return E.errToObj,new e({...this._def,unknownKeys:`strict`,...t===void 0?{}:{errorMap:(e,n)=>{let r=this._def.errorMap?.(e,n).message??n.defaultError;return e.code===`unrecognized_keys`?{message:E.errToObj(t).message??r}:{message:r}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:M.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let e of v.objectKeys(t))t[e]&&this.shape[e]&&(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let e of v.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return kt(this)}partial(t){let n={};for(let e of v.objectKeys(this.shape)){let r=this.shape[e];n[e]=t&&!t[e]?r:r.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let e of v.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof Kt;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return Ht(v.objectKeys(this.shape))}};A.create=(e,t)=>new A({shape:()=>e,unknownKeys:`strip`,catchall:Et.create(),typeName:M.ZodObject,...O(t)}),A.strictCreate=(e,t)=>new A({shape:()=>e,unknownKeys:`strict`,catchall:Et.create(),typeName:M.ZodObject,...O(t)}),A.lazycreate=(e,t)=>new A({shape:e,unknownKeys:`strip`,catchall:Et.create(),typeName:M.ZodObject,...O(t)});var At=class extends k{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function r(e){for(let t of e)if(t.result.status===`valid`)return t.result;for(let n of e)if(n.result.status===`dirty`)return t.common.issues.push(...n.ctx.common.issues),n.result;let n=e.map(e=>new x(e.ctx.common.issues));return S(t,{code:b.invalid_union,unionErrors:n}),w}if(t.common.async)return Promise.all(n.map(async e=>{let n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(r);{let e,r=[];for(let i of n){let n={...t,common:{...t.common,issues:[]},parent:null},a=i._parseSync({data:t.data,path:t.path,parent:n});if(a.status===`valid`)return a;a.status===`dirty`&&!e&&(e={result:a,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let i=r.map(e=>new x(e));return S(t,{code:b.invalid_union,unionErrors:i}),w}}get options(){return this._def.options}};At.create=(e,t)=>new At({options:e,typeName:M.ZodUnion,...O(t)});var jt=e=>e instanceof Bt?jt(e.schema):e instanceof j?jt(e.innerType()):e instanceof Vt?[e.value]:e instanceof Ut?e.options:e instanceof Wt?v.objectValues(e.enum):e instanceof Jt?jt(e._def.innerType):e instanceof St?[void 0]:e instanceof Ct?[null]:e instanceof Kt?[void 0,...jt(e.unwrap())]:e instanceof qt?[null,...jt(e.unwrap())]:e instanceof Zt||e instanceof $t?jt(e.unwrap()):e instanceof Yt?jt(e._def.innerType):[],Mt=class e extends k{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==y.object)return S(t,{code:b.invalid_type,expected:y.object,received:t.parsedType}),w;let n=this.discriminator,r=t.data[n],i=this.optionsMap.get(r);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}):(S(t,{code:b.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),w)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let i=new Map;for(let e of n){let n=jt(e.shape[t]);if(!n.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let r of n){if(i.has(r))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(r)}`);i.set(r,e)}}return new e({typeName:M.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...O(r)})}};function Nt(e,t){let n=Pe(e),r=Pe(t);if(e===t)return{valid:!0,data:e};if(n===y.object&&r===y.object){let n=v.objectKeys(t),r=v.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=Nt(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}if(n===y.array&&r===y.array){if(e.length!==t.length)return{valid:!1};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=Nt(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}return n===y.date&&r===y.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var Pt=class extends k{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(Be(e)||Be(r))return w;let i=Nt(e.value,r.value);return i.valid?((Ve(e)||Ve(r))&&t.dirty(),{status:t.value,value:i.data}):(S(n,{code:b.invalid_intersection_types}),w)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Pt.create=(e,t,n)=>new Pt({left:e,right:t,typeName:M.ZodIntersection,...O(n)});var Ft=class e extends k{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==y.array)return S(n,{code:b.invalid_type,expected:y.array,received:n.parsedType}),w;if(n.data.length<this._def.items.length)return S(n,{code:b.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),w;!this._def.rest&&n.data.length>this._def.items.length&&(S(n,{code:b.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let r=[...n.data].map((e,t)=>{let r=this._def.items[t]||this._def.rest;return r?r._parse(new D(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>C.mergeArray(t,e)):C.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Ft.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new Ft({items:e,typeName:M.ZodTuple,rest:null,...O(t)})};var It=class e extends k{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==y.object)return S(n,{code:b.invalid_type,expected:y.object,received:n.parsedType}),w;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new D(n,e,n.path,e)),value:a._parse(new D(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?C.mergeObjectAsync(t,r):C.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof k?new e({keyType:t,valueType:n,typeName:M.ZodRecord,...O(r)}):new e({keyType:ht.create(),valueType:t,typeName:M.ZodRecord,...O(n)})}},Lt=class extends k{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==y.map)return S(n,{code:b.invalid_type,expected:y.map,received:n.parsedType}),w;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new D(n,e,n.path,[a,`key`])),value:i._parse(new D(n,t,n.path,[a,`value`]))}));if(n.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let n of a){let r=await n.key,i=await n.value;if(r.status===`aborted`||i.status===`aborted`)return w;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}})}{let e=new Map;for(let n of a){let r=n.key,i=n.value;if(r.status===`aborted`||i.status===`aborted`)return w;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};Lt.create=(e,t,n)=>new Lt({valueType:t,keyType:e,typeName:M.ZodMap,...O(n)});var Rt=class e extends k{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==y.set)return S(n,{code:b.invalid_type,expected:y.set,received:n.parsedType}),w;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(S(n,{code:b.too_small,minimum:r.minSize.value,type:`set`,inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&n.data.size>r.maxSize.value&&(S(n,{code:b.too_big,maximum:r.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());let i=this._def.valueType;function a(e){let n=new Set;for(let r of e){if(r.status===`aborted`)return w;r.status===`dirty`&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}let o=[...n.data.values()].map((e,t)=>i._parse(new D(n,e,n.path,t)));return n.common.async?Promise.all(o).then(e=>a(e)):a(o)}min(t,n){return new e({...this._def,minSize:{value:t,message:E.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:E.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};Rt.create=(e,t)=>new Rt({valueType:e,minSize:null,maxSize:null,typeName:M.ZodSet,...O(t)});var zt=class e extends k{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==y.function)return S(t,{code:b.invalid_type,expected:y.function,received:t.parsedType}),w;function n(e,n){return Re({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Le(),Fe].filter(e=>!!e),issueData:{code:b.invalid_arguments,argumentsError:n}})}function r(e,n){return Re({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Le(),Fe].filter(e=>!!e),issueData:{code:b.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof Gt){let e=this;return T(async function(...t){let o=new x([]),s=await e._def.args.parseAsync(t,i).catch(e=>{throw o.addIssue(n(t,e)),o}),c=await Reflect.apply(a,this,s);return await e._def.returns._def.type.parseAsync(c,i).catch(e=>{throw o.addIssue(r(c,e)),o})})}{let e=this;return T(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new x([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new x([r(s,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:Ft.create(t).rest(Tt.create())})}returns(t){return new e({...this._def,returns:t})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(t,n,r){return new e({args:t||Ft.create([]).rest(Tt.create()),returns:n||Tt.create(),typeName:M.ZodFunction,...O(r)})}},Bt=class extends k{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})}};Bt.create=(e,t)=>new Bt({getter:e,typeName:M.ZodLazy,...O(t)});var Vt=class extends k{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return S(t,{received:t.data,code:b.invalid_literal,expected:this._def.value}),w}return{status:`valid`,value:e.data}}get value(){return this._def.value}};Vt.create=(e,t)=>new Vt({value:e,typeName:M.ZodLiteral,...O(t)});function Ht(e,t){return new Ut({values:e,typeName:M.ZodEnum,...O(t)})}var Ut=class e extends k{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return S(t,{expected:v.joinValues(n),received:t.parsedType,code:b.invalid_type}),w}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return S(t,{received:t.data,code:b.invalid_enum_value,options:n}),w}return T(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(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(e=>!t.includes(e)),{...this._def,...n})}};Ut.create=Ht;var Wt=class extends k{_parse(e){let t=v.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==y.string&&n.parsedType!==y.number){let e=v.objectValues(t);return S(n,{expected:v.joinValues(e),received:n.parsedType,code:b.invalid_type}),w}if(this._cache||=new Set(v.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=v.objectValues(t);return S(n,{received:n.data,code:b.invalid_enum_value,options:e}),w}return T(e.data)}get enum(){return this._def.values}};Wt.create=(e,t)=>new Wt({values:e,typeName:M.ZodNativeEnum,...O(t)});var Gt=class extends k{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==y.promise&&t.common.async===!1?(S(t,{code:b.invalid_type,expected:y.promise,received:t.parsedType}),w):T((t.parsedType===y.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};Gt.create=(e,t)=>new Gt({type:e,typeName:M.ZodPromise,...O(t)});var j=class extends k{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===M.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{S(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),r.type===`preprocess`){let e=r.transform(n.data,i);if(n.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return w;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?w:r.status===`dirty`||t.value===`dirty`?ze(r.value):r});{if(t.value===`aborted`)return w;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?w:r.status===`dirty`||t.value===`dirty`?ze(r.value):r}}if(r.type===`refinement`){let e=e=>{let t=r.refinement(e,i);if(n.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(n.common.async===!1){let r=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return r.status===`aborted`?w:(r.status===`dirty`&&t.dirty(),e(r.value),{status:t.value,value:r.value})}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>n.status===`aborted`?w:(n.status===`dirty`&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if(r.type===`transform`){if(n.common.async===!1){let e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!He(e))return w;let a=r.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}}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>He(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):w)}v.assertNever(r)}};j.create=(e,t,n)=>new j({schema:e,typeName:M.ZodEffects,effect:t,...O(n)}),j.createWithPreprocess=(e,t,n)=>new j({schema:t,effect:{type:`preprocess`,transform:e},typeName:M.ZodEffects,...O(n)});var Kt=class extends k{_parse(e){return this._getType(e)===y.undefined?T(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Kt.create=(e,t)=>new Kt({innerType:e,typeName:M.ZodOptional,...O(t)});var qt=class extends k{_parse(e){return this._getType(e)===y.null?T(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};qt.create=(e,t)=>new qt({innerType:e,typeName:M.ZodNullable,...O(t)});var Jt=class extends k{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===y.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};Jt.create=(e,t)=>new Jt({innerType:e,typeName:M.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...O(t)});var Yt=class extends k{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Ue(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new x(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new x(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Yt.create=(e,t)=>new Yt({innerType:e,typeName:M.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...O(t)});var Xt=class extends k{_parse(e){if(this._getType(e)!==y.nan){let t=this._getOrReturnCtx(e);return S(t,{code:b.invalid_type,expected:y.nan,received:t.parsedType}),w}return{status:`valid`,value:e.data}}};Xt.create=e=>new Xt({typeName:M.ZodNaN,...O(e)});var Zt=class extends k{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},Qt=class e extends k{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?w:e.status===`dirty`?(t.dirty(),ze(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})();{let e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?w:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(t,n){return new e({in:t,out:n,typeName:M.ZodPipeline})}},$t=class extends k{_parse(e){let t=this._def.innerType._parse(e),n=e=>(He(e)&&(e.value=Object.freeze(e.value)),e);return Ue(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};$t.create=(e,t)=>new $t({innerType:e,typeName:M.ZodReadonly,...O(t)}),A.lazycreate;var M;(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`})(M||={});var N=ht.create,P=_t.create;Xt.create,vt.create;var F=yt.create;bt.create,xt.create,St.create,Ct.create,wt.create;var en=Tt.create,tn=Et.create;Dt.create;var I=Ot.create,L=A.create;A.strictCreate;var R=At.create,nn=Mt.create,rn=Pt.create;Ft.create;var an=It.create;Lt.create,Rt.create,zt.create,Bt.create;var z=Vt.create,B=Ut.create;Wt.create,Gt.create,j.create,Kt.create,qt.create;var on=j.createWithPreprocess;Qt.create,Ae(),Me();var sn=`ERR_JWKS_NO_MATCHING_KEY`,cn=`ERR_JWK_INVALID`,ln=`ERR_JWK_NOT_FOUND`,un=`ERR_JWT_INVALID`,dn=`ERR_JWT_CREATE`,fn=`ERR_JWT_VERIFY`,V=class extends TypeError{constructor(e=`JWK error`,t=cn,n){super(e,n),this.code=t}},pn=class e extends Error{constructor(e=`Unable to create JWT`,t=dn,n){super(e,n),this.code=t}static from(t,n,r){return t instanceof e?t:t instanceof V?new e(r,t.code,{cause:t}):new e(r,n,{cause:t})}},mn=class e extends Error{constructor(e=`Invalid JWT`,t=fn,n){super(e,n),this.code=t}static from(t,n,r){return t instanceof e?t:t instanceof V?new e(r,t.code,{cause:t}):new e(r,n,{cause:t})}},hn=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error(`Unknown type, must be binary type`)}},gn=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let r=t.codePointAt(0);if(r===void 0)throw Error(`Invalid prefix character`);this.prefixCodePoint=r,this.baseDecode=n}decode(e){if(typeof e==`string`){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 vn(this,e)}},_n=class{decoders;constructor(e){this.decoders=e}or(e){return vn(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function vn(e,t){return new _n({...e.decoders??{[e.prefix]:e},...t.decoders??{[t.prefix]:t}})}var yn=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,r){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=r,this.encoder=new hn(e,t,n),this.decoder=new gn(e,t,r)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function bn({name:e,prefix:t,encode:n,decode:r}){return new yn(e,t,n,r)}function xn(e,t,n,r){let i=e.length;for(;e[i-1]===`=`;)--i;let a=new Uint8Array(i*n/8|0),o=0,s=0,c=0;for(let l=0;l<i;++l){let i=t[e[l]];if(i===void 0)throw SyntaxError(`Non-${r} character`);s=s<<n|i,o+=n,o>=8&&(o-=8,a[c++]=255&s>>o)}if(o>=n||255&s<<8-o)throw SyntaxError(`Unexpected end of data`);return a}function Sn(e,t,n){let r=t[t.length-1]===`=`,i=(1<<n)-1,a=``,o=0,s=0;for(let r=0;r<e.length;++r)for(s=s<<8|e[r],o+=8;o>n;)o-=n,a+=t[i&s>>o];if(o!==0&&(a+=t[i&s<<n-o]),r)for(;a.length*n&7;)a+=`=`;return a}function Cn(e){let t={};for(let n=0;n<e.length;++n)t[e[n]]=n;return t}function wn({name:e,prefix:t,bitsPerChar:n,alphabet:r}){let i=Cn(r);return bn({prefix:t,name:e,encode(e){return Sn(e,r,n)},decode(t){return xn(t,i,n,e)}})}wn({prefix:`m`,name:`base64`,alphabet:`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,bitsPerChar:6}),wn({prefix:`M`,name:`base64pad`,alphabet:`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=`,bitsPerChar:6});var Tn=wn({prefix:`u`,name:`base64url`,alphabet:`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_`,bitsPerChar:6});wn({prefix:`U`,name:`base64urlpad`,alphabet:`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=`,bitsPerChar:6});var En=e=>e!==void 0,Dn=e=>(t,n)=>{let r=e.indexOf(t),i=e.indexOf(n);return r===i?0:r===-1?1:i===-1?-1:r-i};function On(e){return e==null?e=>!0:Array.isArray(e)?t=>e.includes(t):t=>t===e}var kn=(e,t)=>function(){let t=e.call(this);return Object.defineProperty(this,e.name,{get:()=>t,enumerable:!0,configurable:!0}),t},An=new TextDecoder;function jn(e){let t=Tn.baseDecode(e),n=An.decode(t);return JSON.parse(n)}var Mn=(e,t)=>{let n;for(let r=0;r<e.length;r++)if(n=e.charCodeAt(r),!(65<=n&&n<=90||97<=n&&n<=122||48<=n&&n<=57||n===45||n===95||n===46)){let n=String.fromCodePoint(e.codePointAt(r));return t.addIssue({code:b.custom,message:`Invalid character "${n}" in JWT at position ${r}`})}},Nn=(e,t=2)=>{if(!Number.isFinite(e)||e<1||(e|0)!==e)throw TypeError(`Count must be a natural number (got ${e})`);let n=e*t+(e-1),r=`Invalid JWT format`;return(i,a)=>{if(i.length<n)return a.addIssue({code:b.custom,message:`${r}: too short`}),!1;let o=0;for(let n=0;n<e-1;n++){let s=i.indexOf(`.`,o);if(s===-1)return a.addIssue({code:b.custom,message:`${r}: expected ${e} segments, got ${n+1}`}),!1;if(s-o<t)return a.addIssue({code:b.custom,message:`${r}: segment ${n+1} is too short`}),!1;o=s+1}return i.indexOf(`.`,o)===-1?i.length-o<t?(a.addIssue({code:b.custom,message:`${r}: last segment is too short`}),!1):!0:(a.addIssue({code:b.custom,message:`${r}: too many segments`}),!1)}};function Pn(e,t,n){return n.indexOf(e,t+1)===-1}var Fn=[`verify`,`encrypt`,`wrapKey`];B(Fn);function In(e){return Fn.includes(e)}function Ln(e){return e===`verify`}function Rn(e){return e===`encrypt`||e===`wrapKey`}var zn=[`sign`,`decrypt`,`unwrapKey`,`deriveKey`,`deriveBits`];B(zn);function Bn(e){return zn.includes(e)}var Vn=B([...zn,...Fn]),Hn=L({kty:N().min(1),alg:N().min(1).optional(),kid:N().min(1).optional(),use:B([`sig`,`enc`]).optional(),key_ops:I(Vn).min(1,{message:`At least one key usage must be specified`}).refine(e=>e.every(Pn),{message:`key_ops must not contain duplicates`}).optional(),x5c:I(N()).optional(),x5t:N().min(1).optional(),"x5t#S256":N().min(1).optional(),x5u:N().url().optional(),ext:F().optional(),iat:P().int().optional(),exp:P().int().optional(),nbf:P().int().optional(),revoked:L({revoked_at:P().int(),reason:N().optional()}).optional()}),Un=R([Hn.extend({kty:z(`RSA`),alg:B([`RS256`,`RS384`,`RS512`,`PS256`,`PS384`,`PS512`]).optional(),n:N().min(1),e:N().min(1),d:N().min(1).optional(),p:N().min(1).optional(),q:N().min(1).optional(),dp:N().min(1).optional(),dq:N().min(1).optional(),qi:N().min(1).optional(),oth:I(L({r:N().optional(),d:N().optional(),t:N().optional()})).min(1).optional()}),Hn.extend({kty:z(`EC`),alg:B([`ES256`,`ES384`,`ES512`]).optional(),crv:B([`P-256`,`P-384`,`P-521`]),x:N().min(1),y:N().min(1),d:N().min(1).optional()}),Hn.extend({kty:z(`EC`),alg:B([`ES256K`]).optional(),crv:B([`secp256k1`]),x:N().min(1),y:N().min(1),d:N().min(1).optional()}),Hn.extend({kty:z(`OKP`),alg:B([`EdDSA`]).optional(),crv:B([`Ed25519`,`Ed448`]),x:N().min(1),d:N().min(1).optional()}),Hn.extend({kty:z(`oct`),alg:B([`HS256`,`HS384`,`HS512`]).optional(),k:N()})]).refine(e=>e.use==null||Yn(e),{message:`"use" can only be used with public keys`,path:[`use`]}).refine(e=>!e.key_ops?.some(Bn)||Jn(e),{message:`private key usage not allowed for public keys`,path:[`key_ops`]}).refine(e=>e.use==null||e.key_ops==null||e.use===`sig`&&e.key_ops.every(Ln)||e.use===`enc`&&e.key_ops.every(Rn),{message:`"key_ops" must be consistent with "use"`,path:[`key_ops`]}),Wn=Un.refine(Gn,{message:`"kid" is required`,path:[`kid`]}).refine(Yn,{message:`private key not allowed`}).refine(e=>!e.key_ops||e.key_ops.every(In),{message:`"key_ops" must not contain private key usage for public keys`,path:[`key_ops`]});Un.refine(Jn,{message:`private key required`});function Gn(e){return`kid`in e&&e.kid!=null}function Kn(e){return`k`in e&&e.k!=null}function qn(e){return`d`in e&&e.d!=null}function Jn(e){return qn(e)||Kn(e)}function Yn(e){return!qn(e)&&!Kn(e)}var{process:Xn}=globalThis,Zn=Xn!==void 0&&typeof Xn?.versions?.node==`string`;function*Qn(e){if(typeof e.alg==`string`)yield e.alg;else switch(e.kty){case`EC`:if($n(e)&&(yield`ECDH-ES`,yield`ECDH-ES+A128KW`,yield`ECDH-ES+A192KW`,yield`ECDH-ES+A256KW`),er(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`:Zn&&(yield`ES256K`);break;default:throw new V(`Unsupported crv "${t}"`)}}return;case`OKP`:if(!e.use)throw new V(`Missing "use" Parameter value`);yield`ECDH-ES`,yield`ECDH-ES+A128KW`,yield`ECDH-ES+A192KW`,yield`ECDH-ES+A256KW`;return;case`RSA`:$n(e)&&(yield`RSA-OAEP`,yield`RSA-OAEP-256`,yield`RSA-OAEP-384`,yield`RSA-OAEP-512`,Zn&&(yield`RSA1_5`)),er(e)&&(yield`PS256`,yield`PS384`,yield`PS512`,yield`RS256`,yield`RS384`,yield`RS512`);return;case`oct`:$n(e)&&(yield`A128GCMKW`,yield`A192GCMKW`,yield`A256GCMKW`,yield`A128KW`,yield`A192KW`,yield`A256KW`),er(e)&&(yield`HS256`,yield`HS384`,yield`HS512`);return;default:throw new V(`Unsupported kty "${e.kty}"`)}}function $n(e){return e.key_ops?.some(Rn)??(e.use==null||e.use===`enc`)}function er(e){return e.key_ops?.some(Ln)??(e.use==null||e.use===`sig`)}L({keys:I(en()).transform(e=>e.map(e=>Un.safeParse(e)).filter(e=>e.success).map(e=>e.data))});var tr=L({keys:I(en()).transform(e=>e.map(e=>Wn.safeParse(e)).filter(e=>e.success).map(e=>e.data))}),nr=N().superRefine(Mn).superRefine(Nn(3)),rr=N().superRefine(Mn).superRefine(Nn(2)),ir=L({alg:N(),jku:N().url().optional(),jwk:L({kty:N(),crv:N().optional(),x:N().optional(),y:N().optional(),e:N().optional(),n:N().optional()}).optional(),kid:N().optional(),x5u:N().optional(),x5c:I(N()).optional(),x5t:N().optional(),"x5t#S256":N().optional(),typ:N().optional(),cty:N().optional(),crit:I(N()).optional()}).passthrough(),ar=N().superRefine((e,t)=>{try{let n=new URL(e);n.protocol!==`http:`&&n.protocol!==`https:`&&t.addIssue({code:b.custom,message:`Only http: and https: protocols are allowed`}),(n.username||n.password)&&t.addIssue({code:b.custom,message:`Credentials not allowed`}),n.search&&t.addIssue({code:b.custom,message:`Query string not allowed`}),n.hash&&t.addIssue({code:b.custom,message:`Fragment not allowed`})}catch{t.addIssue({code:b.invalid_string,validation:`url`})}return e}),or=L({iss:N().optional(),aud:R([N(),I(N()).nonempty()]).optional(),sub:N().optional(),exp:P().int().optional(),nbf:P().int().optional(),iat:P().int().optional(),jti:N().optional(),htm:N().optional(),htu:ar.optional(),ath:N().optional(),acr:N().optional(),azp:N().optional(),amr:I(N()).optional(),cnf:L({kid:N().optional(),jwk:Wn.optional(),jwe:N().optional(),jku:N().url().optional(),jkt:N().optional(),"x5t#S256":N().optional(),osc:N().optional()}).optional(),client_id:N().optional(),scope:N().optional(),nonce:N().optional(),at_hash:N().optional(),c_hash:N().optional(),s_hash:N().optional(),auth_time:P().int().optional(),name:N().optional(),family_name:N().optional(),given_name:N().optional(),middle_name:N().optional(),nickname:N().optional(),preferred_username:N().optional(),gender:N().optional(),picture:N().url().optional(),profile:N().url().optional(),website:N().url().optional(),birthdate:N().regex(/\d{4}-\d{2}-\d{2}/).optional(),zoneinfo:N().regex(/^[A-Za-z0-9_/]+$/).optional(),locale:N().regex(/^[a-z]{2,3}(-[A-Z]{2})?$/).optional(),updated_at:P().int().optional(),email:N().optional(),email_verified:F().optional(),phone_number:N().optional(),phone_number_verified:F().optional(),address:L({formatted:N().optional(),street_address:N().optional(),locality:N().optional(),region:N().optional(),postal_code:N().optional(),country:N().optional()}).optional(),authorization_details:I(L({type:N(),locations:I(N()).optional(),actions:I(N()).optional(),datatypes:I(N()).optional(),identifier:N().optional(),privileges:I(N()).optional()}).passthrough()).optional()}).passthrough();function sr(e){let{0:t,1:n,length:r}=e.split(`.`);if(r>3||r<2)throw new mn(void 0,un);let i=ir.parse(jn(t));if(r===2&&i?.alg!==`none`)throw new mn(void 0,un);return{header:i,payload:or.parse(jn(n))}}var cr=function(e,t,n){for(var r=arguments.length>2,i=0;i<t.length;i++)n=r?t[i].call(e,n):t[i].call(e);return r?n:void 0},lr=function(e,t,n,r,i,a){function o(e){if(e!==void 0&&typeof e!=`function`)throw TypeError(`Function expected`);return e}for(var s=r.kind,c=s===`getter`?`get`:s===`setter`?`set`:`value`,l=!t&&e?r.static?e:e.prototype:null,u=t||(l?Object.getOwnPropertyDescriptor(l,r.name):{}),d,f=!1,p=n.length-1;p>=0;p--){var m={};for(var h in r)m[h]=h===`access`?{}:r[h];for(var h in r.access)m.access[h]=r.access[h];m.addInitializer=function(e){if(f)throw TypeError(`Cannot add initializers after decoration has completed`);a.push(o(e||null))};var g=(0,n[p])(s===`accessor`?{get:u.get,set:u.set}:u[c],m);if(s===`accessor`){if(g===void 0)continue;if(typeof g!=`object`||!g)throw TypeError(`Object expected`);(d=o(g.get))&&(u.get=d),(d=o(g.set))&&(u.set=d),(d=o(g.init))&&i.unshift(d)}else(d=o(g))&&(s===`field`?i.unshift(d):u[c]=d)}l&&Object.defineProperty(l,r.name,u),f=!0},ur=(()=>{let e=[],t,n,r,i,a;return class{static{let o=typeof Symbol==`function`&&Symbol.metadata?Object.create(null):void 0;t=[kn],n=[kn],r=[kn],i=[kn],a=[kn],lr(this,null,t,{kind:`getter`,name:`isPrivate`,static:!1,private:!1,access:{has:e=>`isPrivate`in e,get:e=>e.isPrivate},metadata:o},null,e),lr(this,null,n,{kind:`getter`,name:`isSymetric`,static:!1,private:!1,access:{has:e=>`isSymetric`in e,get:e=>e.isSymetric},metadata:o},null,e),lr(this,null,r,{kind:`getter`,name:`publicJwk`,static:!1,private:!1,access:{has:e=>`publicJwk`in e,get:e=>e.publicJwk},metadata:o},null,e),lr(this,null,i,{kind:`getter`,name:`bareJwk`,static:!1,private:!1,access:{has:e=>`bareJwk`in e,get:e=>e.bareJwk},metadata:o},null,e),lr(this,null,a,{kind:`getter`,name:`algorithms`,static:!1,private:!1,access:{has:e=>`algorithms`in e,get:e=>e.algorithms},metadata:o},null,e),o&&Object.defineProperty(this,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})}constructor(t){this.jwk=(cr(this,e),t)}get isPrivate(){return Jn(this.jwk)}get isSymetric(){return Kn(this.jwk)}get privateJwk(){if(this.isPrivate)return this.jwk}get publicJwk(){if(this.isSymetric)return;if(!this.isPrivate)return this.jwk;let e=Wn.safeParse({...this.jwk,d:void 0,k:void 0,use:void 0,key_ops:dr(this.keyOps)??Fn});if(e.success)return Object.freeze(e.data)}get bareJwk(){if(this.isSymetric)return;let{kty:e,crv:t,e:n,n:r,x:i,y:a}=this.jwk;return Object.freeze(Un.parse({crv:t,e:n,kty:e,n:r,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(Qn(this.jwk)))}get isRevoked(){return this.jwk.revoked!=null}isActive(e){if(!e?.allowRevoked&&this.isRevoked)return!1;let t=e?.clockTolerance??0;if(t!==1/0){let n=e?.currentDate?.getTime()??Date.now(),{exp:r,nbf:i}=this.jwk;if(i!=null&&!(n>=i*1e3-t)||r!=null&&!(n<r*1e3+t))return!1}return!0}matches(e){return!(e.kid!=null&&!(Array.isArray(e.kid)?this.kid!=null&&e.kid.includes(this.kid):this.kid===e.kid)||e.alg!=null&&!(Array.isArray(e.alg)?e.alg.some(e=>this.algorithms.includes(e)):this.algorithms.includes(e.alg))||e.usage!=null&&(!(this.keyOps==null||this.keyOps.includes(e.usage)||e.usage===`verify`&&this.keyOps.includes(`sign`)||e.usage===`encrypt`&&this.keyOps.includes(`decrypt`)||e.usage===`wrapKey`&&this.keyOps.includes(`unwrapKey`))||!(this.use==null||this.use===`sig`&&Ln(e.usage)||this.use===`enc`&&Rn(e.usage))||!(this.isPrivate||In(e.usage))))}}})();function dr(e){if(e==null)return;let t=new Set(e.filter(In));return e.includes(`sign`)&&t.add(`verify`),e.includes(`decrypt`)&&t.add(`encrypt`),e.includes(`unwrapKey`)&&t.add(`wrapKey`),Array.from(t)}var fr=function(e,t,n){for(var r=arguments.length>2,i=0;i<t.length;i++)n=r?t[i].call(e,n):t[i].call(e);return r?n:void 0},pr=function(e,t,n,r,i,a){function o(e){if(e!==void 0&&typeof e!=`function`)throw TypeError(`Function expected`);return e}for(var s=r.kind,c=s===`getter`?`get`:s===`setter`?`set`:`value`,l=!t&&e?r.static?e:e.prototype:null,u=t||(l?Object.getOwnPropertyDescriptor(l,r.name):{}),d,f=!1,p=n.length-1;p>=0;p--){var m={};for(var h in r)m[h]=h===`access`?{}:r[h];for(var h in r.access)m.access[h]=r.access[h];m.addInitializer=function(e){if(f)throw TypeError(`Cannot add initializers after decoration has completed`);a.push(o(e||null))};var g=(0,n[p])(s===`accessor`?{get:u.get,set:u.set}:u[c],m);if(s===`accessor`){if(g===void 0)continue;if(typeof g!=`object`||!g)throw TypeError(`Object expected`);(d=o(g.get))&&(u.get=d),(d=o(g.set))&&(u.set=d),(d=o(g.init))&&i.unshift(d)}else(d=o(g))&&(s===`field`?i.unshift(d):u[c]=d)}l&&Object.defineProperty(l,r.name,u),f=!0},mr=e=>e.privateJwk,hr=e=>e.publicJwk,gr=(()=>{let e=[],t,n,r;return class i{static{let i=typeof Symbol==`function`&&Symbol.metadata?Object.create(null):void 0;pr(this,null,t,{kind:`getter`,name:`signAlgorithms`,static:!1,private:!1,access:{has:e=>`signAlgorithms`in e,get:e=>e.signAlgorithms},metadata:i},null,e),pr(this,null,n,{kind:`getter`,name:`publicJwks`,static:!1,private:!1,access:{has:e=>`publicJwks`in e,get:e=>e.publicJwks},metadata:i},null,e),pr(this,null,r,{kind:`getter`,name:`privateJwks`,static:!1,private:!1,access:{has:e=>`privateJwks`in e,get:e=>e.privateJwks},metadata:i},null,e),i&&Object.defineProperty(this,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i})}constructor(t,n=t instanceof i?[...t.preferredSigningAlgorithms]:[`EdDSA`,`ES256K`,`ES256`,`PS256`,`PS384`,`PS512`,`HS256`,`HS384`,`HS512`]){this.preferredSigningAlgorithms=(fr(this,e),n);let r=[],a=new Set;for(let e of t)if(e&&(r.push(e),e.kid)){if(a.has(e.kid))throw new V(`Duplicate key: ${e.kid}`);a.add(e.kid)}this.keys=Object.freeze(r)}get size(){return this.keys.length}get signAlgorithms(){let e=new Set;for(let t of this)if(t.use===`sig`)for(let n of t.algorithms)e.add(n);return Object.freeze([...e].sort(Dn(this.preferredSigningAlgorithms)))}get publicJwks(){return Object.freeze({keys:Object.freeze(Array.from(this,hr).filter(En))})}get privateJwks(){return Object.freeze({keys:Object.freeze(Array.from(this,mr).filter(En))})}has(e){return this.keys.some(t=>t.kid===e)}get(e){let t=this.find(e);if(t)return t;throw new V(`Key not found ${e.kid??e.alg??e.usage??`<unknown>`}`,ln)}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:n,...r}){let i=[];Array.isArray(t)&&t.length===1&&(t=t[0]);for(let a of this.list({...r,kid:e,alg:t,usage:n})){if(typeof t==`string`)return{key:a,alg:t};i.push(a)}let a=On(t),o=i.map(e=>[e,e.algorithms.filter(a)]);for(let e of this.preferredSigningAlgorithms)for(let[t,n]of o)if(n.includes(e))return{key:t,alg:e};for(let[e,t]of o)for(let n of t)return{key:e,alg:n};throw new V(`No private key found for ${e||t||n}`,ln)}[(t=[kn],n=[kn],r=[kn],Symbol.iterator)](){return this.keys.values()}async createJwt({alg:e,kid:t,...n},r){try{let{key:i,alg:a}=this.findPrivateKey({alg:e,kid:t,usage:`sign`,allowRevoked:!1}),o={...n,alg:a,kid:i.kid};return typeof r==`function`&&(r=await r(o,i)),await i.createJwt(o,r)}catch(e){throw pn.from(e)}}async verifyJwt(e,t){let{header:n}=sr(e),{kid:r,alg:i}=n,a=[];for(let n of this.list({...t,kid:r,alg:i,usage:`verify`}))try{return{...await n.verifyJwt(e,t),key:n}}catch(e){a.push(e)}switch(a.length){case 0:throw new mn(`No key matched`,sn);case 1:throw mn.from(a[0],un);default:throw mn.from(a,un)}}toJSON(){return structuredClone(this.publicJwks)}}})(),_r=crypto,vr=e=>e instanceof CryptoKey,H=new TextEncoder,yr=new TextDecoder;function br(...e){let t=e.reduce((e,{length:t})=>e+t,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}var xr=e=>{let t=e;typeof t==`string`&&(t=H.encode(t));let n=32768,r=[];for(let e=0;e<t.length;e+=n)r.push(String.fromCharCode.apply(null,t.subarray(e,e+n)));return btoa(r.join(``))},Sr=e=>xr(e).replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`),Cr=e=>{let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n},wr=e=>{let t=e;t instanceof Uint8Array&&(t=yr.decode(t)),t=t.replace(/-/g,`+`).replace(/_/g,`/`).replace(/\s/g,``);try{return Cr(t)}catch{throw TypeError(`The input to be decoded is not correctly encoded.`)}},Tr=e({JOSEAlgNotAllowed:()=>Dr,JOSEError:()=>U,JOSENotSupported:()=>G,JWEDecryptionFailed:()=>Or,JWEInvalid:()=>kr,JWKInvalid:()=>jr,JWKSInvalid:()=>Mr,JWKSMultipleMatchingKeys:()=>Pr,JWKSNoMatchingKey:()=>Nr,JWKSTimeout:()=>Fr,JWSInvalid:()=>K,JWSSignatureVerificationFailed:()=>Ir,JWTClaimValidationFailed:()=>W,JWTExpired:()=>Er,JWTInvalid:()=>Ar}),U=class extends Error{constructor(e,t){super(e,t),this.code=`ERR_JOSE_GENERIC`,this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};U.code=`ERR_JOSE_GENERIC`;var W=class extends U{constructor(e,t,n=`unspecified`,r=`unspecified`){super(e,{cause:{claim:n,reason:r,payload:t}}),this.code=`ERR_JWT_CLAIM_VALIDATION_FAILED`,this.claim=n,this.reason=r,this.payload=t}};W.code=`ERR_JWT_CLAIM_VALIDATION_FAILED`;var Er=class extends U{constructor(e,t,n=`unspecified`,r=`unspecified`){super(e,{cause:{claim:n,reason:r,payload:t}}),this.code=`ERR_JWT_EXPIRED`,this.claim=n,this.reason=r,this.payload=t}};Er.code=`ERR_JWT_EXPIRED`;var Dr=class extends U{constructor(){super(...arguments),this.code=`ERR_JOSE_ALG_NOT_ALLOWED`}};Dr.code=`ERR_JOSE_ALG_NOT_ALLOWED`;var G=class extends U{constructor(){super(...arguments),this.code=`ERR_JOSE_NOT_SUPPORTED`}};G.code=`ERR_JOSE_NOT_SUPPORTED`;var Or=class extends U{constructor(e=`decryption operation failed`,t){super(e,t),this.code=`ERR_JWE_DECRYPTION_FAILED`}};Or.code=`ERR_JWE_DECRYPTION_FAILED`;var kr=class extends U{constructor(){super(...arguments),this.code=`ERR_JWE_INVALID`}};kr.code=`ERR_JWE_INVALID`;var K=class extends U{constructor(){super(...arguments),this.code=`ERR_JWS_INVALID`}};K.code=`ERR_JWS_INVALID`;var Ar=class extends U{constructor(){super(...arguments),this.code=`ERR_JWT_INVALID`}};Ar.code=`ERR_JWT_INVALID`;var jr=class extends U{constructor(){super(...arguments),this.code=`ERR_JWK_INVALID`}};jr.code=`ERR_JWK_INVALID`;var Mr=class extends U{constructor(){super(...arguments),this.code=`ERR_JWKS_INVALID`}};Mr.code=`ERR_JWKS_INVALID`;var Nr=class extends U{constructor(e=`no applicable key found in the JSON Web Key Set`,t){super(e,t),this.code=`ERR_JWKS_NO_MATCHING_KEY`}};Nr.code=`ERR_JWKS_NO_MATCHING_KEY`;var Pr=class extends U{constructor(e=`multiple matching keys found in the JSON Web Key Set`,t){super(e,t),this.code=`ERR_JWKS_MULTIPLE_MATCHING_KEYS`}};Pr.code=`ERR_JWKS_MULTIPLE_MATCHING_KEYS`;var Fr=class extends U{constructor(e=`request timed out`,t){super(e,t),this.code=`ERR_JWKS_TIMEOUT`}};Fr.code=`ERR_JWKS_TIMEOUT`;var Ir=class extends U{constructor(e=`signature verification failed`,t){super(e,t),this.code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`}};Ir.code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;function q(e,t=`algorithm.name`){return TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function Lr(e,t){return e.name===t}function Rr(e){return parseInt(e.name.slice(4),10)}function zr(e){switch(e){case`ES256`:return`P-256`;case`ES384`:return`P-384`;case`ES512`:return`P-521`;default:throw Error(`unreachable`)}}function Br(e,t){if(t.length&&!t.some(t=>e.usages.includes(t))){let e=`CryptoKey does not support this operation, its usages must include `;if(t.length>2){let n=t.pop();e+=`one of ${t.join(`, `)}, or ${n}.`}else t.length===2?e+=`one of ${t[0]} or ${t[1]}.`:e+=`${t[0]}.`;throw TypeError(e)}}function Vr(e,t,...n){switch(t){case`HS256`:case`HS384`:case`HS512`:{if(!Lr(e.algorithm,`HMAC`))throw q(`HMAC`);let n=parseInt(t.slice(2),10);if(Rr(e.algorithm.hash)!==n)throw q(`SHA-${n}`,`algorithm.hash`);break}case`RS256`:case`RS384`:case`RS512`:{if(!Lr(e.algorithm,`RSASSA-PKCS1-v1_5`))throw q(`RSASSA-PKCS1-v1_5`);let n=parseInt(t.slice(2),10);if(Rr(e.algorithm.hash)!==n)throw q(`SHA-${n}`,`algorithm.hash`);break}case`PS256`:case`PS384`:case`PS512`:{if(!Lr(e.algorithm,`RSA-PSS`))throw q(`RSA-PSS`);let n=parseInt(t.slice(2),10);if(Rr(e.algorithm.hash)!==n)throw q(`SHA-${n}`,`algorithm.hash`);break}case`EdDSA`:if(e.algorithm.name!==`Ed25519`&&e.algorithm.name!==`Ed448`)throw q(`Ed25519 or Ed448`);break;case`Ed25519`:if(!Lr(e.algorithm,`Ed25519`))throw q(`Ed25519`);break;case`ES256`:case`ES384`:case`ES512`:{if(!Lr(e.algorithm,`ECDSA`))throw q(`ECDSA`);let n=zr(t);if(e.algorithm.namedCurve!==n)throw q(n,`algorithm.namedCurve`);break}default:throw TypeError(`CryptoKey does not support this operation`)}Br(e,n)}function Hr(e,t,...n){if(n=n.filter(Boolean),n.length>2){let t=n.pop();e+=`one of type ${n.join(`, `)}, or ${t}.`}else n.length===2?e+=`one of type ${n[0]} or ${n[1]}.`:e+=`of type ${n[0]}.`;return t==null?e+=` Received ${t}`:typeof t==`function`&&t.name?e+=` Received function ${t.name}`:typeof t==`object`&&t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var Ur=(e,...t)=>Hr(`Key must be `,e,...t);function Wr(e,t,...n){return Hr(`Key for the ${e} algorithm must be `,t,...n)}var Gr=e=>vr(e)?!0:e?.[Symbol.toStringTag]===`KeyObject`,Kr=[`CryptoKey`],qr=(...e)=>{let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let n;for(let e of t){let t=Object.keys(e);if(!n||n.size===0)n=new Set(t);else for(let e of t){if(n.has(e))return!1;n.add(e)}}return!0};function Jr(e){return typeof e==`object`&&!!e}function Yr(e){if(!Jr(e)||Object.prototype.toString.call(e)!==`[object Object]`)return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}var Xr=(e,t)=>{if(e.startsWith(`RS`)||e.startsWith(`PS`)){let{modulusLength:n}=t.algorithm;if(typeof n!=`number`||n<2048)throw TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}};function Zr(e){return Yr(e)&&typeof e.kty==`string`}function Qr(e){return e.kty!==`oct`&&typeof e.d==`string`}function $r(e){return e.kty!==`oct`&&e.d===void 0}function ei(e){return Zr(e)&&e.kty===`oct`&&typeof e.k==`string`}function ti(e){let t,n;switch(e.kty){case`RSA`:switch(e.alg){case`PS256`:case`PS384`:case`PS512`:t={name:`RSA-PSS`,hash:`SHA-${e.alg.slice(-3)}`},n=e.d?[`sign`]:[`verify`];break;case`RS256`:case`RS384`:case`RS512`:t={name:`RSASSA-PKCS1-v1_5`,hash:`SHA-${e.alg.slice(-3)}`},n=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}`},n=e.d?[`decrypt`,`unwrapKey`]:[`encrypt`,`wrapKey`];break;default:throw new G(`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`)}break;case`EC`:switch(e.alg){case`ES256`:t={name:`ECDSA`,namedCurve:`P-256`},n=e.d?[`sign`]:[`verify`];break;case`ES384`:t={name:`ECDSA`,namedCurve:`P-384`},n=e.d?[`sign`]:[`verify`];break;case`ES512`:t={name:`ECDSA`,namedCurve:`P-521`},n=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},n=e.d?[`deriveBits`]:[];break;default:throw new G(`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`)}break;case`OKP`:switch(e.alg){case`Ed25519`:t={name:`Ed25519`},n=e.d?[`sign`]:[`verify`];break;case`EdDSA`:t={name:e.crv},n=e.d?[`sign`]:[`verify`];break;case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:t={name:e.crv},n=e.d?[`deriveBits`]:[];break;default:throw new G(`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`)}break;default:throw new G(`Invalid or unsupported JWK "kty" (Key Type) Parameter value`)}return{algorithm:t,keyUsages:n}}var ni=async e=>{if(!e.alg)throw TypeError(`"alg" argument is required when "jwk.alg" is not present`);let{algorithm:t,keyUsages:n}=ti(e),r=[t,e.ext??!1,e.key_ops??n],i={...e};return delete i.alg,delete i.use,_r.subtle.importKey(`jwk`,i,...r)},ri=e=>wr(e),ii,ai,oi=e=>e?.[Symbol.toStringTag]===`KeyObject`,si=async(e,t,n,r,i=!1)=>{let a=e.get(t);if(a?.[r])return a[r];let o=await ni({...n,alg:r});return i&&Object.freeze(t),a?a[r]=o:e.set(t,{[r]:o}),o},ci={normalizePublicKey:(e,t)=>{if(oi(e)){let n=e.export({format:`jwk`});return delete n.d,delete n.dp,delete n.dq,delete n.p,delete n.q,delete n.qi,n.k?ri(n.k):(ai||=new WeakMap,si(ai,e,n,t))}return Zr(e)?e.k?wr(e.k):(ai||=new WeakMap,si(ai,e,e,t,!0)):e},normalizePrivateKey:(e,t)=>{if(oi(e)){let n=e.export({format:`jwk`});return n.k?ri(n.k):(ii||=new WeakMap,si(ii,e,n,t))}return Zr(e)?e.k?wr(e.k):(ii||=new WeakMap,si(ii,e,e,t,!0)):e}},li=(e,t,n=0)=>{n===0&&(t.unshift(t.length),t.unshift(6));let r=e.indexOf(t[0],n);if(r===-1)return!1;let i=e.subarray(r,r+t.length);return i.length===t.length?i.every((e,n)=>e===t[n])||li(e,t,r+1):!1},ui=e=>{switch(!0){case li(e,[42,134,72,206,61,3,1,7]):return`P-256`;case li(e,[43,129,4,0,34]):return`P-384`;case li(e,[43,129,4,0,35]):return`P-521`;case li(e,[43,101,110]):return`X25519`;case li(e,[43,101,111]):return`X448`;case li(e,[43,101,112]):return`Ed25519`;case li(e,[43,101,113]):return`Ed448`;default:throw new G(`Invalid or unsupported EC Key Curve or OKP Key Sub Type`)}},di=async(e,t,n,r,i)=>{let a,o,s=new Uint8Array(atob(n.replace(e,``)).split(``).map(e=>e.charCodeAt(0))),c=t===`spki`;switch(r){case`PS256`:case`PS384`:case`PS512`:a={name:`RSA-PSS`,hash:`SHA-${r.slice(-3)}`},o=c?[`verify`]:[`sign`];break;case`RS256`:case`RS384`:case`RS512`:a={name:`RSASSA-PKCS1-v1_5`,hash:`SHA-${r.slice(-3)}`},o=c?[`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(r.slice(-3),10)||1}`},o=c?[`encrypt`,`wrapKey`]:[`decrypt`,`unwrapKey`];break;case`ES256`:a={name:`ECDSA`,namedCurve:`P-256`},o=c?[`verify`]:[`sign`];break;case`ES384`:a={name:`ECDSA`,namedCurve:`P-384`},o=c?[`verify`]:[`sign`];break;case`ES512`:a={name:`ECDSA`,namedCurve:`P-521`},o=c?[`verify`]:[`sign`];break;case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:{let e=ui(s);a=e.startsWith(`P-`)?{name:`ECDH`,namedCurve:e}:{name:e},o=c?[]:[`deriveBits`];break}case`Ed25519`:a={name:`Ed25519`},o=c?[`verify`]:[`sign`];break;case`EdDSA`:a={name:ui(s)},o=c?[`verify`]:[`sign`];break;default:throw new G(`Invalid or unsupported "alg" (Algorithm) value`)}return _r.subtle.importKey(t,s,a,i?.extractable??!1,o)},fi=(e,t,n)=>di(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,`pkcs8`,e,t,n);async function pi(e,t,n){if(typeof e!=`string`||e.indexOf(`-----BEGIN PRIVATE KEY-----`)!==0)throw TypeError(`"pkcs8" must be PKCS#8 formatted string`);return fi(e,t,n)}async function mi(e,t){if(!Yr(e))throw TypeError(`JWK must be an object`);switch(t||=e.alg,e.kty){case`oct`:if(typeof e.k!=`string`||!e.k)throw TypeError(`missing "k" (Key Value) Parameter value`);return wr(e.k);case`RSA`:if(`oth`in e&&e.oth!==void 0)throw new G(`RSA JWK "oth" (Other Primes Info) Parameter value is not supported`);case`EC`:case`OKP`:return ni({...e,alg:t});default:throw new G(`Unsupported "kty" (Key Type) Parameter value`)}}var hi=e=>e?.[Symbol.toStringTag],gi=(e,t,n)=>{if(t.use!==void 0&&t.use!==`sig`)throw TypeError(`Invalid key for this operation, when present its use must be sig`);if(t.key_ops!==void 0&&t.key_ops.includes?.(n)!==!0)throw TypeError(`Invalid key for this operation, when present its key_ops must include ${n}`);if(t.alg!==void 0&&t.alg!==e)throw TypeError(`Invalid key for this operation, when present its alg must be ${e}`);return!0},_i=(e,t,n,r)=>{if(!(t instanceof Uint8Array)){if(r&&Zr(t)){if(ei(t)&&gi(e,t,n))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(!Gr(t))throw TypeError(Wr(e,t,...Kr,`Uint8Array`,r?`JSON Web Key`:null));if(t.type!==`secret`)throw TypeError(`${hi(t)} instances for symmetric algorithms must be of type "secret"`)}},vi=(e,t,n,r)=>{if(r&&Zr(t))switch(n){case`sign`:if(Qr(t)&&gi(e,t,n))return;throw TypeError(`JSON Web Key for this operation be a private JWK`);case`verify`:if($r(t)&&gi(e,t,n))return;throw TypeError(`JSON Web Key for this operation be a public JWK`)}if(!Gr(t))throw TypeError(Wr(e,t,...Kr,r?`JSON Web Key`:null));if(t.type===`secret`)throw TypeError(`${hi(t)} instances for asymmetric algorithms must not be of type "secret"`);if(n===`sign`&&t.type===`public`)throw TypeError(`${hi(t)} instances for asymmetric algorithm signing must be of type "private"`);if(n===`decrypt`&&t.type===`public`)throw TypeError(`${hi(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&n===`verify`&&t.type===`private`)throw TypeError(`${hi(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&n===`encrypt`&&t.type===`private`)throw TypeError(`${hi(t)} instances for asymmetric algorithm encryption must be of type "public"`)};function yi(e,t,n,r){t.startsWith(`HS`)||t===`dir`||t.startsWith(`PBES2`)||/^A\d{3}(?:GCM)?KW$/.test(t)?_i(t,n,r,e):vi(t,n,r,e)}yi.bind(void 0,!1);var bi=yi.bind(void 0,!0);function xi(e,t,n,r,i){if(i.crit!==void 0&&r?.crit===void 0)throw new e(`"crit" (Critical) Header Parameter MUST be integrity protected`);if(!r||r.crit===void 0)return new Set;if(!Array.isArray(r.crit)||r.crit.length===0||r.crit.some(e=>typeof e!=`string`||e.length===0))throw new e(`"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present`);let a;a=n===void 0?t:new Map([...Object.entries(n),...t.entries()]);for(let t of r.crit){if(!a.has(t))throw new G(`Extension Header Parameter "${t}" is not recognized`);if(i[t]===void 0)throw new e(`Extension Header Parameter "${t}" is missing`);if(a.get(t)&&r[t]===void 0)throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return new Set(r.crit)}var Si=(e,t)=>{if(t!==void 0&&(!Array.isArray(t)||t.some(e=>typeof e!=`string`)))throw TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)},Ci=async e=>{if(e instanceof Uint8Array)return{kty:`oct`,k:Sr(e)};if(!vr(e))throw TypeError(Ur(e,...Kr,`Uint8Array`));if(!e.extractable)throw TypeError(`non-extractable CryptoKey cannot be exported as a JWK`);let{ext:t,key_ops:n,alg:r,use:i,...a}=await _r.subtle.exportKey(`jwk`,e);return a};async function wi(e){return Ci(e)}function Ti(e,t){let n=`SHA-${e.slice(-3)}`;switch(e){case`HS256`:case`HS384`:case`HS512`:return{hash:n,name:`HMAC`};case`PS256`:case`PS384`:case`PS512`:return{hash:n,name:`RSA-PSS`,saltLength:e.slice(-3)>>3};case`RS256`:case`RS384`:case`RS512`:return{hash:n,name:`RSASSA-PKCS1-v1_5`};case`ES256`:case`ES384`:case`ES512`:return{hash:n,name:`ECDSA`,namedCurve:t.namedCurve};case`Ed25519`:return{name:`Ed25519`};case`EdDSA`:return{name:t.name};default:throw new G(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function Ei(e,t,n){if(n===`sign`&&(t=await ci.normalizePrivateKey(t,e)),n===`verify`&&(t=await ci.normalizePublicKey(t,e)),vr(t))return Vr(t,e,n),t;if(t instanceof Uint8Array){if(!e.startsWith(`HS`))throw TypeError(Ur(t,...Kr));return _r.subtle.importKey(`raw`,t,{hash:`SHA-${e.slice(-3)}`,name:`HMAC`},!1,[n])}throw TypeError(Ur(t,...Kr,`Uint8Array`,`JSON Web Key`))}var Di=async(e,t,n,r)=>{let i=await Ei(e,t,`verify`);Xr(e,i);let a=Ti(e,i.algorithm);try{return await _r.subtle.verify(a,i,n,r)}catch{return!1}};async function Oi(e,t,n){if(!Yr(e))throw new K(`Flattened JWS must be an object`);if(e.protected===void 0&&e.header===void 0)throw new K(`Flattened JWS must have either of the "protected" or "header" members`);if(e.protected!==void 0&&typeof e.protected!=`string`)throw new K(`JWS Protected Header incorrect type`);if(e.payload===void 0)throw new K(`JWS Payload missing`);if(typeof e.signature!=`string`)throw new K(`JWS Signature missing or incorrect type`);if(e.header!==void 0&&!Yr(e.header))throw new K(`JWS Unprotected Header incorrect type`);let r={};if(e.protected)try{let t=wr(e.protected);r=JSON.parse(yr.decode(t))}catch{throw new K(`JWS Protected Header is invalid`)}if(!qr(r,e.header))throw new K(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let i={...r,...e.header},a=xi(K,new Map([[`b64`,!0]]),n?.crit,r,i),o=!0;if(a.has(`b64`)&&(o=r.b64,typeof o!=`boolean`))throw new K(`The "b64" (base64url-encode payload) Header Parameter must be a boolean`);let{alg:s}=i;if(typeof s!=`string`||!s)throw new K(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);let c=n&&Si(`algorithms`,n.algorithms);if(c&&!c.has(s))throw new Dr(`"alg" (Algorithm) Header Parameter value not allowed`);if(o){if(typeof e.payload!=`string`)throw new K(`JWS Payload must be a string`)}else if(typeof e.payload!=`string`&&!(e.payload instanceof Uint8Array))throw new K(`JWS Payload must be a string or an Uint8Array instance`);let l=!1;typeof t==`function`?(t=await t(r,e),l=!0,bi(s,t,`verify`),Zr(t)&&(t=await mi(t,s))):bi(s,t,`verify`);let u=br(H.encode(e.protected??``),H.encode(`.`),typeof e.payload==`string`?H.encode(e.payload):e.payload),d;try{d=wr(e.signature)}catch{throw new K(`Failed to base64url decode the signature`)}if(!await Di(s,t,d,u))throw new Ir;let f;if(o)try{f=wr(e.payload)}catch{throw new K(`Failed to base64url decode the payload`)}else f=typeof e.payload==`string`?H.encode(e.payload):e.payload;let p={payload:f};return e.protected!==void 0&&(p.protectedHeader=r),e.header!==void 0&&(p.unprotectedHeader=e.header),l?{...p,key:t}:p}async function ki(e,t,n){if(e instanceof Uint8Array&&(e=yr.decode(e)),typeof e!=`string`)throw new K(`Compact JWS must be a string or Uint8Array`);let{0:r,1:i,2:a,length:o}=e.split(`.`);if(o!==3)throw new K(`Invalid Compact JWS`);let s=await Oi({payload:i,protected:r,signature:a},t,n),c={payload:s.payload,protectedHeader:s.protectedHeader};return typeof t==`function`?{...c,key:s.key}:c}var Ai=e=>Math.floor(e.getTime()/1e3),ji=60,Mi=3600,Ni=Mi*24,Pi=Ni*7,Fi=Ni*365.25,Ii=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,Li=e=>{let t=Ii.exec(e);if(!t||t[4]&&t[1])throw TypeError(`Invalid time period format`);let n=parseFloat(t[2]),r=t[3].toLowerCase(),i;switch(r){case`sec`:case`secs`:case`second`:case`seconds`:case`s`:i=Math.round(n);break;case`minute`:case`minutes`:case`min`:case`mins`:case`m`:i=Math.round(n*ji);break;case`hour`:case`hours`:case`hr`:case`hrs`:case`h`:i=Math.round(n*Mi);break;case`day`:case`days`:case`d`:i=Math.round(n*Ni);break;case`week`:case`weeks`:case`w`:i=Math.round(n*Pi);break;default:i=Math.round(n*Fi)}return t[1]===`-`||t[4]===`ago`?-i:i},Ri=e=>e.toLowerCase().replace(/^application\//,``),zi=(e,t)=>typeof e==`string`?t.includes(e):Array.isArray(e)?t.some(Set.prototype.has.bind(new Set(e))):!1,Bi=(e,t,n={})=>{let r;try{r=JSON.parse(yr.decode(t))}catch{}if(!Yr(r))throw new Ar(`JWT Claims Set must be a top-level JSON object`);let{typ:i}=n;if(i&&(typeof e.typ!=`string`||Ri(e.typ)!==Ri(i)))throw new W(`unexpected "typ" JWT header value`,r,`typ`,`check_failed`);let{requiredClaims:a=[],issuer:o,subject:s,audience:c,maxTokenAge:l}=n,u=[...a];l!==void 0&&u.push(`iat`),c!==void 0&&u.push(`aud`),s!==void 0&&u.push(`sub`),o!==void 0&&u.push(`iss`);for(let e of new Set(u.reverse()))if(!(e in r))throw new W(`missing required "${e}" claim`,r,e,`missing`);if(o&&!(Array.isArray(o)?o:[o]).includes(r.iss))throw new W(`unexpected "iss" claim value`,r,`iss`,`check_failed`);if(s&&r.sub!==s)throw new W(`unexpected "sub" claim value`,r,`sub`,`check_failed`);if(c&&!zi(r.aud,typeof c==`string`?[c]:c))throw new W(`unexpected "aud" claim value`,r,`aud`,`check_failed`);let d;switch(typeof n.clockTolerance){case`string`:d=Li(n.clockTolerance);break;case`number`:d=n.clockTolerance;break;case`undefined`:d=0;break;default:throw TypeError(`Invalid clockTolerance option type`)}let{currentDate:f}=n,p=Ai(f||new Date);if((r.iat!==void 0||l)&&typeof r.iat!=`number`)throw new W(`"iat" claim must be a number`,r,`iat`,`invalid`);if(r.nbf!==void 0){if(typeof r.nbf!=`number`)throw new W(`"nbf" claim must be a number`,r,`nbf`,`invalid`);if(r.nbf>p+d)throw new W(`"nbf" claim timestamp check failed`,r,`nbf`,`check_failed`)}if(r.exp!==void 0){if(typeof r.exp!=`number`)throw new W(`"exp" claim must be a number`,r,`exp`,`invalid`);if(r.exp<=p-d)throw new Er(`"exp" claim timestamp check failed`,r,`exp`,`check_failed`)}if(l){let e=p-r.iat,t=typeof l==`number`?l:Li(l);if(e-d>t)throw new Er(`"iat" claim timestamp check failed (too far in the past)`,r,`iat`,`check_failed`);if(e<0-d)throw new W(`"iat" claim timestamp check failed (it should be in the past)`,r,`iat`,`check_failed`)}return r};async function Vi(e,t,n){let r=await ki(e,t,n);if(r.protectedHeader.crit?.includes(`b64`)&&r.protectedHeader.b64===!1)throw new Ar(`JWTs MUST NOT use unencoded payload`);let i={payload:Bi(r.protectedHeader,r.payload,n),protectedHeader:r.protectedHeader};return typeof t==`function`?{...i,key:r.key}:i}var Hi=async(e,t,n)=>{let r=await Ei(e,t,`sign`);Xr(e,r);let i=await _r.subtle.sign(Ti(e,r.algorithm),r,n);return new Uint8Array(i)},Ui=class{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){if(!this._protectedHeader&&!this._unprotectedHeader)throw new K(`either setProtectedHeader or setUnprotectedHeader must be called before #sign()`);if(!qr(this._protectedHeader,this._unprotectedHeader))throw new K(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let n={...this._protectedHeader,...this._unprotectedHeader},r=xi(K,new Map([[`b64`,!0]]),t?.crit,this._protectedHeader,n),i=!0;if(r.has(`b64`)&&(i=this._protectedHeader.b64,typeof i!=`boolean`))throw new K(`The "b64" (base64url-encode payload) Header Parameter must be a boolean`);let{alg:a}=n;if(typeof a!=`string`||!a)throw new K(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);bi(a,e,`sign`);let o=this._payload;i&&(o=H.encode(Sr(o)));let s;s=this._protectedHeader?H.encode(Sr(JSON.stringify(this._protectedHeader))):H.encode(``);let c={signature:Sr(await Hi(a,e,br(s,H.encode(`.`),o))),payload:``};return i&&(c.payload=yr.decode(o)),this._unprotectedHeader&&(c.header=this._unprotectedHeader),this._protectedHeader&&(c.protected=yr.decode(s)),c}},Wi=class{constructor(e){this._flattened=new Ui(e)}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}async sign(e,t){let n=await this._flattened.sign(e,t);if(n.payload===void 0)throw TypeError(`use the flattened module for creating JWS with b64: false`);return`${n.protected}.${n.payload}.${n.signature}`}};function Gi(e,t){if(!Number.isFinite(t))throw TypeError(`Invalid ${e} input`);return t}var Ki=class{constructor(e={}){if(!Yr(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 this._payload=typeof e==`number`?{...this._payload,nbf:Gi(`setNotBefore`,e)}:e instanceof Date?{...this._payload,nbf:Gi(`setNotBefore`,Ai(e))}:{...this._payload,nbf:Ai(new Date)+Li(e)},this}setExpirationTime(e){return this._payload=typeof e==`number`?{...this._payload,exp:Gi(`setExpirationTime`,e)}:e instanceof Date?{...this._payload,exp:Gi(`setExpirationTime`,Ai(e))}:{...this._payload,exp:Ai(new Date)+Li(e)},this}setIssuedAt(e){return this._payload=e===void 0?{...this._payload,iat:Ai(new Date)}:e instanceof Date?{...this._payload,iat:Gi(`setIssuedAt`,Ai(e))}:typeof e==`string`?{...this._payload,iat:Gi(`setIssuedAt`,Ai(new Date)+Li(e))}:{...this._payload,iat:Gi(`setIssuedAt`,e)},this}},qi=class extends Ki{setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,t){let n=new Wi(H.encode(JSON.stringify(this._payload)));if(n.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes(`b64`)&&this._protectedHeader.b64===!1)throw new Ar(`JWTs MUST NOT use unencoded payload`);return n.sign(e,t)}};function Ji(e){let t=e?.modulusLength??2048;if(typeof t!=`number`||t<2048)throw new G(`Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used`);return t}async function Yi(e,t){let n,r;switch(e){case`PS256`:case`PS384`:case`PS512`:n={name:`RSA-PSS`,hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:Ji(t)},r=[`sign`,`verify`];break;case`RS256`:case`RS384`:case`RS512`:n={name:`RSASSA-PKCS1-v1_5`,hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:Ji(t)},r=[`sign`,`verify`];break;case`RSA-OAEP`:case`RSA-OAEP-256`:case`RSA-OAEP-384`:case`RSA-OAEP-512`:n={name:`RSA-OAEP`,hash:`SHA-${parseInt(e.slice(-3),10)||1}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:Ji(t)},r=[`decrypt`,`unwrapKey`,`encrypt`,`wrapKey`];break;case`ES256`:n={name:`ECDSA`,namedCurve:`P-256`},r=[`sign`,`verify`];break;case`ES384`:n={name:`ECDSA`,namedCurve:`P-384`},r=[`sign`,`verify`];break;case`ES512`:n={name:`ECDSA`,namedCurve:`P-521`},r=[`sign`,`verify`];break;case`Ed25519`:n={name:`Ed25519`},r=[`sign`,`verify`];break;case`EdDSA`:{r=[`sign`,`verify`];let e=t?.crv??`Ed25519`;switch(e){case`Ed25519`:case`Ed448`:n={name:e};break;default:throw new G(`Invalid or unsupported crv option provided`)}break}case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:{r=[`deriveKey`,`deriveBits`];let e=t?.crv??`P-256`;switch(e){case`P-256`:case`P-384`:case`P-521`:n={name:`ECDH`,namedCurve:e};break;case`X25519`:case`X448`:n={name:e};break;default:throw new G(`Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448`)}break}default:throw new G(`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`)}return _r.subtle.generateKey(n,t?.extractable??!1,r)}async function Xi(e,t){return Yi(e,t)}function Zi(e,t){if(e!=null&&t!=null&&e!==t)throw TypeError(`Expected "${t}", got "${e}"`);return e??t??void 0}var{JOSEError:Qi}=Tr,$i=class e extends ur{async getKeyObj(e){if(!this.algorithms.includes(e))throw new V(`Key cannot be used with algorithm "${e}"`);try{return await mi(this.jwk,e)}catch(e){throw new V(`Failed to import JWK`,void 0,{cause:e})}}async createJwt(e,t){try{let{kid:n}=e;if(n&&n!==this.kid)throw new pn(`Invalid "kid" (${n}) used to sign with key "${this.kid}"`);let{alg:r}=e;if(!r)throw new pn(`Missing "alg" in JWT header`);let i=await this.getKeyObj(r);return await new qi(t).setProtectedHeader({...e,alg:r,kid:this.kid}).sign(i)}catch(e){throw e instanceof Qi?new pn(e.message,e.code,{cause:e}):pn.from(e)}}async verifyJwt(e,t){try{let n=await Vi(e,async({alg:e})=>this.getKeyObj(e),{...t,algorithms:this.algorithms}),r=ir.safeParse(n.protectedHeader);if(!r.success)throw new mn(`Invalid JWT header`,void 0,{cause:r.error});let i=or.safeParse(n.payload);if(!i.success)throw new mn(`Invalid JWT payload`,void 0,{cause:i.error});return{protectedHeader:r.data,payload:i.data}}catch(e){throw e instanceof Qi?new mn(e.message,e.code,{cause:e}):mn.from(e)}}static async generateKeyPair(e=[`ES256`],t){if(!e.length)throw new V(`No algorithms provided for key generation`);let n=[];for(let r of e)try{return await Xi(r,t)}catch(e){n.push(e)}throw new V(`Failed to generate key pair`,void 0,{cause:AggregateError(n,`None of the algorithms worked`)})}static async generate(e=[`ES256`],t,n){let r=await this.generateKeyPair(e,{...n,extractable:!0});return this.fromKeyLike(r.privateKey,t)}static async fromImportable(e,t){if(typeof e==`string`){if(e.startsWith(`-----`))return this.fromPKCS8(e,``,t);if(e.startsWith(`{`))return this.fromJWK(e,t);throw new V(`Invalid input`)}if(typeof e==`object`)return`kty`in e||`alg`in e?this.fromJWK(e,t):this.fromKeyLike(e,t);throw new V(`Invalid input`)}static async fromKeyLike(e,t,n){let r=await wi(e);if(n){if(!r.alg)r.alg=n;else if(r.alg!==n)throw new V(`Invalid "alg" in JWK`)}return this.fromJWK(r,t)}static async fromPKCS8(e,t,n){let r=await pi(e,t,{extractable:!0});return this.fromKeyLike(r,n)}static async fromJWK(t,n){let r=typeof t==`string`?JSON.parse(t):t;if(!r||typeof r!=`object`)throw new V(`Invalid JWK`);let i=Zi(r.kid,n);return r.use!=null&&Jn(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??=r.use===`sig`?[`sign`]:[`encrypt`],delete r.use),new e(Un.parse({...r,kid:i}))}};function ea(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`:return`${e.name===`RSA-PSS`?`PS`:`RS`}${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`)}}case`Ed448`:case`Ed25519`:return`EdDSA`;default:throw TypeError(`Unexpected algorithm "${e.name}"`)}}function ta(e,t){return typeof e==`object`&&!!e&&`privateKey`in e&&e.privateKey instanceof CryptoKey&&e.privateKey.type===`private`&&(t==null||e.privateKey.extractable===t)&&e.privateKey.usages.includes(`sign`)&&`publicKey`in e&&e.publicKey instanceof CryptoKey&&e.publicKey.type===`public`&&e.publicKey.extractable===!0&&e.publicKey.usages.includes(`verify`)}var na=class e extends $i{static async generate(e=[`ES256`],t=crypto.randomUUID(),n){let r=await this.generateKeyPair(e,n);if(!ta(r))throw TypeError(`Invalid CryptoKeyPair`);return this.fromKeypair(r,t)}static async fromKeypair(t,n){let{alg:r=ea(t.privateKey.algorithm),...i}=await crypto.subtle.exportKey(`jwk`,t.privateKey.extractable?t.privateKey:t.publicKey);return new e(Un.parse({...i,kid:n,alg:r}),t)}constructor(e,t){if(!e.alg)throw new V(`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 V(`Key cannot be used with algorithm "${e}"`);return this.cryptoKeyPair.privateKey}},ra=e=>typeof e==`number`?e:void 0,ia=class e extends Error{constructor(e,t,n,r=400,i){super(t,{cause:i}),this.did=e,this.code=n,this.status=r}get statusCode(){return this.status}toString(){return`${this.constructor.name} ${this.code} (${this.did}): ${this.message}`}static from(t,n){if(t instanceof e)return t;let r=t instanceof Error?t.message:typeof t==`string`?t:`An unknown error occurred`,i=typeof t==`object`&&t?(`statusCode`in t?ra(t.statusCode):void 0)??(`status`in t?ra(t.status):void 0):void 0;return new e(n,r,`did-unknown-error`,i,t)}},J=class extends ia{constructor(e,t,n){super(e,t,`did-invalid`,400,n)}},aa=`did:`,oa=4;function sa(e,t=0,n=e.length){if(!Number.isFinite(n)||!Number.isFinite(t)||n<t||n>e.length)throw TypeError(`Invalid start or end position`);if(n===t)throw new J(e,`Empty method name`);let r;for(let i=t;i<n;i++)if(r=e.charCodeAt(i),(r<97||r>122)&&(r<48||r>57))throw new J(e,`Invalid character at position ${i} in DID method name`)}function ca(e){let t=e.indexOf(`:`,oa);return e.slice(oa,t)}function la(e,t=0,n=e.length){if(!Number.isFinite(n)||!Number.isFinite(t)||n<t||n>e.length)throw TypeError(`Invalid start or end position`);if(n===t)throw new J(e,`DID method-specific id must not be empty`);let r;for(let i=t;i<n;i++)if(r=e.charCodeAt(i),(r<97||r>122)&&(r<65||r>90)&&(r<48||r>57)&&r!==46&&r!==45&&r!==95){if(r===58){if(i===n-1)throw new J(e,`DID cannot end with ":"`);continue}if(r===37){if(r=e.charCodeAt(++i),(r<48||r>57)&&(r<65||r>70)||(r=e.charCodeAt(++i),(r<48||r>57)&&(r<65||r>70)))throw new J(e,`Invalid pct-encoded character at position ${i}`);if(i>=n)throw new J(e,`Incomplete pct-encoded character at position ${i-2}`);continue}throw new J(e,`Disallowed character in DID at position ${i}`)}}function ua(e){if(typeof e!=`string`)throw new J(typeof e,`DID must be a string`);let{length:t}=e;if(t>2048)throw new J(e,`DID is too long (2048 chars max)`);if(!e.startsWith(`did:`))throw new J(e,`DID requires "${aa}" prefix`);let n=e.indexOf(`:`,oa);if(n===-1)throw new J(e,`Missing colon after method name`);sa(e,oa,n),la(e,n+1,t)}var da=N().superRefine((e,t)=>{try{return ua(e),!0}catch(e){return t.addIssue({code:b.custom,message:e instanceof Error?e.message:`Unexpected error`}),!1}});function fa(e,t=0,n=e.length){let r;for(let i=t;i<n;i++)if(r=e.charCodeAt(i),!(r>=65&&r<=90||r>=97&&r<=122||r>=48&&r<=57||r===45||r===46||r===95||r===126)&&r!==33&&r!==36&&r!==38&&r!==39&&r!==40&&r!==41&&r!==42&&r!==43&&r!==44&&r!==59&&r!==61&&r!==58&&r!==64&&r!==47&&r!==63){if(r===37){if(i+2>=n||!pa(e.charCodeAt(i+1))||!pa(e.charCodeAt(i+2)))return!1;i+=2}else return!1}return!0}function pa(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}var ma=URL.canParse?.bind(URL)??((e,t)=>{try{return new URL(e,t),!0}catch{return!1}}),ha=8,ga=32;function _a(e){if(typeof e!=`string`||e.length!==ga||!e.startsWith(`did:plc:`))return!1;for(let t=ha;t<ga;t++)if(!ya(e.charCodeAt(t)))return!1;return!0}function va(e){if(typeof e!=`string`)throw new J(typeof e,`DID must be a string`);if(!e.startsWith(`did:plc:`))throw new J(e,`Invalid did:plc prefix`);if(e.length!==ga)throw new J(e,`did:plc must be ${ga} characters long`);for(let t=ha;t<ga;t++)if(!ya(e.charCodeAt(t)))throw new J(e,`Invalid character at position ${t}`)}var ya=e=>e>=97&&e<=122||e>=50&&e<=55,ba=`did:web:`;function xa(e){if(typeof e!=`string`||!e.startsWith(`did:web:`)||e.charAt(8)===`:`)return!1;try{la(e,ba.length)}catch{return!1}return ma(wa(e))}function Sa(e){if(typeof e!=`string`)throw new J(typeof e,`DID must be a string`);if(!e.startsWith(`did:web:`))throw new J(e,`Invalid did:web prefix`);if(e.charAt(8)===`:`)throw new J(e,`did:web MSID must not start with a colon`);if(la(e,ba.length),!ma(wa(e)))throw new J(e,`Invalid Web DID`)}function Ca(e){try{return new URL(wa(e))}catch(t){throw new J(e,`Invalid Web DID`,t)}}function wa(e){let t=ba.length,n=e.indexOf(`:`,t),r=(n===-1?e.slice(t):e.slice(t,n)).replaceAll(`%3A`,`:`),i=n===-1?``:e.slice(n).replaceAll(`:`,`/`);return`${r.startsWith(`localhost`)&&(r.length===9||r.charCodeAt(9)===58)?`http`:`https`}://${r}${i}`}function Ta(e,t,n){return n.charCodeAt(0)===35?n.length===t.length+1&&n.endsWith(t):n.length===t.length+1+e.length&&n.charCodeAt(e.length)===35&&n.startsWith(e)&&n.endsWith(t)}var Ea=N().refine(Da,`Atproto only allows "plc" and "web" DID methods`);function Da(e){return _a(e)||Aa(e)}function Oa(e){if(typeof e!=`string`)throw new J(typeof e,`DID must be a string`);if(e.startsWith(`did:plc:`))va(e);else if(e.startsWith(`did:web:`))ka(e);else throw new J(e,`Atproto only allows "plc" and "web" DID methods`)}function ka(e){if(Sa(e),ja(e))throw new J(e,`Atproto does not allow path components in Web DIDs`);if(Na(e))throw new J(e,`Atproto does not allow port numbers in Web DIDs, except for localhost`)}function Aa(e){return!(!xa(e)||ja(e)||Na(e))}function ja(e){return e.includes(`:`,ba.length)}function Ma(e){return e===`did:web:localhost`||e.startsWith(`did:web:localhost:`)||e.startsWith(`did:web:localhost%3A`)}function Na(e){if(Ma(e))return!1;let t=e.indexOf(`:`,ba.length);return t===-1?e.includes(`%3A`,ba.length):e.lastIndexOf(`%3A`,t)!==-1}function Pa(e){let t=e.service?.find(Fa,e);if(!t)throw new ia(e.id,`Document ${e.id} does not contain a (valid) #atproto_pds service URL`,`did-service-not-found`);return new URL(t.serviceEndpoint)}function Fa(e){return e?.type===`AtprotoPersonalDataServer`&&typeof e.serviceEndpoint==`string`&&ma(e.serviceEndpoint)&&Ta(this.id,`atproto_pds`,e.id)}Object.freeze([`EcdsaSecp256r1VerificationKey2019`,`EcdsaSecp256k1VerificationKey2019`,`Multikey`]);var Ia=N().url(`RFC3968 compliant URI`),La=R([da,I(da)]),Ra=R([Ia.refine(e=>{let t=e.indexOf(`#`);return t!==-1&&fa(e,t+1)},{message:`Missing or invalid fragment in RFC3968 URI`}),N().refine(e=>e.charCodeAt(0)===35,{message:`Fragment must start with #`}).refine(e=>fa(e,1),{message:`Invalid char in URI fragment`})]),za=L({id:Ra,type:N().min(1),controller:La,publicKeyJwk:an(N(),en()).optional(),publicKeyMultibase:N().optional()}),Ba=L({id:Ra,type:R([N(),I(N())]),serviceEndpoint:R([Ia,an(N(),Ia),I(R([Ia,an(N(),Ia)])).nonempty()])}),Va=R([Ra,za]),Ha=L({"@context":R([z(`https://www.w3.org/ns/did/v1`),I(N().url()).nonempty().refine(e=>e[0]===`https://www.w3.org/ns/did/v1`,{message:`First @context must be https://www.w3.org/ns/did/v1`})]).optional(),id:da,controller:La.optional(),alsoKnownAs:I(Ia).optional(),service:I(Ba).optional(),authentication:I(Va).optional(),verificationMethod:I(za).optional()}).superRefine(({id:e,service:t},n)=>{if(t){let r=new Set;for(let i=0;i<t.length;i++){let a=t[i],o=a.id.startsWith(`#`)?`${e}${a.id}`:a.id;r.has(o)?n.addIssue({code:b.custom,message:`Duplicate service id (${a.id}) found in the document`,path:[`service`,i,`id`]}):r.add(o)}}});function Ua(e,t=`Assertion failed`){if(!e)throw Error(t)}var Wa=()=>!0,Ga=()=>!1,Ka=class{#e=new Map;#t;#n;#r={};constructor(e,t,n={}){this.#t=e,this.#n=t,this.#r=n}async get(e,{signal:t,context:n,allowStale:r=!1,noCache:i=!1}={}){t?.throwIfAborted();let{isStale:a,deleteOnError:o}=this.#r,s=i?Ga:r||a==null?Wa:async t=>!await a(e,t),c;for(;c=this.#e.get(e);){try{let{isFresh:e,value:t}=await c;if(e||await s(t))return t}catch{}t?.throwIfAborted()}let l=Promise.resolve().then(async()=>{t?.throwIfAborted();let r=await this.getStored(e,{signal:t});return r!==void 0&&await s(r)?{isFresh:!1,value:r}:(t?.throwIfAborted(),Promise.resolve().then(async()=>{let a={signal:t,noCache:i,context:n};return this.#t.call(null,e,a,r)}).catch(async t=>{if(r!==void 0)try{await o?.(t,e,r)&&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(()=>{Ua(this.#e.get(e)===l,`Pending item for key "${e}" was replaced before it finished.`),this.#e.delete(e)});Ua(!this.#e.has(e),`Concurrent execution flow for key "${e}" should not exist.`),this.#e.set(e,l);let{value:u}=await l;return u}async getStored(e,t){return this.#n.get(e,t)}async setStored(e,t){await this.#n.set(e,t)}async delStored(e,t){await this.#n.del(e)}},qa=(e,t)=>{console.error(`SimpleStore error during "${t}"`,e)};function Ja(e,t=qa){return{async get(n,r){r?.signal?.throwIfAborted();try{return await e.get(n,r)}catch(e){if(r?.signal?.aborted)throw e;t(e,`get`,n);return}},async set(n,r){try{await e.set(n,r)}catch(e){t(e,`set`,n)}},async del(n){try{await e.del(n)}catch(e){t(e,`del`,n)}},async clear(){try{await e.clear?.()}catch(e){t(e,`clear`)}}}}var Ya=typeof performance==`object`&&performance&&typeof performance.now==`function`?performance:Date,Xa=new Set,Za=typeof process==`object`&&process?process:{},Qa=(e,t,n,r)=>{typeof Za.emitWarning==`function`?Za.emitWarning(e,t,n,r):console.error(`[${n}] ${t}: ${e}`)},$a=globalThis.AbortController,eo=globalThis.AbortSignal;if($a===void 0){eo=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(e,t){this._onabort.push(t)}},$a=class{constructor(){t()}signal=new eo;abort(e){if(!this.signal.aborted){this.signal.reason=e,this.signal.aborted=!0;for(let t of this.signal._onabort)t(e);this.signal.onabort?.(e)}}};let e=Za.env?.LRU_CACHE_IGNORE_AC_WARNING!==`1`,t=()=>{e&&(e=!1,Qa("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))}}var to=e=>!Xa.has(e),no=e=>e&&e===Math.floor(e)&&e>0&&isFinite(e),ro=e=>no(e)?e<=256?Uint8Array:e<=2**16?Uint16Array:e<=2**32?Uint32Array:e<=2**53-1?io:null:null,io=class extends Array{constructor(e){super(e),this.fill(0)}},ao=class e{heap;length;static#e=!1;static create(t){let n=ro(t);if(!n)return[];e.#e=!0;let r=new e(t,n);return e.#e=!1,r}constructor(t,n){if(!e.#e)throw TypeError(`instantiate Stack using Stack.create(n)`);this.heap=new n(t),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},oo=class e{#e;#t;#n;#r;#i;#a;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;#x;#S;static unsafeExposeInternals(e){return{starts:e.#v,ttls:e.#y,sizes:e.#_,keyMap:e.#c,keyList:e.#l,valList:e.#u,next:e.#d,prev:e.#f,get head(){return e.#p},get tail(){return e.#m},free:e.#h,isBackgroundFetch:t=>e.#L(t),backgroundFetch:(t,n,r,i)=>e.#I(t,n,r,i),moveToTail:t=>e.#z(t),indexes:t=>e.#M(t),rindexes:t=>e.#N(t),isStale:t=>e.#D(t)}}get max(){return this.#e}get maxSize(){return this.#t}get calculatedSize(){return this.#s}get size(){return this.#o}get fetchMethod(){return this.#i}get memoMethod(){return this.#a}get dispose(){return this.#n}get disposeAfter(){return this.#r}constructor(t){let{max:n=0,ttl:r,ttlResolution:i=1,ttlAutopurge:a,updateAgeOnGet:o,updateAgeOnHas:s,allowStale:c,dispose:l,disposeAfter:u,noDisposeOnSet:d,noUpdateTTL:f,maxSize:p=0,maxEntrySize:m=0,sizeCalculation:h,fetchMethod:g,memoMethod:ee,noDeleteOnFetchRejection:te,noDeleteOnStaleGet:_,allowStaleOnFetchRejection:ne,allowStaleOnFetchAbort:re,ignoreFetchAbort:ie}=t;if(n!==0&&!no(n))throw TypeError(`max option must be a nonnegative integer`);let ae=n?ro(n):Array;if(!ae)throw Error(`invalid max value: `+n);if(this.#e=n,this.#t=p,this.maxEntrySize=m||this.#t,this.sizeCalculation=h,this.sizeCalculation){if(!this.#t&&!this.maxEntrySize)throw TypeError(`cannot set sizeCalculation without setting maxSize or maxEntrySize`);if(typeof this.sizeCalculation!=`function`)throw TypeError(`sizeCalculation set to non-function`)}if(ee!==void 0&&typeof ee!=`function`)throw TypeError(`memoMethod must be a function if defined`);if(this.#a=ee,g!==void 0&&typeof g!=`function`)throw TypeError(`fetchMethod must be a function if specified`);if(this.#i=g,this.#x=!!g,this.#c=new Map,this.#l=Array(n).fill(void 0),this.#u=Array(n).fill(void 0),this.#d=new ae(n),this.#f=new ae(n),this.#p=0,this.#m=0,this.#h=ao.create(n),this.#o=0,this.#s=0,typeof l==`function`&&(this.#n=l),typeof u==`function`?(this.#r=u,this.#g=[]):(this.#r=void 0,this.#g=void 0),this.#b=!!this.#n,this.#S=!!this.#r,this.noDisposeOnSet=!!d,this.noUpdateTTL=!!f,this.noDeleteOnFetchRejection=!!te,this.allowStaleOnFetchRejection=!!ne,this.allowStaleOnFetchAbort=!!re,this.ignoreFetchAbort=!!ie,this.maxEntrySize!==0){if(this.#t!==0&&!no(this.#t))throw TypeError(`maxSize must be a positive integer if specified`);if(!no(this.maxEntrySize))throw TypeError(`maxEntrySize must be a positive integer if specified`);this.#O()}if(this.allowStale=!!c,this.noDeleteOnStaleGet=!!_,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!s,this.ttlResolution=no(i)||i===0?i:1,this.ttlAutopurge=!!a,this.ttl=r||0,this.ttl){if(!no(this.ttl))throw TypeError(`ttl must be a positive integer if specified`);this.#C()}if(this.#e===0&&this.ttl===0&&this.#t===0)throw TypeError(`At least one of max, maxSize, or ttl is required`);if(!this.ttlAutopurge&&!this.#e&&!this.#t){let t=`LRU_CACHE_UNBOUNDED`;to(t)&&(Xa.add(t),Qa(`TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.`,`UnboundedCacheWarning`,t,e))}}getRemainingTTL(e){return this.#c.has(e)?1/0:0}#C(){let e=new io(this.#e),t=new io(this.#e);this.#y=e,this.#v=t,this.#E=(n,r,i=Ya.now())=>{if(t[n]=r===0?0:i,e[n]=r,r!==0&&this.ttlAutopurge){let e=setTimeout(()=>{this.#D(n)&&this.#B(this.#l[n],`expire`)},r+1);e.unref&&e.unref()}},this.#w=n=>{t[n]=e[n]===0?0:Ya.now()},this.#T=(i,a)=>{if(e[a]){let o=e[a],s=t[a];if(!o||!s)return;i.ttl=o,i.start=s,i.now=n||r(),i.remainingTTL=o-(i.now-s)}};let n=0,r=()=>{let e=Ya.now();if(this.ttlResolution>0){n=e;let t=setTimeout(()=>n=0,this.ttlResolution);t.unref&&t.unref()}return e};this.getRemainingTTL=i=>{let a=this.#c.get(i);if(a===void 0)return 0;let o=e[a],s=t[a];return!o||!s?1/0:o-((n||r())-s)},this.#D=i=>{let a=t[i],o=e[i];return!!o&&!!a&&(n||r())-a>o}}#w=()=>{};#T=()=>{};#E=()=>{};#D=()=>!1;#O(){let e=new io(this.#e);this.#s=0,this.#_=e,this.#k=t=>{this.#s-=e[t],e[t]=0},this.#j=(e,t,n,r)=>{if(this.#L(t))return 0;if(!no(n)){if(r){if(typeof r!=`function`)throw TypeError(`sizeCalculation must be a function`);if(n=r(t,e),!no(n))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 n},this.#A=(t,n,r)=>{if(e[t]=n,this.#t){let n=this.#t-e[t];for(;this.#s>n;)this.#F(!0)}this.#s+=e[t],r&&(r.entrySize=n,r.totalCalculatedSize=this.#s)}}#k=e=>{};#A=(e,t,n)=>{};#j=(e,t,n,r)=>{if(n||r)throw TypeError(`cannot set size without setting maxSize or maxEntrySize on cache`);return 0};*#M({allowStale:e=this.allowStale}={}){if(this.#o)for(let t=this.#m;!(!this.#P(t)||((e||!this.#D(t))&&(yield t),t===this.#p));)t=this.#f[t]}*#N({allowStale:e=this.allowStale}={}){if(this.#o)for(let t=this.#p;!(!this.#P(t)||((e||!this.#D(t))&&(yield t),t===this.#m));)t=this.#d[t]}#P(e){return e!==void 0&&this.#c.get(this.#l[e])===e}*entries(){for(let e of this.#M())this.#u[e]!==void 0&&this.#l[e]!==void 0&&!this.#L(this.#u[e])&&(yield[this.#l[e],this.#u[e]])}*rentries(){for(let e of this.#N())this.#u[e]!==void 0&&this.#l[e]!==void 0&&!this.#L(this.#u[e])&&(yield[this.#l[e],this.#u[e]])}*keys(){for(let e of this.#M()){let t=this.#l[e];t!==void 0&&!this.#L(this.#u[e])&&(yield t)}}*rkeys(){for(let e of this.#N()){let t=this.#l[e];t!==void 0&&!this.#L(this.#u[e])&&(yield t)}}*values(){for(let e of this.#M())this.#u[e]!==void 0&&!this.#L(this.#u[e])&&(yield this.#u[e])}*rvalues(){for(let e of this.#N())this.#u[e]!==void 0&&!this.#L(this.#u[e])&&(yield this.#u[e])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]=`LRUCache`;find(e,t={}){for(let n of this.#M()){let r=this.#u[n],i=this.#L(r)?r.__staleWhileFetching:r;if(i!==void 0&&e(i,this.#l[n],this))return this.get(this.#l[n],t)}}forEach(e,t=this){for(let n of this.#M()){let r=this.#u[n],i=this.#L(r)?r.__staleWhileFetching:r;i!==void 0&&e.call(t,i,this.#l[n],this)}}rforEach(e,t=this){for(let n of this.#N()){let r=this.#u[n],i=this.#L(r)?r.__staleWhileFetching:r;i!==void 0&&e.call(t,i,this.#l[n],this)}}purgeStale(){let e=!1;for(let t of this.#N({allowStale:!0}))this.#D(t)&&(this.#B(this.#l[t],`expire`),e=!0);return e}info(e){let t=this.#c.get(e);if(t===void 0)return;let n=this.#u[t],r=this.#L(n)?n.__staleWhileFetching:n;if(r===void 0)return;let i={value:r};if(this.#y&&this.#v){let e=this.#y[t],n=this.#v[t];e&&n&&(i.ttl=e-(Ya.now()-n),i.start=Date.now())}return this.#_&&(i.size=this.#_[t]),i}dump(){let e=[];for(let t of this.#M({allowStale:!0})){let n=this.#l[t],r=this.#u[t],i=this.#L(r)?r.__staleWhileFetching:r;if(i===void 0||n===void 0)continue;let a={value:i};if(this.#y&&this.#v){a.ttl=this.#y[t];let e=Ya.now()-this.#v[t];a.start=Math.floor(Date.now()-e)}this.#_&&(a.size=this.#_[t]),e.unshift([n,a])}return e}load(e){this.clear();for(let[t,n]of e){if(n.start){let e=Date.now()-n.start;n.start=Ya.now()-e}this.set(t,n.value,n)}}set(e,t,n={}){if(t===void 0)return this.delete(e),this;let{ttl:r=this.ttl,start:i,noDisposeOnSet:a=this.noDisposeOnSet,sizeCalculation:o=this.sizeCalculation,status:s}=n,{noUpdateTTL:c=this.noUpdateTTL}=n,l=this.#j(e,t,n.size||0,o);if(this.maxEntrySize&&l>this.maxEntrySize)return s&&(s.set=`miss`,s.maxEntrySizeExceeded=!0),this.#B(e,`set`),this;let u=this.#o===0?void 0:this.#c.get(e);if(u===void 0)u=this.#o===0?this.#m:this.#h.length===0?this.#o===this.#e?this.#F(!1):this.#o:this.#h.pop(),this.#l[u]=e,this.#u[u]=t,this.#c.set(e,u),this.#d[this.#m]=u,this.#f[u]=this.#m,this.#m=u,this.#o++,this.#A(u,l,s),s&&(s.set=`add`),c=!1;else{this.#z(u);let n=this.#u[u];if(t!==n){if(this.#x&&this.#L(n)){n.__abortController.abort(Error(`replaced`));let{__staleWhileFetching:t}=n;t!==void 0&&!a&&(this.#b&&this.#n?.(t,e,`set`),this.#S&&this.#g?.push([t,e,`set`]))}else a||(this.#b&&this.#n?.(n,e,`set`),this.#S&&this.#g?.push([n,e,`set`]));if(this.#k(u),this.#A(u,l,s),this.#u[u]=t,s){s.set=`replace`;let e=n&&this.#L(n)?n.__staleWhileFetching:n;e!==void 0&&(s.oldValue=e)}}else s&&(s.set=`update`)}if(r!==0&&!this.#y&&this.#C(),this.#y&&(c||this.#E(u,r,i),s&&this.#T(s,u)),!a&&this.#S&&this.#g){let e=this.#g,t;for(;t=e?.shift();)this.#r?.(...t)}return this}pop(){try{for(;this.#o;){let e=this.#u[this.#p];if(this.#F(!0),this.#L(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#S&&this.#g){let e=this.#g,t;for(;t=e?.shift();)this.#r?.(...t)}}}#F(e){let t=this.#p,n=this.#l[t],r=this.#u[t];return this.#x&&this.#L(r)?r.__abortController.abort(Error(`evicted`)):(this.#b||this.#S)&&(this.#b&&this.#n?.(r,n,`evict`),this.#S&&this.#g?.push([r,n,`evict`])),this.#k(t),e&&(this.#l[t]=void 0,this.#u[t]=void 0,this.#h.push(t)),this.#o===1?(this.#p=this.#m=0,this.#h.length=0):this.#p=this.#d[t],this.#c.delete(n),this.#o--,t}has(e,t={}){let{updateAgeOnHas:n=this.updateAgeOnHas,status:r}=t,i=this.#c.get(e);if(i!==void 0){let e=this.#u[i];if(this.#L(e)&&e.__staleWhileFetching===void 0)return!1;if(this.#D(i))r&&(r.has=`stale`,this.#T(r,i));else return n&&this.#w(i),r&&(r.has=`hit`,this.#T(r,i)),!0}else r&&(r.has=`miss`);return!1}peek(e,t={}){let{allowStale:n=this.allowStale}=t,r=this.#c.get(e);if(r===void 0||!n&&this.#D(r))return;let i=this.#u[r];return this.#L(i)?i.__staleWhileFetching:i}#I(e,t,n,r){let i=t===void 0?void 0:this.#u[t];if(this.#L(i))return i;let a=new $a,{signal:o}=n;o?.addEventListener(`abort`,()=>a.abort(o.reason),{signal:a.signal});let s={signal:a.signal,options:n,context:r},c=(r,i=!1)=>{let{aborted:o}=a.signal,c=n.ignoreFetchAbort&&r!==void 0;if(n.status&&(o&&!i?(n.status.fetchAborted=!0,n.status.fetchError=a.signal.reason,c&&(n.status.fetchAbortIgnored=!0)):n.status.fetchResolved=!0),o&&!c&&!i)return u(a.signal.reason);let l=f;return this.#u[t]===f&&(r===void 0?l.__staleWhileFetching?this.#u[t]=l.__staleWhileFetching:this.#B(e,`fetch`):(n.status&&(n.status.fetchUpdated=!0),this.set(e,r,s.options))),r},l=e=>(n.status&&(n.status.fetchRejected=!0,n.status.fetchError=e),u(e)),u=r=>{let{aborted:i}=a.signal,o=i&&n.allowStaleOnFetchAbort,s=o||n.allowStaleOnFetchRejection,c=s||n.noDeleteOnFetchRejection,l=f;if(this.#u[t]===f&&(!c||l.__staleWhileFetching===void 0?this.#B(e,`fetch`):o||(this.#u[t]=l.__staleWhileFetching)),s)return n.status&&l.__staleWhileFetching!==void 0&&(n.status.returnedStale=!0),l.__staleWhileFetching;if(l.__returned===l)throw r},d=(t,r)=>{let o=this.#i?.(e,i,s);o&&o instanceof Promise&&o.then(e=>t(e===void 0?void 0:e),r),a.signal.addEventListener(`abort`,()=>{(!n.ignoreFetchAbort||n.allowStaleOnFetchAbort)&&(t(void 0),n.allowStaleOnFetchAbort&&(t=e=>c(e,!0)))})};n.status&&(n.status.fetchDispatched=!0);let f=new Promise(d).then(c,l),p=Object.assign(f,{__abortController:a,__staleWhileFetching:i,__returned:void 0});return t===void 0?(this.set(e,p,{...s.options,status:void 0}),t=this.#c.get(e)):this.#u[t]=p,p}#L(e){if(!this.#x)return!1;let t=e;return!!t&&t instanceof Promise&&t.hasOwnProperty(`__staleWhileFetching`)&&t.__abortController instanceof $a}async fetch(e,t={}){let{allowStale:n=this.allowStale,updateAgeOnGet:r=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,ttl:a=this.ttl,noDisposeOnSet:o=this.noDisposeOnSet,size:s=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:l=this.noUpdateTTL,noDeleteOnFetchRejection:u=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:d=this.allowStaleOnFetchRejection,ignoreFetchAbort:f=this.ignoreFetchAbort,allowStaleOnFetchAbort:p=this.allowStaleOnFetchAbort,context:m,forceRefresh:h=!1,status:g,signal:ee}=t;if(!this.#x)return g&&(g.fetch=`get`),this.get(e,{allowStale:n,updateAgeOnGet:r,noDeleteOnStaleGet:i,status:g});let te={allowStale:n,updateAgeOnGet:r,noDeleteOnStaleGet:i,ttl:a,noDisposeOnSet:o,size:s,sizeCalculation:c,noUpdateTTL:l,noDeleteOnFetchRejection:u,allowStaleOnFetchRejection:d,allowStaleOnFetchAbort:p,ignoreFetchAbort:f,status:g,signal:ee},_=this.#c.get(e);if(_===void 0){g&&(g.fetch=`miss`);let t=this.#I(e,_,te,m);return t.__returned=t}{let t=this.#u[_];if(this.#L(t)){let e=n&&t.__staleWhileFetching!==void 0;return g&&(g.fetch=`inflight`,e&&(g.returnedStale=!0)),e?t.__staleWhileFetching:t.__returned=t}let i=this.#D(_);if(!h&&!i)return g&&(g.fetch=`hit`),this.#z(_),r&&this.#w(_),g&&this.#T(g,_),t;let a=this.#I(e,_,te,m),o=a.__staleWhileFetching!==void 0&&n;return g&&(g.fetch=i?`stale`:`refresh`,o&&i&&(g.returnedStale=!0)),o?a.__staleWhileFetching:a.__returned=a}}async forceFetch(e,t={}){let n=await this.fetch(e,t);if(n===void 0)throw Error(`fetch() returned undefined`);return n}memo(e,t={}){let n=this.#a;if(!n)throw Error(`no memoMethod provided to constructor`);let{context:r,forceRefresh:i,...a}=t,o=this.get(e,a);if(!i&&o!==void 0)return o;let s=n(e,o,{options:a,context:r});return this.set(e,s,a),s}get(e,t={}){let{allowStale:n=this.allowStale,updateAgeOnGet:r=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,status:a}=t,o=this.#c.get(e);if(o!==void 0){let t=this.#u[o],s=this.#L(t);return a&&this.#T(a,o),this.#D(o)?(a&&(a.get=`stale`),s?(a&&n&&t.__staleWhileFetching!==void 0&&(a.returnedStale=!0),n?t.__staleWhileFetching:void 0):(i||this.#B(e,`expire`),a&&n&&(a.returnedStale=!0),n?t:void 0)):(a&&(a.get=`hit`),s?t.__staleWhileFetching:(this.#z(o),r&&this.#w(o),t))}a&&(a.get=`miss`)}#R(e,t){this.#f[t]=e,this.#d[e]=t}#z(e){e!==this.#m&&(e===this.#p?this.#p=this.#d[e]:this.#R(this.#f[e],this.#d[e]),this.#R(this.#m,e),this.#m=e)}delete(e){return this.#B(e,`delete`)}#B(e,t){let n=!1;if(this.#o!==0){let r=this.#c.get(e);if(r!==void 0){if(n=!0,this.#o===1)this.#V(t);else{this.#k(r);let n=this.#u[r];if(this.#L(n)?n.__abortController.abort(Error(`deleted`)):(this.#b||this.#S)&&(this.#b&&this.#n?.(n,e,t),this.#S&&this.#g?.push([n,e,t])),this.#c.delete(e),this.#l[r]=void 0,this.#u[r]=void 0,r===this.#m)this.#m=this.#f[r];else if(r===this.#p)this.#p=this.#d[r];else{let e=this.#f[r];this.#d[e]=this.#d[r];let t=this.#d[r];this.#f[t]=this.#f[r]}this.#o--,this.#h.push(r)}}}if(this.#S&&this.#g?.length){let e=this.#g,t;for(;t=e?.shift();)this.#r?.(...t)}return n}clear(){return this.#V(`delete`)}#V(e){for(let t of this.#N({allowStale:!0})){let n=this.#u[t];if(this.#L(n))n.__abortController.abort(Error(`deleted`));else{let r=this.#l[t];this.#b&&this.#n?.(n,r,e),this.#S&&this.#g?.push([n,r,e])}}if(this.#c.clear(),this.#u.fill(void 0),this.#l.fill(void 0),this.#y&&this.#v&&(this.#y.fill(0),this.#v.fill(0)),this.#_&&this.#_.fill(0),this.#p=0,this.#m=0,this.#h.length=0,this.#s=0,this.#o=0,this.#S&&this.#g){let e=this.#g,t;for(;t=e?.shift();)this.#r?.(...t)}}},so=new WeakMap;function co(e){let t=new Set,n=[e],r=0;for(;n.length;){let e=n.pop();switch(typeof e){case`string`:r+=12+4*Math.ceil(e.length/4);break;case`number`:r+=12;break;case`boolean`:r+=4;break;case`object`:if(r+=4,e===null)break;if(so.has(e)){r+=so.get(e);break}if(t.has(e))continue;if(t.add(e),Array.isArray(e))r+=4,n.push(...e);else{r+=8;let t=Object.getOwnPropertyNames(e);for(let i=0;i<t.length;i++){r+=4;let a=t[i],o=e[a];o!==void 0&&n.push(o),n.push(a)}}break;case`function`:r+=8;break;case`symbol`:r+=8;break;case`bigint`:r+=16}}return typeof e==`object`&&e&&so.set(e,r),r}var lo=Symbol(`nullItem`),uo=e=>e===null?lo:e,fo=e=>e===lo?null:e,po=class{#e;constructor({sizeCalculation:e,...t}){this.#e=new oo({...t,allowStale:!1,updateAgeOnGet:!1,updateAgeOnHas:!1,sizeCalculation:e?(t,n)=>e(fo(t),n):t.maxEntrySize!=null||t.maxSize!=null?co:void 0})}get(e){let t=this.#e.get(e);if(t!==void 0)return fo(t)}set(e,t){this.#e.set(e,uo(t))}del(e){this.#e.delete(e)}clear(){this.#e.clear()}},mo=36e5,ho=52428800,go=class extends po{constructor(e){super(e?.max==null?{ttl:mo,maxSize:ho,...e}:{ttl:mo,...e})}},_o=class{constructor(e,t=new go,n){this.getter=new Ka((t,n)=>e.resolve(t,n),Ja(t,n))}async resolve(e,t){return this.getter.get(e,t)}},vo=class extends Error{constructor(e,t,n){super(t,n),this.statusCode=e}get expose(){return!0}};function yo(e){return function(t,n){return e.call(this,bo(t,n))}}function bo(e,t){return!t&&e instanceof Request?e:new Request(e,t)}var xo=e=>typeof e==`string`?e:void 0;TransformStream;async function So(e,t){e.body&&!e.bodyUsed&&!e.body.locked&&typeof e.body.cancel==`function`&&(typeof t==`function`?e.body.cancel().catch(t):t===`log`?e.body.cancel().catch(Co):await e.body.cancel())}function Co(e){console.warn(`Failed to cancel response body`,e)}var wo=class e extends vo{constructor(e,t,n,r){if(t==null||!n){let e=Eo(To(r?.cause));t??=e[0],n||=e[1]}super(t,n,r),this.request=e}get expose(){return this.statusCode!==500}static from(t,n){return n instanceof e?n:new e(t,void 0,void 0,{cause:n})}};function To(e){return e instanceof TypeError&&e.message===`fetch failed`&&e.cause!==void 0?e.cause:e}function Eo(e){if(typeof e==`string`&&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(typeof t==`string`)switch(!0){case t===`ENOTFOUND`:return[400,`Invalid hostname`];case t===`ECONNREFUSED`:return[502,`Connection refused`];case t===`DEPTH_ZERO_SELF_SIGNED_CERT`: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]}Object.freeze([`example.com`,`*.example.com`,`example.org`,`*.example.org`,`example.net`,`*.example.net`,`googleusercontent.com`,`*.googleusercontent.com`]);function Do(...e){return e.reduce(Oo)}function Oo(e,t){return async(...n)=>t(await e(...n))}var ko=/^application\/(?:[^()<>@,;:/[\]\\?={} \t]+\+)?json$/i,Y=class e extends vo{constructor(e,t=e.status,n=e.statusText,r){super(t,n,r),this.response=e}static async from(t,n=Ao,r=t.status,i){let a=typeof n==`string`?n:typeof n==`function`?await n(t):void 0;return new e(t,r,a,i)}},Ao=async e=>{let t=Fo(e);if(t)try{if(t===`text/plain`)return await e.text();if(ko.test(t)){let t=await e.json();if(typeof t==`string`)return t;if(typeof t==`object`&&t){if(`error_description`in t){let e=xo(t.error_description);if(e)return e}if(`error`in t){let e=xo(t.error);if(e)return e}if(`message`in t){let e=xo(t.message);if(e)return e}}}}catch{}};async function jo(e,t=1/0){if(Fo(e)!==`application/json`)return;No(e,t);let n=e.clone();if(!n.body||t===1/0)return n.json();let r=await Mo(n.body,t);if(!r)throw new Y(e,502,`Response too large`);return JSON.parse(new TextDecoder().decode(r))}async function Mo(e,t){let n=e.getReader(),r=[],i=0;for(let e=await n.read();!e.done;e=await n.read()){if(i+=e.value.byteLength,i>t)return n.cancel().catch(Co),null;r.push(e.value)}if(r.length===1)return r[0];let a=new Uint8Array(i),o=0;for(let e of r)a.set(e,o),o+=e.byteLength;return a}function No(e,t){if(!(t>=0))throw TypeError(`maxBytes must be a non-negative number`);let n=Po(e);if(n!=null&&n>t)throw new Y(e,502,`Response too large`);return n}function Po(e){let t=e.headers.get(`Content-Length`);if(t==null)return;if(!/^\d+$/.test(t))throw new Y(e,502,`Invalid Content-Length`);let n=Number(t);if(!Number.isSafeInteger(n))throw new Y(e,502,`Content-Length too large`);return n}function Fo(e){let t=e.headers.get(`Content-Type`);if(t!=null)return t.split(`;`,1)[0].trim()}function Io(e,t=Co){return async n=>{try{return await e(n)}catch(e){throw await So(n,t??void 0),e}}}function Lo(e){return Io(t=>Ro(t,e))}async function Ro(e,t){if(e.ok)return e;throw await Y.from(e,t)}function zo(e,t=!0){let n=typeof e==`string`?t=>t===e:e instanceof RegExp?t=>e.test(t):e;return Io(e=>Bo(e,n,t))}async function Bo(e,t,n=!0){let r=Fo(e);if(r){if(!t(r.toLowerCase()))throw await Y.from(e,`Unexpected response Content-Type (${r})`,502)}else if(n)throw await Y.from(e,`Missing response Content-Type header`,502);return e}async function Vo(e){try{return{response:e,json:await e.json()}}catch(t){throw new Y(e,502,`Unable to parse response as JSON`,{cause:t})}}function Ho(e=ko,t=!0){return Do(zo(e,t),Io(Vo))}function Uo(e,t){if(`parseAsync`in e&&typeof e.parseAsync==`function`)return async n=>e.parseAsync(n.json,t);if(`parse`in e&&typeof e.parse==`function`)return async n=>e.parse(n.json,t);throw TypeError(`Invalid schema`)}var Wo=Uo;function Go(e=globalThis.fetch,t=globalThis){return yo(async n=>{try{return await e.call(t,n)}catch(e){throw wo.from(n,e)}})}var Ko=class{constructor(e){this.methods=new Map(Object.entries(e))}async resolve(e,t){t?.signal?.throwIfAborted();let n=ca(e),r=this.methods.get(n);if(!r)throw new ia(e,`Unsupported DID method`,`did-method-invalid`,400);try{let n=await r.resolve(e,t);if(n.id!==e)throw new ia(e,`DID document id (${n.id}) does not match DID`,`did-document-id-mismatch`,400);return n}catch(t){if(t instanceof Y){let n=t.response.status>=500?502:t.response.status;throw new ia(e,t.message,`did-fetch-error`,n,t)}throw t instanceof vo?new ia(e,t.message,`did-fetch-error`,400,t):t instanceof x?new ia(e,t.message,`did-document-format-error`,503,t):ia.from(t,e)}}},qo=Do(Lo(),Ho(/^application\/(did\+ld\+)?json$/),Wo(Ha)),Jo=class{constructor(e){this.plcDirectoryUrl=new URL(e?.plcDirectoryUrl||`https://plc.directory/`),this.fetch=Go(e?.fetch)}async resolve(e,t){va(e);let n=new URL(`/${encodeURIComponent(e)}`,this.plcDirectoryUrl);return this.fetch(n,{redirect:`error`,headers:{accept:`application/did+ld+json,application/json`},signal:t?.signal}).then(qo)}},Yo=Do(Lo(),Ho(/^application\/(did\+ld\+)?json$/),Wo(Ha)),Xo=class{constructor({fetch:e=globalThis.fetch,allowHttp:t=!0}={}){this.fetch=Go(e),this.allowHttp=t}async resolve(e,t){let n=Zo(e);if(!this.allowHttp&&n.protocol===`http:`)throw new ia(e,`Resolution of "http" did:web is not allowed`,`did-web-http-not-allowed`);return this.fetch(n,{redirect:`error`,headers:{accept:`application/did+ld+json,application/json`},signal:t?.signal}).then(Yo)}};function Zo(e){let t=Ca(e);return t.pathname===`/`?new URL(`/.well-known/did.json`,t):new URL(`${t.pathname}/did.json`,t)}var Qo=class extends Ko{constructor(e){super({plc:new Jo(e),web:new Xo(e)})}};function $o(e){let{didResolver:t,didCache:n,onDidCacheError:r}=e;return t instanceof _o&&!n?t:new _o(t??new Qo(e),n,r)}var es=class extends Error{constructor(){super(...arguments),this.name=`HandleResolverError`}};function ts(e){return e===null||Da(e)}var ns=L({error:N(),message:N().optional()}),rs=class{constructor(e,t){this.serviceUrl=new URL(e),this.fetch=t?.fetch??globalThis.fetch}async resolve(e,t){let n=new URL(`/xrpc/com.atproto.identity.resolveHandle`,this.serviceUrl);n.searchParams.set(`handle`,e);let r=await this.fetch.call(null,n,{cache:t?.noCache?`no-cache`:void 0,signal:t?.signal,redirect:`error`}),i=await r.json();if(r.status===400){let{error:e,data:t}=ns.safeParse(i);if(e)throw new es(`Invalid response from resolveHandle method: ${e.message}`,{cause:e});if(t.error===`InvalidRequest`&&t.message===`Unable to resolve handle`)return null}if(!r.ok)throw new es(`Invalid status code from resolveHandle method`);let a=i?.did;if(!ts(a))throw new es(`Invalid DID returned from resolveHandle method`);return a}},is=class{constructor(e,t=new po({max:1e3,ttl:6e5}),n){this.getter=new Ka((t,n)=>e.resolve(t,n),Ja(t,n))}async resolve(e,t){return this.getter.get(e,t)}};function as(e){let{handleResolver:t,handleCache:n,onHandleCacheError:r}=e;return t instanceof is&&!n?t:new is(typeof t==`string`||t instanceof URL?new rs(t,e):t,n,r)}var os=`handle.invalid`,ss=class extends Error{constructor(){super(...arguments),this.name=`IdentityResolverError`}};function cs(e){if(e.alsoKnownAs){for(let t of e.alsoKnownAs)if(t.startsWith(`at://`))return t.slice(5)}}function ls(e){let t=cs(e);if(t)return us(t)}function us(e){let t=ds(e);return fs(t)?t:void 0}function ds(e){return e.toLowerCase()}function fs(e){return e.length>0&&e.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(e)}var ps=class{constructor(e,t){this.didResolver=e,this.handleResolver=t}async resolve(e,t){return Da(e)?this.resolveFromDid(e,t):this.resolveFromHandle(e,t)}async resolveFromDid(e,t){let n=await this.getDocumentFromDid(e,t);t?.signal?.throwIfAborted();let r=ls(n),i=r?await this.handleResolver.resolve(r,t).catch(()=>void 0):void 0;return{did:n.id,didDoc:n,handle:r&&i===e?r:os}}async resolveFromHandle(e,t){let n=await this.getDocumentFromHandle(e,t);return{did:n.id,didDoc:n,handle:ls(n)||`handle.invalid`}}async getDocumentFromDid(e,t){return this.didResolver.resolve(e,t)}async getDocumentFromHandle(e,t){let n=us(e);if(!n)throw new ss(`Invalid handle "${e}" provided.`);let r=await this.handleResolver.resolve(n,t);if(!r)throw new ss(`Handle "${n}" does not resolve to a DID`);t?.signal?.throwIfAborted();let i=await this.didResolver.resolve(r,t);if(n!==ls(i))throw new ss(`Did document for "${r}" does not include the handle "${n}"`);return i}};function ms(e){if(`identityResolver`in e&&e.identityResolver!=null)return e.identityResolver;if(`handleResolver`in e&&e.handleResolver!=null)return new ps($o(e),as(e));throw TypeError(`identityResolver or handleResolver option is required`)}var hs=`urn:ietf:params:oauth:client-assertion-type:jwt-bearer`,gs=URL.canParse?.bind(URL)??(e=>{try{return new URL(e),!0}catch{return!1}});function _s(e){return!!(e.match(/^\d+\.\d+\.\d+\.\d+$/)||e.startsWith(`[`)&&e.endsWith(`]`))}function vs(e){return e===`localhost`||e===`127.0.0.1`||e===`[::1]`}function ys(e){let t=e.split(`.`);if(t.length<2)return!0;let n=t.at(-1).toLowerCase();return n===`test`||n===`local`||n===`localhost`||n===`invalid`||n===`example`}function bs(e){let t=e.startsWith(`https://`)?8:e.startsWith(`http://`)?7:-1;if(t===-1)throw TypeError(`URL must use the "https:" or "http:" protocol`);let n=e.indexOf(`#`,t),r=e.indexOf(`?`,t),i=r!==-1&&(n===-1||r<n)?r:-1,a=n===-1?i===-1?e.length:i:i===-1?n:Math.min(n,i),o=e.indexOf(`/`,t),s=o===-1||o>a?a:o;if(t===s)throw TypeError(`URL must contain a host`);return e.substring(s,a)}var xs=e=>{if(typeof e==`string`&&e.startsWith(`{`)&&e.endsWith(`}`))try{return JSON.parse(e)}catch{return e}return e},Ss=e=>{if(typeof e==`string`){let t=Number(e);if(!Number.isNaN(t))return t}return e},Cs=(e,t)=>{if(e.length===0)throw TypeError(`Value cannot be empty`);if(e.includes(` `))throw TypeError(`Value cannot contain spaces`);let n=t.length,r=e.length;if(n<r)return!1;let i=t.indexOf(e),a;for(;i!==-1;){if(a=i+r,(i===0||t.charCodeAt(i-1)===32)&&(a===n||t.charCodeAt(a)===32))return!0;i=t.indexOf(e,a+1)}return!1},ws=N().refine(e=>e.includes(`:`)&&gs(e),{message:`Invalid URL`}),Ts=ws.superRefine((e,t)=>e.startsWith(`http://`)?vs(new URL(e).hostname)?!0:(t.addIssue({code:b.custom,message:`URL must use "localhost", "127.0.0.1" or "[::1]" as hostname`}),!1):(t.addIssue({code:b.custom,message:`URL must use the "http:" protocol`}),!1)),Es=ws.superRefine((e,t)=>{if(!e.startsWith(`https://`))return t.addIssue({code:b.custom,message:`URL must use the "https:" protocol`}),!1;let n=new URL(e);if(vs(n.hostname))return t.addIssue({code:b.custom,message:`https: URL must not use a loopback host`}),!1;if(!_s(n.hostname)){if(!n.hostname.includes(`.`))return t.addIssue({code:b.custom,message:`Domain name must contain at least two segments`}),!1;if(n.hostname.endsWith(`.local`))return t.addIssue({code:b.custom,message:`Domain name must not end with ".local"`}),!1}return!0}),X=N().superRefine((e,t)=>{if(e.startsWith(`http://`)){let n=Ts.safeParse(e);return n.success||n.error.issues.forEach(t.addIssue,t),n.success}if(e.startsWith(`https://`)){let n=Es.safeParse(e);return n.success||n.error.issues.forEach(t.addIssue,t),n.success}return t.addIssue({code:b.custom,message:`URL must use the "http:" or "https:" protocol`}),!1}),Ds=ws.superRefine((e,t)=>{let n=e.indexOf(`.`),r=e.indexOf(`:`);if(n===-1||r===-1||n>r)return t.addIssue({code:b.custom,message:`Private-use URI scheme requires a "." as part of the protocol`}),!1;let i=new URL(e);return i.protocol.includes(`.`)?(ys(i.protocol.slice(0,-1).split(`.`).reverse().join(`.`))&&t.addIssue({code:b.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:b.custom,message:`Private-Use URI Scheme must be in the form <scheme>:/{path} (notice the single slash!) as per RFC 8252`}),!1):!0):(t.addIssue({code:b.custom,message:`Invalid private-use URI scheme`}),!1)}),Os=Object.freeze([`http://127.0.0.1/`,`http://[::1]/`]),ks=/^[\x21\x23-\x5B\x5D-\x7E]+(?: [\x21\x23-\x5B\x5D-\x7E]+)*$/,As=e=>ks.test(e),js=N().refine(As,{message:`Invalid OAuth scope`}),Ms=`atproto`;function Ns(e){return As(e)&&Cs(`atproto`,e)}var Ps=N().refine(Ns,{message:`Invalid ATProto OAuth scope`}),Fs=Ms,Is=N().min(1),Ls=Ts.superRefine((e,t)=>!e.startsWith(`http://localhost`)||(t.addIssue({code:b.custom,message:`Use of "localhost" hostname is not allowed (RFC 8252), use a loopback IP such as "127.0.0.1" instead`}),!1)),Rs=Ls,zs=N().superRefine((e,t)=>{if(e.startsWith(`https:`)){let n=Es.safeParse(e);return n.success||n.error.issues.forEach(t.addIssue,t),n.success}if(e.startsWith(`http:`)){let n=Ls.safeParse(e);return n.success||n.error.issues.forEach(t.addIssue,t),n.success}if(/^[^.:]+(?:\.[^.:]+)+:/.test(e)){let n=Ds.safeParse(e);return n.success||n.error.issues.forEach(t.addIssue,t),n.success}return t.addIssue({code:b.custom,message:`URL must use the "https:" or "http:" protocol, or a private-use URI scheme (RFC 8252)`}),!1}),Bs=`http://localhost`,Vs=Is.superRefine((e,t)=>{let n=Gs(e);return n.success||t.addIssue({code:`custom`,message:n.message}),n.success});function Hs(e){Ws(e)}function Us(e){return Gs(e).success}function Ws(e){let t=Gs(e);if(t.success)return t.value;throw TypeError(`Invalid loopback client ID: ${t.message}`)}function Gs(e){if(!e.startsWith(`http://localhost`))return{success:!1,message:`Value must start with "${Bs}"`};if(e.includes(`#`,16))return{success:!1,message:`Value must not contain a hash component`};let t=e.length>16&&e.charCodeAt(16)===47?17:16;return e.length!==t&&e.charCodeAt(t)!==63?{success:!1,message:`Value must not contain a path component`}:Ks(e.slice(t+1))}function Ks(e){let t={},n=typeof e==`string`?new URLSearchParams(e):e;for(let[e,r]of n)if(e===`scope`){if(`scope`in t)return{success:!1,message:`Duplicate "scope" query parameter`};let e=js.safeParse(r);if(!e.success)return{success:!1,message:`Invalid "scope" query parameter: ${e.error.issues.map(e=>e.message).join(`, `)||`Validation failed`}`};t.scope=e.data}else if(e===`redirect_uri`){let e=Rs.safeParse(r);if(!e.success)return{success:!1,message:`Invalid "redirect_uri" query parameter: ${e.error.issues.map(e=>e.message).join(`, `)||`Validation failed`}`};t.redirect_uris==null?t.redirect_uris=[e.data]:t.redirect_uris.push(e.data)}else return{success:!1,message:`Unexpected query parameter "${e}"`};return{success:!0,value:t}}function qs(e){let{scope:t=Fs,redirect_uris:n}=Ws(e);if(!Ns(t))throw TypeError(`ATProto Loopback ClientID must include "atproto" scope`);return{scope:t,redirect_uris:n??[...Os]}}function Js(e){return Ys(e,qs(e))}function Ys(e,t){return{client_id:e,scope:t.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}}var Xs=I(L({type:N(),locations:I(ws).optional(),actions:I(N()).optional(),datatypes:I(N()).optional(),identifier:N().optional(),privileges:I(N()).optional()})),Zs=R([N().regex(/^DPoP$/i).transform(()=>`DPoP`),N().regex(/^Bearer$/i).transform(()=>`Bearer`)]),Qs=L({access_token:N(),token_type:Zs,scope:N().optional(),refresh_token:N().optional(),expires_in:P().optional(),id_token:nr.optional(),authorization_details:Xs.optional()}).passthrough().extend({token_type:z(`DPoP`),sub:Ea,scope:Ps,id_token:tn().optional()}),$s=N().min(1),ec=L({grant_type:z(`authorization_code`),code:N().min(1),redirect_uri:zs,code_verifier:N().min(43).max(128).regex(/^[a-zA-Z0-9-._~]+$/).optional()}),tc=L({request:R([nr,rr])}),nc=B([`S256`,`plain`]),rc=B([`none`,`login`,`consent`,`select_account`,`create`]),ic=B([`query`,`fragment`,`form_post`]),ac=B([`code`,`token`,`none`,`code id_token token`,`code id_token`,`code token`,`id_token token`,`id_token`]),oc=B([`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`]),sc=R([N(),P(),F()]),cc=L({essential:F().optional(),value:sc.optional(),values:I(sc).optional()}),lc=B([`userinfo`,`id_token`]),uc=L({client_id:Is,state:N().optional(),redirect_uri:zs.optional(),scope:js.optional(),response_type:ac,code_challenge:N().optional(),code_challenge_method:nc.optional(),dpop_jkt:N().optional(),response_mode:ic.optional(),nonce:N().optional(),max_age:on(Ss,P().int().min(0)).optional(),claims:on(xs,an(lc,an(oc,R([z(null),cc])))).optional(),login_hint:N().min(1).optional(),ui_locales:N().regex(/^[a-z]{2,3}(-[A-Z]{2})?( [a-z]{2,3}(-[A-Z]{2})?)*$/).optional(),id_token_hint:nr.optional(),display:B([`page`,`popup`,`touch`,`wap`]).optional(),prompt:rc.optional(),authorization_details:on(xs,Xs).optional()});R([uc,tc]);var dc=L({request_uri:N().min(1)});rn(L({client_id:Is}),R([uc,tc,dc])),B([`invalid_request`,`unauthorized_client`,`access_denied`,`unsupported_response_type`,`invalid_scope`,`server_error`,`temporarily_unavailable`]);var fc=X.superRefine((e,t)=>{if(e.endsWith(`/`))return t.addIssue({code:b.custom,message:`Issuer URL must not end with a slash`}),!1;let n=new URL(e);return n.username||n.password?(t.addIssue({code:b.custom,message:`Issuer URL must not contain a username or password`}),!1):n.hash||n.search?(t.addIssue({code:b.custom,message:`Issuer URL must not contain a query or fragment`}),!1):e===(n.pathname===`/`?n.origin:n.href)||(t.addIssue({code:b.custom,message:`Issuer URL must be in the canonical form`}),!1)}),pc=L({issuer:fc,claims_supported:I(N()).optional(),claims_locales_supported:I(N()).optional(),claims_parameter_supported:F().optional(),request_parameter_supported:F().optional(),request_uri_parameter_supported:F().optional(),require_request_uri_registration:F().optional(),scopes_supported:I(N()).optional(),subject_types_supported:I(N()).optional(),response_types_supported:I(N()).optional(),response_modes_supported:I(N()).optional(),grant_types_supported:I(N()).optional(),code_challenge_methods_supported:I(nc).min(1).optional(),ui_locales_supported:I(N()).optional(),id_token_signing_alg_values_supported:I(N()).optional(),display_values_supported:I(N()).optional(),request_object_signing_alg_values_supported:I(N()).optional(),authorization_response_iss_parameter_supported:F().optional(),authorization_details_types_supported:I(N()).optional(),request_object_encryption_alg_values_supported:I(N()).optional(),request_object_encryption_enc_values_supported:I(N()).optional(),jwks_uri:X.optional(),authorization_endpoint:X,token_endpoint:X,token_endpoint_auth_methods_supported:I(N()).default([`client_secret_basic`]),token_endpoint_auth_signing_alg_values_supported:I(N()).optional(),revocation_endpoint:X.optional(),introspection_endpoint:X.optional(),pushed_authorization_request_endpoint:X.optional(),require_pushed_authorization_requests:F().optional(),userinfo_endpoint:X.optional(),end_session_endpoint:X.optional(),registration_endpoint:X.optional(),dpop_signing_alg_values_supported:I(N()).optional(),protected_resources:I(X).optional(),client_id_metadata_document_supported:F().optional(),prompt_values_supported:I(rc).optional()}).superRefine((e,t)=>{e.require_pushed_authorization_requests&&!e.pushed_authorization_request_endpoint&&t.addIssue({code:b.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:b.custom,message:`Response type "code" is required`}))}).superRefine((e,t)=>{e.token_endpoint_auth_signing_alg_values_supported?.includes(`none`)&&t.addIssue({code:b.custom,message:`Client authentication method "none" is not allowed`})}),mc=L({grant_type:z(`client_credentials`)});R([L({client_id:Is,client_assertion_type:z(hs),client_assertion:nr}),L({client_id:Is,client_secret:N()}),L({client_id:Is})]);var hc=rn(Is,Es).superRefine((e,t)=>{let n=new URL(e);return n.username||n.password?(t.addIssue({code:b.custom,message:`ClientID must not contain credentials`}),!1):n.hash?(t.addIssue({code:b.custom,message:`ClientID must not contain a fragment`}),!1):n.pathname===`/`?(t.addIssue({code:b.custom,message:`ClientID must contain a path component (e.g. "/client-metadata.json")`}),!1):n.pathname.endsWith(`/`)?(t.addIssue({code:b.custom,message:`ClientID path must not end with a trailing slash`}),!1):_s(n.hostname)?(t.addIssue({code:b.custom,message:`ClientID hostname must not be an IP address`}),!1):bs(e)===n.pathname||(t.addIssue({code:b.custom,message:`ClientID must be in canonical form ("${n.href}", got "${e}")`}),!1)});hc.superRefine((e,t)=>{let n=new URL(e);return n.port?(t.addIssue({code:b.custom,message:`ClientID must not contain a port`}),!1):n.search?(t.addIssue({code:b.custom,message:`ClientID must not contain a query string`}),!1):n.pathname===`/oauth-client-metadata.json`||(t.addIssue({code:b.custom,message:`ClientID must be "/oauth-client-metadata.json"`}),!1)});function gc(e){hc.parse(e)}var _c=B([`client_secret_basic`,`client_secret_jwt`,`client_secret_post`,`none`,`private_key_jwt`,`self_signed_tls_client_auth`,`tls_client_auth`]),vc=B([`authorization_code`,`implicit`,`refresh_token`,`password`,`client_credentials`,`urn:ietf:params:oauth:grant-type:jwt-bearer`,`urn:ietf:params:oauth:grant-type:saml2-bearer`]),yc=L({redirect_uris:I(zs).nonempty(),response_types:I(ac).nonempty().default([`code`]),grant_types:I(vc).nonempty().default([`authorization_code`]),scope:js.optional(),token_endpoint_auth_method:_c.default(`client_secret_basic`),token_endpoint_auth_signing_alg:N().optional(),userinfo_signed_response_alg:N().optional(),userinfo_encrypted_response_alg:N().optional(),jwks_uri:X.optional(),jwks:tr.optional(),application_type:B([`web`,`native`]).default(`web`),subject_type:B([`public`,`pairwise`]).default(`public`),request_object_signing_alg:N().optional(),id_token_signed_response_alg:N().optional(),authorization_signed_response_alg:N().default(`RS256`),authorization_encrypted_response_enc:B([`A128CBC-HS256`]).optional(),authorization_encrypted_response_alg:N().optional(),client_id:Is.optional(),client_name:N().optional(),client_uri:X.optional(),policy_uri:X.optional(),tos_uri:X.optional(),logo_uri:X.optional(),default_max_age:P().optional(),require_auth_time:F().optional(),contacts:I(N().email()).optional(),tls_client_certificate_bound_access_tokens:F().optional(),dpop_bound_access_tokens:F().optional(),authorization_details_types:I(N()).optional()}),bc=L({request_uri:N(),expires_in:P().int().positive()}),xc=L({grant_type:z(`password`),username:N(),password:N()}),Sc=L({resource:X.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:I(fc).optional(),jwks_uri:X.optional(),scopes_supported:I(N()).optional(),bearer_methods_supported:I(B([`header`,`body`,`query`])).optional(),resource_signing_alg_values_supported:I(N()).optional(),resource_documentation:X.optional(),resource_policy_uri:X.optional(),resource_tos_uri:X.optional()}),Cc=N().min(1),wc=L({grant_type:z(`refresh_token`),refresh_token:Cc});L({token:R([$s,Cc]),token_type_hint:B([`access_token`,`refresh_token`]).optional()}),nn(`grant_type`,[ec,wc,xc,mc]),B([`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`]),L({sub:N(),iss:N().url().optional(),aud:R([N(),I(N()).min(1)]).optional(),email:N().email().optional(),email_verified:F().optional(),name:N().optional(),preferred_username:N().optional(),picture:N().url().optional()});function Tc(e){return e.get(`content-type`)?.split(`;`)[0].trim()}var Ec=class extends Ka{constructor(e,t,n){super(async(e,t)=>this.fetchMetadata(e,t),Ja(e,n?.onCacheError)),this.fetch=Go(t),this.allowHttpIssuer=n?.allowHttpIssuer===!0}async get(e,t){let n=fc.parse(String(e));if(!this.allowHttpIssuer&&n.startsWith(`http:`))throw TypeError(`Unsecure issuer URL protocol only allowed in development and test environments`);return super.get(n,t)}async fetchMetadata(e,t){let n=new URL(`/.well-known/oauth-authorization-server`,e),r=new Request(n,{headers:{accept:`application/json`},cache:t?.noCache?`no-cache`:void 0,signal:t?.signal,redirect:`manual`}),i=await this.fetch(r);if(i.status!==200)throw await So(i,`log`),await Y.from(i,`Unexpected status code ${i.status} for "${n}"`,void 0,{cause:r});if(Tc(i.headers)!==`application/json`)throw await So(i,`log`),await Y.from(i,`Unexpected content type for "${n}"`,void 0,{cause:r});let a=pc.parse(await i.json());if(a.issuer!==e)throw TypeError(`Invalid issuer ${a.issuer}`);if(a.client_id_metadata_document_supported!==!0)throw TypeError(`Authorization server "${e}" does not support client_id_metadata_document`);return a}},Dc=class extends Ka{constructor(e,t=globalThis.fetch,n){super(async(e,t)=>this.fetchMetadata(e,t),Ja(e,n?.onCacheError)),this.fetch=Go(t),this.allowHttpResource=n?.allowHttpResource===!0}async get(e,t){let{protocol:n,origin:r}=new URL(e);if(n!==`https:`&&n!==`http:`)throw TypeError(`Invalid protected resource metadata URL protocol: ${n}`);if(n===`http:`&&!this.allowHttpResource)throw TypeError(`Unsecure resource metadata URL (${n}) only allowed in development and test environments`);return super.get(r,t)}async fetchMetadata(e,t){let n=new URL(`/.well-known/oauth-protected-resource`,e),r=new Request(n,{signal:t?.signal,headers:{accept:`application/json`},cache:t?.noCache?`no-cache`:void 0,redirect:`manual`}),i=await this.fetch(r);if(i.status===404)return await So(i,`log`),null;if(i.status!==200)throw await So(i,`log`),await Y.from(i,`Unexpected status code ${i.status} for "${n}"`,void 0,{cause:r});if(Tc(i.headers)!==`application/json`)throw await So(i,`log`),await Y.from(i,`Unexpected content type for "${n}"`,void 0,{cause:r});let a=Sc.parse(await i.json());if(a.resource!==e)throw TypeError(`Invalid issuer ${a.resource}`);return a}},Oc=class e extends Error{constructor(e,t){super(e,t)}static from(t,n){if(t instanceof e)return t;let r=t instanceof x?`${t.errors[0].path} ${t.errors[0].message}`:null,i=(n??`Unable to resolve identity`)+(r?` (${r})`:``);return new e(i,{cause:t})}},kc=class{constructor(e,t,n){this.identityResolver=e,this.protectedResourceMetadataResolver=t,this.authorizationServerMetadataResolver=n}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(n){if(!t?.signal?.aborted&&n instanceof Oc)try{let n=fc.safeParse(e);if(n.success)return{metadata:await this.getAuthorizationServerMetadata(n.data,t)}}catch{}throw n}}async resolveFromIdentity(e,t){let n=await this.resolveIdentity(e,t);t?.signal?.throwIfAborted();let r=Pa(n.didDoc);return{identityInfo:n,metadata:await this.getResourceServerMetadata(r,t),pds:r}}async resolveIdentity(e,t){try{return await this.identityResolver.resolve(e,t)}catch(t){throw Oc.from(t,`Failed to resolve identity: ${e}`)}}async getAuthorizationServerMetadata(e,t){try{return await this.authorizationServerMetadataResolver.get(e,t)}catch(t){throw Oc.from(t,`Failed to resolve OAuth server metadata for issuer: ${e}`)}}async getResourceServerMetadata(e,t){try{let n=await this.protectedResourceMetadataResolver.get(e,t);if(!n)return this.getAuthorizationServerMetadata(e,t);if(n.authorization_servers?.length!==1)throw new Oc(n.authorization_servers?.length?`Unable to determine authorization server for PDS: ${e}`:`No authorization servers found for PDS: ${e}`);let r=n.authorization_servers[0];t?.signal?.throwIfAborted();let i=await this.getAuthorizationServerMetadata(r,t);if(i.protected_resources&&!i.protected_resources.includes(n.resource))throw new Oc(`PDS "${e}" not protected by issuer "${r}"`);return i}catch(t){throw Oc.from(t,`Failed to resolve OAuth server metadata for resource: ${e}`)}}};function Ac({fetch:e=globalThis.fetch,allowHttp:t=!1,protectedResourceMetadataCache:n=new po({ttl:6e4,max:100}),authorizationServerMetadataCache:r=new po({ttl:6e4,max:100}),onCacheError:i,...a}){return new kc(ms({...a,allowHttp:t,fetch:e}),new Dc(n,e,{allowHttpResource:t,onCacheError:i}),new Ec(r,e,{allowHttpIssuer:t,onCacheError:i}))}var jc=new Map;function Mc(e){return new Promise(t=>{let n=(jc.get(e)??Promise.resolve()).then(()=>new Promise(r=>{t(()=>{jc.get(e)===n&&jc.delete(e),r()})}));jc.set(e,n)})}var Nc=(e,t)=>Mc(e).then(async e=>{try{return await t()}finally{e()}}),Z=class e extends Error{static from(t,n,r){if(t instanceof e)return t;let i=t instanceof Error?t.message:void 0;return new e(n,i,r,t)}constructor(e,t=e.get(`error_description`)||`OAuth callback error`,n,r){super(t,{cause:r}),this.params=e,this.state=n}},Pc=`ES256`,Fc=class extends Error{},Ic=class extends Error{constructor(e,t=`The session for "${e}" was successfully revoked`,n){super(t,n),this.sub=e}};function Lc(e,t,n){let r=t.token_endpoint_auth_method,i=zc(e);if(!i.includes(r))throw Error(`The server does not support "${r}" authentication. Supported methods are: ${i.join(`, `)}.`);if(r===`private_key_jwt`){if(!n)throw Error(`A keyset is required for private_key_jwt`);let t=Bc(e);for(let e of n.list({alg:t,usage:`sign`}))if(e.kid)return{method:`private_key_jwt`,kid:e.kid};throw Error(t.includes(`ES256`)?`Client authentication method "${r}" requires at least one "${Pc}" signing key with a "kid" property`:`Authorization server requires "${r}" authentication method, but does not support "${Pc}" algorithm.`)}if(r===`none`)return{method:`none`};throw Error(`The ATProto OAuth spec requires that client use either "none" or "private_key_jwt" authentication method.`+(r===`client_secret_basic`?` You might want to explicitly set "token_endpoint_auth_method" to one of those values in the client metadata document.`:` You set "${r}" which is not allowed.`))}function Rc(e,t,n,r,i){if(!zc(t).includes(e.method))throw new Fc(`Client authentication method "${e.method}" no longer supported`);if(e.method===`none`)return()=>({payload:{client_id:n.client_id}});if(e.method===`private_key_jwt`)try{if(!i)throw Error(`A keyset is required for private_key_jwt`);let{key:a,alg:o}=i.findPrivateKey({usage:`sign`,kid:e.kid,alg:Bc(t)});return async()=>({payload:{client_id:n.client_id,client_assertion_type:hs,client_assertion:await a.createJwt({alg:o},{iss:n.client_id,sub:n.client_id,aud:t.issuer,jti:await r.generateNonce(),iat:Math.floor(Date.now()/1e3),exp:Math.floor(Date.now()/1e3)+60})}})}catch(e){throw new Fc(`Failed to load private key`,{cause:e})}throw new Fc(`Unsupported auth method ${e.method}`)}function zc(e){return e.token_endpoint_auth_methods_supported}function Bc(e){return e.token_endpoint_auth_signing_alg_values_supported??[`ES256`]}var Vc=class extends Error{constructor(e,t,n){super(t,n),this.sub=e}},Hc=globalThis.crypto?.subtle,Uc=globalThis.ReadableStream;function Wc({key:e,supportedAlgs:t,nonces:n,sha256:r=Hc===void 0?void 0:Yc,isAuthServer:i,fetch:a=globalThis.fetch}){if(!r)throw TypeError(`crypto.subtle is not available in this environment. Please provide a sha256 function.`);let o=Jc(e,t);return async function(t,s){let c=s==null&&t instanceof Request?t:new Request(t,s),l=c.headers.get(`Authorization`),u=l?.startsWith(`DPoP `)?await r(l.slice(5)):void 0,{origin:d}=new URL(c.url),f=c.method,p=Gc(c.url),m;try{m=await n.get(d)}catch{}let h=await Kc(e,o,f,p,m,u);c.headers.set(`DPoP`,h);let g=await a.call(this,c),ee=g.headers.get(`DPoP-Nonce`);if(!ee||ee===m)return g;try{await n.set(d,ee)}catch{}let te;try{te=await qc(g,i)}catch(e){throw await So(g,`log`),e}if(!te||t===c||Uc&&s?.body instanceof Uc)return g;await So(g,`log`);let _=await Kc(e,o,f,p,ee,u),ne=new Request(t,s);ne.headers.set(`DPoP`,_);let re=await a.call(this,ne),ie=re.headers.get(`DPoP-Nonce`);if(!ie||ie===m)return re;try{await n.set(d,ie)}catch{}return re}}function Gc(e){let t=e.indexOf(`#`),n=e.indexOf(`?`),r=t===-1?n:n===-1?t:Math.min(t,n);return r===-1?e:e.slice(0,r)}async function Kc(e,t,n,r,i,a){let o=e.bareJwk;if(!o)throw Error(`Only asymmetric keys can be used as DPoP proofs`);let s=Math.floor(Date.now()/1e3);return e.createJwt({alg:t,typ:`dpop+jwt`,jwk:o},{iat:s,jti:Math.random().toString(36).slice(2),htm:n,htu:r,nonce:i,ath:a})}async function qc(e,t){if((t===void 0||t===!1)&&e.status===401){let t=e.headers.get(`WWW-Authenticate`);if(t?.startsWith(`DPoP`))return t.includes(`error="use_dpop_nonce"`)}if((t===void 0||t===!0)&&e.status===400)try{return(await jo(e,10240))?.error===`use_dpop_nonce`}catch(e){if(e instanceof Y||e instanceof SyntaxError)return!1;throw e}return!1}function Jc(e,t){if(t){let n=t.find(t=>e.algorithms.includes(t));if(n)return n}else{let[t]=e.algorithms;if(t)return t}throw Error(`Key does not match any alg supported by the server`)}async function Yc(e){if(Hc==null)throw Error(`crypto.subtle is not available in this environment. Please provide a sha256 function.`);let t=new TextEncoder().encode(e),n=await Hc.digest(`SHA-256`,t),r=new Uint8Array(n);return Tn.baseEncode(r)}var Xc=e=>typeof e==`string`?e:void 0;function Zc(e){if(typeof AbortSignal.timeout==`function`)return AbortSignal.timeout(e);let t=new AbortController;return setTimeout(()=>t.abort(Qc(e)),e),t.signal}function Qc(e){let t=`The operation timed out after ${e} ms`;return typeof DOMException==`function`?new DOMException(t,`TimeoutError`):Error(t)}function $c(e){let t=new el,n=function(e){let n=Error(`This operation was aborted`,{cause:this.reason});t.abort(n)};try{for(let r of e)r&&(r.throwIfAborted(),r.addEventListener(`abort`,n,{signal:t.signal}));return t}catch(e){throw t.abort(e),e}}var el=class extends AbortController{[Symbol.dispose](){this.abort(Error(`AbortController was disposed`))}},tl=class extends Error{constructor(e,t){let n=Xc(t?.error),r=Xc(t?.error_description),i=`OAuth ${n?`"${n}"`:`unknown`} error${r?`: ${r}`:``}`;super(i),this.response=e,this.payload=t,this.error=n,this.errorDescription=r}get status(){return this.response.status}get headers(){return this.response.headers}},nl=class{constructor(e,t,n,r,i,a,o,s,c){this.authMethod=e,this.dpopKey=t,this.serverMetadata=n,this.clientMetadata=r,this.dpopNonces=i,this.oauthResolver=a,this.runtime=o,this.keyset=s,this.clientCredentialsFactory=Rc(e,n,r,o,s),this.dpopFetch=Wc({fetch:Go(c),key:t,supportedAlgs:n.dpop_signing_alg_values_supported,sha256:async e=>o.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,n){let r=Date.now(),i=await this.request(`token`,{grant_type:`authorization_code`,redirect_uri:n??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:typeof i.expires_in==`number`?new Date(r+i.expires_in*1e3).toISOString():void 0}}catch(e){throw await this.revoke(i.access_token),e}}async refresh(e){if(!e.refresh_token)throw new Vc(e.sub,`No refresh token available`);let t=await this.verifyIssuer(e.sub),n=Date.now(),r=await this.request(`token`,{grant_type:`refresh_token`,refresh_token:e.refresh_token});return{aud:t,sub:e.sub,iss:this.issuer,scope:r.scope,refresh_token:r.refresh_token,access_token:r.access_token,token_type:r.token_type,expires_at:typeof r.expires_in==`number`?new Date(n+r.expires_in*1e3).toISOString():void 0}}async verifyIssuer(e){let t=await this.oauthResolver.resolveFromIdentity(e,{noCache:!0,allowStale:!1,signal:Zc(1e4)});if(this.issuer!==t.metadata.issuer)throw TypeError(`Issuer mismatch`);return t.pds.href}async request(e,t){let n=this.serverMetadata[`${e}_endpoint`];if(!n)throw Error(`No ${e} endpoint available`);let r=await this.clientCredentialsFactory(),{response:i,json:a}=await this.dpopFetch(n,{method:`POST`,headers:{...r.headers,"Content-Type":`application/x-www-form-urlencoded`},body:rl({...t,...r.payload})}).then(Ho());if(i.ok)switch(e){case`token`:return Qs.parse(a);case`pushed_authorization_request`:return bc.parse(a);default:return a}else throw new tl(i,a)}};function rl(e){return new URLSearchParams(Object.entries(e).filter(il).map(al)).toString()}function il(e){return e[1]!==void 0}function al(e){let t=e[0],n=e[1];switch(typeof n){case`string`:return[t,n];case`number`:case`boolean`:return[t,String(n)];default:{let e=JSON.stringify(n);if(e===void 0)throw Error(`Unsupported value type for ${t}: ${String(n)}`);return[t,e]}}}var ol=class{constructor(e,t,n,r,i,a){this.clientMetadata=e,this.runtime=t,this.resolver=n,this.fetch=r,this.keyset=i,this.dpopNonceCache=a}async fromIssuer(e,t,n,r){let i=await this.resolver.getAuthorizationServerMetadata(e,r);return this.fromMetadata(i,t,n)}async fromMetadata(e,t,n){return new nl(t,n,e,this.clientMetadata,this.dpopNonceCache,this.resolver,this.runtime,this.keyset,this.fetch)}},sl=class extends Error{constructor(e,t=`The session for "${e}" is invalid`,n){super(t,n),this.sub=e}},cl=globalThis.ReadableStream,ll=class{constructor(e,t,n,r=globalThis.fetch){this.server=e,this.sub=t,this.sessionGetter=n,this.dpopFetch=Wc({fetch:Go(r),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),n=t.expires_at==null?void 0:new Date(t.expires_at);return{expiresAt:n,get expired(){return n==null?void 0:n.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 Ic(this.sub))}}async fetchHandler(e,t){let n=await this.getTokenSet(`auto`),r=new URL(e,n.aud),i=`${n.token_type} ${n.access_token}`,a=new Headers(t?.headers);a.set(`Authorization`,i);let o=await this.dpopFetch(r,{...t,headers:a});if(!ul(o))return o;let s;try{s=await this.getTokenSet(!0)}catch{return o}if(cl&&t?.body instanceof cl)return o;let c=`${s.token_type} ${s.access_token}`,l=new URL(e,s.aud);a.set(`Authorization`,c);let u=await this.dpopFetch(l,{...t,headers:a});return ul(u)&&await this.sessionGetter.delStored(this.sub,new sl(this.sub)),u}};function ul(e){if(e.status!==401)return!1;let t=e.headers.get(`WWW-Authenticate`);return t!=null&&(t.startsWith(`Bearer `)||t.startsWith(`DPoP `))&&t.includes(`error="invalid_token"`)}var dl=class{constructor(e){this.implementation=e;let{requestLock:t}=e;this.hasImplementationLock=t!=null,this.usingLock=t?.bind(e)||Nc}async generateKey(e){let t=Array.from(e).sort(pl);return this.implementation.createKey(t)}async sha256(e){let t=new TextEncoder().encode(e),n=await this.implementation.digest(t,{name:`sha256`});return Tn.baseEncode(n)}async generateNonce(e=16){let t=await this.implementation.getRandomValues(e);return Tn.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=fl(e),n=JSON.stringify(t);return this.sha256(n)}async generateVerifier(e=32){if(e<32||e>96)throw TypeError(`Invalid code_verifier length`);let t=await this.implementation.getRandomValues(e);return Tn.baseEncode(t)}};function fl(e){let t=t=>{let n=e[t];if(typeof n!=`string`||!n)throw TypeError(`"${t}" Parameter missing or invalid`);return n};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`)}}function pl(e,t){if(e===`ES256K`)return-1;if(t===`ES256K`)return 1;for(let n of[`ES`,`PS`,`RS`])if(e.startsWith(n))return t.startsWith(n)?parseInt(e.slice(2,5))-parseInt(t.slice(2,5)):-1;else if(t.startsWith(n))return 1;return 0}var ml=function(e,t,n){if(t!=null){if(typeof t!=`object`&&typeof t!=`function`)throw TypeError(`Object expected.`);var r,i;if(n){if(!Symbol.asyncDispose)throw TypeError(`Symbol.asyncDispose is not defined.`);r=t[Symbol.asyncDispose]}if(r===void 0){if(!Symbol.dispose)throw TypeError(`Symbol.dispose is not defined.`);r=t[Symbol.dispose],n&&(i=r)}if(typeof r!=`function`)throw TypeError(`Object not disposable.`);i&&(r=function(){try{i.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:r,async:n})}else n&&e.stack.push({async:!0});return t},hl=(function(e){return function(t){function n(n){t.error=t.hasError?new e(n,t.error,`An error was suppressed during disposal.`):n,t.hasError=!0}var r,i=0;function a(){for(;r=t.stack.pop();)try{if(!r.async&&i===1)return i=0,t.stack.push(r),Promise.resolve().then(a);if(r.dispose){var e=r.dispose.call(r.value);if(r.async)return i|=2,Promise.resolve(e).then(a,function(e){return n(e),a()})}else i|=1}catch(e){n(e)}if(i===1)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}return a()}})(typeof SuppressedError==`function`?SuppressedError:function(e,t,n){var r=Error(n);return r.name=`SuppressedError`,r.error=e,r.suppressed=t,r});function gl(e){return e instanceof Vc||e instanceof Ic||e instanceof sl||e instanceof Fc||e instanceof TypeError}var _l=class extends Ka{#e;#t;#n;constructor(e,t,n,r={}){super(async(e,{signal:i},a)=>{if(a===void 0){let t=new Vc(e,`The session was deleted by another process`);throw await r.onSessionDeleted?.call(null,e,t),t}let{dpopKey:o,authMethod:s,tokenSet:c}=a;if(e!==c.sub)throw new Vc(e,`Stored session sub mismatch`);if(!c.refresh_token)throw new Vc(e,`No refresh token available`);let l=await t.fromIssuer(c.iss,s,o,{signal:i});i?.throwIfAborted();try{let t=await l.refresh(c);if(e!==t.sub)throw new Vc(e,`Token set sub mismatch`);return{dpopKey:o,tokenSet:t,authMethod:l.authMethod}}catch(t){if(t instanceof tl&&t.status===400&&t.error===`invalid_grant`){if(!n.hasImplementationLock){await new Promise(e=>setTimeout(e,1e3));let n=await this.getStored(e);if(n===void 0)throw new Vc(e,`The session was deleted by another process`,{cause:t});if(n.tokenSet.access_token!==c.access_token||n.tokenSet.refresh_token!==c.refresh_token)return n}throw new Vc(e,t.errorDescription??`The session was revoked`,{cause:t})}throw t}},e,{isStale:(e,{tokenSet:t})=>t.expires_at!=null&&new Date(t.expires_at).getTime()<Date.now()+1e4+3e4*Math.random(),deleteOnError:gl}),this.#e=t,this.#t=n,this.#n=r}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(n){let r=[n];try{let{tokenSet:e,dpopKey:n,authMethod:r}=t;await(await this.#e.fromIssuer(e.iss,r,n)).revoke(e.refresh_token??e.access_token)}catch(e){r.push(e)}try{await this.delStored(e,n)}catch(e){r.push(e)}throw AggregateError(r,`Failed to store session for ${e}`)}await this.#n.onSessionUpdated?.call(null,e,t)}async delStored(e,t){await super.delStored(e,t),await this.#n.onSessionDeleted?.call(null,e,t)}async get(e,t){let n=await this.#t.usingLock(`@atproto-oauth-client-${e}`,async()=>{let n={stack:[],error:void 0,hasError:!1};try{let r=Zc(3e4),i=ml(n,$c([t?.signal,r]),!1);return await super.get(e,{...t,signal:i.signal})}catch(e){n.error=e,n.hasError=!0}finally{hl(n)}});if(e!==n.tokenSet.sub)throw Error(`Token set does not match the expected sub`);return n}async getSession(e,t=`auto`){return this.get(e,{noCache:t===!0,allowStale:t===!1})}},vl=yc.extend({client_id:R([hc,Vs])});function yl(e,t){!e.jwks&&!e.jwks_uri&&t?.size&&(e={...e,jwks:t.toJSON()});let n=vl.parse(e);if(n.client_id.startsWith(`http:`)?Hs(n.client_id):gc(n.client_id),!(n.scope?.split(` `))?.includes(`atproto`))throw TypeError(`Client metadata must include the "atproto" scope`);if(!n.response_types.includes(`code`))throw TypeError(`"response_types" must include "code"`);if(!n.grant_types.includes(`authorization_code`))throw TypeError(`"grant_types" must include "authorization_code"`);let r=n.token_endpoint_auth_method,i=n.token_endpoint_auth_signing_alg;switch(r){case`none`:if(i)throw TypeError(`"token_endpoint_auth_signing_alg" must not be provided when "token_endpoint_auth_method" is "${r}"`);break;case`private_key_jwt`:{if(!i)throw TypeError(`"token_endpoint_auth_signing_alg" must be provided when "token_endpoint_auth_method" is "${r}"`);if(!t)throw TypeError(`Client authentication method "${r}" requires a keyset`);let e=Array.from(t.list({usage:`sign`})).filter(e=>e.kid);if(!e.length)throw TypeError(`Client authentication method "${r}" requires at least one active signing key with a "kid" property`);if(!e.some(e=>e.algorithms.includes(`ES256`)))throw TypeError(`Client authentication method "${r}" requires at least one active "${Pc}" signing key`);if(n.jwks){for(let t of e)if(!n.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(!n.jwks_uri)throw TypeError(`Client authentication method "${r}" requires a JWKS`);break}default:throw TypeError(`Unsupported "token_endpoint_auth_method" value: ${r}`)}return n}var bl=class{static async fetchMetadata({clientId:e,fetch:t=globalThis.fetch,signal:n}){n?.throwIfAborted();let r=await t(new Request(e,{redirect:`error`,signal:n}));if(r.status!==200)throw await r.body?.cancel?.(),TypeError(`Failed to fetch client metadata: ${r.status}`);let i=r.headers.get(`content-type`)?.split(`;`)[0].trim();if(i!==`application/json`)throw await r.body?.cancel?.(),TypeError(`Invalid client metadata content type: ${i}`);let a=await r.json();return n?.throwIfAborted(),yc.parse(a)}constructor(e){let{stateStore:t,sessionStore:n,dpopNonceCache:r=new po({ttl:6e4,max:100}),responseMode:i,clientMetadata:a,runtimeImplementation:o,keyset:s}=e;this.keyset=s?s instanceof gr?s:new gr(s):void 0,this.clientMetadata=yl(a,this.keyset),this.responseMode=i,this.runtime=new dl(o),this.fetch=e.fetch??globalThis.fetch,this.oauthResolver=Ac(e),this.serverFactory=new ol(this.clientMetadata,this.runtime,this.oauthResolver,this.fetch,this.keyset,r),this.stateStore=t,this.sessionGetter=new _l(n,this.serverFactory,this.runtime,e)}get identityResolver(){return this.oauthResolver.identityResolver}get jwks(){return this.keyset?.publicJwks??{keys:[]}}async authorize(e,{signal:t,...n}={}){let r=n?.redirect_uri??this.clientMetadata.redirect_uris[0];if(!this.clientMetadata.redirect_uris.includes(r))throw TypeError(`Invalid redirect_uri`);let{identityInfo:i,metadata:a}=await this.oauthResolver.resolve(e,{signal:t}),o=await this.runtime.generatePKCE(),s=await this.runtime.generateKey(a.dpop_signing_alg_values_supported||[`ES256`]),c=Lc(a,this.clientMetadata,this.keyset),l=await this.runtime.generateNonce();await this.stateStore.set(l,{iss:a.issuer,dpopKey:s,authMethod:c,verifier:o.verifier,appState:n?.state});let u={...n,client_id:this.clientMetadata.client_id,redirect_uri:r,code_challenge:o.challenge,code_challenge_method:o.method,state:l,login_hint:i?i.handle===`handle.invalid`?i.did:i.handle:void 0,response_mode:this.responseMode,response_type:`code`,scope:n?.scope??this.clientMetadata.scope},d=new URL(a.authorization_endpoint);if(d.protocol!==`https:`&&d.protocol!==`http:`)throw TypeError(`Invalid authorization endpoint protocol: ${d.protocol}`);if(a.pushed_authorization_request_endpoint){let e=await(await this.serverFactory.fromMetadata(a,c,s)).request(`pushed_authorization_request`,u);return d.searchParams.set(`client_id`,this.clientMetadata.client_id),d.searchParams.set(`request_uri`,e.request_uri),d}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(u))t&&d.searchParams.set(e,String(t));if(d.pathname.length+d.search.length<2048)return d;throw a.pushed_authorization_request_endpoint?Error(`Server does not support pushed authorization requests (PAR)`):Error(`Login URL too long`)}async abortRequest(e){e.searchParams.get(`request_uri`)}async callback(e,t={}){if(e.get(`response`)!=null)throw new Z(e,`JARM not supported`);let n=e.get(`iss`),r=e.get(`state`),i=e.get(`error`),a=e.get(`code`);if(!r)throw new Z(e,`Missing "state" parameter`);let o=await this.stateStore.get(r);if(o)await this.stateStore.del(r);else throw new Z(e,`Unknown authorization session "${r}"`);try{if(i!=null)throw new Z(e,void 0,o.appState);if(!a)throw new Z(e,`Missing "code" query param`,o.appState);let r=await this.serverFactory.fromIssuer(o.iss,o.authMethod,o.dpopKey);if(n!=null){if(!r.issuer)throw new Z(e,`Issuer not found in metadata`,o.appState);if(r.issuer!==n)throw new Z(e,`Issuer mismatch`,o.appState)}else if(r.serverMetadata.authorization_response_iss_parameter_supported)throw new Z(e,`iss missing from the response`,o.appState);let s=await r.exchangeCode(a,o.verifier,t?.redirect_uri??r.clientMetadata.redirect_uris[0]);try{await this.revoke(s.sub)}catch{}try{return await this.sessionGetter.setStored(s.sub,{dpopKey:o.dpopKey,authMethod:r.authMethod,tokenSet:s}),{session:this.createSession(r,s.sub),state:o.appState??null}}catch(e){throw await r.revoke(s.refresh_token||s.access_token),e}}catch(t){throw Z.from(t,e,o.appState)}}async restore(e,t=`auto`){Oa(e);let{dpopKey:n,authMethod:r,tokenSet:i}=await this.sessionGetter.getSession(e,t);try{let a=await this.serverFactory.fromIssuer(i.iss,r,n,{noCache:t===!0,allowStale:t===!1});return this.createSession(a,e)}catch(t){throw t instanceof Fc&&await this.sessionGetter.delStored(e,t),t}}async revoke(e){Oa(e);let t=await this.sessionGetter.getSession(e,!1).catch(e=>{if(gl(e))return null;throw e});if(!t)return;let{dpopKey:n,authMethod:r,tokenSet:i}=t;try{await(await this.serverFactory.fromIssuer(i.iss,r,n)).revoke(i.access_token)}finally{await this.sessionGetter.delStored(e,new Ic(e))}}createSession(e,t){return new ll(e,t,this.sessionGetter,this.fetch)}};function xl(e,t,n){let r=()=>{e.removeEventListener(`success`,i),e.removeEventListener(`error`,a)},i=()=>{t(e.result),r()},a=()=>{n(e.error||Error(`Unknown error`)),r()};e.addEventListener(`success`,i),e.addEventListener(`error`,a)}function Q(e){return new Promise((t,n)=>{xl(e,t,n)})}var Sl=class{constructor(e){this.idbIndex=e}count(e){return Q(this.idbIndex.count(e))}get(e){return Q(this.idbIndex.get(e))}getKey(e){return Q(this.idbIndex.getKey(e))}getAll(e,t){return Q(this.idbIndex.getAll(e,t))}getAllKeys(e,t){return Q(this.idbIndex.getAllKeys(e,t))}deleteAll(e){return new Promise((t,n)=>{let r=this.idbIndex.openCursor(e);r.onsuccess=function(e){let n=e.target.result;n?(n.delete(),n.continue()):t()},r.onerror=function(e){n(e.target?.error||Error(`Unexpected error`))}})}},Cl=class{constructor(e){this.idbObjStore=e}get name(){return this.idbObjStore.name}index(e){return new Sl(this.idbObjStore.index(e))}get(e){return Q(this.idbObjStore.get(e))}getKey(e){return Q(this.idbObjStore.getKey(e))}getAll(e,t){return Q(this.idbObjStore.getAll(e,t))}getAllKeys(e,t){return Q(this.idbObjStore.getAllKeys(e,t))}add(e,t){return Q(this.idbObjStore.add(e,t))}put(e,t){return Q(this.idbObjStore.put(e,t))}delete(e){return Q(this.idbObjStore.delete(e))}clear(){return Q(this.idbObjStore.clear())}},wl=class{#e;constructor(e){this.#e=e;let t=()=>{r()},n=()=>{r()},r=()=>{this.#e=null,e.removeEventListener(`abort`,t),e.removeEventListener(`complete`,n)};e.addEventListener(`abort`,t),e.addEventListener(`complete`,n)}get tx(){if(!this.#e)throw Error(`Transaction already ended`);return this.#e}async abort(){let{tx:e}=this;this.#e=null,e.abort()}async commit(){let{tx:e}=this;this.#e=null,e.commit?.()}objectStore(e){return new Cl(this.tx.objectStore(e))}[Symbol.dispose](){this.#e&&this.commit()}},Tl=class e{static async open(t,n,r){let i=await new Promise((e,r)=>{let i=indexedDB.open(t,n.length);i.onerror=()=>r(i.error),i.onsuccess=()=>e(i.result),i.onupgradeneeded=({oldVersion:e,newVersion:t})=>{let a=i.result;try{for(let r=e;r<(t??n.length);++r){let e=n[r];if(e)e(a);else throw Error(`Missing migration for version ${r}`)}}catch(e){a.close(),r(e)}}});return new e(i,r)}#e;constructor(e,t){this.txOptions=t,this.#e=e;let n=()=>{this.#e=null,e.removeEventListener(`versionchange`,n),e.removeEventListener(`close`,n),e.close()};e.addEventListener(`versionchange`,n),e.addEventListener(`close`,n)}get db(){if(!this.#e)throw Error(`Database closed`);return this.#e}get name(){return this.db.name}get objectStoreNames(){return this.db.objectStoreNames}get version(){return this.db.version}async transaction(e,t,n){return new Promise(async(r,i)=>{try{let a=this.db.transaction(e,t,this.txOptions),o={done:!1};a.oncomplete=()=>{o.done?r(o.value):i(Error(`Transaction completed without result`))},a.onerror=()=>i(a.error),a.onabort=()=>i(a.error||Error(`Transaction aborted`));try{o={done:!0,value:await n(new wl(a))},a.commit()}catch(e){throw a.abort(),e}}catch(e){i(e)}})}close(){let{db:e}=this;this.#e=null,e.close()}async[Symbol.asyncDispose](){this.#e&&await this.close()}};function El(e){if(!(e instanceof na)||!e.kid)throw Error(`Invalid key object`);return{keyId:e.kid,keyPair:e.cryptoKeyPair}}async function Dl(e){return na.fromKeypair(e.keyPair,e.keyId)}var Ol=[`state`,`session`,`didCache`,`dpopNonceCache`,`handleCache`,`authorizationServerMetadataCache`,`protectedResourceMetadataCache`],kl=class{#e;#t;constructor(e){this.#e=Tl.open(e?.name??`@atproto-oauth-client`,[e=>{for(let t of Ol)e.createObjectStore(t,{autoIncrement:!0}).createIndex(`expiresAt`,`expiresAt`,{unique:!1})}],{durability:e?.durability??`strict`}),this.#t=setInterval(()=>{this.cleanup()},e?.cleanupInterval??3e4)}async run(e,t,n){return await(await this.#e).transaction([e],t,t=>n(t.objectStore(e)))}createStore(e,{encode:t,decode:n,expiresAt:r}){return{get:async t=>{let r=await this.run(e,`readonly`,e=>e.get(t));if(r!==void 0){if(r.expiresAt!=null&&new Date(r.expiresAt)<new Date)await this.run(e,`readwrite`,e=>e.delete(t));else return n(r.value)}},set:async(n,i)=>{let a={value:await t(i),expiresAt:r(i)?.toISOString()};await this.run(e,`readwrite`,e=>e.put(a,n))},del:async t=>{await this.run(e,`readwrite`,e=>e.delete(t))}}}getSessionStore(){return this.createStore(`session`,{expiresAt:({tokenSet:e})=>e.refresh_token||e.expires_at==null?null:new Date(e.expires_at),encode:({dpopKey:e,...t})=>({...t,dpopKey:El(e)}),decode:async({dpopKey:e,...t})=>({...t,dpopKey:await Dl(e)})})}getStateStore(){return this.createStore(`state`,{expiresAt:e=>new Date(Date.now()+6e5),encode:({dpopKey:e,...t})=>({...t,dpopKey:El(e)}),decode:async({dpopKey:e,...t})=>({...t,dpopKey:await Dl(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.#e;for(let t of Ol)await e.transaction([t],`readwrite`,e=>e.objectStore(t).index(`expiresAt`).deleteAll(IDBKeyRange.upperBound(Date.now())))}async[Symbol.asyncDispose](){clearInterval(this.#t),this.#t=void 0;let e=this.#e;this.#e=Promise.reject(Error(`Database has been disposed`)),this.#e.catch(()=>null);let t=await e.catch(()=>null);t&&await t[Symbol.asyncDispose]()}},Al=typeof navigator<`u`&&navigator.locks?.request?(e,t)=>navigator.locks.request(e,{mode:`exclusive`},async()=>t()):void 0,jl=class{constructor(){if(this.requestLock=Al,typeof crypto!=`object`||!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 na.generate(e)}getRandomValues(e){return crypto.getRandomValues(new Uint8Array(e))}async digest(e,{name:t}){switch(t){case`sha256`:case`sha384`:case`sha512`:{let n=await crypto.subtle.digest(`SHA-${t.slice(3)}`,e);return new Uint8Array(n)}default:throw Error(`Unsupported digest algorithm: ${t}`)}}},Ml=class extends Error{constructor(){super(`Login complete, please close the popup window.`),this.code=`LOGIN_CONTINUED_IN_PARENT_WINDOW`}};function Nl(e,t=`127.0.0.1`){if(!vs(e.hostname))throw TypeError(`Expected a loopback host, got ${e.hostname}`);let n=`http://${e.hostname===`localhost`?t:e.hostname}${e.port&&!e.port.startsWith(`:`)?`:${e.port}`:e.port}${e.pathname}`;return`http://localhost${e.pathname===`/`?``:e.pathname}?redirect_uri=${encodeURIComponent(n)}`}var $=`@@atproto/oauth-client-browser`,Pl=`${$}(popup-channel)`,Fl=`${$}(popup-state):`,Il=new BroadcastChannel(`${$}(synchronization-channel:2)`),Ll=new jl,Rl=class e extends bl{static async load({clientId:t,...n}){if(t.startsWith(`http:`)){let r=Js(t);return new e({clientMetadata:r,...n})}if(t.startsWith(`https:`)){gc(t);let r=await bl.fetchMetadata({clientId:t,...n});return new e({...n,clientMetadata:r})}throw TypeError(`Invalid client id: ${t}`)}constructor({clientMetadata:e=Js(Nl(window.location)),responseMode:t=`fragment`,...n}){if(!globalThis.crypto?.subtle)throw Error(`WebCrypto API is required`);if(![`query`,`fragment`].includes(t))throw TypeError(`Invalid response mode: ${t}`);let r=new kl;super({...n,clientMetadata:e,responseMode:t,keyset:void 0,runtimeImplementation:Ll,sessionStore:r.getSessionStore(),stateStore:r.getStateStore(),didCache:r.getDidCache(),handleCache:r.getHandleCache(),dpopNonceCache:r.getDpopNonceCache(),authorizationServerMetadataCache:r.getAuthorizationServerMetadataCache(),protectedResourceMetadataCache:r.getProtectedResourceMetadataCache(),onSessionDeleted:async(e,t)=>(localStorage.getItem(`${$}(sub)`)===e&&localStorage.removeItem(`${$}(sub)`),Il.postMessage({name:`onSessionDeleted`,args:[e,t]}),n.onSessionDeleted?.call(null,e,t)),onSessionUpdated:async(e,t)=>(Il.postMessage({name:`onSessionUpdated`,args:[e,t]}),n.onSessionUpdated?.call(null,e,t))}),this.ac=new AbortController,this.database=r;let{signal:i}=this.ac;Il.addEventListener(`message`,e=>{if(e.source===window)return;let{name:t,args:r}=e.data,i=n[t];i?.(...r)},{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 zl(this.clientMetadata);let t=localStorage.getItem(`${$}(sub)`);if(t)try{return{session:await this.restore(t,e)}}catch(e){throw localStorage.removeItem(`${$}(sub)`),e}}async restore(e,t){let n=await super.restore(e,t);return localStorage.setItem(`${$}(sub)`,n.sub),n}async revoke(e){return localStorage.removeItem(`${$}(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 n=await this.authorize(e,t);return window.location.href=n.href,new Promise((e,t)=>{setTimeout(e=>{this.abortRequest(n).then(()=>t(e),n=>t(AggregateError([e,n])))},5e3,Error(`User navigated back`))})}async signInPopup(e,t){let n=t?.popupName??`_blank`,r=t?.popupFeatures??`width=600,height=600,menubar=no,toolbar=no`,i=window.open(`about:blank`,n,r),a=`${Math.random().toString(36).slice(2)}`,o=await this.authorize(e,{...t,state:`${Fl}${a}`,display:t?.display??`popup`});return t?.signal?.throwIfAborted(),i?i.window.location.href=o.href:i=window.open(o.href,n,r),i?.focus(),new Promise((e,n)=>{let r=new BroadcastChannel(Pl),o=()=>{clearTimeout(c),r.removeEventListener(`message`,l),r.close(),t?.signal?.removeEventListener(`abort`,s),i?.close()},s=()=>{n(Error(t?.signal?.aborted?`Aborted`:`Timeout`)),o()};t?.signal?.addEventListener(`abort`,s);let c=setTimeout(s,3e5),l=async({data:i})=>{if(i.key!==a||!(`result`in i))return;r.postMessage({key:a,ack:!0}),o();let{result:s}=i;if(s.status===`fulfilled`){let r=s.value;try{t?.signal?.throwIfAborted(),e(await this.restore(r,!1))}catch(e){n(e),this.revoke(r)}}else{let{message:e,params:t}=s.reason;n(new Z(new URLSearchParams(t),e))}};r.addEventListener(`message`,l)})}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=this.responseMode===`fragment`?new URLSearchParams(location.hash.slice(1)):new URLSearchParams(location.search);return!e.has(`state`)||!(e.has(`code`)||e.has(`error`))?null:e}async initCallback(e=this.readCallbackParams(),t=this.findRedirectUrl()){if(!e)throw TypeError(`No OAuth callback parameters found in the URL`);this.responseMode===`fragment`?history.replaceState(null,``,location.pathname+location.search):this.responseMode===`query`&&history.replaceState(null,``,location.pathname);let n=e=>{let t=new BroadcastChannel(Pl);return new Promise(n=>{let r=e=>{clearTimeout(a),t.removeEventListener(`message`,i),t.close(),n(e)},i=({data:t})=>{`ack`in t&&e.key===t.key&&r(!0)};t.addEventListener(`message`,i),t.postMessage(e);let a=setTimeout(r,500,!1)})};return this.callback(e,{redirect_uri:t}).then(async e=>{if(e.state?.startsWith(Fl))throw await n({key:e.state.slice(Fl.length),result:{status:`fulfilled`,value:e.session.sub}})||await e.session.signOut(),new Ml;return localStorage.setItem(`${$}(sub)`,e.session.sub),e}).catch(async e=>{throw e instanceof Z&&e.state?.startsWith(Fl)?(await n({key:e.state.slice(Fl.length),result:{status:`rejected`,reason:{message:e.message,params:Array.from(e.params.entries())}}}),new Ml):e}).catch(e=>{throw e instanceof Ml&&window.close(),e})}async[Symbol.asyncDispose](){try{this.ac.abort()}finally{await this.database[Symbol.asyncDispose]()}}async dispose(){await this[Symbol.asyncDispose]()}};function zl(e){if(!Us(e.client_id)||window.location.hostname!==`localhost`)return;let t=new URL(window.location.href);for(let n of e.redirect_uris){let e=new URL(n);if((e.hostname===`127.0.0.1`||e.hostname===`[::1]`)&&(!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}`)}var Bl=`acs.github.io`,Vl=`https://${Bl}/democlip/oauth-client-metadata.json`,Hl=`https://bsky.social`,Ul=`https://video.bsky.app`,Wl=`atproto transition:generic`,Gl=[`localhost`,`127.0.0.1`,`[::1]`],Kl=class{session;fetchFn;constructor(e,t=globalThis.fetch){this.session=e,this.fetchFn=t.bind(globalThis)}async uploadVideo(e){let t=await this.serviceToken(),n=new URL(`/xrpc/app.bsky.video.uploadVideo`,Ul);n.searchParams.set(`did`,this.session.did),n.searchParams.set(`name`,e.name);let r=await this.fetchFn(n,{method:`POST`,headers:{authorization:`Bearer ${t}`,"content-type":e.blob.type,"content-length":String(e.blob.size)},body:e.blob});return this.jobFrom(r)}async videoJob(e){let t=new URL(`/xrpc/app.bsky.video.getJobStatus`,Ul);t.searchParams.set(`jobId`,e);let n=await this.fetchFn(t);return this.jobFrom(n)}async createPost(e){let t=await this.session.fetchHandler(`/xrpc/com.atproto.repo.createRecord`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({repo:this.session.did,collection:`app.bsky.feed.post`,record:e})}),n=await this.ok(t);return{uri:n.uri,cid:n.cid}}async serviceToken(){let{aud:e}=await this.session.getTokenInfo(),t=new URLSearchParams({aud:`did:web:${new URL(e).host}`,lxm:`com.atproto.repo.uploadBlob`,exp:String(Math.floor(Date.now()/1e3)+1800)}),n=await this.session.fetchHandler(`/xrpc/com.atproto.server.getServiceAuth?${t}`,{method:`GET`});return(await this.ok(n)).token}async ok(e){if(e.ok)return e.json();let t=await e.text().catch(()=>``),n=t;try{n=JSON.parse(t).message??t}catch{}throw Error(`Bluesky ${e.status}: ${n||e.statusText}`)}async jobFrom(e){let t=await Jl(e),n=t?.jobStatus,r=t&&(t.jobId||t.state||t.blob)?t:null,i=n??r;if(i)return ql(i,t?.blob??null);let a=t?.message||t?.error,o=t?JSON.stringify(t).slice(0,200):`no JSON body`;throw Error(`Bluesky's video service answered ${e.status}: ${a??o}`)}};function ql(e,t=null){return{jobId:e.jobId??``,state:e.state??`JOB_STATE_COMPLETED`,progress:e.progress,blob:e.blob??t,error:e.error,failureCode:e.failureCode,message:e.message}}async function Jl(e){try{return await e.json()}catch{return null}}var Yl=null,Xl=null;function Zl(e){return e.protocol===`http:`&&Gl.includes(e.hostname)}function Ql(e,t){return`${Nl(e)}&scope=${encodeURIComponent(t)}`}function $l(){return Yl??=eu(),Yl}function eu(){let e=window.location;return Zl(e)?Rl.load({clientId:Ql(e,Wl),handleResolver:Hl,allowHttp:!0}):Rl.load({clientId:Vl,handleResolver:Hl})}async function tu(){try{Xl=(await(await $l()).init(!1))?.session??Xl}catch(e){console.warn(`Bluesky session could not be restored`,e)}}function nu(e){return e.trim().replace(/^@/,``)}async function ru(e){let t=window.location;if(!Zl(t)&&t.hostname!==Bl)throw Error(`Bluesky sign-in works on the deployed app, or on a dev server over http at 127.0.0.1`);await(await $l()).signIn(nu(e))}async function iu(){await Xl?.signOut(),Xl=null,ou=null}function au(){return Xl?.did??null}var ou=null;async function su(){return Xl?(ou??=await cu(Xl),ou):null}async function cu(e){try{let t=await e.fetchHandler(`/xrpc/com.atproto.repo.describeRepo?repo=${encodeURIComponent(e.did)}`);return t.ok?(await t.json()).handle??null:null}catch{return null}}async function lu(){if(await tu(),!Xl)throw Error(`not signed in to Bluesky`);return new Kl(Xl)}export{Kl as XrpcBlueskyService,au as blueskyDid,su as blueskyHandle,lu as blueskyService,cu as fetchHandle,tu as initBluesky,Zl as isLoopback,Ql as loopbackClientId,nu as normalizeHandle,ru as signIn,iu as signOut};
|
|
1
|
+
import{n as e,t}from"./main-VCi5PISp.js";var n=t(((e,t,n)=>{var r=function(e){return e&&e.Math===Math&&e};t.exports=r(typeof globalThis==`object`&&globalThis)||r(typeof window==`object`&&window)||r(typeof self==`object`&&self)||r(typeof global==`object`&&global)||r(typeof n==`object`&&n)||(function(){return this})()||Function(`return this`)()})),r=t(((e,t)=>{t.exports=n()})),i=t(((e,t)=>{t.exports=function(e){try{return!!e()}catch{return!0}}})),a=t(((e,t)=>{t.exports=!i()(function(){var e=function(){}.bind();return typeof e!=`function`||e.hasOwnProperty(`prototype`)})})),o=t(((e,t)=>{var n=a(),r=Function.prototype,i=r.call,o=n&&r.bind.bind(i,i);t.exports=n?o:function(e){return function(){return i.apply(e,arguments)}}})),s=t(((e,t)=>{t.exports=function(e){return e==null}})),c=t(((e,t)=>{var n=s(),r=TypeError;t.exports=function(e){if(n(e))throw new r(`Can't call method on `+e);return e}})),l=t(((e,t)=>{var n=c(),r=Object;t.exports=function(e){return r(n(e))}})),u=t(((e,t)=>{var n=o(),r=l(),i=n({}.hasOwnProperty);t.exports=Object.hasOwn||function(e,t){return i(r(e),t)}})),d=t(((e,t)=>{t.exports=!1})),f=t(((e,t)=>{var r=n(),i=Object.defineProperty;t.exports=function(e,t){try{i(r,e,{value:t,configurable:!0,writable:!0})}catch{r[e]=t}return t}})),p=t(((e,t)=>{var r=d(),i=n(),a=f(),o=`__core-js_shared__`,s=t.exports=i[o]||a(o,{});(s.versions||=[]).push({version:`3.51.0`,mode:r?`pure`:`global`,copyright:`© 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.51.0/LICENSE`,source:`https://github.com/zloirock/core-js`})})),m=t(((e,t)=>{var n=p(),r=Object.create||Object;t.exports=function(e,t){return n[e]||(n[e]=t||r(null))}})),h=t(((e,t)=>{var n=o(),r=0,i=Math.random(),a=n(1.1.toString);t.exports=function(e){return`Symbol(`+(e===void 0?``:e)+`)_`+a(++r+i,36)}})),g=t(((e,t)=>{var r=n().navigator,i=r&&r.userAgent;t.exports=i?String(i):``})),ee=t(((e,t)=>{var r=n(),i=g(),a=r.process,o=r.Deno,s=a&&a.versions||o&&o.version,c=s&&s.v8,l,u;c&&(l=c.split(`.`),u=l[0]>0&&l[0]<4?1:+(l[0]+l[1])),!u&&i&&(l=i.match(/Edge\/(\d+)/),(!l||l[1]>=74)&&(l=i.match(/Chrome\/(\d+)/),l&&(u=+l[1]))),t.exports=u})),te=t(((e,t)=>{var r=ee(),a=i(),o=n().String;t.exports=!!Object.getOwnPropertySymbols&&!a(function(){var e=Symbol(`symbol detection`);return!o(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&r&&r<41})})),_=t(((e,t)=>{t.exports=te()&&!Symbol.sham&&typeof Symbol.iterator==`symbol`})),ne=t(((e,t)=>{var r=n(),i=m(),a=u(),o=h(),s=te(),c=_(),l=r.Symbol,d=i(`wks`),f=c?l.for||l:l&&l.withoutSetter||o;t.exports=function(e){return a(d,e)||(d[e]=s&&a(l,e)?l[e]:f(`Symbol.`+e)),d[e]}})),re=t((e=>{e.f=ne()})),ie=t(((e,t)=>{t.exports=!i()(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})})),ae=t(((e,t)=>{var n=typeof document==`object`&&document.all;t.exports=n===void 0&&n!==void 0?function(e){return typeof e==`function`||e===n}:function(e){return typeof e==`function`}})),oe=t(((e,t)=>{var n=ae();t.exports=function(e){return typeof e==`object`?e!==null:n(e)}})),se=t(((e,t)=>{var r=n(),i=oe(),a=r.document,o=i(a)&&i(a.createElement);t.exports=function(e){return o?a.createElement(e):{}}})),ce=t(((e,t)=>{var n=ie(),r=i(),a=se();t.exports=!n&&!r(function(){return Object.defineProperty(a(`div`),"a",{get:function(){return 7}}).a!==7})})),le=t(((e,t)=>{var n=ie(),r=i();t.exports=n&&r(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})})),ue=t(((e,t)=>{var n=oe(),r=String,i=TypeError;t.exports=function(e){if(n(e))return e;throw new i(r(e)+` is not an object`)}})),de=t(((e,t)=>{var n=a(),r=Function.prototype.call;t.exports=n?r.bind(r):function(){return r.apply(r,arguments)}})),fe=t(((e,t)=>{var r=n(),i=ae(),a=function(e){return i(e)?e:void 0};t.exports=function(e,t){return arguments.length<2?a(r[e]):r[e]&&r[e][t]}})),pe=t(((e,t)=>{t.exports=o()({}.isPrototypeOf)})),me=t(((e,t)=>{var n=fe(),r=ae(),i=pe(),a=_(),o=Object;t.exports=a?function(e){return typeof e==`symbol`}:function(e){var t=n(`Symbol`);return r(t)&&i(t.prototype,o(e))}})),he=t(((e,t)=>{var n=String;t.exports=function(e){try{return n(e)}catch{return`Object`}}})),ge=t(((e,t)=>{var n=ae(),r=he(),i=TypeError;t.exports=function(e){if(n(e))return e;throw new i(r(e)+` is not a function`)}})),_e=t(((e,t)=>{var n=ge(),r=s();t.exports=function(e,t){var i=e[t];return r(i)?void 0:n(i)}})),ve=t(((e,t)=>{var n=de(),r=ae(),i=oe(),a=TypeError;t.exports=function(e,t){var o,s;if(t===`string`&&r(o=e.toString)&&!i(s=n(o,e))||r(o=e.valueOf)&&!i(s=n(o,e))||t!==`string`&&r(o=e.toString)&&!i(s=n(o,e)))return s;throw new a(`Can't convert object to primitive value`)}})),ye=t(((e,t)=>{var n=de(),r=oe(),i=me(),a=_e(),o=ve(),s=ne(),c=TypeError,l=s(`toPrimitive`);t.exports=function(e,t){if(!r(e)||i(e))return e;var s=a(e,l),u;if(s){if(t===void 0&&(t=`default`),u=n(s,e,t),!r(u)||i(u))return u;throw new c(`Can't convert object to primitive value`)}return t===void 0&&(t=`number`),o(e,t)}})),be=t(((e,t)=>{var n=ye(),r=me();t.exports=function(e){var t=n(e,`string`);return r(t)?t:t+``}})),xe=t((e=>{var t=ie(),n=ce(),r=le(),i=ue(),a=be(),o=TypeError,s=Object.defineProperty,c=Object.getOwnPropertyDescriptor,l=`enumerable`,u=`configurable`,d=`writable`;e.f=t?r?function(e,t,n){if(i(e),t=a(t),i(n),typeof e==`function`&&t===`prototype`&&`value`in n&&d in n&&!n[d]){var r=c(e,t);r&&r[d]&&(e[t]=n.value,n={configurable:u in n?n[u]:r[u],enumerable:l in n?n[l]:r[l],writable:!1})}return s(e,t,n)}:s:function(e,t,r){if(i(e),t=a(t),i(r),n)try{return s(e,t,r)}catch{}if(`get`in r||`set`in r)throw new o(`Accessors not supported`);return`value`in r&&(e[t]=r.value),e}})),Se=t(((e,t)=>{var n=r(),i=u(),a=re(),o=xe().f;t.exports=function(e){var t=n.Symbol||={};i(t,e)||o(t,e,{value:a.f(e)})}})),Ce=t((e=>{var t={}.propertyIsEnumerable,n=Object.getOwnPropertyDescriptor;e.f=n&&!t.call({1:2},1)?function(e){var t=n(this,e);return!!t&&t.enumerable}:t})),we=t(((e,t)=>{t.exports=function(e,t){return{enumerable:!(e&1),configurable:!(e&2),writable:!(e&4),value:t}}})),Te=t(((e,t)=>{var n=o(),r=n({}.toString),i=n(``.slice);t.exports=function(e){return i(r(e),8,-1)}})),Ee=t(((e,t)=>{var n=o(),r=i(),a=Te(),s=Object,c=n(``.split);t.exports=r(function(){return!s(`z`).propertyIsEnumerable(0)})?function(e){return a(e)===`String`?c(e,``):s(e)}:s})),De=t(((e,t)=>{var n=Ee(),r=c();t.exports=function(e){return n(r(e))}})),Oe=t((e=>{var t=ie(),n=de(),r=Ce(),i=we(),a=De(),o=be(),s=u(),c=ce(),l=Object.getOwnPropertyDescriptor;e.f=t?l:function(e,t){if(e=a(e),t=o(t),c)try{return l(e,t)}catch{}if(s(e,t))return i(!n(r.f,e,t),e[t])}})),ke=t((()=>{var e=n(),t=Se(),r=xe().f,i=Oe().f,a=e.Symbol;if(t(`asyncDispose`),a){var o=i(a,`asyncDispose`);o.enumerable&&o.configurable&&o.writable&&r(a,`asyncDispose`,{value:o.value,enumerable:!1,configurable:!1,writable:!1})}})),Ae=t(((e,t)=>{ke(),t.exports=re().f(`asyncDispose`)})),je=t((()=>{var e=n(),t=Se(),r=xe().f,i=Oe().f,a=e.Symbol;if(t(`dispose`),a){var o=i(a,`dispose`);o.enumerable&&o.configurable&&o.writable&&r(a,`dispose`,{value:o.value,enumerable:!1,configurable:!1,writable:!1})}})),Me=t(((e,t)=>{je(),t.exports=re().f(`dispose`)})),v;(function(e){e.assertEqual=e=>{};function t(e){}e.assertIs=t;function n(e){throw Error()}e.assertNever=n,e.arrayToEnum=e=>{let t={};for(let n of e)t[n]=n;return t},e.getValidEnumValues=t=>{let n=e.objectKeys(t).filter(e=>typeof t[t[e]]!=`number`),r={};for(let e of n)r[e]=t[e];return e.objectValues(r)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys=typeof Object.keys==`function`?e=>Object.keys(e):e=>{let t=[];for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(let n of e)if(t(n))return n},e.isInteger=typeof Number.isInteger==`function`?e=>Number.isInteger(e):e=>typeof e==`number`&&Number.isFinite(e)&&Math.floor(e)===e;function r(e,t=` | `){return e.map(e=>typeof e==`string`?`'${e}'`:e).join(t)}e.joinValues=r,e.jsonStringifyReplacer=(e,t)=>typeof t==`bigint`?t.toString():t})(v||={});var Ne;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(Ne||={});var y=v.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),Pe=e=>{switch(typeof e){case`undefined`:return y.undefined;case`string`:return y.string;case`number`:return Number.isNaN(e)?y.nan:y.number;case`boolean`:return y.boolean;case`function`:return y.function;case`bigint`:return y.bigint;case`symbol`:return y.symbol;case`object`:return Array.isArray(e)?y.array:e===null?y.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?y.promise:typeof Map<`u`&&e instanceof Map?y.map:typeof Set<`u`&&e instanceof Set?y.set:typeof Date<`u`&&e instanceof Date?y.date:y.object;default:return y.unknown}},b=v.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`]),x=class e 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},n={_errors:[]},r=e=>{for(let i of e.issues)if(i.code===`invalid_union`)i.unionErrors.map(r);else if(i.code===`invalid_return_type`)r(i.returnTypeError);else if(i.code===`invalid_arguments`)r(i.argumentsError);else if(i.path.length===0)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){let n=i.path[r];r===i.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(i))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(this),n}static assert(t){if(!(t instanceof e))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,v.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=e=>e.message){let t={},n=[];for(let r of this.issues)if(r.path.length>0){let n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};x.create=e=>new x(e);var Fe=(e,t)=>{let n;switch(e.code){case b.invalid_type:n=e.received===y.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case b.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,v.jsonStringifyReplacer)}`;break;case b.unrecognized_keys:n=`Unrecognized key(s) in object: ${v.joinValues(e.keys,`, `)}`;break;case b.invalid_union:n=`Invalid input`;break;case b.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${v.joinValues(e.options)}`;break;case b.invalid_enum_value:n=`Invalid enum value. Expected ${v.joinValues(e.options)}, received '${e.received}'`;break;case b.invalid_arguments:n=`Invalid function arguments`;break;case b.invalid_return_type:n=`Invalid function return type`;break;case b.invalid_date:n=`Invalid date`;break;case b.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:v.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case b.too_small:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at least`:`more than`} ${e.minimum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at least`:`over`} ${e.minimum} character(s)`:e.type===`number`||e.type===`bigint`?`Number must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${e.minimum}`:e.type===`date`?`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 b.too_big:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at most`:`less than`} ${e.maximum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at most`:`under`} ${e.maximum} character(s)`:e.type===`number`?`Number must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`bigint`?`BigInt must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`date`?`Date must be ${e.exact?`exactly`:e.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(e.maximum))}`:`Invalid input`;break;case b.custom:n=`Invalid input`;break;case b.invalid_intersection_types:n=`Intersection results could not be merged`;break;case b.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case b.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,v.assertNever(e)}return{message:n}},Ie=Fe;function Le(){return Ie}var Re=e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,a=[...n,...i.path||[]],o={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let s=``,c=r.filter(e=>!!e).slice().reverse();for(let e of c)s=e(o,{data:t,defaultError:s}).message;return{...i,path:a,message:s}};function S(e,t){let n=Le(),r=Re({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Fe?void 0:Fe].filter(e=>!!e)});e.common.issues.push(r)}var C=class e{constructor(){this.value=`valid`}dirty(){this.value===`valid`&&(this.value=`dirty`)}abort(){this.value!==`aborted`&&(this.value=`aborted`)}static mergeArray(e,t){let n=[];for(let r of t){if(r.status===`aborted`)return w;r.status===`dirty`&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(t,n){let r=[];for(let e of n){let t=await e.key,n=await e.value;r.push({key:t,value:n})}return e.mergeObjectSync(t,r)}static mergeObjectSync(e,t){let n={};for(let r of t){let{key:t,value:i}=r;if(t.status===`aborted`||i.status===`aborted`)return w;t.status===`dirty`&&e.dirty(),i.status===`dirty`&&e.dirty(),t.value!==`__proto__`&&(i.value!==void 0||r.alwaysSet)&&(n[t.value]=i.value)}return{status:e.value,value:n}}},w=Object.freeze({status:`aborted`}),ze=e=>({status:`dirty`,value:e}),T=e=>({status:`valid`,value:e}),Be=e=>e.status===`aborted`,Ve=e=>e.status===`dirty`,He=e=>e.status===`valid`,Ue=e=>typeof Promise<`u`&&e instanceof Promise,E;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(E||={});var D=class{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}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}},We=(e,t)=>{if(He(t))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 x(e.common.issues);return this._error=t,this._error}}};function O(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))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 t.code===`invalid_enum_value`?{message:a??i.defaultError}:i.data===void 0?{message:a??r??i.defaultError}:t.code===`invalid_type`?{message:a??n??i.defaultError}:{message:i.defaultError}},description:i}}var k=class{get description(){return this._def.description}_getType(e){return Pe(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Pe(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new C,ctx:{common:e.parent.common,data:e.data,parsedType:Pe(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(Ue(t))throw Error(`Synchronous parse encountered promise.`);return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Pe(e)};return We(n,this._parseSync({data:e,path:n.path,parent:n}))}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Pe(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return He(n)?{value:n.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=>He(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Pe(e)},r=this._parse({data:e,path:n.path,parent:n});return We(n,await(Ue(r)?r:Promise.resolve(r)))}refine(e,t){let n=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,r)=>{let i=e(t),a=()=>r.addIssue({code:b.custom,...n(t)});return typeof Promise<`u`&&i instanceof Promise?i.then(e=>e?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t==`function`?t(n,r):t),!1))}_refinement(e){return new j({schema:this,typeName:M.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 Kt.create(this,this._def)}nullable(){return qt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ot.create(this)}promise(){return Gt.create(this,this._def)}or(e){return At.create([this,e],this._def)}and(e){return Pt.create(this,e,this._def)}transform(e){return new j({...O(this._def),schema:this,typeName:M.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new Jt({...O(this._def),innerType:this,defaultValue:t,typeName:M.ZodDefault})}brand(){return new Zt({typeName:M.ZodBranded,type:this,...O(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new Yt({...O(this._def),innerType:this,catchValue:t,typeName:M.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Qt.create(this,e)}readonly(){return $t.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Ge=/^c[^\s-]{8,}$/i,Ke=/^[0-9a-z]+$/,qe=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Je=/^[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,Ye=/^[a-z0-9_-]{21}$/i,Xe=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Ze=/^[-+]?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)?)??$/,Qe=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,$e=`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,et,tt=/^(?:(?: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])$/,nt=/^(?:(?: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])$/,rt=/^(([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]))$/,it=/^(([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])$/,at=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ot=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,st=`((\\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])))`,ct=RegExp(`^${st}$`);function lt(e){let t=`[0-5]\\d`;e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision??(t=`${t}(\\.\\d+)?`);let n=e.precision?`+`:`?`;return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function ut(e){return RegExp(`^${lt(e)}$`)}function dt(e){let t=`${st}T${lt(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function ft(e,t){return!((t!==`v4`&&t||!tt.test(e))&&(t!==`v6`&&t||!rt.test(e)))}function pt(e,t){if(!Xe.test(e))return!1;try{let[n]=e.split(`.`);if(!n)return!1;let r=n.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(n.length+(4-n.length%4)%4,`=`),i=JSON.parse(atob(r));return!(typeof i!=`object`||!i||`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&i.alg!==t)}catch{return!1}}function mt(e,t){return!((t!==`v4`&&t||!nt.test(e))&&(t!==`v6`&&t||!it.test(e)))}var ht=class e extends k{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==y.string){let t=this._getOrReturnCtx(e);return S(t,{code:b.invalid_type,expected:y.string,received:t.parsedType}),w}let t=new C,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),S(n,{code:b.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`max`)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),S(n,{code:b.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`length`){let i=e.data.length>r.value,a=e.data.length<r.value;(i||a)&&(n=this._getOrReturnCtx(e,n),i?S(n,{code:b.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&S(n,{code:b.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)Qe.test(e.data)||(n=this._getOrReturnCtx(e,n),S(n,{validation:`email`,code:b.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)et||=new RegExp($e,`u`),et.test(e.data)||(n=this._getOrReturnCtx(e,n),S(n,{validation:`emoji`,code:b.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)Je.test(e.data)||(n=this._getOrReturnCtx(e,n),S(n,{validation:`uuid`,code:b.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)Ye.test(e.data)||(n=this._getOrReturnCtx(e,n),S(n,{validation:`nanoid`,code:b.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)Ge.test(e.data)||(n=this._getOrReturnCtx(e,n),S(n,{validation:`cuid`,code:b.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)Ke.test(e.data)||(n=this._getOrReturnCtx(e,n),S(n,{validation:`cuid2`,code:b.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)qe.test(e.data)||(n=this._getOrReturnCtx(e,n),S(n,{validation:`ulid`,code:b.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),S(n,{validation:`url`,code:b.invalid_string,message:r.message}),t.dirty()}else r.kind===`regex`?(r.regex.lastIndex=0,r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),S(n,{validation:`regex`,code:b.invalid_string,message:r.message}),t.dirty())):r.kind===`trim`?e.data=e.data.trim():r.kind===`includes`?e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),S(n,{code:b.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty()):r.kind===`toLowerCase`?e.data=e.data.toLowerCase():r.kind===`toUpperCase`?e.data=e.data.toUpperCase():r.kind===`startsWith`?e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),S(n,{code:b.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),S(n,{code:b.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?dt(r).test(e.data)||(n=this._getOrReturnCtx(e,n),S(n,{code:b.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?ct.test(e.data)||(n=this._getOrReturnCtx(e,n),S(n,{code:b.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?ut(r).test(e.data)||(n=this._getOrReturnCtx(e,n),S(n,{code:b.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?Ze.test(e.data)||(n=this._getOrReturnCtx(e,n),S(n,{validation:`duration`,code:b.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?ft(e.data,r.version)||(n=this._getOrReturnCtx(e,n),S(n,{validation:`ip`,code:b.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?pt(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),S(n,{validation:`jwt`,code:b.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?mt(e.data,r.version)||(n=this._getOrReturnCtx(e,n),S(n,{validation:`cidr`,code:b.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?at.test(e.data)||(n=this._getOrReturnCtx(e,n),S(n,{validation:`base64`,code:b.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?ot.test(e.data)||(n=this._getOrReturnCtx(e,n),S(n,{validation:`base64url`,code:b.invalid_string,message:r.message}),t.dirty()):v.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:b.invalid_string,...E.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...E.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...E.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...E.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...E.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...E.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...E.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...E.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...E.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...E.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...E.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...E.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...E.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...E.errToObj(e)})}datetime(e){return typeof e==`string`?this._addCheck({kind:`datetime`,precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:`datetime`,precision:e?.precision===void 0?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...E.errToObj(e?.message)})}date(e){return this._addCheck({kind:`date`,message:e})}time(e){return typeof e==`string`?this._addCheck({kind:`time`,precision:null,message:e}):this._addCheck({kind:`time`,precision:e?.precision===void 0?null:e?.precision,...E.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...E.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...E.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...E.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...E.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...E.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...E.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...E.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...E.errToObj(t)})}nonempty(e){return this.min(1,E.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:`trim`}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toLowerCase`}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toUpperCase`}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind===`datetime`)}get isDate(){return!!this._def.checks.find(e=>e.kind===`date`)}get isTime(){return!!this._def.checks.find(e=>e.kind===`time`)}get isDuration(){return!!this._def.checks.find(e=>e.kind===`duration`)}get isEmail(){return!!this._def.checks.find(e=>e.kind===`email`)}get isURL(){return!!this._def.checks.find(e=>e.kind===`url`)}get isEmoji(){return!!this._def.checks.find(e=>e.kind===`emoji`)}get isUUID(){return!!this._def.checks.find(e=>e.kind===`uuid`)}get isNANOID(){return!!this._def.checks.find(e=>e.kind===`nanoid`)}get isCUID(){return!!this._def.checks.find(e=>e.kind===`cuid`)}get isCUID2(){return!!this._def.checks.find(e=>e.kind===`cuid2`)}get isULID(){return!!this._def.checks.find(e=>e.kind===`ulid`)}get isIP(){return!!this._def.checks.find(e=>e.kind===`ip`)}get isCIDR(){return!!this._def.checks.find(e=>e.kind===`cidr`)}get isBase64(){return!!this._def.checks.find(e=>e.kind===`base64`)}get isBase64url(){return!!this._def.checks.find(e=>e.kind===`base64url`)}get minLength(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};ht.create=e=>new ht({checks:[],typeName:M.ZodString,coerce:e?.coerce??!1,...O(e)});function gt(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=(t.toString().split(`.`)[1]||``).length,i=n>r?n:r;return Number.parseInt(e.toFixed(i).replace(`.`,``))%Number.parseInt(t.toFixed(i).replace(`.`,``))/10**i}var _t=class e extends k{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==y.number){let t=this._getOrReturnCtx(e);return S(t,{code:b.invalid_type,expected:y.number,received:t.parsedType}),w}let t,n=new C;for(let r of this._def.checks)r.kind===`int`?v.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),S(t,{code:b.invalid_type,expected:`integer`,received:`float`,message:r.message}),n.dirty()):r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),S(t,{code:b.too_small,minimum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),S(t,{code:b.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?gt(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),S(t,{code:b.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),S(t,{code:b.not_finite,message:r.message}),n.dirty()):v.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,E.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,E.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,E.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,E.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:E.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:E.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:E.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:E.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:E.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:E.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:E.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:E.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:E.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:E.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind===`int`||e.kind===`multipleOf`&&v.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks)if(n.kind===`finite`||n.kind===`int`||n.kind===`multipleOf`)return!0;else n.kind===`min`?(t===null||n.value>t)&&(t=n.value):n.kind===`max`&&(e===null||n.value<e)&&(e=n.value);return Number.isFinite(t)&&Number.isFinite(e)}};_t.create=e=>new _t({checks:[],typeName:M.ZodNumber,coerce:e?.coerce||!1,...O(e)});var vt=class e extends k{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==y.bigint)return this._getInvalidInput(e);let t,n=new C;for(let r of this._def.checks)r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),S(t,{code:b.too_small,type:`bigint`,minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),S(t,{code:b.too_big,type:`bigint`,maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`multipleOf`?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),S(t,{code:b.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):v.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return S(t,{code:b.invalid_type,expected:y.bigint,received:t.parsedType}),w}gte(e,t){return this.setLimit(`min`,e,!0,E.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,E.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,E.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,E.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:E.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!1,message:E.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:E.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:E.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:E.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:E.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};vt.create=e=>new vt({checks:[],typeName:M.ZodBigInt,coerce:e?.coerce??!1,...O(e)});var yt=class extends k{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==y.boolean){let t=this._getOrReturnCtx(e);return S(t,{code:b.invalid_type,expected:y.boolean,received:t.parsedType}),w}return T(e.data)}};yt.create=e=>new yt({typeName:M.ZodBoolean,coerce:e?.coerce||!1,...O(e)});var bt=class e extends k{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==y.date){let t=this._getOrReturnCtx(e);return S(t,{code:b.invalid_type,expected:y.date,received:t.parsedType}),w}if(Number.isNaN(e.data.getTime()))return S(this._getOrReturnCtx(e),{code:b.invalid_date}),w;let t=new C,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),S(n,{code:b.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:`date`}),t.dirty()):r.kind===`max`?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),S(n,{code:b.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):v.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:`min`,value:e.getTime(),message:E.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:E.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e==null?null:new Date(e)}get maxDate(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e==null?null:new Date(e)}};bt.create=e=>new bt({checks:[],coerce:e?.coerce||!1,typeName:M.ZodDate,...O(e)});var xt=class extends k{_parse(e){if(this._getType(e)!==y.symbol){let t=this._getOrReturnCtx(e);return S(t,{code:b.invalid_type,expected:y.symbol,received:t.parsedType}),w}return T(e.data)}};xt.create=e=>new xt({typeName:M.ZodSymbol,...O(e)});var St=class extends k{_parse(e){if(this._getType(e)!==y.undefined){let t=this._getOrReturnCtx(e);return S(t,{code:b.invalid_type,expected:y.undefined,received:t.parsedType}),w}return T(e.data)}};St.create=e=>new St({typeName:M.ZodUndefined,...O(e)});var Ct=class extends k{_parse(e){if(this._getType(e)!==y.null){let t=this._getOrReturnCtx(e);return S(t,{code:b.invalid_type,expected:y.null,received:t.parsedType}),w}return T(e.data)}};Ct.create=e=>new Ct({typeName:M.ZodNull,...O(e)});var wt=class extends k{constructor(){super(...arguments),this._any=!0}_parse(e){return T(e.data)}};wt.create=e=>new wt({typeName:M.ZodAny,...O(e)});var Tt=class extends k{constructor(){super(...arguments),this._unknown=!0}_parse(e){return T(e.data)}};Tt.create=e=>new Tt({typeName:M.ZodUnknown,...O(e)});var Et=class extends k{_parse(e){let t=this._getOrReturnCtx(e);return S(t,{code:b.invalid_type,expected:y.never,received:t.parsedType}),w}};Et.create=e=>new Et({typeName:M.ZodNever,...O(e)});var Dt=class extends k{_parse(e){if(this._getType(e)!==y.undefined){let t=this._getOrReturnCtx(e);return S(t,{code:b.invalid_type,expected:y.void,received:t.parsedType}),w}return T(e.data)}};Dt.create=e=>new Dt({typeName:M.ZodVoid,...O(e)});var Ot=class e extends k{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==y.array)return S(t,{code:b.invalid_type,expected:y.array,received:t.parsedType}),w;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(S(t,{code:e?b.too_big:b.too_small,minimum:i?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(S(t,{code:b.too_small,minimum:r.minLength.value,type:`array`,inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(S(t,{code:b.too_big,maximum:r.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new D(t,e,t.path,n)))).then(e=>C.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new D(t,e,t.path,n)));return C.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:E.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:E.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:E.toString(n)}})}nonempty(e){return this.min(1,e)}};Ot.create=(e,t)=>new Ot({type:e,minLength:null,maxLength:null,exactLength:null,typeName:M.ZodArray,...O(t)});function kt(e){if(e instanceof A){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=Kt.create(kt(r))}return new A({...e._def,shape:()=>t})}return e instanceof Ot?new Ot({...e._def,type:kt(e.element)}):e instanceof Kt?Kt.create(kt(e.unwrap())):e instanceof qt?qt.create(kt(e.unwrap())):e instanceof Ft?Ft.create(e.items.map(e=>kt(e))):e}var A=class e extends k{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=v.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==y.object){let t=this._getOrReturnCtx(e);return S(t,{code:b.invalid_type,expected:y.object,received:t.parsedType}),w}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Et&&this._def.unknownKeys===`strip`))for(let e in n.data)i.includes(e)||a.push(e);let o=[];for(let e of i){let t=r[e],i=n.data[e];o.push({key:{status:`valid`,value:e},value:t._parse(new D(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof Et){let e=this._def.unknownKeys;if(e===`passthrough`)for(let e of a)o.push({key:{status:`valid`,value:e},value:{status:`valid`,value:n.data[e]}});else if(e===`strict`)a.length>0&&(S(n,{code:b.unrecognized_keys,keys:a}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of a){let r=n.data[t];o.push({key:{status:`valid`,value:t},value:e._parse(new D(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of o){let n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>C.mergeObjectSync(t,e)):C.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return E.errToObj,new e({...this._def,unknownKeys:`strict`,...t===void 0?{}:{errorMap:(e,n)=>{let r=this._def.errorMap?.(e,n).message??n.defaultError;return e.code===`unrecognized_keys`?{message:E.errToObj(t).message??r}:{message:r}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:M.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let e of v.objectKeys(t))t[e]&&this.shape[e]&&(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let e of v.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return kt(this)}partial(t){let n={};for(let e of v.objectKeys(this.shape)){let r=this.shape[e];n[e]=t&&!t[e]?r:r.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let e of v.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof Kt;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return Ht(v.objectKeys(this.shape))}};A.create=(e,t)=>new A({shape:()=>e,unknownKeys:`strip`,catchall:Et.create(),typeName:M.ZodObject,...O(t)}),A.strictCreate=(e,t)=>new A({shape:()=>e,unknownKeys:`strict`,catchall:Et.create(),typeName:M.ZodObject,...O(t)}),A.lazycreate=(e,t)=>new A({shape:e,unknownKeys:`strip`,catchall:Et.create(),typeName:M.ZodObject,...O(t)});var At=class extends k{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function r(e){for(let t of e)if(t.result.status===`valid`)return t.result;for(let n of e)if(n.result.status===`dirty`)return t.common.issues.push(...n.ctx.common.issues),n.result;let n=e.map(e=>new x(e.ctx.common.issues));return S(t,{code:b.invalid_union,unionErrors:n}),w}if(t.common.async)return Promise.all(n.map(async e=>{let n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(r);{let e,r=[];for(let i of n){let n={...t,common:{...t.common,issues:[]},parent:null},a=i._parseSync({data:t.data,path:t.path,parent:n});if(a.status===`valid`)return a;a.status===`dirty`&&!e&&(e={result:a,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let i=r.map(e=>new x(e));return S(t,{code:b.invalid_union,unionErrors:i}),w}}get options(){return this._def.options}};At.create=(e,t)=>new At({options:e,typeName:M.ZodUnion,...O(t)});var jt=e=>e instanceof Bt?jt(e.schema):e instanceof j?jt(e.innerType()):e instanceof Vt?[e.value]:e instanceof Ut?e.options:e instanceof Wt?v.objectValues(e.enum):e instanceof Jt?jt(e._def.innerType):e instanceof St?[void 0]:e instanceof Ct?[null]:e instanceof Kt?[void 0,...jt(e.unwrap())]:e instanceof qt?[null,...jt(e.unwrap())]:e instanceof Zt||e instanceof $t?jt(e.unwrap()):e instanceof Yt?jt(e._def.innerType):[],Mt=class e extends k{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==y.object)return S(t,{code:b.invalid_type,expected:y.object,received:t.parsedType}),w;let n=this.discriminator,r=t.data[n],i=this.optionsMap.get(r);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}):(S(t,{code:b.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),w)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let i=new Map;for(let e of n){let n=jt(e.shape[t]);if(!n.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let r of n){if(i.has(r))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(r)}`);i.set(r,e)}}return new e({typeName:M.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...O(r)})}};function Nt(e,t){let n=Pe(e),r=Pe(t);if(e===t)return{valid:!0,data:e};if(n===y.object&&r===y.object){let n=v.objectKeys(t),r=v.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=Nt(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}if(n===y.array&&r===y.array){if(e.length!==t.length)return{valid:!1};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=Nt(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}return n===y.date&&r===y.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var Pt=class extends k{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(Be(e)||Be(r))return w;let i=Nt(e.value,r.value);return i.valid?((Ve(e)||Ve(r))&&t.dirty(),{status:t.value,value:i.data}):(S(n,{code:b.invalid_intersection_types}),w)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Pt.create=(e,t,n)=>new Pt({left:e,right:t,typeName:M.ZodIntersection,...O(n)});var Ft=class e extends k{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==y.array)return S(n,{code:b.invalid_type,expected:y.array,received:n.parsedType}),w;if(n.data.length<this._def.items.length)return S(n,{code:b.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),w;!this._def.rest&&n.data.length>this._def.items.length&&(S(n,{code:b.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let r=[...n.data].map((e,t)=>{let r=this._def.items[t]||this._def.rest;return r?r._parse(new D(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>C.mergeArray(t,e)):C.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Ft.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new Ft({items:e,typeName:M.ZodTuple,rest:null,...O(t)})};var It=class e extends k{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==y.object)return S(n,{code:b.invalid_type,expected:y.object,received:n.parsedType}),w;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new D(n,e,n.path,e)),value:a._parse(new D(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?C.mergeObjectAsync(t,r):C.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof k?new e({keyType:t,valueType:n,typeName:M.ZodRecord,...O(r)}):new e({keyType:ht.create(),valueType:t,typeName:M.ZodRecord,...O(n)})}},Lt=class extends k{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==y.map)return S(n,{code:b.invalid_type,expected:y.map,received:n.parsedType}),w;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new D(n,e,n.path,[a,`key`])),value:i._parse(new D(n,t,n.path,[a,`value`]))}));if(n.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let n of a){let r=await n.key,i=await n.value;if(r.status===`aborted`||i.status===`aborted`)return w;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}})}{let e=new Map;for(let n of a){let r=n.key,i=n.value;if(r.status===`aborted`||i.status===`aborted`)return w;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};Lt.create=(e,t,n)=>new Lt({valueType:t,keyType:e,typeName:M.ZodMap,...O(n)});var Rt=class e extends k{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==y.set)return S(n,{code:b.invalid_type,expected:y.set,received:n.parsedType}),w;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(S(n,{code:b.too_small,minimum:r.minSize.value,type:`set`,inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&n.data.size>r.maxSize.value&&(S(n,{code:b.too_big,maximum:r.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());let i=this._def.valueType;function a(e){let n=new Set;for(let r of e){if(r.status===`aborted`)return w;r.status===`dirty`&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}let o=[...n.data.values()].map((e,t)=>i._parse(new D(n,e,n.path,t)));return n.common.async?Promise.all(o).then(e=>a(e)):a(o)}min(t,n){return new e({...this._def,minSize:{value:t,message:E.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:E.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};Rt.create=(e,t)=>new Rt({valueType:e,minSize:null,maxSize:null,typeName:M.ZodSet,...O(t)});var zt=class e extends k{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==y.function)return S(t,{code:b.invalid_type,expected:y.function,received:t.parsedType}),w;function n(e,n){return Re({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Le(),Fe].filter(e=>!!e),issueData:{code:b.invalid_arguments,argumentsError:n}})}function r(e,n){return Re({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Le(),Fe].filter(e=>!!e),issueData:{code:b.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof Gt){let e=this;return T(async function(...t){let o=new x([]),s=await e._def.args.parseAsync(t,i).catch(e=>{throw o.addIssue(n(t,e)),o}),c=await Reflect.apply(a,this,s);return await e._def.returns._def.type.parseAsync(c,i).catch(e=>{throw o.addIssue(r(c,e)),o})})}{let e=this;return T(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new x([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new x([r(s,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:Ft.create(t).rest(Tt.create())})}returns(t){return new e({...this._def,returns:t})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(t,n,r){return new e({args:t||Ft.create([]).rest(Tt.create()),returns:n||Tt.create(),typeName:M.ZodFunction,...O(r)})}},Bt=class extends k{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})}};Bt.create=(e,t)=>new Bt({getter:e,typeName:M.ZodLazy,...O(t)});var Vt=class extends k{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return S(t,{received:t.data,code:b.invalid_literal,expected:this._def.value}),w}return{status:`valid`,value:e.data}}get value(){return this._def.value}};Vt.create=(e,t)=>new Vt({value:e,typeName:M.ZodLiteral,...O(t)});function Ht(e,t){return new Ut({values:e,typeName:M.ZodEnum,...O(t)})}var Ut=class e extends k{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return S(t,{expected:v.joinValues(n),received:t.parsedType,code:b.invalid_type}),w}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return S(t,{received:t.data,code:b.invalid_enum_value,options:n}),w}return T(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(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(e=>!t.includes(e)),{...this._def,...n})}};Ut.create=Ht;var Wt=class extends k{_parse(e){let t=v.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==y.string&&n.parsedType!==y.number){let e=v.objectValues(t);return S(n,{expected:v.joinValues(e),received:n.parsedType,code:b.invalid_type}),w}if(this._cache||=new Set(v.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=v.objectValues(t);return S(n,{received:n.data,code:b.invalid_enum_value,options:e}),w}return T(e.data)}get enum(){return this._def.values}};Wt.create=(e,t)=>new Wt({values:e,typeName:M.ZodNativeEnum,...O(t)});var Gt=class extends k{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==y.promise&&t.common.async===!1?(S(t,{code:b.invalid_type,expected:y.promise,received:t.parsedType}),w):T((t.parsedType===y.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};Gt.create=(e,t)=>new Gt({type:e,typeName:M.ZodPromise,...O(t)});var j=class extends k{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===M.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{S(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),r.type===`preprocess`){let e=r.transform(n.data,i);if(n.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return w;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?w:r.status===`dirty`||t.value===`dirty`?ze(r.value):r});{if(t.value===`aborted`)return w;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?w:r.status===`dirty`||t.value===`dirty`?ze(r.value):r}}if(r.type===`refinement`){let e=e=>{let t=r.refinement(e,i);if(n.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(n.common.async===!1){let r=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return r.status===`aborted`?w:(r.status===`dirty`&&t.dirty(),e(r.value),{status:t.value,value:r.value})}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>n.status===`aborted`?w:(n.status===`dirty`&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if(r.type===`transform`){if(n.common.async===!1){let e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!He(e))return w;let a=r.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}}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>He(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):w)}v.assertNever(r)}};j.create=(e,t,n)=>new j({schema:e,typeName:M.ZodEffects,effect:t,...O(n)}),j.createWithPreprocess=(e,t,n)=>new j({schema:t,effect:{type:`preprocess`,transform:e},typeName:M.ZodEffects,...O(n)});var Kt=class extends k{_parse(e){return this._getType(e)===y.undefined?T(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Kt.create=(e,t)=>new Kt({innerType:e,typeName:M.ZodOptional,...O(t)});var qt=class extends k{_parse(e){return this._getType(e)===y.null?T(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};qt.create=(e,t)=>new qt({innerType:e,typeName:M.ZodNullable,...O(t)});var Jt=class extends k{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===y.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};Jt.create=(e,t)=>new Jt({innerType:e,typeName:M.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...O(t)});var Yt=class extends k{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Ue(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new x(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new x(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Yt.create=(e,t)=>new Yt({innerType:e,typeName:M.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...O(t)});var Xt=class extends k{_parse(e){if(this._getType(e)!==y.nan){let t=this._getOrReturnCtx(e);return S(t,{code:b.invalid_type,expected:y.nan,received:t.parsedType}),w}return{status:`valid`,value:e.data}}};Xt.create=e=>new Xt({typeName:M.ZodNaN,...O(e)});var Zt=class extends k{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},Qt=class e extends k{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?w:e.status===`dirty`?(t.dirty(),ze(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})();{let e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?w:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(t,n){return new e({in:t,out:n,typeName:M.ZodPipeline})}},$t=class extends k{_parse(e){let t=this._def.innerType._parse(e),n=e=>(He(e)&&(e.value=Object.freeze(e.value)),e);return Ue(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};$t.create=(e,t)=>new $t({innerType:e,typeName:M.ZodReadonly,...O(t)}),A.lazycreate;var M;(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`})(M||={});var N=ht.create,P=_t.create;Xt.create,vt.create;var F=yt.create;bt.create,xt.create,St.create,Ct.create,wt.create;var en=Tt.create,tn=Et.create;Dt.create;var I=Ot.create,L=A.create;A.strictCreate;var R=At.create,nn=Mt.create,rn=Pt.create;Ft.create;var an=It.create;Lt.create,Rt.create,zt.create,Bt.create;var z=Vt.create,B=Ut.create;Wt.create,Gt.create,j.create,Kt.create,qt.create;var on=j.createWithPreprocess;Qt.create,Ae(),Me();var sn=`ERR_JWKS_NO_MATCHING_KEY`,cn=`ERR_JWK_INVALID`,ln=`ERR_JWK_NOT_FOUND`,un=`ERR_JWT_INVALID`,dn=`ERR_JWT_CREATE`,fn=`ERR_JWT_VERIFY`,V=class extends TypeError{constructor(e=`JWK error`,t=cn,n){super(e,n),this.code=t}},pn=class e extends Error{constructor(e=`Unable to create JWT`,t=dn,n){super(e,n),this.code=t}static from(t,n,r){return t instanceof e?t:t instanceof V?new e(r,t.code,{cause:t}):new e(r,n,{cause:t})}},mn=class e extends Error{constructor(e=`Invalid JWT`,t=fn,n){super(e,n),this.code=t}static from(t,n,r){return t instanceof e?t:t instanceof V?new e(r,t.code,{cause:t}):new e(r,n,{cause:t})}},hn=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error(`Unknown type, must be binary type`)}},gn=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let r=t.codePointAt(0);if(r===void 0)throw Error(`Invalid prefix character`);this.prefixCodePoint=r,this.baseDecode=n}decode(e){if(typeof e==`string`){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 vn(this,e)}},_n=class{decoders;constructor(e){this.decoders=e}or(e){return vn(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function vn(e,t){return new _n({...e.decoders??{[e.prefix]:e},...t.decoders??{[t.prefix]:t}})}var yn=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,r){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=r,this.encoder=new hn(e,t,n),this.decoder=new gn(e,t,r)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function bn({name:e,prefix:t,encode:n,decode:r}){return new yn(e,t,n,r)}function xn(e,t,n,r){let i=e.length;for(;e[i-1]===`=`;)--i;let a=new Uint8Array(i*n/8|0),o=0,s=0,c=0;for(let l=0;l<i;++l){let i=t[e[l]];if(i===void 0)throw SyntaxError(`Non-${r} character`);s=s<<n|i,o+=n,o>=8&&(o-=8,a[c++]=255&s>>o)}if(o>=n||255&s<<8-o)throw SyntaxError(`Unexpected end of data`);return a}function Sn(e,t,n){let r=t[t.length-1]===`=`,i=(1<<n)-1,a=``,o=0,s=0;for(let r=0;r<e.length;++r)for(s=s<<8|e[r],o+=8;o>n;)o-=n,a+=t[i&s>>o];if(o!==0&&(a+=t[i&s<<n-o]),r)for(;a.length*n&7;)a+=`=`;return a}function Cn(e){let t={};for(let n=0;n<e.length;++n)t[e[n]]=n;return t}function wn({name:e,prefix:t,bitsPerChar:n,alphabet:r}){let i=Cn(r);return bn({prefix:t,name:e,encode(e){return Sn(e,r,n)},decode(t){return xn(t,i,n,e)}})}wn({prefix:`m`,name:`base64`,alphabet:`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,bitsPerChar:6}),wn({prefix:`M`,name:`base64pad`,alphabet:`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=`,bitsPerChar:6});var Tn=wn({prefix:`u`,name:`base64url`,alphabet:`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_`,bitsPerChar:6});wn({prefix:`U`,name:`base64urlpad`,alphabet:`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=`,bitsPerChar:6});var En=e=>e!==void 0,Dn=e=>(t,n)=>{let r=e.indexOf(t),i=e.indexOf(n);return r===i?0:r===-1?1:i===-1?-1:r-i};function On(e){return e==null?e=>!0:Array.isArray(e)?t=>e.includes(t):t=>t===e}var kn=(e,t)=>function(){let t=e.call(this);return Object.defineProperty(this,e.name,{get:()=>t,enumerable:!0,configurable:!0}),t},An=new TextDecoder;function jn(e){let t=Tn.baseDecode(e),n=An.decode(t);return JSON.parse(n)}var Mn=(e,t)=>{let n;for(let r=0;r<e.length;r++)if(n=e.charCodeAt(r),!(65<=n&&n<=90||97<=n&&n<=122||48<=n&&n<=57||n===45||n===95||n===46)){let n=String.fromCodePoint(e.codePointAt(r));return t.addIssue({code:b.custom,message:`Invalid character "${n}" in JWT at position ${r}`})}},Nn=(e,t=2)=>{if(!Number.isFinite(e)||e<1||(e|0)!==e)throw TypeError(`Count must be a natural number (got ${e})`);let n=e*t+(e-1),r=`Invalid JWT format`;return(i,a)=>{if(i.length<n)return a.addIssue({code:b.custom,message:`${r}: too short`}),!1;let o=0;for(let n=0;n<e-1;n++){let s=i.indexOf(`.`,o);if(s===-1)return a.addIssue({code:b.custom,message:`${r}: expected ${e} segments, got ${n+1}`}),!1;if(s-o<t)return a.addIssue({code:b.custom,message:`${r}: segment ${n+1} is too short`}),!1;o=s+1}return i.indexOf(`.`,o)===-1?i.length-o<t?(a.addIssue({code:b.custom,message:`${r}: last segment is too short`}),!1):!0:(a.addIssue({code:b.custom,message:`${r}: too many segments`}),!1)}};function Pn(e,t,n){return n.indexOf(e,t+1)===-1}var Fn=[`verify`,`encrypt`,`wrapKey`];B(Fn);function In(e){return Fn.includes(e)}function Ln(e){return e===`verify`}function Rn(e){return e===`encrypt`||e===`wrapKey`}var zn=[`sign`,`decrypt`,`unwrapKey`,`deriveKey`,`deriveBits`];B(zn);function Bn(e){return zn.includes(e)}var Vn=B([...zn,...Fn]),Hn=L({kty:N().min(1),alg:N().min(1).optional(),kid:N().min(1).optional(),use:B([`sig`,`enc`]).optional(),key_ops:I(Vn).min(1,{message:`At least one key usage must be specified`}).refine(e=>e.every(Pn),{message:`key_ops must not contain duplicates`}).optional(),x5c:I(N()).optional(),x5t:N().min(1).optional(),"x5t#S256":N().min(1).optional(),x5u:N().url().optional(),ext:F().optional(),iat:P().int().optional(),exp:P().int().optional(),nbf:P().int().optional(),revoked:L({revoked_at:P().int(),reason:N().optional()}).optional()}),Un=R([Hn.extend({kty:z(`RSA`),alg:B([`RS256`,`RS384`,`RS512`,`PS256`,`PS384`,`PS512`]).optional(),n:N().min(1),e:N().min(1),d:N().min(1).optional(),p:N().min(1).optional(),q:N().min(1).optional(),dp:N().min(1).optional(),dq:N().min(1).optional(),qi:N().min(1).optional(),oth:I(L({r:N().optional(),d:N().optional(),t:N().optional()})).min(1).optional()}),Hn.extend({kty:z(`EC`),alg:B([`ES256`,`ES384`,`ES512`]).optional(),crv:B([`P-256`,`P-384`,`P-521`]),x:N().min(1),y:N().min(1),d:N().min(1).optional()}),Hn.extend({kty:z(`EC`),alg:B([`ES256K`]).optional(),crv:B([`secp256k1`]),x:N().min(1),y:N().min(1),d:N().min(1).optional()}),Hn.extend({kty:z(`OKP`),alg:B([`EdDSA`]).optional(),crv:B([`Ed25519`,`Ed448`]),x:N().min(1),d:N().min(1).optional()}),Hn.extend({kty:z(`oct`),alg:B([`HS256`,`HS384`,`HS512`]).optional(),k:N()})]).refine(e=>e.use==null||Yn(e),{message:`"use" can only be used with public keys`,path:[`use`]}).refine(e=>!e.key_ops?.some(Bn)||Jn(e),{message:`private key usage not allowed for public keys`,path:[`key_ops`]}).refine(e=>e.use==null||e.key_ops==null||e.use===`sig`&&e.key_ops.every(Ln)||e.use===`enc`&&e.key_ops.every(Rn),{message:`"key_ops" must be consistent with "use"`,path:[`key_ops`]}),Wn=Un.refine(Gn,{message:`"kid" is required`,path:[`kid`]}).refine(Yn,{message:`private key not allowed`}).refine(e=>!e.key_ops||e.key_ops.every(In),{message:`"key_ops" must not contain private key usage for public keys`,path:[`key_ops`]});Un.refine(Jn,{message:`private key required`});function Gn(e){return`kid`in e&&e.kid!=null}function Kn(e){return`k`in e&&e.k!=null}function qn(e){return`d`in e&&e.d!=null}function Jn(e){return qn(e)||Kn(e)}function Yn(e){return!qn(e)&&!Kn(e)}var{process:Xn}=globalThis,Zn=Xn!==void 0&&typeof Xn?.versions?.node==`string`;function*Qn(e){if(typeof e.alg==`string`)yield e.alg;else switch(e.kty){case`EC`:if($n(e)&&(yield`ECDH-ES`,yield`ECDH-ES+A128KW`,yield`ECDH-ES+A192KW`,yield`ECDH-ES+A256KW`),er(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`:Zn&&(yield`ES256K`);break;default:throw new V(`Unsupported crv "${t}"`)}}return;case`OKP`:if(!e.use)throw new V(`Missing "use" Parameter value`);yield`ECDH-ES`,yield`ECDH-ES+A128KW`,yield`ECDH-ES+A192KW`,yield`ECDH-ES+A256KW`;return;case`RSA`:$n(e)&&(yield`RSA-OAEP`,yield`RSA-OAEP-256`,yield`RSA-OAEP-384`,yield`RSA-OAEP-512`,Zn&&(yield`RSA1_5`)),er(e)&&(yield`PS256`,yield`PS384`,yield`PS512`,yield`RS256`,yield`RS384`,yield`RS512`);return;case`oct`:$n(e)&&(yield`A128GCMKW`,yield`A192GCMKW`,yield`A256GCMKW`,yield`A128KW`,yield`A192KW`,yield`A256KW`),er(e)&&(yield`HS256`,yield`HS384`,yield`HS512`);return;default:throw new V(`Unsupported kty "${e.kty}"`)}}function $n(e){return e.key_ops?.some(Rn)??(e.use==null||e.use===`enc`)}function er(e){return e.key_ops?.some(Ln)??(e.use==null||e.use===`sig`)}L({keys:I(en()).transform(e=>e.map(e=>Un.safeParse(e)).filter(e=>e.success).map(e=>e.data))});var tr=L({keys:I(en()).transform(e=>e.map(e=>Wn.safeParse(e)).filter(e=>e.success).map(e=>e.data))}),nr=N().superRefine(Mn).superRefine(Nn(3)),rr=N().superRefine(Mn).superRefine(Nn(2)),ir=L({alg:N(),jku:N().url().optional(),jwk:L({kty:N(),crv:N().optional(),x:N().optional(),y:N().optional(),e:N().optional(),n:N().optional()}).optional(),kid:N().optional(),x5u:N().optional(),x5c:I(N()).optional(),x5t:N().optional(),"x5t#S256":N().optional(),typ:N().optional(),cty:N().optional(),crit:I(N()).optional()}).passthrough(),ar=N().superRefine((e,t)=>{try{let n=new URL(e);n.protocol!==`http:`&&n.protocol!==`https:`&&t.addIssue({code:b.custom,message:`Only http: and https: protocols are allowed`}),(n.username||n.password)&&t.addIssue({code:b.custom,message:`Credentials not allowed`}),n.search&&t.addIssue({code:b.custom,message:`Query string not allowed`}),n.hash&&t.addIssue({code:b.custom,message:`Fragment not allowed`})}catch{t.addIssue({code:b.invalid_string,validation:`url`})}return e}),or=L({iss:N().optional(),aud:R([N(),I(N()).nonempty()]).optional(),sub:N().optional(),exp:P().int().optional(),nbf:P().int().optional(),iat:P().int().optional(),jti:N().optional(),htm:N().optional(),htu:ar.optional(),ath:N().optional(),acr:N().optional(),azp:N().optional(),amr:I(N()).optional(),cnf:L({kid:N().optional(),jwk:Wn.optional(),jwe:N().optional(),jku:N().url().optional(),jkt:N().optional(),"x5t#S256":N().optional(),osc:N().optional()}).optional(),client_id:N().optional(),scope:N().optional(),nonce:N().optional(),at_hash:N().optional(),c_hash:N().optional(),s_hash:N().optional(),auth_time:P().int().optional(),name:N().optional(),family_name:N().optional(),given_name:N().optional(),middle_name:N().optional(),nickname:N().optional(),preferred_username:N().optional(),gender:N().optional(),picture:N().url().optional(),profile:N().url().optional(),website:N().url().optional(),birthdate:N().regex(/\d{4}-\d{2}-\d{2}/).optional(),zoneinfo:N().regex(/^[A-Za-z0-9_/]+$/).optional(),locale:N().regex(/^[a-z]{2,3}(-[A-Z]{2})?$/).optional(),updated_at:P().int().optional(),email:N().optional(),email_verified:F().optional(),phone_number:N().optional(),phone_number_verified:F().optional(),address:L({formatted:N().optional(),street_address:N().optional(),locality:N().optional(),region:N().optional(),postal_code:N().optional(),country:N().optional()}).optional(),authorization_details:I(L({type:N(),locations:I(N()).optional(),actions:I(N()).optional(),datatypes:I(N()).optional(),identifier:N().optional(),privileges:I(N()).optional()}).passthrough()).optional()}).passthrough();function sr(e){let{0:t,1:n,length:r}=e.split(`.`);if(r>3||r<2)throw new mn(void 0,un);let i=ir.parse(jn(t));if(r===2&&i?.alg!==`none`)throw new mn(void 0,un);return{header:i,payload:or.parse(jn(n))}}var cr=function(e,t,n){for(var r=arguments.length>2,i=0;i<t.length;i++)n=r?t[i].call(e,n):t[i].call(e);return r?n:void 0},lr=function(e,t,n,r,i,a){function o(e){if(e!==void 0&&typeof e!=`function`)throw TypeError(`Function expected`);return e}for(var s=r.kind,c=s===`getter`?`get`:s===`setter`?`set`:`value`,l=!t&&e?r.static?e:e.prototype:null,u=t||(l?Object.getOwnPropertyDescriptor(l,r.name):{}),d,f=!1,p=n.length-1;p>=0;p--){var m={};for(var h in r)m[h]=h===`access`?{}:r[h];for(var h in r.access)m.access[h]=r.access[h];m.addInitializer=function(e){if(f)throw TypeError(`Cannot add initializers after decoration has completed`);a.push(o(e||null))};var g=(0,n[p])(s===`accessor`?{get:u.get,set:u.set}:u[c],m);if(s===`accessor`){if(g===void 0)continue;if(typeof g!=`object`||!g)throw TypeError(`Object expected`);(d=o(g.get))&&(u.get=d),(d=o(g.set))&&(u.set=d),(d=o(g.init))&&i.unshift(d)}else(d=o(g))&&(s===`field`?i.unshift(d):u[c]=d)}l&&Object.defineProperty(l,r.name,u),f=!0},ur=(()=>{let e=[],t,n,r,i,a;return class{static{let o=typeof Symbol==`function`&&Symbol.metadata?Object.create(null):void 0;t=[kn],n=[kn],r=[kn],i=[kn],a=[kn],lr(this,null,t,{kind:`getter`,name:`isPrivate`,static:!1,private:!1,access:{has:e=>`isPrivate`in e,get:e=>e.isPrivate},metadata:o},null,e),lr(this,null,n,{kind:`getter`,name:`isSymetric`,static:!1,private:!1,access:{has:e=>`isSymetric`in e,get:e=>e.isSymetric},metadata:o},null,e),lr(this,null,r,{kind:`getter`,name:`publicJwk`,static:!1,private:!1,access:{has:e=>`publicJwk`in e,get:e=>e.publicJwk},metadata:o},null,e),lr(this,null,i,{kind:`getter`,name:`bareJwk`,static:!1,private:!1,access:{has:e=>`bareJwk`in e,get:e=>e.bareJwk},metadata:o},null,e),lr(this,null,a,{kind:`getter`,name:`algorithms`,static:!1,private:!1,access:{has:e=>`algorithms`in e,get:e=>e.algorithms},metadata:o},null,e),o&&Object.defineProperty(this,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})}constructor(t){this.jwk=(cr(this,e),t)}get isPrivate(){return Jn(this.jwk)}get isSymetric(){return Kn(this.jwk)}get privateJwk(){if(this.isPrivate)return this.jwk}get publicJwk(){if(this.isSymetric)return;if(!this.isPrivate)return this.jwk;let e=Wn.safeParse({...this.jwk,d:void 0,k:void 0,use:void 0,key_ops:dr(this.keyOps)??Fn});if(e.success)return Object.freeze(e.data)}get bareJwk(){if(this.isSymetric)return;let{kty:e,crv:t,e:n,n:r,x:i,y:a}=this.jwk;return Object.freeze(Un.parse({crv:t,e:n,kty:e,n:r,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(Qn(this.jwk)))}get isRevoked(){return this.jwk.revoked!=null}isActive(e){if(!e?.allowRevoked&&this.isRevoked)return!1;let t=e?.clockTolerance??0;if(t!==1/0){let n=e?.currentDate?.getTime()??Date.now(),{exp:r,nbf:i}=this.jwk;if(i!=null&&!(n>=i*1e3-t)||r!=null&&!(n<r*1e3+t))return!1}return!0}matches(e){return!(e.kid!=null&&!(Array.isArray(e.kid)?this.kid!=null&&e.kid.includes(this.kid):this.kid===e.kid)||e.alg!=null&&!(Array.isArray(e.alg)?e.alg.some(e=>this.algorithms.includes(e)):this.algorithms.includes(e.alg))||e.usage!=null&&(!(this.keyOps==null||this.keyOps.includes(e.usage)||e.usage===`verify`&&this.keyOps.includes(`sign`)||e.usage===`encrypt`&&this.keyOps.includes(`decrypt`)||e.usage===`wrapKey`&&this.keyOps.includes(`unwrapKey`))||!(this.use==null||this.use===`sig`&&Ln(e.usage)||this.use===`enc`&&Rn(e.usage))||!(this.isPrivate||In(e.usage))))}}})();function dr(e){if(e==null)return;let t=new Set(e.filter(In));return e.includes(`sign`)&&t.add(`verify`),e.includes(`decrypt`)&&t.add(`encrypt`),e.includes(`unwrapKey`)&&t.add(`wrapKey`),Array.from(t)}var fr=function(e,t,n){for(var r=arguments.length>2,i=0;i<t.length;i++)n=r?t[i].call(e,n):t[i].call(e);return r?n:void 0},pr=function(e,t,n,r,i,a){function o(e){if(e!==void 0&&typeof e!=`function`)throw TypeError(`Function expected`);return e}for(var s=r.kind,c=s===`getter`?`get`:s===`setter`?`set`:`value`,l=!t&&e?r.static?e:e.prototype:null,u=t||(l?Object.getOwnPropertyDescriptor(l,r.name):{}),d,f=!1,p=n.length-1;p>=0;p--){var m={};for(var h in r)m[h]=h===`access`?{}:r[h];for(var h in r.access)m.access[h]=r.access[h];m.addInitializer=function(e){if(f)throw TypeError(`Cannot add initializers after decoration has completed`);a.push(o(e||null))};var g=(0,n[p])(s===`accessor`?{get:u.get,set:u.set}:u[c],m);if(s===`accessor`){if(g===void 0)continue;if(typeof g!=`object`||!g)throw TypeError(`Object expected`);(d=o(g.get))&&(u.get=d),(d=o(g.set))&&(u.set=d),(d=o(g.init))&&i.unshift(d)}else(d=o(g))&&(s===`field`?i.unshift(d):u[c]=d)}l&&Object.defineProperty(l,r.name,u),f=!0},mr=e=>e.privateJwk,hr=e=>e.publicJwk,gr=(()=>{let e=[],t,n,r;return class i{static{let i=typeof Symbol==`function`&&Symbol.metadata?Object.create(null):void 0;pr(this,null,t,{kind:`getter`,name:`signAlgorithms`,static:!1,private:!1,access:{has:e=>`signAlgorithms`in e,get:e=>e.signAlgorithms},metadata:i},null,e),pr(this,null,n,{kind:`getter`,name:`publicJwks`,static:!1,private:!1,access:{has:e=>`publicJwks`in e,get:e=>e.publicJwks},metadata:i},null,e),pr(this,null,r,{kind:`getter`,name:`privateJwks`,static:!1,private:!1,access:{has:e=>`privateJwks`in e,get:e=>e.privateJwks},metadata:i},null,e),i&&Object.defineProperty(this,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i})}constructor(t,n=t instanceof i?[...t.preferredSigningAlgorithms]:[`EdDSA`,`ES256K`,`ES256`,`PS256`,`PS384`,`PS512`,`HS256`,`HS384`,`HS512`]){this.preferredSigningAlgorithms=(fr(this,e),n);let r=[],a=new Set;for(let e of t)if(e&&(r.push(e),e.kid)){if(a.has(e.kid))throw new V(`Duplicate key: ${e.kid}`);a.add(e.kid)}this.keys=Object.freeze(r)}get size(){return this.keys.length}get signAlgorithms(){let e=new Set;for(let t of this)if(t.use===`sig`)for(let n of t.algorithms)e.add(n);return Object.freeze([...e].sort(Dn(this.preferredSigningAlgorithms)))}get publicJwks(){return Object.freeze({keys:Object.freeze(Array.from(this,hr).filter(En))})}get privateJwks(){return Object.freeze({keys:Object.freeze(Array.from(this,mr).filter(En))})}has(e){return this.keys.some(t=>t.kid===e)}get(e){let t=this.find(e);if(t)return t;throw new V(`Key not found ${e.kid??e.alg??e.usage??`<unknown>`}`,ln)}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:n,...r}){let i=[];Array.isArray(t)&&t.length===1&&(t=t[0]);for(let a of this.list({...r,kid:e,alg:t,usage:n})){if(typeof t==`string`)return{key:a,alg:t};i.push(a)}let a=On(t),o=i.map(e=>[e,e.algorithms.filter(a)]);for(let e of this.preferredSigningAlgorithms)for(let[t,n]of o)if(n.includes(e))return{key:t,alg:e};for(let[e,t]of o)for(let n of t)return{key:e,alg:n};throw new V(`No private key found for ${e||t||n}`,ln)}[(t=[kn],n=[kn],r=[kn],Symbol.iterator)](){return this.keys.values()}async createJwt({alg:e,kid:t,...n},r){try{let{key:i,alg:a}=this.findPrivateKey({alg:e,kid:t,usage:`sign`,allowRevoked:!1}),o={...n,alg:a,kid:i.kid};return typeof r==`function`&&(r=await r(o,i)),await i.createJwt(o,r)}catch(e){throw pn.from(e)}}async verifyJwt(e,t){let{header:n}=sr(e),{kid:r,alg:i}=n,a=[];for(let n of this.list({...t,kid:r,alg:i,usage:`verify`}))try{return{...await n.verifyJwt(e,t),key:n}}catch(e){a.push(e)}switch(a.length){case 0:throw new mn(`No key matched`,sn);case 1:throw mn.from(a[0],un);default:throw mn.from(a,un)}}toJSON(){return structuredClone(this.publicJwks)}}})(),_r=crypto,vr=e=>e instanceof CryptoKey,H=new TextEncoder,yr=new TextDecoder;function br(...e){let t=e.reduce((e,{length:t})=>e+t,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}var xr=e=>{let t=e;typeof t==`string`&&(t=H.encode(t));let n=32768,r=[];for(let e=0;e<t.length;e+=n)r.push(String.fromCharCode.apply(null,t.subarray(e,e+n)));return btoa(r.join(``))},Sr=e=>xr(e).replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`),Cr=e=>{let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n},wr=e=>{let t=e;t instanceof Uint8Array&&(t=yr.decode(t)),t=t.replace(/-/g,`+`).replace(/_/g,`/`).replace(/\s/g,``);try{return Cr(t)}catch{throw TypeError(`The input to be decoded is not correctly encoded.`)}},Tr=e({JOSEAlgNotAllowed:()=>Dr,JOSEError:()=>U,JOSENotSupported:()=>G,JWEDecryptionFailed:()=>Or,JWEInvalid:()=>kr,JWKInvalid:()=>jr,JWKSInvalid:()=>Mr,JWKSMultipleMatchingKeys:()=>Pr,JWKSNoMatchingKey:()=>Nr,JWKSTimeout:()=>Fr,JWSInvalid:()=>K,JWSSignatureVerificationFailed:()=>Ir,JWTClaimValidationFailed:()=>W,JWTExpired:()=>Er,JWTInvalid:()=>Ar}),U=class extends Error{constructor(e,t){super(e,t),this.code=`ERR_JOSE_GENERIC`,this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};U.code=`ERR_JOSE_GENERIC`;var W=class extends U{constructor(e,t,n=`unspecified`,r=`unspecified`){super(e,{cause:{claim:n,reason:r,payload:t}}),this.code=`ERR_JWT_CLAIM_VALIDATION_FAILED`,this.claim=n,this.reason=r,this.payload=t}};W.code=`ERR_JWT_CLAIM_VALIDATION_FAILED`;var Er=class extends U{constructor(e,t,n=`unspecified`,r=`unspecified`){super(e,{cause:{claim:n,reason:r,payload:t}}),this.code=`ERR_JWT_EXPIRED`,this.claim=n,this.reason=r,this.payload=t}};Er.code=`ERR_JWT_EXPIRED`;var Dr=class extends U{constructor(){super(...arguments),this.code=`ERR_JOSE_ALG_NOT_ALLOWED`}};Dr.code=`ERR_JOSE_ALG_NOT_ALLOWED`;var G=class extends U{constructor(){super(...arguments),this.code=`ERR_JOSE_NOT_SUPPORTED`}};G.code=`ERR_JOSE_NOT_SUPPORTED`;var Or=class extends U{constructor(e=`decryption operation failed`,t){super(e,t),this.code=`ERR_JWE_DECRYPTION_FAILED`}};Or.code=`ERR_JWE_DECRYPTION_FAILED`;var kr=class extends U{constructor(){super(...arguments),this.code=`ERR_JWE_INVALID`}};kr.code=`ERR_JWE_INVALID`;var K=class extends U{constructor(){super(...arguments),this.code=`ERR_JWS_INVALID`}};K.code=`ERR_JWS_INVALID`;var Ar=class extends U{constructor(){super(...arguments),this.code=`ERR_JWT_INVALID`}};Ar.code=`ERR_JWT_INVALID`;var jr=class extends U{constructor(){super(...arguments),this.code=`ERR_JWK_INVALID`}};jr.code=`ERR_JWK_INVALID`;var Mr=class extends U{constructor(){super(...arguments),this.code=`ERR_JWKS_INVALID`}};Mr.code=`ERR_JWKS_INVALID`;var Nr=class extends U{constructor(e=`no applicable key found in the JSON Web Key Set`,t){super(e,t),this.code=`ERR_JWKS_NO_MATCHING_KEY`}};Nr.code=`ERR_JWKS_NO_MATCHING_KEY`;var Pr=class extends U{constructor(e=`multiple matching keys found in the JSON Web Key Set`,t){super(e,t),this.code=`ERR_JWKS_MULTIPLE_MATCHING_KEYS`}};Pr.code=`ERR_JWKS_MULTIPLE_MATCHING_KEYS`;var Fr=class extends U{constructor(e=`request timed out`,t){super(e,t),this.code=`ERR_JWKS_TIMEOUT`}};Fr.code=`ERR_JWKS_TIMEOUT`;var Ir=class extends U{constructor(e=`signature verification failed`,t){super(e,t),this.code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`}};Ir.code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;function q(e,t=`algorithm.name`){return TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function Lr(e,t){return e.name===t}function Rr(e){return parseInt(e.name.slice(4),10)}function zr(e){switch(e){case`ES256`:return`P-256`;case`ES384`:return`P-384`;case`ES512`:return`P-521`;default:throw Error(`unreachable`)}}function Br(e,t){if(t.length&&!t.some(t=>e.usages.includes(t))){let e=`CryptoKey does not support this operation, its usages must include `;if(t.length>2){let n=t.pop();e+=`one of ${t.join(`, `)}, or ${n}.`}else t.length===2?e+=`one of ${t[0]} or ${t[1]}.`:e+=`${t[0]}.`;throw TypeError(e)}}function Vr(e,t,...n){switch(t){case`HS256`:case`HS384`:case`HS512`:{if(!Lr(e.algorithm,`HMAC`))throw q(`HMAC`);let n=parseInt(t.slice(2),10);if(Rr(e.algorithm.hash)!==n)throw q(`SHA-${n}`,`algorithm.hash`);break}case`RS256`:case`RS384`:case`RS512`:{if(!Lr(e.algorithm,`RSASSA-PKCS1-v1_5`))throw q(`RSASSA-PKCS1-v1_5`);let n=parseInt(t.slice(2),10);if(Rr(e.algorithm.hash)!==n)throw q(`SHA-${n}`,`algorithm.hash`);break}case`PS256`:case`PS384`:case`PS512`:{if(!Lr(e.algorithm,`RSA-PSS`))throw q(`RSA-PSS`);let n=parseInt(t.slice(2),10);if(Rr(e.algorithm.hash)!==n)throw q(`SHA-${n}`,`algorithm.hash`);break}case`EdDSA`:if(e.algorithm.name!==`Ed25519`&&e.algorithm.name!==`Ed448`)throw q(`Ed25519 or Ed448`);break;case`Ed25519`:if(!Lr(e.algorithm,`Ed25519`))throw q(`Ed25519`);break;case`ES256`:case`ES384`:case`ES512`:{if(!Lr(e.algorithm,`ECDSA`))throw q(`ECDSA`);let n=zr(t);if(e.algorithm.namedCurve!==n)throw q(n,`algorithm.namedCurve`);break}default:throw TypeError(`CryptoKey does not support this operation`)}Br(e,n)}function Hr(e,t,...n){if(n=n.filter(Boolean),n.length>2){let t=n.pop();e+=`one of type ${n.join(`, `)}, or ${t}.`}else n.length===2?e+=`one of type ${n[0]} or ${n[1]}.`:e+=`of type ${n[0]}.`;return t==null?e+=` Received ${t}`:typeof t==`function`&&t.name?e+=` Received function ${t.name}`:typeof t==`object`&&t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var Ur=(e,...t)=>Hr(`Key must be `,e,...t);function Wr(e,t,...n){return Hr(`Key for the ${e} algorithm must be `,t,...n)}var Gr=e=>vr(e)?!0:e?.[Symbol.toStringTag]===`KeyObject`,Kr=[`CryptoKey`],qr=(...e)=>{let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let n;for(let e of t){let t=Object.keys(e);if(!n||n.size===0)n=new Set(t);else for(let e of t){if(n.has(e))return!1;n.add(e)}}return!0};function Jr(e){return typeof e==`object`&&!!e}function Yr(e){if(!Jr(e)||Object.prototype.toString.call(e)!==`[object Object]`)return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}var Xr=(e,t)=>{if(e.startsWith(`RS`)||e.startsWith(`PS`)){let{modulusLength:n}=t.algorithm;if(typeof n!=`number`||n<2048)throw TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}};function Zr(e){return Yr(e)&&typeof e.kty==`string`}function Qr(e){return e.kty!==`oct`&&typeof e.d==`string`}function $r(e){return e.kty!==`oct`&&e.d===void 0}function ei(e){return Zr(e)&&e.kty===`oct`&&typeof e.k==`string`}function ti(e){let t,n;switch(e.kty){case`RSA`:switch(e.alg){case`PS256`:case`PS384`:case`PS512`:t={name:`RSA-PSS`,hash:`SHA-${e.alg.slice(-3)}`},n=e.d?[`sign`]:[`verify`];break;case`RS256`:case`RS384`:case`RS512`:t={name:`RSASSA-PKCS1-v1_5`,hash:`SHA-${e.alg.slice(-3)}`},n=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}`},n=e.d?[`decrypt`,`unwrapKey`]:[`encrypt`,`wrapKey`];break;default:throw new G(`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`)}break;case`EC`:switch(e.alg){case`ES256`:t={name:`ECDSA`,namedCurve:`P-256`},n=e.d?[`sign`]:[`verify`];break;case`ES384`:t={name:`ECDSA`,namedCurve:`P-384`},n=e.d?[`sign`]:[`verify`];break;case`ES512`:t={name:`ECDSA`,namedCurve:`P-521`},n=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},n=e.d?[`deriveBits`]:[];break;default:throw new G(`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`)}break;case`OKP`:switch(e.alg){case`Ed25519`:t={name:`Ed25519`},n=e.d?[`sign`]:[`verify`];break;case`EdDSA`:t={name:e.crv},n=e.d?[`sign`]:[`verify`];break;case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:t={name:e.crv},n=e.d?[`deriveBits`]:[];break;default:throw new G(`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`)}break;default:throw new G(`Invalid or unsupported JWK "kty" (Key Type) Parameter value`)}return{algorithm:t,keyUsages:n}}var ni=async e=>{if(!e.alg)throw TypeError(`"alg" argument is required when "jwk.alg" is not present`);let{algorithm:t,keyUsages:n}=ti(e),r=[t,e.ext??!1,e.key_ops??n],i={...e};return delete i.alg,delete i.use,_r.subtle.importKey(`jwk`,i,...r)},ri=e=>wr(e),ii,ai,oi=e=>e?.[Symbol.toStringTag]===`KeyObject`,si=async(e,t,n,r,i=!1)=>{let a=e.get(t);if(a?.[r])return a[r];let o=await ni({...n,alg:r});return i&&Object.freeze(t),a?a[r]=o:e.set(t,{[r]:o}),o},ci={normalizePublicKey:(e,t)=>{if(oi(e)){let n=e.export({format:`jwk`});return delete n.d,delete n.dp,delete n.dq,delete n.p,delete n.q,delete n.qi,n.k?ri(n.k):(ai||=new WeakMap,si(ai,e,n,t))}return Zr(e)?e.k?wr(e.k):(ai||=new WeakMap,si(ai,e,e,t,!0)):e},normalizePrivateKey:(e,t)=>{if(oi(e)){let n=e.export({format:`jwk`});return n.k?ri(n.k):(ii||=new WeakMap,si(ii,e,n,t))}return Zr(e)?e.k?wr(e.k):(ii||=new WeakMap,si(ii,e,e,t,!0)):e}},li=(e,t,n=0)=>{n===0&&(t.unshift(t.length),t.unshift(6));let r=e.indexOf(t[0],n);if(r===-1)return!1;let i=e.subarray(r,r+t.length);return i.length===t.length?i.every((e,n)=>e===t[n])||li(e,t,r+1):!1},ui=e=>{switch(!0){case li(e,[42,134,72,206,61,3,1,7]):return`P-256`;case li(e,[43,129,4,0,34]):return`P-384`;case li(e,[43,129,4,0,35]):return`P-521`;case li(e,[43,101,110]):return`X25519`;case li(e,[43,101,111]):return`X448`;case li(e,[43,101,112]):return`Ed25519`;case li(e,[43,101,113]):return`Ed448`;default:throw new G(`Invalid or unsupported EC Key Curve or OKP Key Sub Type`)}},di=async(e,t,n,r,i)=>{let a,o,s=new Uint8Array(atob(n.replace(e,``)).split(``).map(e=>e.charCodeAt(0))),c=t===`spki`;switch(r){case`PS256`:case`PS384`:case`PS512`:a={name:`RSA-PSS`,hash:`SHA-${r.slice(-3)}`},o=c?[`verify`]:[`sign`];break;case`RS256`:case`RS384`:case`RS512`:a={name:`RSASSA-PKCS1-v1_5`,hash:`SHA-${r.slice(-3)}`},o=c?[`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(r.slice(-3),10)||1}`},o=c?[`encrypt`,`wrapKey`]:[`decrypt`,`unwrapKey`];break;case`ES256`:a={name:`ECDSA`,namedCurve:`P-256`},o=c?[`verify`]:[`sign`];break;case`ES384`:a={name:`ECDSA`,namedCurve:`P-384`},o=c?[`verify`]:[`sign`];break;case`ES512`:a={name:`ECDSA`,namedCurve:`P-521`},o=c?[`verify`]:[`sign`];break;case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:{let e=ui(s);a=e.startsWith(`P-`)?{name:`ECDH`,namedCurve:e}:{name:e},o=c?[]:[`deriveBits`];break}case`Ed25519`:a={name:`Ed25519`},o=c?[`verify`]:[`sign`];break;case`EdDSA`:a={name:ui(s)},o=c?[`verify`]:[`sign`];break;default:throw new G(`Invalid or unsupported "alg" (Algorithm) value`)}return _r.subtle.importKey(t,s,a,i?.extractable??!1,o)},fi=(e,t,n)=>di(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,`pkcs8`,e,t,n);async function pi(e,t,n){if(typeof e!=`string`||e.indexOf(`-----BEGIN PRIVATE KEY-----`)!==0)throw TypeError(`"pkcs8" must be PKCS#8 formatted string`);return fi(e,t,n)}async function mi(e,t){if(!Yr(e))throw TypeError(`JWK must be an object`);switch(t||=e.alg,e.kty){case`oct`:if(typeof e.k!=`string`||!e.k)throw TypeError(`missing "k" (Key Value) Parameter value`);return wr(e.k);case`RSA`:if(`oth`in e&&e.oth!==void 0)throw new G(`RSA JWK "oth" (Other Primes Info) Parameter value is not supported`);case`EC`:case`OKP`:return ni({...e,alg:t});default:throw new G(`Unsupported "kty" (Key Type) Parameter value`)}}var hi=e=>e?.[Symbol.toStringTag],gi=(e,t,n)=>{if(t.use!==void 0&&t.use!==`sig`)throw TypeError(`Invalid key for this operation, when present its use must be sig`);if(t.key_ops!==void 0&&t.key_ops.includes?.(n)!==!0)throw TypeError(`Invalid key for this operation, when present its key_ops must include ${n}`);if(t.alg!==void 0&&t.alg!==e)throw TypeError(`Invalid key for this operation, when present its alg must be ${e}`);return!0},_i=(e,t,n,r)=>{if(!(t instanceof Uint8Array)){if(r&&Zr(t)){if(ei(t)&&gi(e,t,n))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(!Gr(t))throw TypeError(Wr(e,t,...Kr,`Uint8Array`,r?`JSON Web Key`:null));if(t.type!==`secret`)throw TypeError(`${hi(t)} instances for symmetric algorithms must be of type "secret"`)}},vi=(e,t,n,r)=>{if(r&&Zr(t))switch(n){case`sign`:if(Qr(t)&&gi(e,t,n))return;throw TypeError(`JSON Web Key for this operation be a private JWK`);case`verify`:if($r(t)&&gi(e,t,n))return;throw TypeError(`JSON Web Key for this operation be a public JWK`)}if(!Gr(t))throw TypeError(Wr(e,t,...Kr,r?`JSON Web Key`:null));if(t.type===`secret`)throw TypeError(`${hi(t)} instances for asymmetric algorithms must not be of type "secret"`);if(n===`sign`&&t.type===`public`)throw TypeError(`${hi(t)} instances for asymmetric algorithm signing must be of type "private"`);if(n===`decrypt`&&t.type===`public`)throw TypeError(`${hi(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&n===`verify`&&t.type===`private`)throw TypeError(`${hi(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&n===`encrypt`&&t.type===`private`)throw TypeError(`${hi(t)} instances for asymmetric algorithm encryption must be of type "public"`)};function yi(e,t,n,r){t.startsWith(`HS`)||t===`dir`||t.startsWith(`PBES2`)||/^A\d{3}(?:GCM)?KW$/.test(t)?_i(t,n,r,e):vi(t,n,r,e)}yi.bind(void 0,!1);var bi=yi.bind(void 0,!0);function xi(e,t,n,r,i){if(i.crit!==void 0&&r?.crit===void 0)throw new e(`"crit" (Critical) Header Parameter MUST be integrity protected`);if(!r||r.crit===void 0)return new Set;if(!Array.isArray(r.crit)||r.crit.length===0||r.crit.some(e=>typeof e!=`string`||e.length===0))throw new e(`"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present`);let a;a=n===void 0?t:new Map([...Object.entries(n),...t.entries()]);for(let t of r.crit){if(!a.has(t))throw new G(`Extension Header Parameter "${t}" is not recognized`);if(i[t]===void 0)throw new e(`Extension Header Parameter "${t}" is missing`);if(a.get(t)&&r[t]===void 0)throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return new Set(r.crit)}var Si=(e,t)=>{if(t!==void 0&&(!Array.isArray(t)||t.some(e=>typeof e!=`string`)))throw TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)},Ci=async e=>{if(e instanceof Uint8Array)return{kty:`oct`,k:Sr(e)};if(!vr(e))throw TypeError(Ur(e,...Kr,`Uint8Array`));if(!e.extractable)throw TypeError(`non-extractable CryptoKey cannot be exported as a JWK`);let{ext:t,key_ops:n,alg:r,use:i,...a}=await _r.subtle.exportKey(`jwk`,e);return a};async function wi(e){return Ci(e)}function Ti(e,t){let n=`SHA-${e.slice(-3)}`;switch(e){case`HS256`:case`HS384`:case`HS512`:return{hash:n,name:`HMAC`};case`PS256`:case`PS384`:case`PS512`:return{hash:n,name:`RSA-PSS`,saltLength:e.slice(-3)>>3};case`RS256`:case`RS384`:case`RS512`:return{hash:n,name:`RSASSA-PKCS1-v1_5`};case`ES256`:case`ES384`:case`ES512`:return{hash:n,name:`ECDSA`,namedCurve:t.namedCurve};case`Ed25519`:return{name:`Ed25519`};case`EdDSA`:return{name:t.name};default:throw new G(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function Ei(e,t,n){if(n===`sign`&&(t=await ci.normalizePrivateKey(t,e)),n===`verify`&&(t=await ci.normalizePublicKey(t,e)),vr(t))return Vr(t,e,n),t;if(t instanceof Uint8Array){if(!e.startsWith(`HS`))throw TypeError(Ur(t,...Kr));return _r.subtle.importKey(`raw`,t,{hash:`SHA-${e.slice(-3)}`,name:`HMAC`},!1,[n])}throw TypeError(Ur(t,...Kr,`Uint8Array`,`JSON Web Key`))}var Di=async(e,t,n,r)=>{let i=await Ei(e,t,`verify`);Xr(e,i);let a=Ti(e,i.algorithm);try{return await _r.subtle.verify(a,i,n,r)}catch{return!1}};async function Oi(e,t,n){if(!Yr(e))throw new K(`Flattened JWS must be an object`);if(e.protected===void 0&&e.header===void 0)throw new K(`Flattened JWS must have either of the "protected" or "header" members`);if(e.protected!==void 0&&typeof e.protected!=`string`)throw new K(`JWS Protected Header incorrect type`);if(e.payload===void 0)throw new K(`JWS Payload missing`);if(typeof e.signature!=`string`)throw new K(`JWS Signature missing or incorrect type`);if(e.header!==void 0&&!Yr(e.header))throw new K(`JWS Unprotected Header incorrect type`);let r={};if(e.protected)try{let t=wr(e.protected);r=JSON.parse(yr.decode(t))}catch{throw new K(`JWS Protected Header is invalid`)}if(!qr(r,e.header))throw new K(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let i={...r,...e.header},a=xi(K,new Map([[`b64`,!0]]),n?.crit,r,i),o=!0;if(a.has(`b64`)&&(o=r.b64,typeof o!=`boolean`))throw new K(`The "b64" (base64url-encode payload) Header Parameter must be a boolean`);let{alg:s}=i;if(typeof s!=`string`||!s)throw new K(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);let c=n&&Si(`algorithms`,n.algorithms);if(c&&!c.has(s))throw new Dr(`"alg" (Algorithm) Header Parameter value not allowed`);if(o){if(typeof e.payload!=`string`)throw new K(`JWS Payload must be a string`)}else if(typeof e.payload!=`string`&&!(e.payload instanceof Uint8Array))throw new K(`JWS Payload must be a string or an Uint8Array instance`);let l=!1;typeof t==`function`?(t=await t(r,e),l=!0,bi(s,t,`verify`),Zr(t)&&(t=await mi(t,s))):bi(s,t,`verify`);let u=br(H.encode(e.protected??``),H.encode(`.`),typeof e.payload==`string`?H.encode(e.payload):e.payload),d;try{d=wr(e.signature)}catch{throw new K(`Failed to base64url decode the signature`)}if(!await Di(s,t,d,u))throw new Ir;let f;if(o)try{f=wr(e.payload)}catch{throw new K(`Failed to base64url decode the payload`)}else f=typeof e.payload==`string`?H.encode(e.payload):e.payload;let p={payload:f};return e.protected!==void 0&&(p.protectedHeader=r),e.header!==void 0&&(p.unprotectedHeader=e.header),l?{...p,key:t}:p}async function ki(e,t,n){if(e instanceof Uint8Array&&(e=yr.decode(e)),typeof e!=`string`)throw new K(`Compact JWS must be a string or Uint8Array`);let{0:r,1:i,2:a,length:o}=e.split(`.`);if(o!==3)throw new K(`Invalid Compact JWS`);let s=await Oi({payload:i,protected:r,signature:a},t,n),c={payload:s.payload,protectedHeader:s.protectedHeader};return typeof t==`function`?{...c,key:s.key}:c}var Ai=e=>Math.floor(e.getTime()/1e3),ji=60,Mi=3600,Ni=Mi*24,Pi=Ni*7,Fi=Ni*365.25,Ii=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,Li=e=>{let t=Ii.exec(e);if(!t||t[4]&&t[1])throw TypeError(`Invalid time period format`);let n=parseFloat(t[2]),r=t[3].toLowerCase(),i;switch(r){case`sec`:case`secs`:case`second`:case`seconds`:case`s`:i=Math.round(n);break;case`minute`:case`minutes`:case`min`:case`mins`:case`m`:i=Math.round(n*ji);break;case`hour`:case`hours`:case`hr`:case`hrs`:case`h`:i=Math.round(n*Mi);break;case`day`:case`days`:case`d`:i=Math.round(n*Ni);break;case`week`:case`weeks`:case`w`:i=Math.round(n*Pi);break;default:i=Math.round(n*Fi)}return t[1]===`-`||t[4]===`ago`?-i:i},Ri=e=>e.toLowerCase().replace(/^application\//,``),zi=(e,t)=>typeof e==`string`?t.includes(e):Array.isArray(e)?t.some(Set.prototype.has.bind(new Set(e))):!1,Bi=(e,t,n={})=>{let r;try{r=JSON.parse(yr.decode(t))}catch{}if(!Yr(r))throw new Ar(`JWT Claims Set must be a top-level JSON object`);let{typ:i}=n;if(i&&(typeof e.typ!=`string`||Ri(e.typ)!==Ri(i)))throw new W(`unexpected "typ" JWT header value`,r,`typ`,`check_failed`);let{requiredClaims:a=[],issuer:o,subject:s,audience:c,maxTokenAge:l}=n,u=[...a];l!==void 0&&u.push(`iat`),c!==void 0&&u.push(`aud`),s!==void 0&&u.push(`sub`),o!==void 0&&u.push(`iss`);for(let e of new Set(u.reverse()))if(!(e in r))throw new W(`missing required "${e}" claim`,r,e,`missing`);if(o&&!(Array.isArray(o)?o:[o]).includes(r.iss))throw new W(`unexpected "iss" claim value`,r,`iss`,`check_failed`);if(s&&r.sub!==s)throw new W(`unexpected "sub" claim value`,r,`sub`,`check_failed`);if(c&&!zi(r.aud,typeof c==`string`?[c]:c))throw new W(`unexpected "aud" claim value`,r,`aud`,`check_failed`);let d;switch(typeof n.clockTolerance){case`string`:d=Li(n.clockTolerance);break;case`number`:d=n.clockTolerance;break;case`undefined`:d=0;break;default:throw TypeError(`Invalid clockTolerance option type`)}let{currentDate:f}=n,p=Ai(f||new Date);if((r.iat!==void 0||l)&&typeof r.iat!=`number`)throw new W(`"iat" claim must be a number`,r,`iat`,`invalid`);if(r.nbf!==void 0){if(typeof r.nbf!=`number`)throw new W(`"nbf" claim must be a number`,r,`nbf`,`invalid`);if(r.nbf>p+d)throw new W(`"nbf" claim timestamp check failed`,r,`nbf`,`check_failed`)}if(r.exp!==void 0){if(typeof r.exp!=`number`)throw new W(`"exp" claim must be a number`,r,`exp`,`invalid`);if(r.exp<=p-d)throw new Er(`"exp" claim timestamp check failed`,r,`exp`,`check_failed`)}if(l){let e=p-r.iat,t=typeof l==`number`?l:Li(l);if(e-d>t)throw new Er(`"iat" claim timestamp check failed (too far in the past)`,r,`iat`,`check_failed`);if(e<0-d)throw new W(`"iat" claim timestamp check failed (it should be in the past)`,r,`iat`,`check_failed`)}return r};async function Vi(e,t,n){let r=await ki(e,t,n);if(r.protectedHeader.crit?.includes(`b64`)&&r.protectedHeader.b64===!1)throw new Ar(`JWTs MUST NOT use unencoded payload`);let i={payload:Bi(r.protectedHeader,r.payload,n),protectedHeader:r.protectedHeader};return typeof t==`function`?{...i,key:r.key}:i}var Hi=async(e,t,n)=>{let r=await Ei(e,t,`sign`);Xr(e,r);let i=await _r.subtle.sign(Ti(e,r.algorithm),r,n);return new Uint8Array(i)},Ui=class{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){if(!this._protectedHeader&&!this._unprotectedHeader)throw new K(`either setProtectedHeader or setUnprotectedHeader must be called before #sign()`);if(!qr(this._protectedHeader,this._unprotectedHeader))throw new K(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let n={...this._protectedHeader,...this._unprotectedHeader},r=xi(K,new Map([[`b64`,!0]]),t?.crit,this._protectedHeader,n),i=!0;if(r.has(`b64`)&&(i=this._protectedHeader.b64,typeof i!=`boolean`))throw new K(`The "b64" (base64url-encode payload) Header Parameter must be a boolean`);let{alg:a}=n;if(typeof a!=`string`||!a)throw new K(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);bi(a,e,`sign`);let o=this._payload;i&&(o=H.encode(Sr(o)));let s;s=this._protectedHeader?H.encode(Sr(JSON.stringify(this._protectedHeader))):H.encode(``);let c={signature:Sr(await Hi(a,e,br(s,H.encode(`.`),o))),payload:``};return i&&(c.payload=yr.decode(o)),this._unprotectedHeader&&(c.header=this._unprotectedHeader),this._protectedHeader&&(c.protected=yr.decode(s)),c}},Wi=class{constructor(e){this._flattened=new Ui(e)}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}async sign(e,t){let n=await this._flattened.sign(e,t);if(n.payload===void 0)throw TypeError(`use the flattened module for creating JWS with b64: false`);return`${n.protected}.${n.payload}.${n.signature}`}};function Gi(e,t){if(!Number.isFinite(t))throw TypeError(`Invalid ${e} input`);return t}var Ki=class{constructor(e={}){if(!Yr(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 this._payload=typeof e==`number`?{...this._payload,nbf:Gi(`setNotBefore`,e)}:e instanceof Date?{...this._payload,nbf:Gi(`setNotBefore`,Ai(e))}:{...this._payload,nbf:Ai(new Date)+Li(e)},this}setExpirationTime(e){return this._payload=typeof e==`number`?{...this._payload,exp:Gi(`setExpirationTime`,e)}:e instanceof Date?{...this._payload,exp:Gi(`setExpirationTime`,Ai(e))}:{...this._payload,exp:Ai(new Date)+Li(e)},this}setIssuedAt(e){return this._payload=e===void 0?{...this._payload,iat:Ai(new Date)}:e instanceof Date?{...this._payload,iat:Gi(`setIssuedAt`,Ai(e))}:typeof e==`string`?{...this._payload,iat:Gi(`setIssuedAt`,Ai(new Date)+Li(e))}:{...this._payload,iat:Gi(`setIssuedAt`,e)},this}},qi=class extends Ki{setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,t){let n=new Wi(H.encode(JSON.stringify(this._payload)));if(n.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes(`b64`)&&this._protectedHeader.b64===!1)throw new Ar(`JWTs MUST NOT use unencoded payload`);return n.sign(e,t)}};function Ji(e){let t=e?.modulusLength??2048;if(typeof t!=`number`||t<2048)throw new G(`Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used`);return t}async function Yi(e,t){let n,r;switch(e){case`PS256`:case`PS384`:case`PS512`:n={name:`RSA-PSS`,hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:Ji(t)},r=[`sign`,`verify`];break;case`RS256`:case`RS384`:case`RS512`:n={name:`RSASSA-PKCS1-v1_5`,hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:Ji(t)},r=[`sign`,`verify`];break;case`RSA-OAEP`:case`RSA-OAEP-256`:case`RSA-OAEP-384`:case`RSA-OAEP-512`:n={name:`RSA-OAEP`,hash:`SHA-${parseInt(e.slice(-3),10)||1}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:Ji(t)},r=[`decrypt`,`unwrapKey`,`encrypt`,`wrapKey`];break;case`ES256`:n={name:`ECDSA`,namedCurve:`P-256`},r=[`sign`,`verify`];break;case`ES384`:n={name:`ECDSA`,namedCurve:`P-384`},r=[`sign`,`verify`];break;case`ES512`:n={name:`ECDSA`,namedCurve:`P-521`},r=[`sign`,`verify`];break;case`Ed25519`:n={name:`Ed25519`},r=[`sign`,`verify`];break;case`EdDSA`:{r=[`sign`,`verify`];let e=t?.crv??`Ed25519`;switch(e){case`Ed25519`:case`Ed448`:n={name:e};break;default:throw new G(`Invalid or unsupported crv option provided`)}break}case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:{r=[`deriveKey`,`deriveBits`];let e=t?.crv??`P-256`;switch(e){case`P-256`:case`P-384`:case`P-521`:n={name:`ECDH`,namedCurve:e};break;case`X25519`:case`X448`:n={name:e};break;default:throw new G(`Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448`)}break}default:throw new G(`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`)}return _r.subtle.generateKey(n,t?.extractable??!1,r)}async function Xi(e,t){return Yi(e,t)}function Zi(e,t){if(e!=null&&t!=null&&e!==t)throw TypeError(`Expected "${t}", got "${e}"`);return e??t??void 0}var{JOSEError:Qi}=Tr,$i=class e extends ur{async getKeyObj(e){if(!this.algorithms.includes(e))throw new V(`Key cannot be used with algorithm "${e}"`);try{return await mi(this.jwk,e)}catch(e){throw new V(`Failed to import JWK`,void 0,{cause:e})}}async createJwt(e,t){try{let{kid:n}=e;if(n&&n!==this.kid)throw new pn(`Invalid "kid" (${n}) used to sign with key "${this.kid}"`);let{alg:r}=e;if(!r)throw new pn(`Missing "alg" in JWT header`);let i=await this.getKeyObj(r);return await new qi(t).setProtectedHeader({...e,alg:r,kid:this.kid}).sign(i)}catch(e){throw e instanceof Qi?new pn(e.message,e.code,{cause:e}):pn.from(e)}}async verifyJwt(e,t){try{let n=await Vi(e,async({alg:e})=>this.getKeyObj(e),{...t,algorithms:this.algorithms}),r=ir.safeParse(n.protectedHeader);if(!r.success)throw new mn(`Invalid JWT header`,void 0,{cause:r.error});let i=or.safeParse(n.payload);if(!i.success)throw new mn(`Invalid JWT payload`,void 0,{cause:i.error});return{protectedHeader:r.data,payload:i.data}}catch(e){throw e instanceof Qi?new mn(e.message,e.code,{cause:e}):mn.from(e)}}static async generateKeyPair(e=[`ES256`],t){if(!e.length)throw new V(`No algorithms provided for key generation`);let n=[];for(let r of e)try{return await Xi(r,t)}catch(e){n.push(e)}throw new V(`Failed to generate key pair`,void 0,{cause:AggregateError(n,`None of the algorithms worked`)})}static async generate(e=[`ES256`],t,n){let r=await this.generateKeyPair(e,{...n,extractable:!0});return this.fromKeyLike(r.privateKey,t)}static async fromImportable(e,t){if(typeof e==`string`){if(e.startsWith(`-----`))return this.fromPKCS8(e,``,t);if(e.startsWith(`{`))return this.fromJWK(e,t);throw new V(`Invalid input`)}if(typeof e==`object`)return`kty`in e||`alg`in e?this.fromJWK(e,t):this.fromKeyLike(e,t);throw new V(`Invalid input`)}static async fromKeyLike(e,t,n){let r=await wi(e);if(n){if(!r.alg)r.alg=n;else if(r.alg!==n)throw new V(`Invalid "alg" in JWK`)}return this.fromJWK(r,t)}static async fromPKCS8(e,t,n){let r=await pi(e,t,{extractable:!0});return this.fromKeyLike(r,n)}static async fromJWK(t,n){let r=typeof t==`string`?JSON.parse(t):t;if(!r||typeof r!=`object`)throw new V(`Invalid JWK`);let i=Zi(r.kid,n);return r.use!=null&&Jn(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??=r.use===`sig`?[`sign`]:[`encrypt`],delete r.use),new e(Un.parse({...r,kid:i}))}};function ea(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`:return`${e.name===`RSA-PSS`?`PS`:`RS`}${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`)}}case`Ed448`:case`Ed25519`:return`EdDSA`;default:throw TypeError(`Unexpected algorithm "${e.name}"`)}}function ta(e,t){return typeof e==`object`&&!!e&&`privateKey`in e&&e.privateKey instanceof CryptoKey&&e.privateKey.type===`private`&&(t==null||e.privateKey.extractable===t)&&e.privateKey.usages.includes(`sign`)&&`publicKey`in e&&e.publicKey instanceof CryptoKey&&e.publicKey.type===`public`&&e.publicKey.extractable===!0&&e.publicKey.usages.includes(`verify`)}var na=class e extends $i{static async generate(e=[`ES256`],t=crypto.randomUUID(),n){let r=await this.generateKeyPair(e,n);if(!ta(r))throw TypeError(`Invalid CryptoKeyPair`);return this.fromKeypair(r,t)}static async fromKeypair(t,n){let{alg:r=ea(t.privateKey.algorithm),...i}=await crypto.subtle.exportKey(`jwk`,t.privateKey.extractable?t.privateKey:t.publicKey);return new e(Un.parse({...i,kid:n,alg:r}),t)}constructor(e,t){if(!e.alg)throw new V(`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 V(`Key cannot be used with algorithm "${e}"`);return this.cryptoKeyPair.privateKey}},ra=e=>typeof e==`number`?e:void 0,ia=class e extends Error{constructor(e,t,n,r=400,i){super(t,{cause:i}),this.did=e,this.code=n,this.status=r}get statusCode(){return this.status}toString(){return`${this.constructor.name} ${this.code} (${this.did}): ${this.message}`}static from(t,n){if(t instanceof e)return t;let r=t instanceof Error?t.message:typeof t==`string`?t:`An unknown error occurred`,i=typeof t==`object`&&t?(`statusCode`in t?ra(t.statusCode):void 0)??(`status`in t?ra(t.status):void 0):void 0;return new e(n,r,`did-unknown-error`,i,t)}},J=class extends ia{constructor(e,t,n){super(e,t,`did-invalid`,400,n)}},aa=`did:`,oa=4;function sa(e,t=0,n=e.length){if(!Number.isFinite(n)||!Number.isFinite(t)||n<t||n>e.length)throw TypeError(`Invalid start or end position`);if(n===t)throw new J(e,`Empty method name`);let r;for(let i=t;i<n;i++)if(r=e.charCodeAt(i),(r<97||r>122)&&(r<48||r>57))throw new J(e,`Invalid character at position ${i} in DID method name`)}function ca(e){let t=e.indexOf(`:`,oa);return e.slice(oa,t)}function la(e,t=0,n=e.length){if(!Number.isFinite(n)||!Number.isFinite(t)||n<t||n>e.length)throw TypeError(`Invalid start or end position`);if(n===t)throw new J(e,`DID method-specific id must not be empty`);let r;for(let i=t;i<n;i++)if(r=e.charCodeAt(i),(r<97||r>122)&&(r<65||r>90)&&(r<48||r>57)&&r!==46&&r!==45&&r!==95){if(r===58){if(i===n-1)throw new J(e,`DID cannot end with ":"`);continue}if(r===37){if(r=e.charCodeAt(++i),(r<48||r>57)&&(r<65||r>70)||(r=e.charCodeAt(++i),(r<48||r>57)&&(r<65||r>70)))throw new J(e,`Invalid pct-encoded character at position ${i}`);if(i>=n)throw new J(e,`Incomplete pct-encoded character at position ${i-2}`);continue}throw new J(e,`Disallowed character in DID at position ${i}`)}}function ua(e){if(typeof e!=`string`)throw new J(typeof e,`DID must be a string`);let{length:t}=e;if(t>2048)throw new J(e,`DID is too long (2048 chars max)`);if(!e.startsWith(`did:`))throw new J(e,`DID requires "${aa}" prefix`);let n=e.indexOf(`:`,oa);if(n===-1)throw new J(e,`Missing colon after method name`);sa(e,oa,n),la(e,n+1,t)}var da=N().superRefine((e,t)=>{try{return ua(e),!0}catch(e){return t.addIssue({code:b.custom,message:e instanceof Error?e.message:`Unexpected error`}),!1}});function fa(e,t=0,n=e.length){let r;for(let i=t;i<n;i++)if(r=e.charCodeAt(i),!(r>=65&&r<=90||r>=97&&r<=122||r>=48&&r<=57||r===45||r===46||r===95||r===126)&&r!==33&&r!==36&&r!==38&&r!==39&&r!==40&&r!==41&&r!==42&&r!==43&&r!==44&&r!==59&&r!==61&&r!==58&&r!==64&&r!==47&&r!==63){if(r===37){if(i+2>=n||!pa(e.charCodeAt(i+1))||!pa(e.charCodeAt(i+2)))return!1;i+=2}else return!1}return!0}function pa(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}var ma=URL.canParse?.bind(URL)??((e,t)=>{try{return new URL(e,t),!0}catch{return!1}}),ha=8,ga=32;function _a(e){if(typeof e!=`string`||e.length!==ga||!e.startsWith(`did:plc:`))return!1;for(let t=ha;t<ga;t++)if(!ya(e.charCodeAt(t)))return!1;return!0}function va(e){if(typeof e!=`string`)throw new J(typeof e,`DID must be a string`);if(!e.startsWith(`did:plc:`))throw new J(e,`Invalid did:plc prefix`);if(e.length!==ga)throw new J(e,`did:plc must be ${ga} characters long`);for(let t=ha;t<ga;t++)if(!ya(e.charCodeAt(t)))throw new J(e,`Invalid character at position ${t}`)}var ya=e=>e>=97&&e<=122||e>=50&&e<=55,ba=`did:web:`;function xa(e){if(typeof e!=`string`||!e.startsWith(`did:web:`)||e.charAt(8)===`:`)return!1;try{la(e,ba.length)}catch{return!1}return ma(wa(e))}function Sa(e){if(typeof e!=`string`)throw new J(typeof e,`DID must be a string`);if(!e.startsWith(`did:web:`))throw new J(e,`Invalid did:web prefix`);if(e.charAt(8)===`:`)throw new J(e,`did:web MSID must not start with a colon`);if(la(e,ba.length),!ma(wa(e)))throw new J(e,`Invalid Web DID`)}function Ca(e){try{return new URL(wa(e))}catch(t){throw new J(e,`Invalid Web DID`,t)}}function wa(e){let t=ba.length,n=e.indexOf(`:`,t),r=(n===-1?e.slice(t):e.slice(t,n)).replaceAll(`%3A`,`:`),i=n===-1?``:e.slice(n).replaceAll(`:`,`/`);return`${r.startsWith(`localhost`)&&(r.length===9||r.charCodeAt(9)===58)?`http`:`https`}://${r}${i}`}function Ta(e,t,n){return n.charCodeAt(0)===35?n.length===t.length+1&&n.endsWith(t):n.length===t.length+1+e.length&&n.charCodeAt(e.length)===35&&n.startsWith(e)&&n.endsWith(t)}var Ea=N().refine(Da,`Atproto only allows "plc" and "web" DID methods`);function Da(e){return _a(e)||Aa(e)}function Oa(e){if(typeof e!=`string`)throw new J(typeof e,`DID must be a string`);if(e.startsWith(`did:plc:`))va(e);else if(e.startsWith(`did:web:`))ka(e);else throw new J(e,`Atproto only allows "plc" and "web" DID methods`)}function ka(e){if(Sa(e),ja(e))throw new J(e,`Atproto does not allow path components in Web DIDs`);if(Na(e))throw new J(e,`Atproto does not allow port numbers in Web DIDs, except for localhost`)}function Aa(e){return!(!xa(e)||ja(e)||Na(e))}function ja(e){return e.includes(`:`,ba.length)}function Ma(e){return e===`did:web:localhost`||e.startsWith(`did:web:localhost:`)||e.startsWith(`did:web:localhost%3A`)}function Na(e){if(Ma(e))return!1;let t=e.indexOf(`:`,ba.length);return t===-1?e.includes(`%3A`,ba.length):e.lastIndexOf(`%3A`,t)!==-1}function Pa(e){let t=e.service?.find(Fa,e);if(!t)throw new ia(e.id,`Document ${e.id} does not contain a (valid) #atproto_pds service URL`,`did-service-not-found`);return new URL(t.serviceEndpoint)}function Fa(e){return e?.type===`AtprotoPersonalDataServer`&&typeof e.serviceEndpoint==`string`&&ma(e.serviceEndpoint)&&Ta(this.id,`atproto_pds`,e.id)}Object.freeze([`EcdsaSecp256r1VerificationKey2019`,`EcdsaSecp256k1VerificationKey2019`,`Multikey`]);var Ia=N().url(`RFC3968 compliant URI`),La=R([da,I(da)]),Ra=R([Ia.refine(e=>{let t=e.indexOf(`#`);return t!==-1&&fa(e,t+1)},{message:`Missing or invalid fragment in RFC3968 URI`}),N().refine(e=>e.charCodeAt(0)===35,{message:`Fragment must start with #`}).refine(e=>fa(e,1),{message:`Invalid char in URI fragment`})]),za=L({id:Ra,type:N().min(1),controller:La,publicKeyJwk:an(N(),en()).optional(),publicKeyMultibase:N().optional()}),Ba=L({id:Ra,type:R([N(),I(N())]),serviceEndpoint:R([Ia,an(N(),Ia),I(R([Ia,an(N(),Ia)])).nonempty()])}),Va=R([Ra,za]),Ha=L({"@context":R([z(`https://www.w3.org/ns/did/v1`),I(N().url()).nonempty().refine(e=>e[0]===`https://www.w3.org/ns/did/v1`,{message:`First @context must be https://www.w3.org/ns/did/v1`})]).optional(),id:da,controller:La.optional(),alsoKnownAs:I(Ia).optional(),service:I(Ba).optional(),authentication:I(Va).optional(),verificationMethod:I(za).optional()}).superRefine(({id:e,service:t},n)=>{if(t){let r=new Set;for(let i=0;i<t.length;i++){let a=t[i],o=a.id.startsWith(`#`)?`${e}${a.id}`:a.id;r.has(o)?n.addIssue({code:b.custom,message:`Duplicate service id (${a.id}) found in the document`,path:[`service`,i,`id`]}):r.add(o)}}});function Ua(e,t=`Assertion failed`){if(!e)throw Error(t)}var Wa=()=>!0,Ga=()=>!1,Ka=class{#e=new Map;#t;#n;#r={};constructor(e,t,n={}){this.#t=e,this.#n=t,this.#r=n}async get(e,{signal:t,context:n,allowStale:r=!1,noCache:i=!1}={}){t?.throwIfAborted();let{isStale:a,deleteOnError:o}=this.#r,s=i?Ga:r||a==null?Wa:async t=>!await a(e,t),c;for(;c=this.#e.get(e);){try{let{isFresh:e,value:t}=await c;if(e||await s(t))return t}catch{}t?.throwIfAborted()}let l=Promise.resolve().then(async()=>{t?.throwIfAborted();let r=await this.getStored(e,{signal:t});return r!==void 0&&await s(r)?{isFresh:!1,value:r}:(t?.throwIfAborted(),Promise.resolve().then(async()=>{let a={signal:t,noCache:i,context:n};return this.#t.call(null,e,a,r)}).catch(async t=>{if(r!==void 0)try{await o?.(t,e,r)&&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(()=>{Ua(this.#e.get(e)===l,`Pending item for key "${e}" was replaced before it finished.`),this.#e.delete(e)});Ua(!this.#e.has(e),`Concurrent execution flow for key "${e}" should not exist.`),this.#e.set(e,l);let{value:u}=await l;return u}async getStored(e,t){return this.#n.get(e,t)}async setStored(e,t){await this.#n.set(e,t)}async delStored(e,t){await this.#n.del(e)}},qa=(e,t)=>{console.error(`SimpleStore error during "${t}"`,e)};function Ja(e,t=qa){return{async get(n,r){r?.signal?.throwIfAborted();try{return await e.get(n,r)}catch(e){if(r?.signal?.aborted)throw e;t(e,`get`,n);return}},async set(n,r){try{await e.set(n,r)}catch(e){t(e,`set`,n)}},async del(n){try{await e.del(n)}catch(e){t(e,`del`,n)}},async clear(){try{await e.clear?.()}catch(e){t(e,`clear`)}}}}var Ya=typeof performance==`object`&&performance&&typeof performance.now==`function`?performance:Date,Xa=new Set,Za=typeof process==`object`&&process?process:{},Qa=(e,t,n,r)=>{typeof Za.emitWarning==`function`?Za.emitWarning(e,t,n,r):console.error(`[${n}] ${t}: ${e}`)},$a=globalThis.AbortController,eo=globalThis.AbortSignal;if($a===void 0){eo=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(e,t){this._onabort.push(t)}},$a=class{constructor(){t()}signal=new eo;abort(e){if(!this.signal.aborted){this.signal.reason=e,this.signal.aborted=!0;for(let t of this.signal._onabort)t(e);this.signal.onabort?.(e)}}};let e=Za.env?.LRU_CACHE_IGNORE_AC_WARNING!==`1`,t=()=>{e&&(e=!1,Qa("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))}}var to=e=>!Xa.has(e),no=e=>e&&e===Math.floor(e)&&e>0&&isFinite(e),ro=e=>no(e)?e<=256?Uint8Array:e<=2**16?Uint16Array:e<=2**32?Uint32Array:e<=2**53-1?io:null:null,io=class extends Array{constructor(e){super(e),this.fill(0)}},ao=class e{heap;length;static#e=!1;static create(t){let n=ro(t);if(!n)return[];e.#e=!0;let r=new e(t,n);return e.#e=!1,r}constructor(t,n){if(!e.#e)throw TypeError(`instantiate Stack using Stack.create(n)`);this.heap=new n(t),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},oo=class e{#e;#t;#n;#r;#i;#a;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;#x;#S;static unsafeExposeInternals(e){return{starts:e.#v,ttls:e.#y,sizes:e.#_,keyMap:e.#c,keyList:e.#l,valList:e.#u,next:e.#d,prev:e.#f,get head(){return e.#p},get tail(){return e.#m},free:e.#h,isBackgroundFetch:t=>e.#L(t),backgroundFetch:(t,n,r,i)=>e.#I(t,n,r,i),moveToTail:t=>e.#z(t),indexes:t=>e.#M(t),rindexes:t=>e.#N(t),isStale:t=>e.#D(t)}}get max(){return this.#e}get maxSize(){return this.#t}get calculatedSize(){return this.#s}get size(){return this.#o}get fetchMethod(){return this.#i}get memoMethod(){return this.#a}get dispose(){return this.#n}get disposeAfter(){return this.#r}constructor(t){let{max:n=0,ttl:r,ttlResolution:i=1,ttlAutopurge:a,updateAgeOnGet:o,updateAgeOnHas:s,allowStale:c,dispose:l,disposeAfter:u,noDisposeOnSet:d,noUpdateTTL:f,maxSize:p=0,maxEntrySize:m=0,sizeCalculation:h,fetchMethod:g,memoMethod:ee,noDeleteOnFetchRejection:te,noDeleteOnStaleGet:_,allowStaleOnFetchRejection:ne,allowStaleOnFetchAbort:re,ignoreFetchAbort:ie}=t;if(n!==0&&!no(n))throw TypeError(`max option must be a nonnegative integer`);let ae=n?ro(n):Array;if(!ae)throw Error(`invalid max value: `+n);if(this.#e=n,this.#t=p,this.maxEntrySize=m||this.#t,this.sizeCalculation=h,this.sizeCalculation){if(!this.#t&&!this.maxEntrySize)throw TypeError(`cannot set sizeCalculation without setting maxSize or maxEntrySize`);if(typeof this.sizeCalculation!=`function`)throw TypeError(`sizeCalculation set to non-function`)}if(ee!==void 0&&typeof ee!=`function`)throw TypeError(`memoMethod must be a function if defined`);if(this.#a=ee,g!==void 0&&typeof g!=`function`)throw TypeError(`fetchMethod must be a function if specified`);if(this.#i=g,this.#x=!!g,this.#c=new Map,this.#l=Array(n).fill(void 0),this.#u=Array(n).fill(void 0),this.#d=new ae(n),this.#f=new ae(n),this.#p=0,this.#m=0,this.#h=ao.create(n),this.#o=0,this.#s=0,typeof l==`function`&&(this.#n=l),typeof u==`function`?(this.#r=u,this.#g=[]):(this.#r=void 0,this.#g=void 0),this.#b=!!this.#n,this.#S=!!this.#r,this.noDisposeOnSet=!!d,this.noUpdateTTL=!!f,this.noDeleteOnFetchRejection=!!te,this.allowStaleOnFetchRejection=!!ne,this.allowStaleOnFetchAbort=!!re,this.ignoreFetchAbort=!!ie,this.maxEntrySize!==0){if(this.#t!==0&&!no(this.#t))throw TypeError(`maxSize must be a positive integer if specified`);if(!no(this.maxEntrySize))throw TypeError(`maxEntrySize must be a positive integer if specified`);this.#O()}if(this.allowStale=!!c,this.noDeleteOnStaleGet=!!_,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!s,this.ttlResolution=no(i)||i===0?i:1,this.ttlAutopurge=!!a,this.ttl=r||0,this.ttl){if(!no(this.ttl))throw TypeError(`ttl must be a positive integer if specified`);this.#C()}if(this.#e===0&&this.ttl===0&&this.#t===0)throw TypeError(`At least one of max, maxSize, or ttl is required`);if(!this.ttlAutopurge&&!this.#e&&!this.#t){let t=`LRU_CACHE_UNBOUNDED`;to(t)&&(Xa.add(t),Qa(`TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.`,`UnboundedCacheWarning`,t,e))}}getRemainingTTL(e){return this.#c.has(e)?1/0:0}#C(){let e=new io(this.#e),t=new io(this.#e);this.#y=e,this.#v=t,this.#E=(n,r,i=Ya.now())=>{if(t[n]=r===0?0:i,e[n]=r,r!==0&&this.ttlAutopurge){let e=setTimeout(()=>{this.#D(n)&&this.#B(this.#l[n],`expire`)},r+1);e.unref&&e.unref()}},this.#w=n=>{t[n]=e[n]===0?0:Ya.now()},this.#T=(i,a)=>{if(e[a]){let o=e[a],s=t[a];if(!o||!s)return;i.ttl=o,i.start=s,i.now=n||r(),i.remainingTTL=o-(i.now-s)}};let n=0,r=()=>{let e=Ya.now();if(this.ttlResolution>0){n=e;let t=setTimeout(()=>n=0,this.ttlResolution);t.unref&&t.unref()}return e};this.getRemainingTTL=i=>{let a=this.#c.get(i);if(a===void 0)return 0;let o=e[a],s=t[a];return!o||!s?1/0:o-((n||r())-s)},this.#D=i=>{let a=t[i],o=e[i];return!!o&&!!a&&(n||r())-a>o}}#w=()=>{};#T=()=>{};#E=()=>{};#D=()=>!1;#O(){let e=new io(this.#e);this.#s=0,this.#_=e,this.#k=t=>{this.#s-=e[t],e[t]=0},this.#j=(e,t,n,r)=>{if(this.#L(t))return 0;if(!no(n)){if(r){if(typeof r!=`function`)throw TypeError(`sizeCalculation must be a function`);if(n=r(t,e),!no(n))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 n},this.#A=(t,n,r)=>{if(e[t]=n,this.#t){let n=this.#t-e[t];for(;this.#s>n;)this.#F(!0)}this.#s+=e[t],r&&(r.entrySize=n,r.totalCalculatedSize=this.#s)}}#k=e=>{};#A=(e,t,n)=>{};#j=(e,t,n,r)=>{if(n||r)throw TypeError(`cannot set size without setting maxSize or maxEntrySize on cache`);return 0};*#M({allowStale:e=this.allowStale}={}){if(this.#o)for(let t=this.#m;!(!this.#P(t)||((e||!this.#D(t))&&(yield t),t===this.#p));)t=this.#f[t]}*#N({allowStale:e=this.allowStale}={}){if(this.#o)for(let t=this.#p;!(!this.#P(t)||((e||!this.#D(t))&&(yield t),t===this.#m));)t=this.#d[t]}#P(e){return e!==void 0&&this.#c.get(this.#l[e])===e}*entries(){for(let e of this.#M())this.#u[e]!==void 0&&this.#l[e]!==void 0&&!this.#L(this.#u[e])&&(yield[this.#l[e],this.#u[e]])}*rentries(){for(let e of this.#N())this.#u[e]!==void 0&&this.#l[e]!==void 0&&!this.#L(this.#u[e])&&(yield[this.#l[e],this.#u[e]])}*keys(){for(let e of this.#M()){let t=this.#l[e];t!==void 0&&!this.#L(this.#u[e])&&(yield t)}}*rkeys(){for(let e of this.#N()){let t=this.#l[e];t!==void 0&&!this.#L(this.#u[e])&&(yield t)}}*values(){for(let e of this.#M())this.#u[e]!==void 0&&!this.#L(this.#u[e])&&(yield this.#u[e])}*rvalues(){for(let e of this.#N())this.#u[e]!==void 0&&!this.#L(this.#u[e])&&(yield this.#u[e])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]=`LRUCache`;find(e,t={}){for(let n of this.#M()){let r=this.#u[n],i=this.#L(r)?r.__staleWhileFetching:r;if(i!==void 0&&e(i,this.#l[n],this))return this.get(this.#l[n],t)}}forEach(e,t=this){for(let n of this.#M()){let r=this.#u[n],i=this.#L(r)?r.__staleWhileFetching:r;i!==void 0&&e.call(t,i,this.#l[n],this)}}rforEach(e,t=this){for(let n of this.#N()){let r=this.#u[n],i=this.#L(r)?r.__staleWhileFetching:r;i!==void 0&&e.call(t,i,this.#l[n],this)}}purgeStale(){let e=!1;for(let t of this.#N({allowStale:!0}))this.#D(t)&&(this.#B(this.#l[t],`expire`),e=!0);return e}info(e){let t=this.#c.get(e);if(t===void 0)return;let n=this.#u[t],r=this.#L(n)?n.__staleWhileFetching:n;if(r===void 0)return;let i={value:r};if(this.#y&&this.#v){let e=this.#y[t],n=this.#v[t];e&&n&&(i.ttl=e-(Ya.now()-n),i.start=Date.now())}return this.#_&&(i.size=this.#_[t]),i}dump(){let e=[];for(let t of this.#M({allowStale:!0})){let n=this.#l[t],r=this.#u[t],i=this.#L(r)?r.__staleWhileFetching:r;if(i===void 0||n===void 0)continue;let a={value:i};if(this.#y&&this.#v){a.ttl=this.#y[t];let e=Ya.now()-this.#v[t];a.start=Math.floor(Date.now()-e)}this.#_&&(a.size=this.#_[t]),e.unshift([n,a])}return e}load(e){this.clear();for(let[t,n]of e){if(n.start){let e=Date.now()-n.start;n.start=Ya.now()-e}this.set(t,n.value,n)}}set(e,t,n={}){if(t===void 0)return this.delete(e),this;let{ttl:r=this.ttl,start:i,noDisposeOnSet:a=this.noDisposeOnSet,sizeCalculation:o=this.sizeCalculation,status:s}=n,{noUpdateTTL:c=this.noUpdateTTL}=n,l=this.#j(e,t,n.size||0,o);if(this.maxEntrySize&&l>this.maxEntrySize)return s&&(s.set=`miss`,s.maxEntrySizeExceeded=!0),this.#B(e,`set`),this;let u=this.#o===0?void 0:this.#c.get(e);if(u===void 0)u=this.#o===0?this.#m:this.#h.length===0?this.#o===this.#e?this.#F(!1):this.#o:this.#h.pop(),this.#l[u]=e,this.#u[u]=t,this.#c.set(e,u),this.#d[this.#m]=u,this.#f[u]=this.#m,this.#m=u,this.#o++,this.#A(u,l,s),s&&(s.set=`add`),c=!1;else{this.#z(u);let n=this.#u[u];if(t!==n){if(this.#x&&this.#L(n)){n.__abortController.abort(Error(`replaced`));let{__staleWhileFetching:t}=n;t!==void 0&&!a&&(this.#b&&this.#n?.(t,e,`set`),this.#S&&this.#g?.push([t,e,`set`]))}else a||(this.#b&&this.#n?.(n,e,`set`),this.#S&&this.#g?.push([n,e,`set`]));if(this.#k(u),this.#A(u,l,s),this.#u[u]=t,s){s.set=`replace`;let e=n&&this.#L(n)?n.__staleWhileFetching:n;e!==void 0&&(s.oldValue=e)}}else s&&(s.set=`update`)}if(r!==0&&!this.#y&&this.#C(),this.#y&&(c||this.#E(u,r,i),s&&this.#T(s,u)),!a&&this.#S&&this.#g){let e=this.#g,t;for(;t=e?.shift();)this.#r?.(...t)}return this}pop(){try{for(;this.#o;){let e=this.#u[this.#p];if(this.#F(!0),this.#L(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#S&&this.#g){let e=this.#g,t;for(;t=e?.shift();)this.#r?.(...t)}}}#F(e){let t=this.#p,n=this.#l[t],r=this.#u[t];return this.#x&&this.#L(r)?r.__abortController.abort(Error(`evicted`)):(this.#b||this.#S)&&(this.#b&&this.#n?.(r,n,`evict`),this.#S&&this.#g?.push([r,n,`evict`])),this.#k(t),e&&(this.#l[t]=void 0,this.#u[t]=void 0,this.#h.push(t)),this.#o===1?(this.#p=this.#m=0,this.#h.length=0):this.#p=this.#d[t],this.#c.delete(n),this.#o--,t}has(e,t={}){let{updateAgeOnHas:n=this.updateAgeOnHas,status:r}=t,i=this.#c.get(e);if(i!==void 0){let e=this.#u[i];if(this.#L(e)&&e.__staleWhileFetching===void 0)return!1;if(this.#D(i))r&&(r.has=`stale`,this.#T(r,i));else return n&&this.#w(i),r&&(r.has=`hit`,this.#T(r,i)),!0}else r&&(r.has=`miss`);return!1}peek(e,t={}){let{allowStale:n=this.allowStale}=t,r=this.#c.get(e);if(r===void 0||!n&&this.#D(r))return;let i=this.#u[r];return this.#L(i)?i.__staleWhileFetching:i}#I(e,t,n,r){let i=t===void 0?void 0:this.#u[t];if(this.#L(i))return i;let a=new $a,{signal:o}=n;o?.addEventListener(`abort`,()=>a.abort(o.reason),{signal:a.signal});let s={signal:a.signal,options:n,context:r},c=(r,i=!1)=>{let{aborted:o}=a.signal,c=n.ignoreFetchAbort&&r!==void 0;if(n.status&&(o&&!i?(n.status.fetchAborted=!0,n.status.fetchError=a.signal.reason,c&&(n.status.fetchAbortIgnored=!0)):n.status.fetchResolved=!0),o&&!c&&!i)return u(a.signal.reason);let l=f;return this.#u[t]===f&&(r===void 0?l.__staleWhileFetching?this.#u[t]=l.__staleWhileFetching:this.#B(e,`fetch`):(n.status&&(n.status.fetchUpdated=!0),this.set(e,r,s.options))),r},l=e=>(n.status&&(n.status.fetchRejected=!0,n.status.fetchError=e),u(e)),u=r=>{let{aborted:i}=a.signal,o=i&&n.allowStaleOnFetchAbort,s=o||n.allowStaleOnFetchRejection,c=s||n.noDeleteOnFetchRejection,l=f;if(this.#u[t]===f&&(!c||l.__staleWhileFetching===void 0?this.#B(e,`fetch`):o||(this.#u[t]=l.__staleWhileFetching)),s)return n.status&&l.__staleWhileFetching!==void 0&&(n.status.returnedStale=!0),l.__staleWhileFetching;if(l.__returned===l)throw r},d=(t,r)=>{let o=this.#i?.(e,i,s);o&&o instanceof Promise&&o.then(e=>t(e===void 0?void 0:e),r),a.signal.addEventListener(`abort`,()=>{(!n.ignoreFetchAbort||n.allowStaleOnFetchAbort)&&(t(void 0),n.allowStaleOnFetchAbort&&(t=e=>c(e,!0)))})};n.status&&(n.status.fetchDispatched=!0);let f=new Promise(d).then(c,l),p=Object.assign(f,{__abortController:a,__staleWhileFetching:i,__returned:void 0});return t===void 0?(this.set(e,p,{...s.options,status:void 0}),t=this.#c.get(e)):this.#u[t]=p,p}#L(e){if(!this.#x)return!1;let t=e;return!!t&&t instanceof Promise&&t.hasOwnProperty(`__staleWhileFetching`)&&t.__abortController instanceof $a}async fetch(e,t={}){let{allowStale:n=this.allowStale,updateAgeOnGet:r=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,ttl:a=this.ttl,noDisposeOnSet:o=this.noDisposeOnSet,size:s=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:l=this.noUpdateTTL,noDeleteOnFetchRejection:u=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:d=this.allowStaleOnFetchRejection,ignoreFetchAbort:f=this.ignoreFetchAbort,allowStaleOnFetchAbort:p=this.allowStaleOnFetchAbort,context:m,forceRefresh:h=!1,status:g,signal:ee}=t;if(!this.#x)return g&&(g.fetch=`get`),this.get(e,{allowStale:n,updateAgeOnGet:r,noDeleteOnStaleGet:i,status:g});let te={allowStale:n,updateAgeOnGet:r,noDeleteOnStaleGet:i,ttl:a,noDisposeOnSet:o,size:s,sizeCalculation:c,noUpdateTTL:l,noDeleteOnFetchRejection:u,allowStaleOnFetchRejection:d,allowStaleOnFetchAbort:p,ignoreFetchAbort:f,status:g,signal:ee},_=this.#c.get(e);if(_===void 0){g&&(g.fetch=`miss`);let t=this.#I(e,_,te,m);return t.__returned=t}{let t=this.#u[_];if(this.#L(t)){let e=n&&t.__staleWhileFetching!==void 0;return g&&(g.fetch=`inflight`,e&&(g.returnedStale=!0)),e?t.__staleWhileFetching:t.__returned=t}let i=this.#D(_);if(!h&&!i)return g&&(g.fetch=`hit`),this.#z(_),r&&this.#w(_),g&&this.#T(g,_),t;let a=this.#I(e,_,te,m),o=a.__staleWhileFetching!==void 0&&n;return g&&(g.fetch=i?`stale`:`refresh`,o&&i&&(g.returnedStale=!0)),o?a.__staleWhileFetching:a.__returned=a}}async forceFetch(e,t={}){let n=await this.fetch(e,t);if(n===void 0)throw Error(`fetch() returned undefined`);return n}memo(e,t={}){let n=this.#a;if(!n)throw Error(`no memoMethod provided to constructor`);let{context:r,forceRefresh:i,...a}=t,o=this.get(e,a);if(!i&&o!==void 0)return o;let s=n(e,o,{options:a,context:r});return this.set(e,s,a),s}get(e,t={}){let{allowStale:n=this.allowStale,updateAgeOnGet:r=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,status:a}=t,o=this.#c.get(e);if(o!==void 0){let t=this.#u[o],s=this.#L(t);return a&&this.#T(a,o),this.#D(o)?(a&&(a.get=`stale`),s?(a&&n&&t.__staleWhileFetching!==void 0&&(a.returnedStale=!0),n?t.__staleWhileFetching:void 0):(i||this.#B(e,`expire`),a&&n&&(a.returnedStale=!0),n?t:void 0)):(a&&(a.get=`hit`),s?t.__staleWhileFetching:(this.#z(o),r&&this.#w(o),t))}a&&(a.get=`miss`)}#R(e,t){this.#f[t]=e,this.#d[e]=t}#z(e){e!==this.#m&&(e===this.#p?this.#p=this.#d[e]:this.#R(this.#f[e],this.#d[e]),this.#R(this.#m,e),this.#m=e)}delete(e){return this.#B(e,`delete`)}#B(e,t){let n=!1;if(this.#o!==0){let r=this.#c.get(e);if(r!==void 0){if(n=!0,this.#o===1)this.#V(t);else{this.#k(r);let n=this.#u[r];if(this.#L(n)?n.__abortController.abort(Error(`deleted`)):(this.#b||this.#S)&&(this.#b&&this.#n?.(n,e,t),this.#S&&this.#g?.push([n,e,t])),this.#c.delete(e),this.#l[r]=void 0,this.#u[r]=void 0,r===this.#m)this.#m=this.#f[r];else if(r===this.#p)this.#p=this.#d[r];else{let e=this.#f[r];this.#d[e]=this.#d[r];let t=this.#d[r];this.#f[t]=this.#f[r]}this.#o--,this.#h.push(r)}}}if(this.#S&&this.#g?.length){let e=this.#g,t;for(;t=e?.shift();)this.#r?.(...t)}return n}clear(){return this.#V(`delete`)}#V(e){for(let t of this.#N({allowStale:!0})){let n=this.#u[t];if(this.#L(n))n.__abortController.abort(Error(`deleted`));else{let r=this.#l[t];this.#b&&this.#n?.(n,r,e),this.#S&&this.#g?.push([n,r,e])}}if(this.#c.clear(),this.#u.fill(void 0),this.#l.fill(void 0),this.#y&&this.#v&&(this.#y.fill(0),this.#v.fill(0)),this.#_&&this.#_.fill(0),this.#p=0,this.#m=0,this.#h.length=0,this.#s=0,this.#o=0,this.#S&&this.#g){let e=this.#g,t;for(;t=e?.shift();)this.#r?.(...t)}}},so=new WeakMap;function co(e){let t=new Set,n=[e],r=0;for(;n.length;){let e=n.pop();switch(typeof e){case`string`:r+=12+4*Math.ceil(e.length/4);break;case`number`:r+=12;break;case`boolean`:r+=4;break;case`object`:if(r+=4,e===null)break;if(so.has(e)){r+=so.get(e);break}if(t.has(e))continue;if(t.add(e),Array.isArray(e))r+=4,n.push(...e);else{r+=8;let t=Object.getOwnPropertyNames(e);for(let i=0;i<t.length;i++){r+=4;let a=t[i],o=e[a];o!==void 0&&n.push(o),n.push(a)}}break;case`function`:r+=8;break;case`symbol`:r+=8;break;case`bigint`:r+=16}}return typeof e==`object`&&e&&so.set(e,r),r}var lo=Symbol(`nullItem`),uo=e=>e===null?lo:e,fo=e=>e===lo?null:e,po=class{#e;constructor({sizeCalculation:e,...t}){this.#e=new oo({...t,allowStale:!1,updateAgeOnGet:!1,updateAgeOnHas:!1,sizeCalculation:e?(t,n)=>e(fo(t),n):t.maxEntrySize!=null||t.maxSize!=null?co:void 0})}get(e){let t=this.#e.get(e);if(t!==void 0)return fo(t)}set(e,t){this.#e.set(e,uo(t))}del(e){this.#e.delete(e)}clear(){this.#e.clear()}},mo=36e5,ho=52428800,go=class extends po{constructor(e){super(e?.max==null?{ttl:mo,maxSize:ho,...e}:{ttl:mo,...e})}},_o=class{constructor(e,t=new go,n){this.getter=new Ka((t,n)=>e.resolve(t,n),Ja(t,n))}async resolve(e,t){return this.getter.get(e,t)}},vo=class extends Error{constructor(e,t,n){super(t,n),this.statusCode=e}get expose(){return!0}};function yo(e){return function(t,n){return e.call(this,bo(t,n))}}function bo(e,t){return!t&&e instanceof Request?e:new Request(e,t)}var xo=e=>typeof e==`string`?e:void 0;TransformStream;async function So(e,t){e.body&&!e.bodyUsed&&!e.body.locked&&typeof e.body.cancel==`function`&&(typeof t==`function`?e.body.cancel().catch(t):t===`log`?e.body.cancel().catch(Co):await e.body.cancel())}function Co(e){console.warn(`Failed to cancel response body`,e)}var wo=class e extends vo{constructor(e,t,n,r){if(t==null||!n){let e=Eo(To(r?.cause));t??=e[0],n||=e[1]}super(t,n,r),this.request=e}get expose(){return this.statusCode!==500}static from(t,n){return n instanceof e?n:new e(t,void 0,void 0,{cause:n})}};function To(e){return e instanceof TypeError&&e.message===`fetch failed`&&e.cause!==void 0?e.cause:e}function Eo(e){if(typeof e==`string`&&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(typeof t==`string`)switch(!0){case t===`ENOTFOUND`:return[400,`Invalid hostname`];case t===`ECONNREFUSED`:return[502,`Connection refused`];case t===`DEPTH_ZERO_SELF_SIGNED_CERT`: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]}Object.freeze([`example.com`,`*.example.com`,`example.org`,`*.example.org`,`example.net`,`*.example.net`,`googleusercontent.com`,`*.googleusercontent.com`]);function Do(...e){return e.reduce(Oo)}function Oo(e,t){return async(...n)=>t(await e(...n))}var ko=/^application\/(?:[^()<>@,;:/[\]\\?={} \t]+\+)?json$/i,Y=class e extends vo{constructor(e,t=e.status,n=e.statusText,r){super(t,n,r),this.response=e}static async from(t,n=Ao,r=t.status,i){let a=typeof n==`string`?n:typeof n==`function`?await n(t):void 0;return new e(t,r,a,i)}},Ao=async e=>{let t=Fo(e);if(t)try{if(t===`text/plain`)return await e.text();if(ko.test(t)){let t=await e.json();if(typeof t==`string`)return t;if(typeof t==`object`&&t){if(`error_description`in t){let e=xo(t.error_description);if(e)return e}if(`error`in t){let e=xo(t.error);if(e)return e}if(`message`in t){let e=xo(t.message);if(e)return e}}}}catch{}};async function jo(e,t=1/0){if(Fo(e)!==`application/json`)return;No(e,t);let n=e.clone();if(!n.body||t===1/0)return n.json();let r=await Mo(n.body,t);if(!r)throw new Y(e,502,`Response too large`);return JSON.parse(new TextDecoder().decode(r))}async function Mo(e,t){let n=e.getReader(),r=[],i=0;for(let e=await n.read();!e.done;e=await n.read()){if(i+=e.value.byteLength,i>t)return n.cancel().catch(Co),null;r.push(e.value)}if(r.length===1)return r[0];let a=new Uint8Array(i),o=0;for(let e of r)a.set(e,o),o+=e.byteLength;return a}function No(e,t){if(!(t>=0))throw TypeError(`maxBytes must be a non-negative number`);let n=Po(e);if(n!=null&&n>t)throw new Y(e,502,`Response too large`);return n}function Po(e){let t=e.headers.get(`Content-Length`);if(t==null)return;if(!/^\d+$/.test(t))throw new Y(e,502,`Invalid Content-Length`);let n=Number(t);if(!Number.isSafeInteger(n))throw new Y(e,502,`Content-Length too large`);return n}function Fo(e){let t=e.headers.get(`Content-Type`);if(t!=null)return t.split(`;`,1)[0].trim()}function Io(e,t=Co){return async n=>{try{return await e(n)}catch(e){throw await So(n,t??void 0),e}}}function Lo(e){return Io(t=>Ro(t,e))}async function Ro(e,t){if(e.ok)return e;throw await Y.from(e,t)}function zo(e,t=!0){let n=typeof e==`string`?t=>t===e:e instanceof RegExp?t=>e.test(t):e;return Io(e=>Bo(e,n,t))}async function Bo(e,t,n=!0){let r=Fo(e);if(r){if(!t(r.toLowerCase()))throw await Y.from(e,`Unexpected response Content-Type (${r})`,502)}else if(n)throw await Y.from(e,`Missing response Content-Type header`,502);return e}async function Vo(e){try{return{response:e,json:await e.json()}}catch(t){throw new Y(e,502,`Unable to parse response as JSON`,{cause:t})}}function Ho(e=ko,t=!0){return Do(zo(e,t),Io(Vo))}function Uo(e,t){if(`parseAsync`in e&&typeof e.parseAsync==`function`)return async n=>e.parseAsync(n.json,t);if(`parse`in e&&typeof e.parse==`function`)return async n=>e.parse(n.json,t);throw TypeError(`Invalid schema`)}var Wo=Uo;function Go(e=globalThis.fetch,t=globalThis){return yo(async n=>{try{return await e.call(t,n)}catch(e){throw wo.from(n,e)}})}var Ko=class{constructor(e){this.methods=new Map(Object.entries(e))}async resolve(e,t){t?.signal?.throwIfAborted();let n=ca(e),r=this.methods.get(n);if(!r)throw new ia(e,`Unsupported DID method`,`did-method-invalid`,400);try{let n=await r.resolve(e,t);if(n.id!==e)throw new ia(e,`DID document id (${n.id}) does not match DID`,`did-document-id-mismatch`,400);return n}catch(t){if(t instanceof Y){let n=t.response.status>=500?502:t.response.status;throw new ia(e,t.message,`did-fetch-error`,n,t)}throw t instanceof vo?new ia(e,t.message,`did-fetch-error`,400,t):t instanceof x?new ia(e,t.message,`did-document-format-error`,503,t):ia.from(t,e)}}},qo=Do(Lo(),Ho(/^application\/(did\+ld\+)?json$/),Wo(Ha)),Jo=class{constructor(e){this.plcDirectoryUrl=new URL(e?.plcDirectoryUrl||`https://plc.directory/`),this.fetch=Go(e?.fetch)}async resolve(e,t){va(e);let n=new URL(`/${encodeURIComponent(e)}`,this.plcDirectoryUrl);return this.fetch(n,{redirect:`error`,headers:{accept:`application/did+ld+json,application/json`},signal:t?.signal}).then(qo)}},Yo=Do(Lo(),Ho(/^application\/(did\+ld\+)?json$/),Wo(Ha)),Xo=class{constructor({fetch:e=globalThis.fetch,allowHttp:t=!0}={}){this.fetch=Go(e),this.allowHttp=t}async resolve(e,t){let n=Zo(e);if(!this.allowHttp&&n.protocol===`http:`)throw new ia(e,`Resolution of "http" did:web is not allowed`,`did-web-http-not-allowed`);return this.fetch(n,{redirect:`error`,headers:{accept:`application/did+ld+json,application/json`},signal:t?.signal}).then(Yo)}};function Zo(e){let t=Ca(e);return t.pathname===`/`?new URL(`/.well-known/did.json`,t):new URL(`${t.pathname}/did.json`,t)}var Qo=class extends Ko{constructor(e){super({plc:new Jo(e),web:new Xo(e)})}};function $o(e){let{didResolver:t,didCache:n,onDidCacheError:r}=e;return t instanceof _o&&!n?t:new _o(t??new Qo(e),n,r)}var es=class extends Error{constructor(){super(...arguments),this.name=`HandleResolverError`}};function ts(e){return e===null||Da(e)}var ns=L({error:N(),message:N().optional()}),rs=class{constructor(e,t){this.serviceUrl=new URL(e),this.fetch=t?.fetch??globalThis.fetch}async resolve(e,t){let n=new URL(`/xrpc/com.atproto.identity.resolveHandle`,this.serviceUrl);n.searchParams.set(`handle`,e);let r=await this.fetch.call(null,n,{cache:t?.noCache?`no-cache`:void 0,signal:t?.signal,redirect:`error`}),i=await r.json();if(r.status===400){let{error:e,data:t}=ns.safeParse(i);if(e)throw new es(`Invalid response from resolveHandle method: ${e.message}`,{cause:e});if(t.error===`InvalidRequest`&&t.message===`Unable to resolve handle`)return null}if(!r.ok)throw new es(`Invalid status code from resolveHandle method`);let a=i?.did;if(!ts(a))throw new es(`Invalid DID returned from resolveHandle method`);return a}},is=class{constructor(e,t=new po({max:1e3,ttl:6e5}),n){this.getter=new Ka((t,n)=>e.resolve(t,n),Ja(t,n))}async resolve(e,t){return this.getter.get(e,t)}};function as(e){let{handleResolver:t,handleCache:n,onHandleCacheError:r}=e;return t instanceof is&&!n?t:new is(typeof t==`string`||t instanceof URL?new rs(t,e):t,n,r)}var os=`handle.invalid`,ss=class extends Error{constructor(){super(...arguments),this.name=`IdentityResolverError`}};function cs(e){if(e.alsoKnownAs){for(let t of e.alsoKnownAs)if(t.startsWith(`at://`))return t.slice(5)}}function ls(e){let t=cs(e);if(t)return us(t)}function us(e){let t=ds(e);return fs(t)?t:void 0}function ds(e){return e.toLowerCase()}function fs(e){return e.length>0&&e.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(e)}var ps=class{constructor(e,t){this.didResolver=e,this.handleResolver=t}async resolve(e,t){return Da(e)?this.resolveFromDid(e,t):this.resolveFromHandle(e,t)}async resolveFromDid(e,t){let n=await this.getDocumentFromDid(e,t);t?.signal?.throwIfAborted();let r=ls(n),i=r?await this.handleResolver.resolve(r,t).catch(()=>void 0):void 0;return{did:n.id,didDoc:n,handle:r&&i===e?r:os}}async resolveFromHandle(e,t){let n=await this.getDocumentFromHandle(e,t);return{did:n.id,didDoc:n,handle:ls(n)||`handle.invalid`}}async getDocumentFromDid(e,t){return this.didResolver.resolve(e,t)}async getDocumentFromHandle(e,t){let n=us(e);if(!n)throw new ss(`Invalid handle "${e}" provided.`);let r=await this.handleResolver.resolve(n,t);if(!r)throw new ss(`Handle "${n}" does not resolve to a DID`);t?.signal?.throwIfAborted();let i=await this.didResolver.resolve(r,t);if(n!==ls(i))throw new ss(`Did document for "${r}" does not include the handle "${n}"`);return i}};function ms(e){if(`identityResolver`in e&&e.identityResolver!=null)return e.identityResolver;if(`handleResolver`in e&&e.handleResolver!=null)return new ps($o(e),as(e));throw TypeError(`identityResolver or handleResolver option is required`)}var hs=`urn:ietf:params:oauth:client-assertion-type:jwt-bearer`,gs=URL.canParse?.bind(URL)??(e=>{try{return new URL(e),!0}catch{return!1}});function _s(e){return!!(e.match(/^\d+\.\d+\.\d+\.\d+$/)||e.startsWith(`[`)&&e.endsWith(`]`))}function vs(e){return e===`localhost`||e===`127.0.0.1`||e===`[::1]`}function ys(e){let t=e.split(`.`);if(t.length<2)return!0;let n=t.at(-1).toLowerCase();return n===`test`||n===`local`||n===`localhost`||n===`invalid`||n===`example`}function bs(e){let t=e.startsWith(`https://`)?8:e.startsWith(`http://`)?7:-1;if(t===-1)throw TypeError(`URL must use the "https:" or "http:" protocol`);let n=e.indexOf(`#`,t),r=e.indexOf(`?`,t),i=r!==-1&&(n===-1||r<n)?r:-1,a=n===-1?i===-1?e.length:i:i===-1?n:Math.min(n,i),o=e.indexOf(`/`,t),s=o===-1||o>a?a:o;if(t===s)throw TypeError(`URL must contain a host`);return e.substring(s,a)}var xs=e=>{if(typeof e==`string`&&e.startsWith(`{`)&&e.endsWith(`}`))try{return JSON.parse(e)}catch{return e}return e},Ss=e=>{if(typeof e==`string`){let t=Number(e);if(!Number.isNaN(t))return t}return e},Cs=(e,t)=>{if(e.length===0)throw TypeError(`Value cannot be empty`);if(e.includes(` `))throw TypeError(`Value cannot contain spaces`);let n=t.length,r=e.length;if(n<r)return!1;let i=t.indexOf(e),a;for(;i!==-1;){if(a=i+r,(i===0||t.charCodeAt(i-1)===32)&&(a===n||t.charCodeAt(a)===32))return!0;i=t.indexOf(e,a+1)}return!1},ws=N().refine(e=>e.includes(`:`)&&gs(e),{message:`Invalid URL`}),Ts=ws.superRefine((e,t)=>e.startsWith(`http://`)?vs(new URL(e).hostname)?!0:(t.addIssue({code:b.custom,message:`URL must use "localhost", "127.0.0.1" or "[::1]" as hostname`}),!1):(t.addIssue({code:b.custom,message:`URL must use the "http:" protocol`}),!1)),Es=ws.superRefine((e,t)=>{if(!e.startsWith(`https://`))return t.addIssue({code:b.custom,message:`URL must use the "https:" protocol`}),!1;let n=new URL(e);if(vs(n.hostname))return t.addIssue({code:b.custom,message:`https: URL must not use a loopback host`}),!1;if(!_s(n.hostname)){if(!n.hostname.includes(`.`))return t.addIssue({code:b.custom,message:`Domain name must contain at least two segments`}),!1;if(n.hostname.endsWith(`.local`))return t.addIssue({code:b.custom,message:`Domain name must not end with ".local"`}),!1}return!0}),X=N().superRefine((e,t)=>{if(e.startsWith(`http://`)){let n=Ts.safeParse(e);return n.success||n.error.issues.forEach(t.addIssue,t),n.success}if(e.startsWith(`https://`)){let n=Es.safeParse(e);return n.success||n.error.issues.forEach(t.addIssue,t),n.success}return t.addIssue({code:b.custom,message:`URL must use the "http:" or "https:" protocol`}),!1}),Ds=ws.superRefine((e,t)=>{let n=e.indexOf(`.`),r=e.indexOf(`:`);if(n===-1||r===-1||n>r)return t.addIssue({code:b.custom,message:`Private-use URI scheme requires a "." as part of the protocol`}),!1;let i=new URL(e);return i.protocol.includes(`.`)?(ys(i.protocol.slice(0,-1).split(`.`).reverse().join(`.`))&&t.addIssue({code:b.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:b.custom,message:`Private-Use URI Scheme must be in the form <scheme>:/{path} (notice the single slash!) as per RFC 8252`}),!1):!0):(t.addIssue({code:b.custom,message:`Invalid private-use URI scheme`}),!1)}),Os=Object.freeze([`http://127.0.0.1/`,`http://[::1]/`]),ks=/^[\x21\x23-\x5B\x5D-\x7E]+(?: [\x21\x23-\x5B\x5D-\x7E]+)*$/,As=e=>ks.test(e),js=N().refine(As,{message:`Invalid OAuth scope`}),Ms=`atproto`;function Ns(e){return As(e)&&Cs(`atproto`,e)}var Ps=N().refine(Ns,{message:`Invalid ATProto OAuth scope`}),Fs=Ms,Is=N().min(1),Ls=Ts.superRefine((e,t)=>!e.startsWith(`http://localhost`)||(t.addIssue({code:b.custom,message:`Use of "localhost" hostname is not allowed (RFC 8252), use a loopback IP such as "127.0.0.1" instead`}),!1)),Rs=Ls,zs=N().superRefine((e,t)=>{if(e.startsWith(`https:`)){let n=Es.safeParse(e);return n.success||n.error.issues.forEach(t.addIssue,t),n.success}if(e.startsWith(`http:`)){let n=Ls.safeParse(e);return n.success||n.error.issues.forEach(t.addIssue,t),n.success}if(/^[^.:]+(?:\.[^.:]+)+:/.test(e)){let n=Ds.safeParse(e);return n.success||n.error.issues.forEach(t.addIssue,t),n.success}return t.addIssue({code:b.custom,message:`URL must use the "https:" or "http:" protocol, or a private-use URI scheme (RFC 8252)`}),!1}),Bs=`http://localhost`,Vs=Is.superRefine((e,t)=>{let n=Gs(e);return n.success||t.addIssue({code:`custom`,message:n.message}),n.success});function Hs(e){Ws(e)}function Us(e){return Gs(e).success}function Ws(e){let t=Gs(e);if(t.success)return t.value;throw TypeError(`Invalid loopback client ID: ${t.message}`)}function Gs(e){if(!e.startsWith(`http://localhost`))return{success:!1,message:`Value must start with "${Bs}"`};if(e.includes(`#`,16))return{success:!1,message:`Value must not contain a hash component`};let t=e.length>16&&e.charCodeAt(16)===47?17:16;return e.length!==t&&e.charCodeAt(t)!==63?{success:!1,message:`Value must not contain a path component`}:Ks(e.slice(t+1))}function Ks(e){let t={},n=typeof e==`string`?new URLSearchParams(e):e;for(let[e,r]of n)if(e===`scope`){if(`scope`in t)return{success:!1,message:`Duplicate "scope" query parameter`};let e=js.safeParse(r);if(!e.success)return{success:!1,message:`Invalid "scope" query parameter: ${e.error.issues.map(e=>e.message).join(`, `)||`Validation failed`}`};t.scope=e.data}else if(e===`redirect_uri`){let e=Rs.safeParse(r);if(!e.success)return{success:!1,message:`Invalid "redirect_uri" query parameter: ${e.error.issues.map(e=>e.message).join(`, `)||`Validation failed`}`};t.redirect_uris==null?t.redirect_uris=[e.data]:t.redirect_uris.push(e.data)}else return{success:!1,message:`Unexpected query parameter "${e}"`};return{success:!0,value:t}}function qs(e){let{scope:t=Fs,redirect_uris:n}=Ws(e);if(!Ns(t))throw TypeError(`ATProto Loopback ClientID must include "atproto" scope`);return{scope:t,redirect_uris:n??[...Os]}}function Js(e){return Ys(e,qs(e))}function Ys(e,t){return{client_id:e,scope:t.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}}var Xs=I(L({type:N(),locations:I(ws).optional(),actions:I(N()).optional(),datatypes:I(N()).optional(),identifier:N().optional(),privileges:I(N()).optional()})),Zs=R([N().regex(/^DPoP$/i).transform(()=>`DPoP`),N().regex(/^Bearer$/i).transform(()=>`Bearer`)]),Qs=L({access_token:N(),token_type:Zs,scope:N().optional(),refresh_token:N().optional(),expires_in:P().optional(),id_token:nr.optional(),authorization_details:Xs.optional()}).passthrough().extend({token_type:z(`DPoP`),sub:Ea,scope:Ps,id_token:tn().optional()}),$s=N().min(1),ec=L({grant_type:z(`authorization_code`),code:N().min(1),redirect_uri:zs,code_verifier:N().min(43).max(128).regex(/^[a-zA-Z0-9-._~]+$/).optional()}),tc=L({request:R([nr,rr])}),nc=B([`S256`,`plain`]),rc=B([`none`,`login`,`consent`,`select_account`,`create`]),ic=B([`query`,`fragment`,`form_post`]),ac=B([`code`,`token`,`none`,`code id_token token`,`code id_token`,`code token`,`id_token token`,`id_token`]),oc=B([`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`]),sc=R([N(),P(),F()]),cc=L({essential:F().optional(),value:sc.optional(),values:I(sc).optional()}),lc=B([`userinfo`,`id_token`]),uc=L({client_id:Is,state:N().optional(),redirect_uri:zs.optional(),scope:js.optional(),response_type:ac,code_challenge:N().optional(),code_challenge_method:nc.optional(),dpop_jkt:N().optional(),response_mode:ic.optional(),nonce:N().optional(),max_age:on(Ss,P().int().min(0)).optional(),claims:on(xs,an(lc,an(oc,R([z(null),cc])))).optional(),login_hint:N().min(1).optional(),ui_locales:N().regex(/^[a-z]{2,3}(-[A-Z]{2})?( [a-z]{2,3}(-[A-Z]{2})?)*$/).optional(),id_token_hint:nr.optional(),display:B([`page`,`popup`,`touch`,`wap`]).optional(),prompt:rc.optional(),authorization_details:on(xs,Xs).optional()});R([uc,tc]);var dc=L({request_uri:N().min(1)});rn(L({client_id:Is}),R([uc,tc,dc])),B([`invalid_request`,`unauthorized_client`,`access_denied`,`unsupported_response_type`,`invalid_scope`,`server_error`,`temporarily_unavailable`]);var fc=X.superRefine((e,t)=>{if(e.endsWith(`/`))return t.addIssue({code:b.custom,message:`Issuer URL must not end with a slash`}),!1;let n=new URL(e);return n.username||n.password?(t.addIssue({code:b.custom,message:`Issuer URL must not contain a username or password`}),!1):n.hash||n.search?(t.addIssue({code:b.custom,message:`Issuer URL must not contain a query or fragment`}),!1):e===(n.pathname===`/`?n.origin:n.href)||(t.addIssue({code:b.custom,message:`Issuer URL must be in the canonical form`}),!1)}),pc=L({issuer:fc,claims_supported:I(N()).optional(),claims_locales_supported:I(N()).optional(),claims_parameter_supported:F().optional(),request_parameter_supported:F().optional(),request_uri_parameter_supported:F().optional(),require_request_uri_registration:F().optional(),scopes_supported:I(N()).optional(),subject_types_supported:I(N()).optional(),response_types_supported:I(N()).optional(),response_modes_supported:I(N()).optional(),grant_types_supported:I(N()).optional(),code_challenge_methods_supported:I(nc).min(1).optional(),ui_locales_supported:I(N()).optional(),id_token_signing_alg_values_supported:I(N()).optional(),display_values_supported:I(N()).optional(),request_object_signing_alg_values_supported:I(N()).optional(),authorization_response_iss_parameter_supported:F().optional(),authorization_details_types_supported:I(N()).optional(),request_object_encryption_alg_values_supported:I(N()).optional(),request_object_encryption_enc_values_supported:I(N()).optional(),jwks_uri:X.optional(),authorization_endpoint:X,token_endpoint:X,token_endpoint_auth_methods_supported:I(N()).default([`client_secret_basic`]),token_endpoint_auth_signing_alg_values_supported:I(N()).optional(),revocation_endpoint:X.optional(),introspection_endpoint:X.optional(),pushed_authorization_request_endpoint:X.optional(),require_pushed_authorization_requests:F().optional(),userinfo_endpoint:X.optional(),end_session_endpoint:X.optional(),registration_endpoint:X.optional(),dpop_signing_alg_values_supported:I(N()).optional(),protected_resources:I(X).optional(),client_id_metadata_document_supported:F().optional(),prompt_values_supported:I(rc).optional()}).superRefine((e,t)=>{e.require_pushed_authorization_requests&&!e.pushed_authorization_request_endpoint&&t.addIssue({code:b.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:b.custom,message:`Response type "code" is required`}))}).superRefine((e,t)=>{e.token_endpoint_auth_signing_alg_values_supported?.includes(`none`)&&t.addIssue({code:b.custom,message:`Client authentication method "none" is not allowed`})}),mc=L({grant_type:z(`client_credentials`)});R([L({client_id:Is,client_assertion_type:z(hs),client_assertion:nr}),L({client_id:Is,client_secret:N()}),L({client_id:Is})]);var hc=rn(Is,Es).superRefine((e,t)=>{let n=new URL(e);return n.username||n.password?(t.addIssue({code:b.custom,message:`ClientID must not contain credentials`}),!1):n.hash?(t.addIssue({code:b.custom,message:`ClientID must not contain a fragment`}),!1):n.pathname===`/`?(t.addIssue({code:b.custom,message:`ClientID must contain a path component (e.g. "/client-metadata.json")`}),!1):n.pathname.endsWith(`/`)?(t.addIssue({code:b.custom,message:`ClientID path must not end with a trailing slash`}),!1):_s(n.hostname)?(t.addIssue({code:b.custom,message:`ClientID hostname must not be an IP address`}),!1):bs(e)===n.pathname||(t.addIssue({code:b.custom,message:`ClientID must be in canonical form ("${n.href}", got "${e}")`}),!1)});hc.superRefine((e,t)=>{let n=new URL(e);return n.port?(t.addIssue({code:b.custom,message:`ClientID must not contain a port`}),!1):n.search?(t.addIssue({code:b.custom,message:`ClientID must not contain a query string`}),!1):n.pathname===`/oauth-client-metadata.json`||(t.addIssue({code:b.custom,message:`ClientID must be "/oauth-client-metadata.json"`}),!1)});function gc(e){hc.parse(e)}var _c=B([`client_secret_basic`,`client_secret_jwt`,`client_secret_post`,`none`,`private_key_jwt`,`self_signed_tls_client_auth`,`tls_client_auth`]),vc=B([`authorization_code`,`implicit`,`refresh_token`,`password`,`client_credentials`,`urn:ietf:params:oauth:grant-type:jwt-bearer`,`urn:ietf:params:oauth:grant-type:saml2-bearer`]),yc=L({redirect_uris:I(zs).nonempty(),response_types:I(ac).nonempty().default([`code`]),grant_types:I(vc).nonempty().default([`authorization_code`]),scope:js.optional(),token_endpoint_auth_method:_c.default(`client_secret_basic`),token_endpoint_auth_signing_alg:N().optional(),userinfo_signed_response_alg:N().optional(),userinfo_encrypted_response_alg:N().optional(),jwks_uri:X.optional(),jwks:tr.optional(),application_type:B([`web`,`native`]).default(`web`),subject_type:B([`public`,`pairwise`]).default(`public`),request_object_signing_alg:N().optional(),id_token_signed_response_alg:N().optional(),authorization_signed_response_alg:N().default(`RS256`),authorization_encrypted_response_enc:B([`A128CBC-HS256`]).optional(),authorization_encrypted_response_alg:N().optional(),client_id:Is.optional(),client_name:N().optional(),client_uri:X.optional(),policy_uri:X.optional(),tos_uri:X.optional(),logo_uri:X.optional(),default_max_age:P().optional(),require_auth_time:F().optional(),contacts:I(N().email()).optional(),tls_client_certificate_bound_access_tokens:F().optional(),dpop_bound_access_tokens:F().optional(),authorization_details_types:I(N()).optional()}),bc=L({request_uri:N(),expires_in:P().int().positive()}),xc=L({grant_type:z(`password`),username:N(),password:N()}),Sc=L({resource:X.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:I(fc).optional(),jwks_uri:X.optional(),scopes_supported:I(N()).optional(),bearer_methods_supported:I(B([`header`,`body`,`query`])).optional(),resource_signing_alg_values_supported:I(N()).optional(),resource_documentation:X.optional(),resource_policy_uri:X.optional(),resource_tos_uri:X.optional()}),Cc=N().min(1),wc=L({grant_type:z(`refresh_token`),refresh_token:Cc});L({token:R([$s,Cc]),token_type_hint:B([`access_token`,`refresh_token`]).optional()}),nn(`grant_type`,[ec,wc,xc,mc]),B([`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`]),L({sub:N(),iss:N().url().optional(),aud:R([N(),I(N()).min(1)]).optional(),email:N().email().optional(),email_verified:F().optional(),name:N().optional(),preferred_username:N().optional(),picture:N().url().optional()});function Tc(e){return e.get(`content-type`)?.split(`;`)[0].trim()}var Ec=class extends Ka{constructor(e,t,n){super(async(e,t)=>this.fetchMetadata(e,t),Ja(e,n?.onCacheError)),this.fetch=Go(t),this.allowHttpIssuer=n?.allowHttpIssuer===!0}async get(e,t){let n=fc.parse(String(e));if(!this.allowHttpIssuer&&n.startsWith(`http:`))throw TypeError(`Unsecure issuer URL protocol only allowed in development and test environments`);return super.get(n,t)}async fetchMetadata(e,t){let n=new URL(`/.well-known/oauth-authorization-server`,e),r=new Request(n,{headers:{accept:`application/json`},cache:t?.noCache?`no-cache`:void 0,signal:t?.signal,redirect:`manual`}),i=await this.fetch(r);if(i.status!==200)throw await So(i,`log`),await Y.from(i,`Unexpected status code ${i.status} for "${n}"`,void 0,{cause:r});if(Tc(i.headers)!==`application/json`)throw await So(i,`log`),await Y.from(i,`Unexpected content type for "${n}"`,void 0,{cause:r});let a=pc.parse(await i.json());if(a.issuer!==e)throw TypeError(`Invalid issuer ${a.issuer}`);if(a.client_id_metadata_document_supported!==!0)throw TypeError(`Authorization server "${e}" does not support client_id_metadata_document`);return a}},Dc=class extends Ka{constructor(e,t=globalThis.fetch,n){super(async(e,t)=>this.fetchMetadata(e,t),Ja(e,n?.onCacheError)),this.fetch=Go(t),this.allowHttpResource=n?.allowHttpResource===!0}async get(e,t){let{protocol:n,origin:r}=new URL(e);if(n!==`https:`&&n!==`http:`)throw TypeError(`Invalid protected resource metadata URL protocol: ${n}`);if(n===`http:`&&!this.allowHttpResource)throw TypeError(`Unsecure resource metadata URL (${n}) only allowed in development and test environments`);return super.get(r,t)}async fetchMetadata(e,t){let n=new URL(`/.well-known/oauth-protected-resource`,e),r=new Request(n,{signal:t?.signal,headers:{accept:`application/json`},cache:t?.noCache?`no-cache`:void 0,redirect:`manual`}),i=await this.fetch(r);if(i.status===404)return await So(i,`log`),null;if(i.status!==200)throw await So(i,`log`),await Y.from(i,`Unexpected status code ${i.status} for "${n}"`,void 0,{cause:r});if(Tc(i.headers)!==`application/json`)throw await So(i,`log`),await Y.from(i,`Unexpected content type for "${n}"`,void 0,{cause:r});let a=Sc.parse(await i.json());if(a.resource!==e)throw TypeError(`Invalid issuer ${a.resource}`);return a}},Oc=class e extends Error{constructor(e,t){super(e,t)}static from(t,n){if(t instanceof e)return t;let r=t instanceof x?`${t.errors[0].path} ${t.errors[0].message}`:null,i=(n??`Unable to resolve identity`)+(r?` (${r})`:``);return new e(i,{cause:t})}},kc=class{constructor(e,t,n){this.identityResolver=e,this.protectedResourceMetadataResolver=t,this.authorizationServerMetadataResolver=n}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(n){if(!t?.signal?.aborted&&n instanceof Oc)try{let n=fc.safeParse(e);if(n.success)return{metadata:await this.getAuthorizationServerMetadata(n.data,t)}}catch{}throw n}}async resolveFromIdentity(e,t){let n=await this.resolveIdentity(e,t);t?.signal?.throwIfAborted();let r=Pa(n.didDoc);return{identityInfo:n,metadata:await this.getResourceServerMetadata(r,t),pds:r}}async resolveIdentity(e,t){try{return await this.identityResolver.resolve(e,t)}catch(t){throw Oc.from(t,`Failed to resolve identity: ${e}`)}}async getAuthorizationServerMetadata(e,t){try{return await this.authorizationServerMetadataResolver.get(e,t)}catch(t){throw Oc.from(t,`Failed to resolve OAuth server metadata for issuer: ${e}`)}}async getResourceServerMetadata(e,t){try{let n=await this.protectedResourceMetadataResolver.get(e,t);if(!n)return this.getAuthorizationServerMetadata(e,t);if(n.authorization_servers?.length!==1)throw new Oc(n.authorization_servers?.length?`Unable to determine authorization server for PDS: ${e}`:`No authorization servers found for PDS: ${e}`);let r=n.authorization_servers[0];t?.signal?.throwIfAborted();let i=await this.getAuthorizationServerMetadata(r,t);if(i.protected_resources&&!i.protected_resources.includes(n.resource))throw new Oc(`PDS "${e}" not protected by issuer "${r}"`);return i}catch(t){throw Oc.from(t,`Failed to resolve OAuth server metadata for resource: ${e}`)}}};function Ac({fetch:e=globalThis.fetch,allowHttp:t=!1,protectedResourceMetadataCache:n=new po({ttl:6e4,max:100}),authorizationServerMetadataCache:r=new po({ttl:6e4,max:100}),onCacheError:i,...a}){return new kc(ms({...a,allowHttp:t,fetch:e}),new Dc(n,e,{allowHttpResource:t,onCacheError:i}),new Ec(r,e,{allowHttpIssuer:t,onCacheError:i}))}var jc=new Map;function Mc(e){return new Promise(t=>{let n=(jc.get(e)??Promise.resolve()).then(()=>new Promise(r=>{t(()=>{jc.get(e)===n&&jc.delete(e),r()})}));jc.set(e,n)})}var Nc=(e,t)=>Mc(e).then(async e=>{try{return await t()}finally{e()}}),Z=class e extends Error{static from(t,n,r){if(t instanceof e)return t;let i=t instanceof Error?t.message:void 0;return new e(n,i,r,t)}constructor(e,t=e.get(`error_description`)||`OAuth callback error`,n,r){super(t,{cause:r}),this.params=e,this.state=n}},Pc=`ES256`,Fc=class extends Error{},Ic=class extends Error{constructor(e,t=`The session for "${e}" was successfully revoked`,n){super(t,n),this.sub=e}};function Lc(e,t,n){let r=t.token_endpoint_auth_method,i=zc(e);if(!i.includes(r))throw Error(`The server does not support "${r}" authentication. Supported methods are: ${i.join(`, `)}.`);if(r===`private_key_jwt`){if(!n)throw Error(`A keyset is required for private_key_jwt`);let t=Bc(e);for(let e of n.list({alg:t,usage:`sign`}))if(e.kid)return{method:`private_key_jwt`,kid:e.kid};throw Error(t.includes(`ES256`)?`Client authentication method "${r}" requires at least one "${Pc}" signing key with a "kid" property`:`Authorization server requires "${r}" authentication method, but does not support "${Pc}" algorithm.`)}if(r===`none`)return{method:`none`};throw Error(`The ATProto OAuth spec requires that client use either "none" or "private_key_jwt" authentication method.`+(r===`client_secret_basic`?` You might want to explicitly set "token_endpoint_auth_method" to one of those values in the client metadata document.`:` You set "${r}" which is not allowed.`))}function Rc(e,t,n,r,i){if(!zc(t).includes(e.method))throw new Fc(`Client authentication method "${e.method}" no longer supported`);if(e.method===`none`)return()=>({payload:{client_id:n.client_id}});if(e.method===`private_key_jwt`)try{if(!i)throw Error(`A keyset is required for private_key_jwt`);let{key:a,alg:o}=i.findPrivateKey({usage:`sign`,kid:e.kid,alg:Bc(t)});return async()=>({payload:{client_id:n.client_id,client_assertion_type:hs,client_assertion:await a.createJwt({alg:o},{iss:n.client_id,sub:n.client_id,aud:t.issuer,jti:await r.generateNonce(),iat:Math.floor(Date.now()/1e3),exp:Math.floor(Date.now()/1e3)+60})}})}catch(e){throw new Fc(`Failed to load private key`,{cause:e})}throw new Fc(`Unsupported auth method ${e.method}`)}function zc(e){return e.token_endpoint_auth_methods_supported}function Bc(e){return e.token_endpoint_auth_signing_alg_values_supported??[`ES256`]}var Vc=class extends Error{constructor(e,t,n){super(t,n),this.sub=e}},Hc=globalThis.crypto?.subtle,Uc=globalThis.ReadableStream;function Wc({key:e,supportedAlgs:t,nonces:n,sha256:r=Hc===void 0?void 0:Yc,isAuthServer:i,fetch:a=globalThis.fetch}){if(!r)throw TypeError(`crypto.subtle is not available in this environment. Please provide a sha256 function.`);let o=Jc(e,t);return async function(t,s){let c=s==null&&t instanceof Request?t:new Request(t,s),l=c.headers.get(`Authorization`),u=l?.startsWith(`DPoP `)?await r(l.slice(5)):void 0,{origin:d}=new URL(c.url),f=c.method,p=Gc(c.url),m;try{m=await n.get(d)}catch{}let h=await Kc(e,o,f,p,m,u);c.headers.set(`DPoP`,h);let g=await a.call(this,c),ee=g.headers.get(`DPoP-Nonce`);if(!ee||ee===m)return g;try{await n.set(d,ee)}catch{}let te;try{te=await qc(g,i)}catch(e){throw await So(g,`log`),e}if(!te||t===c||Uc&&s?.body instanceof Uc)return g;await So(g,`log`);let _=await Kc(e,o,f,p,ee,u),ne=new Request(t,s);ne.headers.set(`DPoP`,_);let re=await a.call(this,ne),ie=re.headers.get(`DPoP-Nonce`);if(!ie||ie===m)return re;try{await n.set(d,ie)}catch{}return re}}function Gc(e){let t=e.indexOf(`#`),n=e.indexOf(`?`),r=t===-1?n:n===-1?t:Math.min(t,n);return r===-1?e:e.slice(0,r)}async function Kc(e,t,n,r,i,a){let o=e.bareJwk;if(!o)throw Error(`Only asymmetric keys can be used as DPoP proofs`);let s=Math.floor(Date.now()/1e3);return e.createJwt({alg:t,typ:`dpop+jwt`,jwk:o},{iat:s,jti:Math.random().toString(36).slice(2),htm:n,htu:r,nonce:i,ath:a})}async function qc(e,t){if((t===void 0||t===!1)&&e.status===401){let t=e.headers.get(`WWW-Authenticate`);if(t?.startsWith(`DPoP`))return t.includes(`error="use_dpop_nonce"`)}if((t===void 0||t===!0)&&e.status===400)try{return(await jo(e,10240))?.error===`use_dpop_nonce`}catch(e){if(e instanceof Y||e instanceof SyntaxError)return!1;throw e}return!1}function Jc(e,t){if(t){let n=t.find(t=>e.algorithms.includes(t));if(n)return n}else{let[t]=e.algorithms;if(t)return t}throw Error(`Key does not match any alg supported by the server`)}async function Yc(e){if(Hc==null)throw Error(`crypto.subtle is not available in this environment. Please provide a sha256 function.`);let t=new TextEncoder().encode(e),n=await Hc.digest(`SHA-256`,t),r=new Uint8Array(n);return Tn.baseEncode(r)}var Xc=e=>typeof e==`string`?e:void 0;function Zc(e){if(typeof AbortSignal.timeout==`function`)return AbortSignal.timeout(e);let t=new AbortController;return setTimeout(()=>t.abort(Qc(e)),e),t.signal}function Qc(e){let t=`The operation timed out after ${e} ms`;return typeof DOMException==`function`?new DOMException(t,`TimeoutError`):Error(t)}function $c(e){let t=new el,n=function(e){let n=Error(`This operation was aborted`,{cause:this.reason});t.abort(n)};try{for(let r of e)r&&(r.throwIfAborted(),r.addEventListener(`abort`,n,{signal:t.signal}));return t}catch(e){throw t.abort(e),e}}var el=class extends AbortController{[Symbol.dispose](){this.abort(Error(`AbortController was disposed`))}},tl=class extends Error{constructor(e,t){let n=Xc(t?.error),r=Xc(t?.error_description),i=`OAuth ${n?`"${n}"`:`unknown`} error${r?`: ${r}`:``}`;super(i),this.response=e,this.payload=t,this.error=n,this.errorDescription=r}get status(){return this.response.status}get headers(){return this.response.headers}},nl=class{constructor(e,t,n,r,i,a,o,s,c){this.authMethod=e,this.dpopKey=t,this.serverMetadata=n,this.clientMetadata=r,this.dpopNonces=i,this.oauthResolver=a,this.runtime=o,this.keyset=s,this.clientCredentialsFactory=Rc(e,n,r,o,s),this.dpopFetch=Wc({fetch:Go(c),key:t,supportedAlgs:n.dpop_signing_alg_values_supported,sha256:async e=>o.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,n){let r=Date.now(),i=await this.request(`token`,{grant_type:`authorization_code`,redirect_uri:n??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:typeof i.expires_in==`number`?new Date(r+i.expires_in*1e3).toISOString():void 0}}catch(e){throw await this.revoke(i.access_token),e}}async refresh(e){if(!e.refresh_token)throw new Vc(e.sub,`No refresh token available`);let t=await this.verifyIssuer(e.sub),n=Date.now(),r=await this.request(`token`,{grant_type:`refresh_token`,refresh_token:e.refresh_token});return{aud:t,sub:e.sub,iss:this.issuer,scope:r.scope,refresh_token:r.refresh_token,access_token:r.access_token,token_type:r.token_type,expires_at:typeof r.expires_in==`number`?new Date(n+r.expires_in*1e3).toISOString():void 0}}async verifyIssuer(e){let t=await this.oauthResolver.resolveFromIdentity(e,{noCache:!0,allowStale:!1,signal:Zc(1e4)});if(this.issuer!==t.metadata.issuer)throw TypeError(`Issuer mismatch`);return t.pds.href}async request(e,t){let n=this.serverMetadata[`${e}_endpoint`];if(!n)throw Error(`No ${e} endpoint available`);let r=await this.clientCredentialsFactory(),{response:i,json:a}=await this.dpopFetch(n,{method:`POST`,headers:{...r.headers,"Content-Type":`application/x-www-form-urlencoded`},body:rl({...t,...r.payload})}).then(Ho());if(i.ok)switch(e){case`token`:return Qs.parse(a);case`pushed_authorization_request`:return bc.parse(a);default:return a}else throw new tl(i,a)}};function rl(e){return new URLSearchParams(Object.entries(e).filter(il).map(al)).toString()}function il(e){return e[1]!==void 0}function al(e){let t=e[0],n=e[1];switch(typeof n){case`string`:return[t,n];case`number`:case`boolean`:return[t,String(n)];default:{let e=JSON.stringify(n);if(e===void 0)throw Error(`Unsupported value type for ${t}: ${String(n)}`);return[t,e]}}}var ol=class{constructor(e,t,n,r,i,a){this.clientMetadata=e,this.runtime=t,this.resolver=n,this.fetch=r,this.keyset=i,this.dpopNonceCache=a}async fromIssuer(e,t,n,r){let i=await this.resolver.getAuthorizationServerMetadata(e,r);return this.fromMetadata(i,t,n)}async fromMetadata(e,t,n){return new nl(t,n,e,this.clientMetadata,this.dpopNonceCache,this.resolver,this.runtime,this.keyset,this.fetch)}},sl=class extends Error{constructor(e,t=`The session for "${e}" is invalid`,n){super(t,n),this.sub=e}},cl=globalThis.ReadableStream,ll=class{constructor(e,t,n,r=globalThis.fetch){this.server=e,this.sub=t,this.sessionGetter=n,this.dpopFetch=Wc({fetch:Go(r),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),n=t.expires_at==null?void 0:new Date(t.expires_at);return{expiresAt:n,get expired(){return n==null?void 0:n.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 Ic(this.sub))}}async fetchHandler(e,t){let n=await this.getTokenSet(`auto`),r=new URL(e,n.aud),i=`${n.token_type} ${n.access_token}`,a=new Headers(t?.headers);a.set(`Authorization`,i);let o=await this.dpopFetch(r,{...t,headers:a});if(!ul(o))return o;let s;try{s=await this.getTokenSet(!0)}catch{return o}if(cl&&t?.body instanceof cl)return o;let c=`${s.token_type} ${s.access_token}`,l=new URL(e,s.aud);a.set(`Authorization`,c);let u=await this.dpopFetch(l,{...t,headers:a});return ul(u)&&await this.sessionGetter.delStored(this.sub,new sl(this.sub)),u}};function ul(e){if(e.status!==401)return!1;let t=e.headers.get(`WWW-Authenticate`);return t!=null&&(t.startsWith(`Bearer `)||t.startsWith(`DPoP `))&&t.includes(`error="invalid_token"`)}var dl=class{constructor(e){this.implementation=e;let{requestLock:t}=e;this.hasImplementationLock=t!=null,this.usingLock=t?.bind(e)||Nc}async generateKey(e){let t=Array.from(e).sort(pl);return this.implementation.createKey(t)}async sha256(e){let t=new TextEncoder().encode(e),n=await this.implementation.digest(t,{name:`sha256`});return Tn.baseEncode(n)}async generateNonce(e=16){let t=await this.implementation.getRandomValues(e);return Tn.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=fl(e),n=JSON.stringify(t);return this.sha256(n)}async generateVerifier(e=32){if(e<32||e>96)throw TypeError(`Invalid code_verifier length`);let t=await this.implementation.getRandomValues(e);return Tn.baseEncode(t)}};function fl(e){let t=t=>{let n=e[t];if(typeof n!=`string`||!n)throw TypeError(`"${t}" Parameter missing or invalid`);return n};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`)}}function pl(e,t){if(e===`ES256K`)return-1;if(t===`ES256K`)return 1;for(let n of[`ES`,`PS`,`RS`])if(e.startsWith(n))return t.startsWith(n)?parseInt(e.slice(2,5))-parseInt(t.slice(2,5)):-1;else if(t.startsWith(n))return 1;return 0}var ml=function(e,t,n){if(t!=null){if(typeof t!=`object`&&typeof t!=`function`)throw TypeError(`Object expected.`);var r,i;if(n){if(!Symbol.asyncDispose)throw TypeError(`Symbol.asyncDispose is not defined.`);r=t[Symbol.asyncDispose]}if(r===void 0){if(!Symbol.dispose)throw TypeError(`Symbol.dispose is not defined.`);r=t[Symbol.dispose],n&&(i=r)}if(typeof r!=`function`)throw TypeError(`Object not disposable.`);i&&(r=function(){try{i.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:r,async:n})}else n&&e.stack.push({async:!0});return t},hl=(function(e){return function(t){function n(n){t.error=t.hasError?new e(n,t.error,`An error was suppressed during disposal.`):n,t.hasError=!0}var r,i=0;function a(){for(;r=t.stack.pop();)try{if(!r.async&&i===1)return i=0,t.stack.push(r),Promise.resolve().then(a);if(r.dispose){var e=r.dispose.call(r.value);if(r.async)return i|=2,Promise.resolve(e).then(a,function(e){return n(e),a()})}else i|=1}catch(e){n(e)}if(i===1)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}return a()}})(typeof SuppressedError==`function`?SuppressedError:function(e,t,n){var r=Error(n);return r.name=`SuppressedError`,r.error=e,r.suppressed=t,r});function gl(e){return e instanceof Vc||e instanceof Ic||e instanceof sl||e instanceof Fc||e instanceof TypeError}var _l=class extends Ka{#e;#t;#n;constructor(e,t,n,r={}){super(async(e,{signal:i},a)=>{if(a===void 0){let t=new Vc(e,`The session was deleted by another process`);throw await r.onSessionDeleted?.call(null,e,t),t}let{dpopKey:o,authMethod:s,tokenSet:c}=a;if(e!==c.sub)throw new Vc(e,`Stored session sub mismatch`);if(!c.refresh_token)throw new Vc(e,`No refresh token available`);let l=await t.fromIssuer(c.iss,s,o,{signal:i});i?.throwIfAborted();try{let t=await l.refresh(c);if(e!==t.sub)throw new Vc(e,`Token set sub mismatch`);return{dpopKey:o,tokenSet:t,authMethod:l.authMethod}}catch(t){if(t instanceof tl&&t.status===400&&t.error===`invalid_grant`){if(!n.hasImplementationLock){await new Promise(e=>setTimeout(e,1e3));let n=await this.getStored(e);if(n===void 0)throw new Vc(e,`The session was deleted by another process`,{cause:t});if(n.tokenSet.access_token!==c.access_token||n.tokenSet.refresh_token!==c.refresh_token)return n}throw new Vc(e,t.errorDescription??`The session was revoked`,{cause:t})}throw t}},e,{isStale:(e,{tokenSet:t})=>t.expires_at!=null&&new Date(t.expires_at).getTime()<Date.now()+1e4+3e4*Math.random(),deleteOnError:gl}),this.#e=t,this.#t=n,this.#n=r}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(n){let r=[n];try{let{tokenSet:e,dpopKey:n,authMethod:r}=t;await(await this.#e.fromIssuer(e.iss,r,n)).revoke(e.refresh_token??e.access_token)}catch(e){r.push(e)}try{await this.delStored(e,n)}catch(e){r.push(e)}throw AggregateError(r,`Failed to store session for ${e}`)}await this.#n.onSessionUpdated?.call(null,e,t)}async delStored(e,t){await super.delStored(e,t),await this.#n.onSessionDeleted?.call(null,e,t)}async get(e,t){let n=await this.#t.usingLock(`@atproto-oauth-client-${e}`,async()=>{let n={stack:[],error:void 0,hasError:!1};try{let r=Zc(3e4),i=ml(n,$c([t?.signal,r]),!1);return await super.get(e,{...t,signal:i.signal})}catch(e){n.error=e,n.hasError=!0}finally{hl(n)}});if(e!==n.tokenSet.sub)throw Error(`Token set does not match the expected sub`);return n}async getSession(e,t=`auto`){return this.get(e,{noCache:t===!0,allowStale:t===!1})}},vl=yc.extend({client_id:R([hc,Vs])});function yl(e,t){!e.jwks&&!e.jwks_uri&&t?.size&&(e={...e,jwks:t.toJSON()});let n=vl.parse(e);if(n.client_id.startsWith(`http:`)?Hs(n.client_id):gc(n.client_id),!(n.scope?.split(` `))?.includes(`atproto`))throw TypeError(`Client metadata must include the "atproto" scope`);if(!n.response_types.includes(`code`))throw TypeError(`"response_types" must include "code"`);if(!n.grant_types.includes(`authorization_code`))throw TypeError(`"grant_types" must include "authorization_code"`);let r=n.token_endpoint_auth_method,i=n.token_endpoint_auth_signing_alg;switch(r){case`none`:if(i)throw TypeError(`"token_endpoint_auth_signing_alg" must not be provided when "token_endpoint_auth_method" is "${r}"`);break;case`private_key_jwt`:{if(!i)throw TypeError(`"token_endpoint_auth_signing_alg" must be provided when "token_endpoint_auth_method" is "${r}"`);if(!t)throw TypeError(`Client authentication method "${r}" requires a keyset`);let e=Array.from(t.list({usage:`sign`})).filter(e=>e.kid);if(!e.length)throw TypeError(`Client authentication method "${r}" requires at least one active signing key with a "kid" property`);if(!e.some(e=>e.algorithms.includes(`ES256`)))throw TypeError(`Client authentication method "${r}" requires at least one active "${Pc}" signing key`);if(n.jwks){for(let t of e)if(!n.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(!n.jwks_uri)throw TypeError(`Client authentication method "${r}" requires a JWKS`);break}default:throw TypeError(`Unsupported "token_endpoint_auth_method" value: ${r}`)}return n}var bl=class{static async fetchMetadata({clientId:e,fetch:t=globalThis.fetch,signal:n}){n?.throwIfAborted();let r=await t(new Request(e,{redirect:`error`,signal:n}));if(r.status!==200)throw await r.body?.cancel?.(),TypeError(`Failed to fetch client metadata: ${r.status}`);let i=r.headers.get(`content-type`)?.split(`;`)[0].trim();if(i!==`application/json`)throw await r.body?.cancel?.(),TypeError(`Invalid client metadata content type: ${i}`);let a=await r.json();return n?.throwIfAborted(),yc.parse(a)}constructor(e){let{stateStore:t,sessionStore:n,dpopNonceCache:r=new po({ttl:6e4,max:100}),responseMode:i,clientMetadata:a,runtimeImplementation:o,keyset:s}=e;this.keyset=s?s instanceof gr?s:new gr(s):void 0,this.clientMetadata=yl(a,this.keyset),this.responseMode=i,this.runtime=new dl(o),this.fetch=e.fetch??globalThis.fetch,this.oauthResolver=Ac(e),this.serverFactory=new ol(this.clientMetadata,this.runtime,this.oauthResolver,this.fetch,this.keyset,r),this.stateStore=t,this.sessionGetter=new _l(n,this.serverFactory,this.runtime,e)}get identityResolver(){return this.oauthResolver.identityResolver}get jwks(){return this.keyset?.publicJwks??{keys:[]}}async authorize(e,{signal:t,...n}={}){let r=n?.redirect_uri??this.clientMetadata.redirect_uris[0];if(!this.clientMetadata.redirect_uris.includes(r))throw TypeError(`Invalid redirect_uri`);let{identityInfo:i,metadata:a}=await this.oauthResolver.resolve(e,{signal:t}),o=await this.runtime.generatePKCE(),s=await this.runtime.generateKey(a.dpop_signing_alg_values_supported||[`ES256`]),c=Lc(a,this.clientMetadata,this.keyset),l=await this.runtime.generateNonce();await this.stateStore.set(l,{iss:a.issuer,dpopKey:s,authMethod:c,verifier:o.verifier,appState:n?.state});let u={...n,client_id:this.clientMetadata.client_id,redirect_uri:r,code_challenge:o.challenge,code_challenge_method:o.method,state:l,login_hint:i?i.handle===`handle.invalid`?i.did:i.handle:void 0,response_mode:this.responseMode,response_type:`code`,scope:n?.scope??this.clientMetadata.scope},d=new URL(a.authorization_endpoint);if(d.protocol!==`https:`&&d.protocol!==`http:`)throw TypeError(`Invalid authorization endpoint protocol: ${d.protocol}`);if(a.pushed_authorization_request_endpoint){let e=await(await this.serverFactory.fromMetadata(a,c,s)).request(`pushed_authorization_request`,u);return d.searchParams.set(`client_id`,this.clientMetadata.client_id),d.searchParams.set(`request_uri`,e.request_uri),d}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(u))t&&d.searchParams.set(e,String(t));if(d.pathname.length+d.search.length<2048)return d;throw a.pushed_authorization_request_endpoint?Error(`Server does not support pushed authorization requests (PAR)`):Error(`Login URL too long`)}async abortRequest(e){e.searchParams.get(`request_uri`)}async callback(e,t={}){if(e.get(`response`)!=null)throw new Z(e,`JARM not supported`);let n=e.get(`iss`),r=e.get(`state`),i=e.get(`error`),a=e.get(`code`);if(!r)throw new Z(e,`Missing "state" parameter`);let o=await this.stateStore.get(r);if(o)await this.stateStore.del(r);else throw new Z(e,`Unknown authorization session "${r}"`);try{if(i!=null)throw new Z(e,void 0,o.appState);if(!a)throw new Z(e,`Missing "code" query param`,o.appState);let r=await this.serverFactory.fromIssuer(o.iss,o.authMethod,o.dpopKey);if(n!=null){if(!r.issuer)throw new Z(e,`Issuer not found in metadata`,o.appState);if(r.issuer!==n)throw new Z(e,`Issuer mismatch`,o.appState)}else if(r.serverMetadata.authorization_response_iss_parameter_supported)throw new Z(e,`iss missing from the response`,o.appState);let s=await r.exchangeCode(a,o.verifier,t?.redirect_uri??r.clientMetadata.redirect_uris[0]);try{await this.revoke(s.sub)}catch{}try{return await this.sessionGetter.setStored(s.sub,{dpopKey:o.dpopKey,authMethod:r.authMethod,tokenSet:s}),{session:this.createSession(r,s.sub),state:o.appState??null}}catch(e){throw await r.revoke(s.refresh_token||s.access_token),e}}catch(t){throw Z.from(t,e,o.appState)}}async restore(e,t=`auto`){Oa(e);let{dpopKey:n,authMethod:r,tokenSet:i}=await this.sessionGetter.getSession(e,t);try{let a=await this.serverFactory.fromIssuer(i.iss,r,n,{noCache:t===!0,allowStale:t===!1});return this.createSession(a,e)}catch(t){throw t instanceof Fc&&await this.sessionGetter.delStored(e,t),t}}async revoke(e){Oa(e);let t=await this.sessionGetter.getSession(e,!1).catch(e=>{if(gl(e))return null;throw e});if(!t)return;let{dpopKey:n,authMethod:r,tokenSet:i}=t;try{await(await this.serverFactory.fromIssuer(i.iss,r,n)).revoke(i.access_token)}finally{await this.sessionGetter.delStored(e,new Ic(e))}}createSession(e,t){return new ll(e,t,this.sessionGetter,this.fetch)}};function xl(e,t,n){let r=()=>{e.removeEventListener(`success`,i),e.removeEventListener(`error`,a)},i=()=>{t(e.result),r()},a=()=>{n(e.error||Error(`Unknown error`)),r()};e.addEventListener(`success`,i),e.addEventListener(`error`,a)}function Q(e){return new Promise((t,n)=>{xl(e,t,n)})}var Sl=class{constructor(e){this.idbIndex=e}count(e){return Q(this.idbIndex.count(e))}get(e){return Q(this.idbIndex.get(e))}getKey(e){return Q(this.idbIndex.getKey(e))}getAll(e,t){return Q(this.idbIndex.getAll(e,t))}getAllKeys(e,t){return Q(this.idbIndex.getAllKeys(e,t))}deleteAll(e){return new Promise((t,n)=>{let r=this.idbIndex.openCursor(e);r.onsuccess=function(e){let n=e.target.result;n?(n.delete(),n.continue()):t()},r.onerror=function(e){n(e.target?.error||Error(`Unexpected error`))}})}},Cl=class{constructor(e){this.idbObjStore=e}get name(){return this.idbObjStore.name}index(e){return new Sl(this.idbObjStore.index(e))}get(e){return Q(this.idbObjStore.get(e))}getKey(e){return Q(this.idbObjStore.getKey(e))}getAll(e,t){return Q(this.idbObjStore.getAll(e,t))}getAllKeys(e,t){return Q(this.idbObjStore.getAllKeys(e,t))}add(e,t){return Q(this.idbObjStore.add(e,t))}put(e,t){return Q(this.idbObjStore.put(e,t))}delete(e){return Q(this.idbObjStore.delete(e))}clear(){return Q(this.idbObjStore.clear())}},wl=class{#e;constructor(e){this.#e=e;let t=()=>{r()},n=()=>{r()},r=()=>{this.#e=null,e.removeEventListener(`abort`,t),e.removeEventListener(`complete`,n)};e.addEventListener(`abort`,t),e.addEventListener(`complete`,n)}get tx(){if(!this.#e)throw Error(`Transaction already ended`);return this.#e}async abort(){let{tx:e}=this;this.#e=null,e.abort()}async commit(){let{tx:e}=this;this.#e=null,e.commit?.()}objectStore(e){return new Cl(this.tx.objectStore(e))}[Symbol.dispose](){this.#e&&this.commit()}},Tl=class e{static async open(t,n,r){let i=await new Promise((e,r)=>{let i=indexedDB.open(t,n.length);i.onerror=()=>r(i.error),i.onsuccess=()=>e(i.result),i.onupgradeneeded=({oldVersion:e,newVersion:t})=>{let a=i.result;try{for(let r=e;r<(t??n.length);++r){let e=n[r];if(e)e(a);else throw Error(`Missing migration for version ${r}`)}}catch(e){a.close(),r(e)}}});return new e(i,r)}#e;constructor(e,t){this.txOptions=t,this.#e=e;let n=()=>{this.#e=null,e.removeEventListener(`versionchange`,n),e.removeEventListener(`close`,n),e.close()};e.addEventListener(`versionchange`,n),e.addEventListener(`close`,n)}get db(){if(!this.#e)throw Error(`Database closed`);return this.#e}get name(){return this.db.name}get objectStoreNames(){return this.db.objectStoreNames}get version(){return this.db.version}async transaction(e,t,n){return new Promise(async(r,i)=>{try{let a=this.db.transaction(e,t,this.txOptions),o={done:!1};a.oncomplete=()=>{o.done?r(o.value):i(Error(`Transaction completed without result`))},a.onerror=()=>i(a.error),a.onabort=()=>i(a.error||Error(`Transaction aborted`));try{o={done:!0,value:await n(new wl(a))},a.commit()}catch(e){throw a.abort(),e}}catch(e){i(e)}})}close(){let{db:e}=this;this.#e=null,e.close()}async[Symbol.asyncDispose](){this.#e&&await this.close()}};function El(e){if(!(e instanceof na)||!e.kid)throw Error(`Invalid key object`);return{keyId:e.kid,keyPair:e.cryptoKeyPair}}async function Dl(e){return na.fromKeypair(e.keyPair,e.keyId)}var Ol=[`state`,`session`,`didCache`,`dpopNonceCache`,`handleCache`,`authorizationServerMetadataCache`,`protectedResourceMetadataCache`],kl=class{#e;#t;constructor(e){this.#e=Tl.open(e?.name??`@atproto-oauth-client`,[e=>{for(let t of Ol)e.createObjectStore(t,{autoIncrement:!0}).createIndex(`expiresAt`,`expiresAt`,{unique:!1})}],{durability:e?.durability??`strict`}),this.#t=setInterval(()=>{this.cleanup()},e?.cleanupInterval??3e4)}async run(e,t,n){return await(await this.#e).transaction([e],t,t=>n(t.objectStore(e)))}createStore(e,{encode:t,decode:n,expiresAt:r}){return{get:async t=>{let r=await this.run(e,`readonly`,e=>e.get(t));if(r!==void 0){if(r.expiresAt!=null&&new Date(r.expiresAt)<new Date)await this.run(e,`readwrite`,e=>e.delete(t));else return n(r.value)}},set:async(n,i)=>{let a={value:await t(i),expiresAt:r(i)?.toISOString()};await this.run(e,`readwrite`,e=>e.put(a,n))},del:async t=>{await this.run(e,`readwrite`,e=>e.delete(t))}}}getSessionStore(){return this.createStore(`session`,{expiresAt:({tokenSet:e})=>e.refresh_token||e.expires_at==null?null:new Date(e.expires_at),encode:({dpopKey:e,...t})=>({...t,dpopKey:El(e)}),decode:async({dpopKey:e,...t})=>({...t,dpopKey:await Dl(e)})})}getStateStore(){return this.createStore(`state`,{expiresAt:e=>new Date(Date.now()+6e5),encode:({dpopKey:e,...t})=>({...t,dpopKey:El(e)}),decode:async({dpopKey:e,...t})=>({...t,dpopKey:await Dl(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.#e;for(let t of Ol)await e.transaction([t],`readwrite`,e=>e.objectStore(t).index(`expiresAt`).deleteAll(IDBKeyRange.upperBound(Date.now())))}async[Symbol.asyncDispose](){clearInterval(this.#t),this.#t=void 0;let e=this.#e;this.#e=Promise.reject(Error(`Database has been disposed`)),this.#e.catch(()=>null);let t=await e.catch(()=>null);t&&await t[Symbol.asyncDispose]()}},Al=typeof navigator<`u`&&navigator.locks?.request?(e,t)=>navigator.locks.request(e,{mode:`exclusive`},async()=>t()):void 0,jl=class{constructor(){if(this.requestLock=Al,typeof crypto!=`object`||!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 na.generate(e)}getRandomValues(e){return crypto.getRandomValues(new Uint8Array(e))}async digest(e,{name:t}){switch(t){case`sha256`:case`sha384`:case`sha512`:{let n=await crypto.subtle.digest(`SHA-${t.slice(3)}`,e);return new Uint8Array(n)}default:throw Error(`Unsupported digest algorithm: ${t}`)}}},Ml=class extends Error{constructor(){super(`Login complete, please close the popup window.`),this.code=`LOGIN_CONTINUED_IN_PARENT_WINDOW`}};function Nl(e,t=`127.0.0.1`){if(!vs(e.hostname))throw TypeError(`Expected a loopback host, got ${e.hostname}`);let n=`http://${e.hostname===`localhost`?t:e.hostname}${e.port&&!e.port.startsWith(`:`)?`:${e.port}`:e.port}${e.pathname}`;return`http://localhost${e.pathname===`/`?``:e.pathname}?redirect_uri=${encodeURIComponent(n)}`}var $=`@@atproto/oauth-client-browser`,Pl=`${$}(popup-channel)`,Fl=`${$}(popup-state):`,Il=new BroadcastChannel(`${$}(synchronization-channel:2)`),Ll=new jl,Rl=class e extends bl{static async load({clientId:t,...n}){if(t.startsWith(`http:`)){let r=Js(t);return new e({clientMetadata:r,...n})}if(t.startsWith(`https:`)){gc(t);let r=await bl.fetchMetadata({clientId:t,...n});return new e({...n,clientMetadata:r})}throw TypeError(`Invalid client id: ${t}`)}constructor({clientMetadata:e=Js(Nl(window.location)),responseMode:t=`fragment`,...n}){if(!globalThis.crypto?.subtle)throw Error(`WebCrypto API is required`);if(![`query`,`fragment`].includes(t))throw TypeError(`Invalid response mode: ${t}`);let r=new kl;super({...n,clientMetadata:e,responseMode:t,keyset:void 0,runtimeImplementation:Ll,sessionStore:r.getSessionStore(),stateStore:r.getStateStore(),didCache:r.getDidCache(),handleCache:r.getHandleCache(),dpopNonceCache:r.getDpopNonceCache(),authorizationServerMetadataCache:r.getAuthorizationServerMetadataCache(),protectedResourceMetadataCache:r.getProtectedResourceMetadataCache(),onSessionDeleted:async(e,t)=>(localStorage.getItem(`${$}(sub)`)===e&&localStorage.removeItem(`${$}(sub)`),Il.postMessage({name:`onSessionDeleted`,args:[e,t]}),n.onSessionDeleted?.call(null,e,t)),onSessionUpdated:async(e,t)=>(Il.postMessage({name:`onSessionUpdated`,args:[e,t]}),n.onSessionUpdated?.call(null,e,t))}),this.ac=new AbortController,this.database=r;let{signal:i}=this.ac;Il.addEventListener(`message`,e=>{if(e.source===window)return;let{name:t,args:r}=e.data,i=n[t];i?.(...r)},{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 zl(this.clientMetadata);let t=localStorage.getItem(`${$}(sub)`);if(t)try{return{session:await this.restore(t,e)}}catch(e){throw localStorage.removeItem(`${$}(sub)`),e}}async restore(e,t){let n=await super.restore(e,t);return localStorage.setItem(`${$}(sub)`,n.sub),n}async revoke(e){return localStorage.removeItem(`${$}(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 n=await this.authorize(e,t);return window.location.href=n.href,new Promise((e,t)=>{setTimeout(e=>{this.abortRequest(n).then(()=>t(e),n=>t(AggregateError([e,n])))},5e3,Error(`User navigated back`))})}async signInPopup(e,t){let n=t?.popupName??`_blank`,r=t?.popupFeatures??`width=600,height=600,menubar=no,toolbar=no`,i=window.open(`about:blank`,n,r),a=`${Math.random().toString(36).slice(2)}`,o=await this.authorize(e,{...t,state:`${Fl}${a}`,display:t?.display??`popup`});return t?.signal?.throwIfAborted(),i?i.window.location.href=o.href:i=window.open(o.href,n,r),i?.focus(),new Promise((e,n)=>{let r=new BroadcastChannel(Pl),o=()=>{clearTimeout(c),r.removeEventListener(`message`,l),r.close(),t?.signal?.removeEventListener(`abort`,s),i?.close()},s=()=>{n(Error(t?.signal?.aborted?`Aborted`:`Timeout`)),o()};t?.signal?.addEventListener(`abort`,s);let c=setTimeout(s,3e5),l=async({data:i})=>{if(i.key!==a||!(`result`in i))return;r.postMessage({key:a,ack:!0}),o();let{result:s}=i;if(s.status===`fulfilled`){let r=s.value;try{t?.signal?.throwIfAborted(),e(await this.restore(r,!1))}catch(e){n(e),this.revoke(r)}}else{let{message:e,params:t}=s.reason;n(new Z(new URLSearchParams(t),e))}};r.addEventListener(`message`,l)})}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=this.responseMode===`fragment`?new URLSearchParams(location.hash.slice(1)):new URLSearchParams(location.search);return!e.has(`state`)||!(e.has(`code`)||e.has(`error`))?null:e}async initCallback(e=this.readCallbackParams(),t=this.findRedirectUrl()){if(!e)throw TypeError(`No OAuth callback parameters found in the URL`);this.responseMode===`fragment`?history.replaceState(null,``,location.pathname+location.search):this.responseMode===`query`&&history.replaceState(null,``,location.pathname);let n=e=>{let t=new BroadcastChannel(Pl);return new Promise(n=>{let r=e=>{clearTimeout(a),t.removeEventListener(`message`,i),t.close(),n(e)},i=({data:t})=>{`ack`in t&&e.key===t.key&&r(!0)};t.addEventListener(`message`,i),t.postMessage(e);let a=setTimeout(r,500,!1)})};return this.callback(e,{redirect_uri:t}).then(async e=>{if(e.state?.startsWith(Fl))throw await n({key:e.state.slice(Fl.length),result:{status:`fulfilled`,value:e.session.sub}})||await e.session.signOut(),new Ml;return localStorage.setItem(`${$}(sub)`,e.session.sub),e}).catch(async e=>{throw e instanceof Z&&e.state?.startsWith(Fl)?(await n({key:e.state.slice(Fl.length),result:{status:`rejected`,reason:{message:e.message,params:Array.from(e.params.entries())}}}),new Ml):e}).catch(e=>{throw e instanceof Ml&&window.close(),e})}async[Symbol.asyncDispose](){try{this.ac.abort()}finally{await this.database[Symbol.asyncDispose]()}}async dispose(){await this[Symbol.asyncDispose]()}};function zl(e){if(!Us(e.client_id)||window.location.hostname!==`localhost`)return;let t=new URL(window.location.href);for(let n of e.redirect_uris){let e=new URL(n);if((e.hostname===`127.0.0.1`||e.hostname===`[::1]`)&&(!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}`)}var Bl=`acs.github.io`,Vl=`https://${Bl}/democlip/oauth-client-metadata.json`,Hl=`https://bsky.social`,Ul=`https://video.bsky.app`,Wl=`atproto transition:generic`,Gl=[`localhost`,`127.0.0.1`,`[::1]`],Kl=class{session;fetchFn;constructor(e,t=globalThis.fetch){this.session=e,this.fetchFn=t.bind(globalThis)}async uploadVideo(e){let t=await this.serviceToken(),n=new URL(`/xrpc/app.bsky.video.uploadVideo`,Ul);n.searchParams.set(`did`,this.session.did),n.searchParams.set(`name`,e.name);let r=await this.fetchFn(n,{method:`POST`,headers:{authorization:`Bearer ${t}`,"content-type":e.blob.type,"content-length":String(e.blob.size)},body:e.blob});return this.jobFrom(r)}async videoJob(e){let t=new URL(`/xrpc/app.bsky.video.getJobStatus`,Ul);t.searchParams.set(`jobId`,e);let n=await this.fetchFn(t);return this.jobFrom(n)}async createPost(e){let t=await this.session.fetchHandler(`/xrpc/com.atproto.repo.createRecord`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({repo:this.session.did,collection:`app.bsky.feed.post`,record:e})}),n=await this.ok(t);return{uri:n.uri,cid:n.cid}}async serviceToken(){let{aud:e}=await this.session.getTokenInfo(),t=new URLSearchParams({aud:`did:web:${new URL(e).host}`,lxm:`com.atproto.repo.uploadBlob`,exp:String(Math.floor(Date.now()/1e3)+1800)}),n=await this.session.fetchHandler(`/xrpc/com.atproto.server.getServiceAuth?${t}`,{method:`GET`});return(await this.ok(n)).token}async ok(e){if(e.ok)return e.json();let t=await e.text().catch(()=>``),n=t;try{n=JSON.parse(t).message??t}catch{}throw Error(`Bluesky ${e.status}: ${n||e.statusText}`)}async jobFrom(e){let t=await Jl(e),n=t?.jobStatus,r=t&&(t.jobId||t.state||t.blob)?t:null,i=n??r;if(i)return ql(i,t?.blob??null);let a=t?.message||t?.error,o=t?JSON.stringify(t).slice(0,200):`no JSON body`;throw Error(`Bluesky's video service answered ${e.status}: ${a??o}`)}};function ql(e,t=null){return{jobId:e.jobId??``,state:e.state??`JOB_STATE_COMPLETED`,progress:e.progress,blob:e.blob??t,error:e.error,failureCode:e.failureCode,message:e.message}}async function Jl(e){try{return await e.json()}catch{return null}}var Yl=null,Xl=null;function Zl(e){return e.protocol===`http:`&&Gl.includes(e.hostname)}function Ql(e,t){return`${Nl(e)}&scope=${encodeURIComponent(t)}`}function $l(){return Yl??=eu(),Yl}function eu(){let e=window.location;return Zl(e)?Rl.load({clientId:Ql(e,Wl),handleResolver:Hl,allowHttp:!0}):Rl.load({clientId:Vl,handleResolver:Hl})}async function tu(){try{Xl=(await(await $l()).init(!1))?.session??Xl}catch(e){console.warn(`Bluesky session could not be restored`,e)}}function nu(e){return e.trim().replace(/^@/,``)}async function ru(e){let t=window.location;if(!Zl(t)&&t.hostname!==Bl)throw Error(`Bluesky sign-in works on the deployed app, or on a dev server over http at 127.0.0.1`);await(await $l()).signIn(nu(e))}async function iu(){await Xl?.signOut(),Xl=null,ou=null}function au(){return Xl?.did??null}var ou=null;async function su(){return Xl?(ou??=await cu(Xl),ou):null}async function cu(e){try{let t=await e.fetchHandler(`/xrpc/com.atproto.repo.describeRepo?repo=${encodeURIComponent(e.did)}`);return t.ok?(await t.json()).handle??null:null}catch{return null}}async function lu(){if(await tu(),!Xl)throw Error(`not signed in to Bluesky`);return new Kl(Xl)}export{Kl as XrpcBlueskyService,au as blueskyDid,su as blueskyHandle,lu as blueskyService,cu as fetchHandle,tu as initBluesky,Zl as isLoopback,Ql as loopbackClientId,nu as normalizeHandle,ru as signIn,iu as signOut};
|
|
2
2
|
/*!
|
|
3
3
|
DemoClip — third-party notices
|
|
4
4
|
==============================
|